xref: /openbmc/linux/kernel/bpf/verifier.c (revision 61f4d204)
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 
30 #include "disasm.h"
31 
32 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
33 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
34 	[_id] = & _name ## _verifier_ops,
35 #define BPF_MAP_TYPE(_id, _ops)
36 #define BPF_LINK_TYPE(_id, _name)
37 #include <linux/bpf_types.h>
38 #undef BPF_PROG_TYPE
39 #undef BPF_MAP_TYPE
40 #undef BPF_LINK_TYPE
41 };
42 
43 /* bpf_check() is a static code analyzer that walks eBPF program
44  * instruction by instruction and updates register/stack state.
45  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
46  *
47  * The first pass is depth-first-search to check that the program is a DAG.
48  * It rejects the following programs:
49  * - larger than BPF_MAXINSNS insns
50  * - if loop is present (detected via back-edge)
51  * - unreachable insns exist (shouldn't be a forest. program = one function)
52  * - out of bounds or malformed jumps
53  * The second pass is all possible path descent from the 1st insn.
54  * Since it's analyzing all paths through the program, the length of the
55  * analysis is limited to 64k insn, which may be hit even if total number of
56  * insn is less then 4K, but there are too many branches that change stack/regs.
57  * Number of 'branches to be analyzed' is limited to 1k
58  *
59  * On entry to each instruction, each register has a type, and the instruction
60  * changes the types of the registers depending on instruction semantics.
61  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
62  * copied to R1.
63  *
64  * All registers are 64-bit.
65  * R0 - return register
66  * R1-R5 argument passing registers
67  * R6-R9 callee saved registers
68  * R10 - frame pointer read-only
69  *
70  * At the start of BPF program the register R1 contains a pointer to bpf_context
71  * and has type PTR_TO_CTX.
72  *
73  * Verifier tracks arithmetic operations on pointers in case:
74  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
75  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
76  * 1st insn copies R10 (which has FRAME_PTR) type into R1
77  * and 2nd arithmetic instruction is pattern matched to recognize
78  * that it wants to construct a pointer to some element within stack.
79  * So after 2nd insn, the register R1 has type PTR_TO_STACK
80  * (and -20 constant is saved for further stack bounds checking).
81  * Meaning that this reg is a pointer to stack plus known immediate constant.
82  *
83  * Most of the time the registers have SCALAR_VALUE type, which
84  * means the register has some value, but it's not a valid pointer.
85  * (like pointer plus pointer becomes SCALAR_VALUE type)
86  *
87  * When verifier sees load or store instructions the type of base register
88  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
89  * four pointer types recognized by check_mem_access() function.
90  *
91  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
92  * and the range of [ptr, ptr + map's value_size) is accessible.
93  *
94  * registers used to pass values to function calls are checked against
95  * function argument constraints.
96  *
97  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
98  * It means that the register type passed to this function must be
99  * PTR_TO_STACK and it will be used inside the function as
100  * 'pointer to map element key'
101  *
102  * For example the argument constraints for bpf_map_lookup_elem():
103  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
104  *   .arg1_type = ARG_CONST_MAP_PTR,
105  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
106  *
107  * ret_type says that this function returns 'pointer to map elem value or null'
108  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
109  * 2nd argument should be a pointer to stack, which will be used inside
110  * the helper function as a pointer to map element key.
111  *
112  * On the kernel side the helper function looks like:
113  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
114  * {
115  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
116  *    void *key = (void *) (unsigned long) r2;
117  *    void *value;
118  *
119  *    here kernel can access 'key' and 'map' pointers safely, knowing that
120  *    [key, key + map->key_size) bytes are valid and were initialized on
121  *    the stack of eBPF program.
122  * }
123  *
124  * Corresponding eBPF program may look like:
125  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
126  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
127  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
128  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
129  * here verifier looks at prototype of map_lookup_elem() and sees:
130  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
131  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
132  *
133  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
134  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
135  * and were initialized prior to this call.
136  * If it's ok, then verifier allows this BPF_CALL insn and looks at
137  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
138  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
139  * returns either pointer to map value or NULL.
140  *
141  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
142  * insn, the register holding that pointer in the true branch changes state to
143  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
144  * branch. See check_cond_jmp_op().
145  *
146  * After the call R0 is set to return type of the function and registers R1-R5
147  * are set to NOT_INIT to indicate that they are no longer readable.
148  *
149  * The following reference types represent a potential reference to a kernel
150  * resource which, after first being allocated, must be checked and freed by
151  * the BPF program:
152  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
153  *
154  * When the verifier sees a helper call return a reference type, it allocates a
155  * pointer id for the reference and stores it in the current function state.
156  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
157  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
158  * passes through a NULL-check conditional. For the branch wherein the state is
159  * changed to CONST_IMM, the verifier releases the reference.
160  *
161  * For each helper function that allocates a reference, such as
162  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
163  * bpf_sk_release(). When a reference type passes into the release function,
164  * the verifier also releases the reference. If any unchecked or unreleased
165  * reference remains at the end of the program, the verifier rejects it.
166  */
167 
168 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
169 struct bpf_verifier_stack_elem {
170 	/* verifer state is 'st'
171 	 * before processing instruction 'insn_idx'
172 	 * and after processing instruction 'prev_insn_idx'
173 	 */
174 	struct bpf_verifier_state st;
175 	int insn_idx;
176 	int prev_insn_idx;
177 	struct bpf_verifier_stack_elem *next;
178 	/* length of verifier log at the time this state was pushed on stack */
179 	u32 log_pos;
180 };
181 
182 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
183 #define BPF_COMPLEXITY_LIMIT_STATES	64
184 
185 #define BPF_MAP_KEY_POISON	(1ULL << 63)
186 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
187 
188 #define BPF_MAP_PTR_UNPRIV	1UL
189 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
190 					  POISON_POINTER_DELTA))
191 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
192 
193 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
194 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
195 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
196 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
197 static int ref_set_non_owning(struct bpf_verifier_env *env,
198 			      struct bpf_reg_state *reg);
199 static void specialize_kfunc(struct bpf_verifier_env *env,
200 			     u32 func_id, u16 offset, unsigned long *addr);
201 static bool is_trusted_reg(const struct bpf_reg_state *reg);
202 
203 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
204 {
205 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
206 }
207 
208 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
209 {
210 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
211 }
212 
213 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
214 			      const struct bpf_map *map, bool unpriv)
215 {
216 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
217 	unpriv |= bpf_map_ptr_unpriv(aux);
218 	aux->map_ptr_state = (unsigned long)map |
219 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
220 }
221 
222 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
223 {
224 	return aux->map_key_state & BPF_MAP_KEY_POISON;
225 }
226 
227 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
228 {
229 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
230 }
231 
232 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
233 {
234 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
235 }
236 
237 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
238 {
239 	bool poisoned = bpf_map_key_poisoned(aux);
240 
241 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
242 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
243 }
244 
245 static bool bpf_helper_call(const struct bpf_insn *insn)
246 {
247 	return insn->code == (BPF_JMP | BPF_CALL) &&
248 	       insn->src_reg == 0;
249 }
250 
251 static bool bpf_pseudo_call(const struct bpf_insn *insn)
252 {
253 	return insn->code == (BPF_JMP | BPF_CALL) &&
254 	       insn->src_reg == BPF_PSEUDO_CALL;
255 }
256 
257 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
258 {
259 	return insn->code == (BPF_JMP | BPF_CALL) &&
260 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
261 }
262 
263 struct bpf_call_arg_meta {
264 	struct bpf_map *map_ptr;
265 	bool raw_mode;
266 	bool pkt_access;
267 	u8 release_regno;
268 	int regno;
269 	int access_size;
270 	int mem_size;
271 	u64 msize_max_value;
272 	int ref_obj_id;
273 	int dynptr_id;
274 	int map_uid;
275 	int func_id;
276 	struct btf *btf;
277 	u32 btf_id;
278 	struct btf *ret_btf;
279 	u32 ret_btf_id;
280 	u32 subprogno;
281 	struct btf_field *kptr_field;
282 };
283 
284 struct bpf_kfunc_call_arg_meta {
285 	/* In parameters */
286 	struct btf *btf;
287 	u32 func_id;
288 	u32 kfunc_flags;
289 	const struct btf_type *func_proto;
290 	const char *func_name;
291 	/* Out parameters */
292 	u32 ref_obj_id;
293 	u8 release_regno;
294 	bool r0_rdonly;
295 	u32 ret_btf_id;
296 	u64 r0_size;
297 	u32 subprogno;
298 	struct {
299 		u64 value;
300 		bool found;
301 	} arg_constant;
302 
303 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
304 	 * generally to pass info about user-defined local kptr types to later
305 	 * verification logic
306 	 *   bpf_obj_drop
307 	 *     Record the local kptr type to be drop'd
308 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
309 	 *     Record the local kptr type to be refcount_incr'd and use
310 	 *     arg_owning_ref to determine whether refcount_acquire should be
311 	 *     fallible
312 	 */
313 	struct btf *arg_btf;
314 	u32 arg_btf_id;
315 	bool arg_owning_ref;
316 
317 	struct {
318 		struct btf_field *field;
319 	} arg_list_head;
320 	struct {
321 		struct btf_field *field;
322 	} arg_rbtree_root;
323 	struct {
324 		enum bpf_dynptr_type type;
325 		u32 id;
326 		u32 ref_obj_id;
327 	} initialized_dynptr;
328 	struct {
329 		u8 spi;
330 		u8 frameno;
331 	} iter;
332 	u64 mem_size;
333 };
334 
335 struct btf *btf_vmlinux;
336 
337 static DEFINE_MUTEX(bpf_verifier_lock);
338 
339 static const struct bpf_line_info *
340 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
341 {
342 	const struct bpf_line_info *linfo;
343 	const struct bpf_prog *prog;
344 	u32 i, nr_linfo;
345 
346 	prog = env->prog;
347 	nr_linfo = prog->aux->nr_linfo;
348 
349 	if (!nr_linfo || insn_off >= prog->len)
350 		return NULL;
351 
352 	linfo = prog->aux->linfo;
353 	for (i = 1; i < nr_linfo; i++)
354 		if (insn_off < linfo[i].insn_off)
355 			break;
356 
357 	return &linfo[i - 1];
358 }
359 
360 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
361 {
362 	struct bpf_verifier_env *env = private_data;
363 	va_list args;
364 
365 	if (!bpf_verifier_log_needed(&env->log))
366 		return;
367 
368 	va_start(args, fmt);
369 	bpf_verifier_vlog(&env->log, fmt, args);
370 	va_end(args);
371 }
372 
373 static const char *ltrim(const char *s)
374 {
375 	while (isspace(*s))
376 		s++;
377 
378 	return s;
379 }
380 
381 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
382 					 u32 insn_off,
383 					 const char *prefix_fmt, ...)
384 {
385 	const struct bpf_line_info *linfo;
386 
387 	if (!bpf_verifier_log_needed(&env->log))
388 		return;
389 
390 	linfo = find_linfo(env, insn_off);
391 	if (!linfo || linfo == env->prev_linfo)
392 		return;
393 
394 	if (prefix_fmt) {
395 		va_list args;
396 
397 		va_start(args, prefix_fmt);
398 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
399 		va_end(args);
400 	}
401 
402 	verbose(env, "%s\n",
403 		ltrim(btf_name_by_offset(env->prog->aux->btf,
404 					 linfo->line_off)));
405 
406 	env->prev_linfo = linfo;
407 }
408 
409 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
410 				   struct bpf_reg_state *reg,
411 				   struct tnum *range, const char *ctx,
412 				   const char *reg_name)
413 {
414 	char tn_buf[48];
415 
416 	verbose(env, "At %s the register %s ", ctx, reg_name);
417 	if (!tnum_is_unknown(reg->var_off)) {
418 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
419 		verbose(env, "has value %s", tn_buf);
420 	} else {
421 		verbose(env, "has unknown scalar value");
422 	}
423 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
424 	verbose(env, " should have been in %s\n", tn_buf);
425 }
426 
427 static bool type_is_pkt_pointer(enum bpf_reg_type type)
428 {
429 	type = base_type(type);
430 	return type == PTR_TO_PACKET ||
431 	       type == PTR_TO_PACKET_META;
432 }
433 
434 static bool type_is_sk_pointer(enum bpf_reg_type type)
435 {
436 	return type == PTR_TO_SOCKET ||
437 		type == PTR_TO_SOCK_COMMON ||
438 		type == PTR_TO_TCP_SOCK ||
439 		type == PTR_TO_XDP_SOCK;
440 }
441 
442 static bool type_may_be_null(u32 type)
443 {
444 	return type & PTR_MAYBE_NULL;
445 }
446 
447 static bool reg_not_null(const struct bpf_reg_state *reg)
448 {
449 	enum bpf_reg_type type;
450 
451 	type = reg->type;
452 	if (type_may_be_null(type))
453 		return false;
454 
455 	type = base_type(type);
456 	return type == PTR_TO_SOCKET ||
457 		type == PTR_TO_TCP_SOCK ||
458 		type == PTR_TO_MAP_VALUE ||
459 		type == PTR_TO_MAP_KEY ||
460 		type == PTR_TO_SOCK_COMMON ||
461 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
462 		type == PTR_TO_MEM;
463 }
464 
465 static bool type_is_ptr_alloc_obj(u32 type)
466 {
467 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
468 }
469 
470 static bool type_is_non_owning_ref(u32 type)
471 {
472 	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
473 }
474 
475 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
476 {
477 	struct btf_record *rec = NULL;
478 	struct btf_struct_meta *meta;
479 
480 	if (reg->type == PTR_TO_MAP_VALUE) {
481 		rec = reg->map_ptr->record;
482 	} else if (type_is_ptr_alloc_obj(reg->type)) {
483 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
484 		if (meta)
485 			rec = meta->record;
486 	}
487 	return rec;
488 }
489 
490 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
491 {
492 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
493 
494 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
495 }
496 
497 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
498 {
499 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
500 }
501 
502 static bool type_is_rdonly_mem(u32 type)
503 {
504 	return type & MEM_RDONLY;
505 }
506 
507 static bool is_acquire_function(enum bpf_func_id func_id,
508 				const struct bpf_map *map)
509 {
510 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
511 
512 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
513 	    func_id == BPF_FUNC_sk_lookup_udp ||
514 	    func_id == BPF_FUNC_skc_lookup_tcp ||
515 	    func_id == BPF_FUNC_ringbuf_reserve ||
516 	    func_id == BPF_FUNC_kptr_xchg)
517 		return true;
518 
519 	if (func_id == BPF_FUNC_map_lookup_elem &&
520 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
521 	     map_type == BPF_MAP_TYPE_SOCKHASH))
522 		return true;
523 
524 	return false;
525 }
526 
527 static bool is_ptr_cast_function(enum bpf_func_id func_id)
528 {
529 	return func_id == BPF_FUNC_tcp_sock ||
530 		func_id == BPF_FUNC_sk_fullsock ||
531 		func_id == BPF_FUNC_skc_to_tcp_sock ||
532 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
533 		func_id == BPF_FUNC_skc_to_udp6_sock ||
534 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
535 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
536 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
537 }
538 
539 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
540 {
541 	return func_id == BPF_FUNC_dynptr_data;
542 }
543 
544 static bool is_callback_calling_kfunc(u32 btf_id);
545 
546 static bool is_callback_calling_function(enum bpf_func_id func_id)
547 {
548 	return func_id == BPF_FUNC_for_each_map_elem ||
549 	       func_id == BPF_FUNC_timer_set_callback ||
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_storage_get_function(enum bpf_func_id func_id)
561 {
562 	return func_id == BPF_FUNC_sk_storage_get ||
563 	       func_id == BPF_FUNC_inode_storage_get ||
564 	       func_id == BPF_FUNC_task_storage_get ||
565 	       func_id == BPF_FUNC_cgrp_storage_get;
566 }
567 
568 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
569 					const struct bpf_map *map)
570 {
571 	int ref_obj_uses = 0;
572 
573 	if (is_ptr_cast_function(func_id))
574 		ref_obj_uses++;
575 	if (is_acquire_function(func_id, map))
576 		ref_obj_uses++;
577 	if (is_dynptr_ref_function(func_id))
578 		ref_obj_uses++;
579 
580 	return ref_obj_uses > 1;
581 }
582 
583 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
584 {
585 	return BPF_CLASS(insn->code) == BPF_STX &&
586 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
587 	       insn->imm == BPF_CMPXCHG;
588 }
589 
590 /* string representation of 'enum bpf_reg_type'
591  *
592  * Note that reg_type_str() can not appear more than once in a single verbose()
593  * statement.
594  */
595 static const char *reg_type_str(struct bpf_verifier_env *env,
596 				enum bpf_reg_type type)
597 {
598 	char postfix[16] = {0}, prefix[64] = {0};
599 	static const char * const str[] = {
600 		[NOT_INIT]		= "?",
601 		[SCALAR_VALUE]		= "scalar",
602 		[PTR_TO_CTX]		= "ctx",
603 		[CONST_PTR_TO_MAP]	= "map_ptr",
604 		[PTR_TO_MAP_VALUE]	= "map_value",
605 		[PTR_TO_STACK]		= "fp",
606 		[PTR_TO_PACKET]		= "pkt",
607 		[PTR_TO_PACKET_META]	= "pkt_meta",
608 		[PTR_TO_PACKET_END]	= "pkt_end",
609 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
610 		[PTR_TO_SOCKET]		= "sock",
611 		[PTR_TO_SOCK_COMMON]	= "sock_common",
612 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
613 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
614 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
615 		[PTR_TO_BTF_ID]		= "ptr_",
616 		[PTR_TO_MEM]		= "mem",
617 		[PTR_TO_BUF]		= "buf",
618 		[PTR_TO_FUNC]		= "func",
619 		[PTR_TO_MAP_KEY]	= "map_key",
620 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
621 	};
622 
623 	if (type & PTR_MAYBE_NULL) {
624 		if (base_type(type) == PTR_TO_BTF_ID)
625 			strncpy(postfix, "or_null_", 16);
626 		else
627 			strncpy(postfix, "_or_null", 16);
628 	}
629 
630 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
631 		 type & MEM_RDONLY ? "rdonly_" : "",
632 		 type & MEM_RINGBUF ? "ringbuf_" : "",
633 		 type & MEM_USER ? "user_" : "",
634 		 type & MEM_PERCPU ? "percpu_" : "",
635 		 type & MEM_RCU ? "rcu_" : "",
636 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
637 		 type & PTR_TRUSTED ? "trusted_" : ""
638 	);
639 
640 	snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
641 		 prefix, str[base_type(type)], postfix);
642 	return env->tmp_str_buf;
643 }
644 
645 static char slot_type_char[] = {
646 	[STACK_INVALID]	= '?',
647 	[STACK_SPILL]	= 'r',
648 	[STACK_MISC]	= 'm',
649 	[STACK_ZERO]	= '0',
650 	[STACK_DYNPTR]	= 'd',
651 	[STACK_ITER]	= 'i',
652 };
653 
654 static void print_liveness(struct bpf_verifier_env *env,
655 			   enum bpf_reg_liveness live)
656 {
657 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
658 	    verbose(env, "_");
659 	if (live & REG_LIVE_READ)
660 		verbose(env, "r");
661 	if (live & REG_LIVE_WRITTEN)
662 		verbose(env, "w");
663 	if (live & REG_LIVE_DONE)
664 		verbose(env, "D");
665 }
666 
667 static int __get_spi(s32 off)
668 {
669 	return (-off - 1) / BPF_REG_SIZE;
670 }
671 
672 static struct bpf_func_state *func(struct bpf_verifier_env *env,
673 				   const struct bpf_reg_state *reg)
674 {
675 	struct bpf_verifier_state *cur = env->cur_state;
676 
677 	return cur->frame[reg->frameno];
678 }
679 
680 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
681 {
682        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
683 
684        /* We need to check that slots between [spi - nr_slots + 1, spi] are
685 	* within [0, allocated_stack).
686 	*
687 	* Please note that the spi grows downwards. For example, a dynptr
688 	* takes the size of two stack slots; the first slot will be at
689 	* spi and the second slot will be at spi - 1.
690 	*/
691        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
692 }
693 
694 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
695 			          const char *obj_kind, int nr_slots)
696 {
697 	int off, spi;
698 
699 	if (!tnum_is_const(reg->var_off)) {
700 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
701 		return -EINVAL;
702 	}
703 
704 	off = reg->off + reg->var_off.value;
705 	if (off % BPF_REG_SIZE) {
706 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
707 		return -EINVAL;
708 	}
709 
710 	spi = __get_spi(off);
711 	if (spi + 1 < nr_slots) {
712 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
713 		return -EINVAL;
714 	}
715 
716 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
717 		return -ERANGE;
718 	return spi;
719 }
720 
721 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
722 {
723 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
724 }
725 
726 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
727 {
728 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
729 }
730 
731 static const char *btf_type_name(const struct btf *btf, u32 id)
732 {
733 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
734 }
735 
736 static const char *dynptr_type_str(enum bpf_dynptr_type type)
737 {
738 	switch (type) {
739 	case BPF_DYNPTR_TYPE_LOCAL:
740 		return "local";
741 	case BPF_DYNPTR_TYPE_RINGBUF:
742 		return "ringbuf";
743 	case BPF_DYNPTR_TYPE_SKB:
744 		return "skb";
745 	case BPF_DYNPTR_TYPE_XDP:
746 		return "xdp";
747 	case BPF_DYNPTR_TYPE_INVALID:
748 		return "<invalid>";
749 	default:
750 		WARN_ONCE(1, "unknown dynptr type %d\n", type);
751 		return "<unknown>";
752 	}
753 }
754 
755 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
756 {
757 	if (!btf || btf_id == 0)
758 		return "<invalid>";
759 
760 	/* we already validated that type is valid and has conforming name */
761 	return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
762 }
763 
764 static const char *iter_state_str(enum bpf_iter_state state)
765 {
766 	switch (state) {
767 	case BPF_ITER_STATE_ACTIVE:
768 		return "active";
769 	case BPF_ITER_STATE_DRAINED:
770 		return "drained";
771 	case BPF_ITER_STATE_INVALID:
772 		return "<invalid>";
773 	default:
774 		WARN_ONCE(1, "unknown iter state %d\n", state);
775 		return "<unknown>";
776 	}
777 }
778 
779 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
780 {
781 	env->scratched_regs |= 1U << regno;
782 }
783 
784 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
785 {
786 	env->scratched_stack_slots |= 1ULL << spi;
787 }
788 
789 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
790 {
791 	return (env->scratched_regs >> regno) & 1;
792 }
793 
794 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
795 {
796 	return (env->scratched_stack_slots >> regno) & 1;
797 }
798 
799 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
800 {
801 	return env->scratched_regs || env->scratched_stack_slots;
802 }
803 
804 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
805 {
806 	env->scratched_regs = 0U;
807 	env->scratched_stack_slots = 0ULL;
808 }
809 
810 /* Used for printing the entire verifier state. */
811 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
812 {
813 	env->scratched_regs = ~0U;
814 	env->scratched_stack_slots = ~0ULL;
815 }
816 
817 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
818 {
819 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
820 	case DYNPTR_TYPE_LOCAL:
821 		return BPF_DYNPTR_TYPE_LOCAL;
822 	case DYNPTR_TYPE_RINGBUF:
823 		return BPF_DYNPTR_TYPE_RINGBUF;
824 	case DYNPTR_TYPE_SKB:
825 		return BPF_DYNPTR_TYPE_SKB;
826 	case DYNPTR_TYPE_XDP:
827 		return BPF_DYNPTR_TYPE_XDP;
828 	default:
829 		return BPF_DYNPTR_TYPE_INVALID;
830 	}
831 }
832 
833 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
834 {
835 	switch (type) {
836 	case BPF_DYNPTR_TYPE_LOCAL:
837 		return DYNPTR_TYPE_LOCAL;
838 	case BPF_DYNPTR_TYPE_RINGBUF:
839 		return DYNPTR_TYPE_RINGBUF;
840 	case BPF_DYNPTR_TYPE_SKB:
841 		return DYNPTR_TYPE_SKB;
842 	case BPF_DYNPTR_TYPE_XDP:
843 		return DYNPTR_TYPE_XDP;
844 	default:
845 		return 0;
846 	}
847 }
848 
849 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
850 {
851 	return type == BPF_DYNPTR_TYPE_RINGBUF;
852 }
853 
854 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
855 			      enum bpf_dynptr_type type,
856 			      bool first_slot, int dynptr_id);
857 
858 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
859 				struct bpf_reg_state *reg);
860 
861 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
862 				   struct bpf_reg_state *sreg1,
863 				   struct bpf_reg_state *sreg2,
864 				   enum bpf_dynptr_type type)
865 {
866 	int id = ++env->id_gen;
867 
868 	__mark_dynptr_reg(sreg1, type, true, id);
869 	__mark_dynptr_reg(sreg2, type, false, id);
870 }
871 
872 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
873 			       struct bpf_reg_state *reg,
874 			       enum bpf_dynptr_type type)
875 {
876 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
877 }
878 
879 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
880 				        struct bpf_func_state *state, int spi);
881 
882 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
883 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
884 {
885 	struct bpf_func_state *state = func(env, reg);
886 	enum bpf_dynptr_type type;
887 	int spi, i, err;
888 
889 	spi = dynptr_get_spi(env, reg);
890 	if (spi < 0)
891 		return spi;
892 
893 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
894 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
895 	 * to ensure that for the following example:
896 	 *	[d1][d1][d2][d2]
897 	 * spi    3   2   1   0
898 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
899 	 * case they do belong to same dynptr, second call won't see slot_type
900 	 * as STACK_DYNPTR and will simply skip destruction.
901 	 */
902 	err = destroy_if_dynptr_stack_slot(env, state, spi);
903 	if (err)
904 		return err;
905 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
906 	if (err)
907 		return err;
908 
909 	for (i = 0; i < BPF_REG_SIZE; i++) {
910 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
911 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
912 	}
913 
914 	type = arg_to_dynptr_type(arg_type);
915 	if (type == BPF_DYNPTR_TYPE_INVALID)
916 		return -EINVAL;
917 
918 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
919 			       &state->stack[spi - 1].spilled_ptr, type);
920 
921 	if (dynptr_type_refcounted(type)) {
922 		/* The id is used to track proper releasing */
923 		int id;
924 
925 		if (clone_ref_obj_id)
926 			id = clone_ref_obj_id;
927 		else
928 			id = acquire_reference_state(env, insn_idx);
929 
930 		if (id < 0)
931 			return id;
932 
933 		state->stack[spi].spilled_ptr.ref_obj_id = id;
934 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
935 	}
936 
937 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
938 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
939 
940 	return 0;
941 }
942 
943 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
944 {
945 	int i;
946 
947 	for (i = 0; i < BPF_REG_SIZE; i++) {
948 		state->stack[spi].slot_type[i] = STACK_INVALID;
949 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
950 	}
951 
952 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
953 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
954 
955 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
956 	 *
957 	 * While we don't allow reading STACK_INVALID, it is still possible to
958 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
959 	 * helpers or insns can do partial read of that part without failing,
960 	 * but check_stack_range_initialized, check_stack_read_var_off, and
961 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
962 	 * the slot conservatively. Hence we need to prevent those liveness
963 	 * marking walks.
964 	 *
965 	 * This was not a problem before because STACK_INVALID is only set by
966 	 * default (where the default reg state has its reg->parent as NULL), or
967 	 * in clean_live_states after REG_LIVE_DONE (at which point
968 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
969 	 * verifier state exploration (like we did above). Hence, for our case
970 	 * parentage chain will still be live (i.e. reg->parent may be
971 	 * non-NULL), while earlier reg->parent was NULL, so we need
972 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
973 	 * done later on reads or by mark_dynptr_read as well to unnecessary
974 	 * mark registers in verifier state.
975 	 */
976 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
977 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
978 }
979 
980 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
981 {
982 	struct bpf_func_state *state = func(env, reg);
983 	int spi, ref_obj_id, i;
984 
985 	spi = dynptr_get_spi(env, reg);
986 	if (spi < 0)
987 		return spi;
988 
989 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
990 		invalidate_dynptr(env, state, spi);
991 		return 0;
992 	}
993 
994 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
995 
996 	/* If the dynptr has a ref_obj_id, then we need to invalidate
997 	 * two things:
998 	 *
999 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
1000 	 * 2) Any slices derived from this dynptr.
1001 	 */
1002 
1003 	/* Invalidate any slices associated with this dynptr */
1004 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
1005 
1006 	/* Invalidate any dynptr clones */
1007 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1008 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1009 			continue;
1010 
1011 		/* it should always be the case that if the ref obj id
1012 		 * matches then the stack slot also belongs to a
1013 		 * dynptr
1014 		 */
1015 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1016 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1017 			return -EFAULT;
1018 		}
1019 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
1020 			invalidate_dynptr(env, state, i);
1021 	}
1022 
1023 	return 0;
1024 }
1025 
1026 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1027 			       struct bpf_reg_state *reg);
1028 
1029 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1030 {
1031 	if (!env->allow_ptr_leaks)
1032 		__mark_reg_not_init(env, reg);
1033 	else
1034 		__mark_reg_unknown(env, reg);
1035 }
1036 
1037 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1038 				        struct bpf_func_state *state, int spi)
1039 {
1040 	struct bpf_func_state *fstate;
1041 	struct bpf_reg_state *dreg;
1042 	int i, dynptr_id;
1043 
1044 	/* We always ensure that STACK_DYNPTR is never set partially,
1045 	 * hence just checking for slot_type[0] is enough. This is
1046 	 * different for STACK_SPILL, where it may be only set for
1047 	 * 1 byte, so code has to use is_spilled_reg.
1048 	 */
1049 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1050 		return 0;
1051 
1052 	/* Reposition spi to first slot */
1053 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1054 		spi = spi + 1;
1055 
1056 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1057 		verbose(env, "cannot overwrite referenced dynptr\n");
1058 		return -EINVAL;
1059 	}
1060 
1061 	mark_stack_slot_scratched(env, spi);
1062 	mark_stack_slot_scratched(env, spi - 1);
1063 
1064 	/* Writing partially to one dynptr stack slot destroys both. */
1065 	for (i = 0; i < BPF_REG_SIZE; i++) {
1066 		state->stack[spi].slot_type[i] = STACK_INVALID;
1067 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1068 	}
1069 
1070 	dynptr_id = state->stack[spi].spilled_ptr.id;
1071 	/* Invalidate any slices associated with this dynptr */
1072 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1073 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1074 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1075 			continue;
1076 		if (dreg->dynptr_id == dynptr_id)
1077 			mark_reg_invalid(env, dreg);
1078 	}));
1079 
1080 	/* Do not release reference state, we are destroying dynptr on stack,
1081 	 * not using some helper to release it. Just reset register.
1082 	 */
1083 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1084 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1085 
1086 	/* Same reason as unmark_stack_slots_dynptr above */
1087 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1088 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1089 
1090 	return 0;
1091 }
1092 
1093 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1094 {
1095 	int spi;
1096 
1097 	if (reg->type == CONST_PTR_TO_DYNPTR)
1098 		return false;
1099 
1100 	spi = dynptr_get_spi(env, reg);
1101 
1102 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1103 	 * error because this just means the stack state hasn't been updated yet.
1104 	 * We will do check_mem_access to check and update stack bounds later.
1105 	 */
1106 	if (spi < 0 && spi != -ERANGE)
1107 		return false;
1108 
1109 	/* We don't need to check if the stack slots are marked by previous
1110 	 * dynptr initializations because we allow overwriting existing unreferenced
1111 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1112 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1113 	 * touching are completely destructed before we reinitialize them for a new
1114 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1115 	 * instead of delaying it until the end where the user will get "Unreleased
1116 	 * reference" error.
1117 	 */
1118 	return true;
1119 }
1120 
1121 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1122 {
1123 	struct bpf_func_state *state = func(env, reg);
1124 	int i, spi;
1125 
1126 	/* This already represents first slot of initialized bpf_dynptr.
1127 	 *
1128 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1129 	 * check_func_arg_reg_off's logic, so we don't need to check its
1130 	 * offset and alignment.
1131 	 */
1132 	if (reg->type == CONST_PTR_TO_DYNPTR)
1133 		return true;
1134 
1135 	spi = dynptr_get_spi(env, reg);
1136 	if (spi < 0)
1137 		return false;
1138 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1139 		return false;
1140 
1141 	for (i = 0; i < BPF_REG_SIZE; i++) {
1142 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1143 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1144 			return false;
1145 	}
1146 
1147 	return true;
1148 }
1149 
1150 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1151 				    enum bpf_arg_type arg_type)
1152 {
1153 	struct bpf_func_state *state = func(env, reg);
1154 	enum bpf_dynptr_type dynptr_type;
1155 	int spi;
1156 
1157 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1158 	if (arg_type == ARG_PTR_TO_DYNPTR)
1159 		return true;
1160 
1161 	dynptr_type = arg_to_dynptr_type(arg_type);
1162 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1163 		return reg->dynptr.type == dynptr_type;
1164 	} else {
1165 		spi = dynptr_get_spi(env, reg);
1166 		if (spi < 0)
1167 			return false;
1168 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1169 	}
1170 }
1171 
1172 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1173 
1174 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1175 				 struct bpf_reg_state *reg, int insn_idx,
1176 				 struct btf *btf, u32 btf_id, int nr_slots)
1177 {
1178 	struct bpf_func_state *state = func(env, reg);
1179 	int spi, i, j, id;
1180 
1181 	spi = iter_get_spi(env, reg, nr_slots);
1182 	if (spi < 0)
1183 		return spi;
1184 
1185 	id = acquire_reference_state(env, insn_idx);
1186 	if (id < 0)
1187 		return id;
1188 
1189 	for (i = 0; i < nr_slots; i++) {
1190 		struct bpf_stack_state *slot = &state->stack[spi - i];
1191 		struct bpf_reg_state *st = &slot->spilled_ptr;
1192 
1193 		__mark_reg_known_zero(st);
1194 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1195 		st->live |= REG_LIVE_WRITTEN;
1196 		st->ref_obj_id = i == 0 ? id : 0;
1197 		st->iter.btf = btf;
1198 		st->iter.btf_id = btf_id;
1199 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1200 		st->iter.depth = 0;
1201 
1202 		for (j = 0; j < BPF_REG_SIZE; j++)
1203 			slot->slot_type[j] = STACK_ITER;
1204 
1205 		mark_stack_slot_scratched(env, spi - i);
1206 	}
1207 
1208 	return 0;
1209 }
1210 
1211 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1212 				   struct bpf_reg_state *reg, int nr_slots)
1213 {
1214 	struct bpf_func_state *state = func(env, reg);
1215 	int spi, i, j;
1216 
1217 	spi = iter_get_spi(env, reg, nr_slots);
1218 	if (spi < 0)
1219 		return spi;
1220 
1221 	for (i = 0; i < nr_slots; i++) {
1222 		struct bpf_stack_state *slot = &state->stack[spi - i];
1223 		struct bpf_reg_state *st = &slot->spilled_ptr;
1224 
1225 		if (i == 0)
1226 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1227 
1228 		__mark_reg_not_init(env, st);
1229 
1230 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1231 		st->live |= REG_LIVE_WRITTEN;
1232 
1233 		for (j = 0; j < BPF_REG_SIZE; j++)
1234 			slot->slot_type[j] = STACK_INVALID;
1235 
1236 		mark_stack_slot_scratched(env, spi - i);
1237 	}
1238 
1239 	return 0;
1240 }
1241 
1242 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1243 				     struct bpf_reg_state *reg, int nr_slots)
1244 {
1245 	struct bpf_func_state *state = func(env, reg);
1246 	int spi, i, j;
1247 
1248 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1249 	 * will do check_mem_access to check and update stack bounds later, so
1250 	 * return true for that case.
1251 	 */
1252 	spi = iter_get_spi(env, reg, nr_slots);
1253 	if (spi == -ERANGE)
1254 		return true;
1255 	if (spi < 0)
1256 		return false;
1257 
1258 	for (i = 0; i < nr_slots; i++) {
1259 		struct bpf_stack_state *slot = &state->stack[spi - i];
1260 
1261 		for (j = 0; j < BPF_REG_SIZE; j++)
1262 			if (slot->slot_type[j] == STACK_ITER)
1263 				return false;
1264 	}
1265 
1266 	return true;
1267 }
1268 
1269 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1270 				   struct btf *btf, u32 btf_id, int nr_slots)
1271 {
1272 	struct bpf_func_state *state = func(env, reg);
1273 	int spi, i, j;
1274 
1275 	spi = iter_get_spi(env, reg, nr_slots);
1276 	if (spi < 0)
1277 		return false;
1278 
1279 	for (i = 0; i < nr_slots; i++) {
1280 		struct bpf_stack_state *slot = &state->stack[spi - i];
1281 		struct bpf_reg_state *st = &slot->spilled_ptr;
1282 
1283 		/* only main (first) slot has ref_obj_id set */
1284 		if (i == 0 && !st->ref_obj_id)
1285 			return false;
1286 		if (i != 0 && st->ref_obj_id)
1287 			return false;
1288 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1289 			return false;
1290 
1291 		for (j = 0; j < BPF_REG_SIZE; j++)
1292 			if (slot->slot_type[j] != STACK_ITER)
1293 				return false;
1294 	}
1295 
1296 	return true;
1297 }
1298 
1299 /* Check if given stack slot is "special":
1300  *   - spilled register state (STACK_SPILL);
1301  *   - dynptr state (STACK_DYNPTR);
1302  *   - iter state (STACK_ITER).
1303  */
1304 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1305 {
1306 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1307 
1308 	switch (type) {
1309 	case STACK_SPILL:
1310 	case STACK_DYNPTR:
1311 	case STACK_ITER:
1312 		return true;
1313 	case STACK_INVALID:
1314 	case STACK_MISC:
1315 	case STACK_ZERO:
1316 		return false;
1317 	default:
1318 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1319 		return true;
1320 	}
1321 }
1322 
1323 /* The reg state of a pointer or a bounded scalar was saved when
1324  * it was spilled to the stack.
1325  */
1326 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1327 {
1328 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1329 }
1330 
1331 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1332 {
1333 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1334 	       stack->spilled_ptr.type == SCALAR_VALUE;
1335 }
1336 
1337 static void scrub_spilled_slot(u8 *stype)
1338 {
1339 	if (*stype != STACK_INVALID)
1340 		*stype = STACK_MISC;
1341 }
1342 
1343 static void print_verifier_state(struct bpf_verifier_env *env,
1344 				 const struct bpf_func_state *state,
1345 				 bool print_all)
1346 {
1347 	const struct bpf_reg_state *reg;
1348 	enum bpf_reg_type t;
1349 	int i;
1350 
1351 	if (state->frameno)
1352 		verbose(env, " frame%d:", state->frameno);
1353 	for (i = 0; i < MAX_BPF_REG; i++) {
1354 		reg = &state->regs[i];
1355 		t = reg->type;
1356 		if (t == NOT_INIT)
1357 			continue;
1358 		if (!print_all && !reg_scratched(env, i))
1359 			continue;
1360 		verbose(env, " R%d", i);
1361 		print_liveness(env, reg->live);
1362 		verbose(env, "=");
1363 		if (t == SCALAR_VALUE && reg->precise)
1364 			verbose(env, "P");
1365 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1366 		    tnum_is_const(reg->var_off)) {
1367 			/* reg->off should be 0 for SCALAR_VALUE */
1368 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1369 			verbose(env, "%lld", reg->var_off.value + reg->off);
1370 		} else {
1371 			const char *sep = "";
1372 
1373 			verbose(env, "%s", reg_type_str(env, t));
1374 			if (base_type(t) == PTR_TO_BTF_ID)
1375 				verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1376 			verbose(env, "(");
1377 /*
1378  * _a stands for append, was shortened to avoid multiline statements below.
1379  * This macro is used to output a comma separated list of attributes.
1380  */
1381 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1382 
1383 			if (reg->id)
1384 				verbose_a("id=%d", reg->id);
1385 			if (reg->ref_obj_id)
1386 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1387 			if (type_is_non_owning_ref(reg->type))
1388 				verbose_a("%s", "non_own_ref");
1389 			if (t != SCALAR_VALUE)
1390 				verbose_a("off=%d", reg->off);
1391 			if (type_is_pkt_pointer(t))
1392 				verbose_a("r=%d", reg->range);
1393 			else if (base_type(t) == CONST_PTR_TO_MAP ||
1394 				 base_type(t) == PTR_TO_MAP_KEY ||
1395 				 base_type(t) == PTR_TO_MAP_VALUE)
1396 				verbose_a("ks=%d,vs=%d",
1397 					  reg->map_ptr->key_size,
1398 					  reg->map_ptr->value_size);
1399 			if (tnum_is_const(reg->var_off)) {
1400 				/* Typically an immediate SCALAR_VALUE, but
1401 				 * could be a pointer whose offset is too big
1402 				 * for reg->off
1403 				 */
1404 				verbose_a("imm=%llx", reg->var_off.value);
1405 			} else {
1406 				if (reg->smin_value != reg->umin_value &&
1407 				    reg->smin_value != S64_MIN)
1408 					verbose_a("smin=%lld", (long long)reg->smin_value);
1409 				if (reg->smax_value != reg->umax_value &&
1410 				    reg->smax_value != S64_MAX)
1411 					verbose_a("smax=%lld", (long long)reg->smax_value);
1412 				if (reg->umin_value != 0)
1413 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1414 				if (reg->umax_value != U64_MAX)
1415 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1416 				if (!tnum_is_unknown(reg->var_off)) {
1417 					char tn_buf[48];
1418 
1419 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1420 					verbose_a("var_off=%s", tn_buf);
1421 				}
1422 				if (reg->s32_min_value != reg->smin_value &&
1423 				    reg->s32_min_value != S32_MIN)
1424 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1425 				if (reg->s32_max_value != reg->smax_value &&
1426 				    reg->s32_max_value != S32_MAX)
1427 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1428 				if (reg->u32_min_value != reg->umin_value &&
1429 				    reg->u32_min_value != U32_MIN)
1430 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1431 				if (reg->u32_max_value != reg->umax_value &&
1432 				    reg->u32_max_value != U32_MAX)
1433 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1434 			}
1435 #undef verbose_a
1436 
1437 			verbose(env, ")");
1438 		}
1439 	}
1440 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1441 		char types_buf[BPF_REG_SIZE + 1];
1442 		bool valid = false;
1443 		int j;
1444 
1445 		for (j = 0; j < BPF_REG_SIZE; j++) {
1446 			if (state->stack[i].slot_type[j] != STACK_INVALID)
1447 				valid = true;
1448 			types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1449 		}
1450 		types_buf[BPF_REG_SIZE] = 0;
1451 		if (!valid)
1452 			continue;
1453 		if (!print_all && !stack_slot_scratched(env, i))
1454 			continue;
1455 		switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1456 		case STACK_SPILL:
1457 			reg = &state->stack[i].spilled_ptr;
1458 			t = reg->type;
1459 
1460 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1461 			print_liveness(env, reg->live);
1462 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1463 			if (t == SCALAR_VALUE && reg->precise)
1464 				verbose(env, "P");
1465 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1466 				verbose(env, "%lld", reg->var_off.value + reg->off);
1467 			break;
1468 		case STACK_DYNPTR:
1469 			i += BPF_DYNPTR_NR_SLOTS - 1;
1470 			reg = &state->stack[i].spilled_ptr;
1471 
1472 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1473 			print_liveness(env, reg->live);
1474 			verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1475 			if (reg->ref_obj_id)
1476 				verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1477 			break;
1478 		case STACK_ITER:
1479 			/* only main slot has ref_obj_id set; skip others */
1480 			reg = &state->stack[i].spilled_ptr;
1481 			if (!reg->ref_obj_id)
1482 				continue;
1483 
1484 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1485 			print_liveness(env, reg->live);
1486 			verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1487 				iter_type_str(reg->iter.btf, reg->iter.btf_id),
1488 				reg->ref_obj_id, iter_state_str(reg->iter.state),
1489 				reg->iter.depth);
1490 			break;
1491 		case STACK_MISC:
1492 		case STACK_ZERO:
1493 		default:
1494 			reg = &state->stack[i].spilled_ptr;
1495 
1496 			for (j = 0; j < BPF_REG_SIZE; j++)
1497 				types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1498 			types_buf[BPF_REG_SIZE] = 0;
1499 
1500 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1501 			print_liveness(env, reg->live);
1502 			verbose(env, "=%s", types_buf);
1503 			break;
1504 		}
1505 	}
1506 	if (state->acquired_refs && state->refs[0].id) {
1507 		verbose(env, " refs=%d", state->refs[0].id);
1508 		for (i = 1; i < state->acquired_refs; i++)
1509 			if (state->refs[i].id)
1510 				verbose(env, ",%d", state->refs[i].id);
1511 	}
1512 	if (state->in_callback_fn)
1513 		verbose(env, " cb");
1514 	if (state->in_async_callback_fn)
1515 		verbose(env, " async_cb");
1516 	verbose(env, "\n");
1517 	mark_verifier_state_clean(env);
1518 }
1519 
1520 static inline u32 vlog_alignment(u32 pos)
1521 {
1522 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1523 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1524 }
1525 
1526 static void print_insn_state(struct bpf_verifier_env *env,
1527 			     const struct bpf_func_state *state)
1528 {
1529 	if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1530 		/* remove new line character */
1531 		bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1532 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1533 	} else {
1534 		verbose(env, "%d:", env->insn_idx);
1535 	}
1536 	print_verifier_state(env, state, false);
1537 }
1538 
1539 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1540  * small to hold src. This is different from krealloc since we don't want to preserve
1541  * the contents of dst.
1542  *
1543  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1544  * not be allocated.
1545  */
1546 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1547 {
1548 	size_t alloc_bytes;
1549 	void *orig = dst;
1550 	size_t bytes;
1551 
1552 	if (ZERO_OR_NULL_PTR(src))
1553 		goto out;
1554 
1555 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1556 		return NULL;
1557 
1558 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1559 	dst = krealloc(orig, alloc_bytes, flags);
1560 	if (!dst) {
1561 		kfree(orig);
1562 		return NULL;
1563 	}
1564 
1565 	memcpy(dst, src, bytes);
1566 out:
1567 	return dst ? dst : ZERO_SIZE_PTR;
1568 }
1569 
1570 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1571  * small to hold new_n items. new items are zeroed out if the array grows.
1572  *
1573  * Contrary to krealloc_array, does not free arr if new_n is zero.
1574  */
1575 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1576 {
1577 	size_t alloc_size;
1578 	void *new_arr;
1579 
1580 	if (!new_n || old_n == new_n)
1581 		goto out;
1582 
1583 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1584 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1585 	if (!new_arr) {
1586 		kfree(arr);
1587 		return NULL;
1588 	}
1589 	arr = new_arr;
1590 
1591 	if (new_n > old_n)
1592 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1593 
1594 out:
1595 	return arr ? arr : ZERO_SIZE_PTR;
1596 }
1597 
1598 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1599 {
1600 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1601 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1602 	if (!dst->refs)
1603 		return -ENOMEM;
1604 
1605 	dst->acquired_refs = src->acquired_refs;
1606 	return 0;
1607 }
1608 
1609 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1610 {
1611 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1612 
1613 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1614 				GFP_KERNEL);
1615 	if (!dst->stack)
1616 		return -ENOMEM;
1617 
1618 	dst->allocated_stack = src->allocated_stack;
1619 	return 0;
1620 }
1621 
1622 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1623 {
1624 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1625 				    sizeof(struct bpf_reference_state));
1626 	if (!state->refs)
1627 		return -ENOMEM;
1628 
1629 	state->acquired_refs = n;
1630 	return 0;
1631 }
1632 
1633 static int grow_stack_state(struct bpf_func_state *state, int size)
1634 {
1635 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1636 
1637 	if (old_n >= n)
1638 		return 0;
1639 
1640 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1641 	if (!state->stack)
1642 		return -ENOMEM;
1643 
1644 	state->allocated_stack = size;
1645 	return 0;
1646 }
1647 
1648 /* Acquire a pointer id from the env and update the state->refs to include
1649  * this new pointer reference.
1650  * On success, returns a valid pointer id to associate with the register
1651  * On failure, returns a negative errno.
1652  */
1653 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1654 {
1655 	struct bpf_func_state *state = cur_func(env);
1656 	int new_ofs = state->acquired_refs;
1657 	int id, err;
1658 
1659 	err = resize_reference_state(state, state->acquired_refs + 1);
1660 	if (err)
1661 		return err;
1662 	id = ++env->id_gen;
1663 	state->refs[new_ofs].id = id;
1664 	state->refs[new_ofs].insn_idx = insn_idx;
1665 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1666 
1667 	return id;
1668 }
1669 
1670 /* release function corresponding to acquire_reference_state(). Idempotent. */
1671 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1672 {
1673 	int i, last_idx;
1674 
1675 	last_idx = state->acquired_refs - 1;
1676 	for (i = 0; i < state->acquired_refs; i++) {
1677 		if (state->refs[i].id == ptr_id) {
1678 			/* Cannot release caller references in callbacks */
1679 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1680 				return -EINVAL;
1681 			if (last_idx && i != last_idx)
1682 				memcpy(&state->refs[i], &state->refs[last_idx],
1683 				       sizeof(*state->refs));
1684 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1685 			state->acquired_refs--;
1686 			return 0;
1687 		}
1688 	}
1689 	return -EINVAL;
1690 }
1691 
1692 static void free_func_state(struct bpf_func_state *state)
1693 {
1694 	if (!state)
1695 		return;
1696 	kfree(state->refs);
1697 	kfree(state->stack);
1698 	kfree(state);
1699 }
1700 
1701 static void clear_jmp_history(struct bpf_verifier_state *state)
1702 {
1703 	kfree(state->jmp_history);
1704 	state->jmp_history = NULL;
1705 	state->jmp_history_cnt = 0;
1706 }
1707 
1708 static void free_verifier_state(struct bpf_verifier_state *state,
1709 				bool free_self)
1710 {
1711 	int i;
1712 
1713 	for (i = 0; i <= state->curframe; i++) {
1714 		free_func_state(state->frame[i]);
1715 		state->frame[i] = NULL;
1716 	}
1717 	clear_jmp_history(state);
1718 	if (free_self)
1719 		kfree(state);
1720 }
1721 
1722 /* copy verifier state from src to dst growing dst stack space
1723  * when necessary to accommodate larger src stack
1724  */
1725 static int copy_func_state(struct bpf_func_state *dst,
1726 			   const struct bpf_func_state *src)
1727 {
1728 	int err;
1729 
1730 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1731 	err = copy_reference_state(dst, src);
1732 	if (err)
1733 		return err;
1734 	return copy_stack_state(dst, src);
1735 }
1736 
1737 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1738 			       const struct bpf_verifier_state *src)
1739 {
1740 	struct bpf_func_state *dst;
1741 	int i, err;
1742 
1743 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1744 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1745 					    GFP_USER);
1746 	if (!dst_state->jmp_history)
1747 		return -ENOMEM;
1748 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1749 
1750 	/* if dst has more stack frames then src frame, free them */
1751 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1752 		free_func_state(dst_state->frame[i]);
1753 		dst_state->frame[i] = NULL;
1754 	}
1755 	dst_state->speculative = src->speculative;
1756 	dst_state->active_rcu_lock = src->active_rcu_lock;
1757 	dst_state->curframe = src->curframe;
1758 	dst_state->active_lock.ptr = src->active_lock.ptr;
1759 	dst_state->active_lock.id = src->active_lock.id;
1760 	dst_state->branches = src->branches;
1761 	dst_state->parent = src->parent;
1762 	dst_state->first_insn_idx = src->first_insn_idx;
1763 	dst_state->last_insn_idx = src->last_insn_idx;
1764 	for (i = 0; i <= src->curframe; i++) {
1765 		dst = dst_state->frame[i];
1766 		if (!dst) {
1767 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1768 			if (!dst)
1769 				return -ENOMEM;
1770 			dst_state->frame[i] = dst;
1771 		}
1772 		err = copy_func_state(dst, src->frame[i]);
1773 		if (err)
1774 			return err;
1775 	}
1776 	return 0;
1777 }
1778 
1779 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1780 {
1781 	while (st) {
1782 		u32 br = --st->branches;
1783 
1784 		/* WARN_ON(br > 1) technically makes sense here,
1785 		 * but see comment in push_stack(), hence:
1786 		 */
1787 		WARN_ONCE((int)br < 0,
1788 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1789 			  br);
1790 		if (br)
1791 			break;
1792 		st = st->parent;
1793 	}
1794 }
1795 
1796 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1797 		     int *insn_idx, bool pop_log)
1798 {
1799 	struct bpf_verifier_state *cur = env->cur_state;
1800 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1801 	int err;
1802 
1803 	if (env->head == NULL)
1804 		return -ENOENT;
1805 
1806 	if (cur) {
1807 		err = copy_verifier_state(cur, &head->st);
1808 		if (err)
1809 			return err;
1810 	}
1811 	if (pop_log)
1812 		bpf_vlog_reset(&env->log, head->log_pos);
1813 	if (insn_idx)
1814 		*insn_idx = head->insn_idx;
1815 	if (prev_insn_idx)
1816 		*prev_insn_idx = head->prev_insn_idx;
1817 	elem = head->next;
1818 	free_verifier_state(&head->st, false);
1819 	kfree(head);
1820 	env->head = elem;
1821 	env->stack_size--;
1822 	return 0;
1823 }
1824 
1825 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1826 					     int insn_idx, int prev_insn_idx,
1827 					     bool speculative)
1828 {
1829 	struct bpf_verifier_state *cur = env->cur_state;
1830 	struct bpf_verifier_stack_elem *elem;
1831 	int err;
1832 
1833 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1834 	if (!elem)
1835 		goto err;
1836 
1837 	elem->insn_idx = insn_idx;
1838 	elem->prev_insn_idx = prev_insn_idx;
1839 	elem->next = env->head;
1840 	elem->log_pos = env->log.end_pos;
1841 	env->head = elem;
1842 	env->stack_size++;
1843 	err = copy_verifier_state(&elem->st, cur);
1844 	if (err)
1845 		goto err;
1846 	elem->st.speculative |= speculative;
1847 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1848 		verbose(env, "The sequence of %d jumps is too complex.\n",
1849 			env->stack_size);
1850 		goto err;
1851 	}
1852 	if (elem->st.parent) {
1853 		++elem->st.parent->branches;
1854 		/* WARN_ON(branches > 2) technically makes sense here,
1855 		 * but
1856 		 * 1. speculative states will bump 'branches' for non-branch
1857 		 * instructions
1858 		 * 2. is_state_visited() heuristics may decide not to create
1859 		 * a new state for a sequence of branches and all such current
1860 		 * and cloned states will be pointing to a single parent state
1861 		 * which might have large 'branches' count.
1862 		 */
1863 	}
1864 	return &elem->st;
1865 err:
1866 	free_verifier_state(env->cur_state, true);
1867 	env->cur_state = NULL;
1868 	/* pop all elements and return */
1869 	while (!pop_stack(env, NULL, NULL, false));
1870 	return NULL;
1871 }
1872 
1873 #define CALLER_SAVED_REGS 6
1874 static const int caller_saved[CALLER_SAVED_REGS] = {
1875 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1876 };
1877 
1878 /* This helper doesn't clear reg->id */
1879 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1880 {
1881 	reg->var_off = tnum_const(imm);
1882 	reg->smin_value = (s64)imm;
1883 	reg->smax_value = (s64)imm;
1884 	reg->umin_value = imm;
1885 	reg->umax_value = imm;
1886 
1887 	reg->s32_min_value = (s32)imm;
1888 	reg->s32_max_value = (s32)imm;
1889 	reg->u32_min_value = (u32)imm;
1890 	reg->u32_max_value = (u32)imm;
1891 }
1892 
1893 /* Mark the unknown part of a register (variable offset or scalar value) as
1894  * known to have the value @imm.
1895  */
1896 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1897 {
1898 	/* Clear off and union(map_ptr, range) */
1899 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1900 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1901 	reg->id = 0;
1902 	reg->ref_obj_id = 0;
1903 	___mark_reg_known(reg, imm);
1904 }
1905 
1906 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1907 {
1908 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1909 	reg->s32_min_value = (s32)imm;
1910 	reg->s32_max_value = (s32)imm;
1911 	reg->u32_min_value = (u32)imm;
1912 	reg->u32_max_value = (u32)imm;
1913 }
1914 
1915 /* Mark the 'variable offset' part of a register as zero.  This should be
1916  * used only on registers holding a pointer type.
1917  */
1918 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1919 {
1920 	__mark_reg_known(reg, 0);
1921 }
1922 
1923 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1924 {
1925 	__mark_reg_known(reg, 0);
1926 	reg->type = SCALAR_VALUE;
1927 }
1928 
1929 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1930 				struct bpf_reg_state *regs, u32 regno)
1931 {
1932 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1933 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1934 		/* Something bad happened, let's kill all regs */
1935 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1936 			__mark_reg_not_init(env, regs + regno);
1937 		return;
1938 	}
1939 	__mark_reg_known_zero(regs + regno);
1940 }
1941 
1942 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1943 			      bool first_slot, int dynptr_id)
1944 {
1945 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1946 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1947 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1948 	 */
1949 	__mark_reg_known_zero(reg);
1950 	reg->type = CONST_PTR_TO_DYNPTR;
1951 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1952 	reg->id = dynptr_id;
1953 	reg->dynptr.type = type;
1954 	reg->dynptr.first_slot = first_slot;
1955 }
1956 
1957 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1958 {
1959 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1960 		const struct bpf_map *map = reg->map_ptr;
1961 
1962 		if (map->inner_map_meta) {
1963 			reg->type = CONST_PTR_TO_MAP;
1964 			reg->map_ptr = map->inner_map_meta;
1965 			/* transfer reg's id which is unique for every map_lookup_elem
1966 			 * as UID of the inner map.
1967 			 */
1968 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1969 				reg->map_uid = reg->id;
1970 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1971 			reg->type = PTR_TO_XDP_SOCK;
1972 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1973 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1974 			reg->type = PTR_TO_SOCKET;
1975 		} else {
1976 			reg->type = PTR_TO_MAP_VALUE;
1977 		}
1978 		return;
1979 	}
1980 
1981 	reg->type &= ~PTR_MAYBE_NULL;
1982 }
1983 
1984 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1985 				struct btf_field_graph_root *ds_head)
1986 {
1987 	__mark_reg_known_zero(&regs[regno]);
1988 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1989 	regs[regno].btf = ds_head->btf;
1990 	regs[regno].btf_id = ds_head->value_btf_id;
1991 	regs[regno].off = ds_head->node_offset;
1992 }
1993 
1994 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1995 {
1996 	return type_is_pkt_pointer(reg->type);
1997 }
1998 
1999 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2000 {
2001 	return reg_is_pkt_pointer(reg) ||
2002 	       reg->type == PTR_TO_PACKET_END;
2003 }
2004 
2005 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2006 {
2007 	return base_type(reg->type) == PTR_TO_MEM &&
2008 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2009 }
2010 
2011 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2012 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2013 				    enum bpf_reg_type which)
2014 {
2015 	/* The register can already have a range from prior markings.
2016 	 * This is fine as long as it hasn't been advanced from its
2017 	 * origin.
2018 	 */
2019 	return reg->type == which &&
2020 	       reg->id == 0 &&
2021 	       reg->off == 0 &&
2022 	       tnum_equals_const(reg->var_off, 0);
2023 }
2024 
2025 /* Reset the min/max bounds of a register */
2026 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2027 {
2028 	reg->smin_value = S64_MIN;
2029 	reg->smax_value = S64_MAX;
2030 	reg->umin_value = 0;
2031 	reg->umax_value = U64_MAX;
2032 
2033 	reg->s32_min_value = S32_MIN;
2034 	reg->s32_max_value = S32_MAX;
2035 	reg->u32_min_value = 0;
2036 	reg->u32_max_value = U32_MAX;
2037 }
2038 
2039 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2040 {
2041 	reg->smin_value = S64_MIN;
2042 	reg->smax_value = S64_MAX;
2043 	reg->umin_value = 0;
2044 	reg->umax_value = U64_MAX;
2045 }
2046 
2047 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2048 {
2049 	reg->s32_min_value = S32_MIN;
2050 	reg->s32_max_value = S32_MAX;
2051 	reg->u32_min_value = 0;
2052 	reg->u32_max_value = U32_MAX;
2053 }
2054 
2055 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2056 {
2057 	struct tnum var32_off = tnum_subreg(reg->var_off);
2058 
2059 	/* min signed is max(sign bit) | min(other bits) */
2060 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2061 			var32_off.value | (var32_off.mask & S32_MIN));
2062 	/* max signed is min(sign bit) | max(other bits) */
2063 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2064 			var32_off.value | (var32_off.mask & S32_MAX));
2065 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2066 	reg->u32_max_value = min(reg->u32_max_value,
2067 				 (u32)(var32_off.value | var32_off.mask));
2068 }
2069 
2070 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2071 {
2072 	/* min signed is max(sign bit) | min(other bits) */
2073 	reg->smin_value = max_t(s64, reg->smin_value,
2074 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2075 	/* max signed is min(sign bit) | max(other bits) */
2076 	reg->smax_value = min_t(s64, reg->smax_value,
2077 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2078 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2079 	reg->umax_value = min(reg->umax_value,
2080 			      reg->var_off.value | reg->var_off.mask);
2081 }
2082 
2083 static void __update_reg_bounds(struct bpf_reg_state *reg)
2084 {
2085 	__update_reg32_bounds(reg);
2086 	__update_reg64_bounds(reg);
2087 }
2088 
2089 /* Uses signed min/max values to inform unsigned, and vice-versa */
2090 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2091 {
2092 	/* Learn sign from signed bounds.
2093 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2094 	 * are the same, so combine.  This works even in the negative case, e.g.
2095 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2096 	 */
2097 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2098 		reg->s32_min_value = reg->u32_min_value =
2099 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2100 		reg->s32_max_value = reg->u32_max_value =
2101 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2102 		return;
2103 	}
2104 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2105 	 * boundary, so we must be careful.
2106 	 */
2107 	if ((s32)reg->u32_max_value >= 0) {
2108 		/* Positive.  We can't learn anything from the smin, but smax
2109 		 * is positive, hence safe.
2110 		 */
2111 		reg->s32_min_value = reg->u32_min_value;
2112 		reg->s32_max_value = reg->u32_max_value =
2113 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2114 	} else if ((s32)reg->u32_min_value < 0) {
2115 		/* Negative.  We can't learn anything from the smax, but smin
2116 		 * is negative, hence safe.
2117 		 */
2118 		reg->s32_min_value = reg->u32_min_value =
2119 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2120 		reg->s32_max_value = reg->u32_max_value;
2121 	}
2122 }
2123 
2124 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2125 {
2126 	/* Learn sign from signed bounds.
2127 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2128 	 * are the same, so combine.  This works even in the negative case, e.g.
2129 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2130 	 */
2131 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
2132 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2133 							  reg->umin_value);
2134 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2135 							  reg->umax_value);
2136 		return;
2137 	}
2138 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2139 	 * boundary, so we must be careful.
2140 	 */
2141 	if ((s64)reg->umax_value >= 0) {
2142 		/* Positive.  We can't learn anything from the smin, but smax
2143 		 * is positive, hence safe.
2144 		 */
2145 		reg->smin_value = reg->umin_value;
2146 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2147 							  reg->umax_value);
2148 	} else if ((s64)reg->umin_value < 0) {
2149 		/* Negative.  We can't learn anything from the smax, but smin
2150 		 * is negative, hence safe.
2151 		 */
2152 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2153 							  reg->umin_value);
2154 		reg->smax_value = reg->umax_value;
2155 	}
2156 }
2157 
2158 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2159 {
2160 	__reg32_deduce_bounds(reg);
2161 	__reg64_deduce_bounds(reg);
2162 }
2163 
2164 /* Attempts to improve var_off based on unsigned min/max information */
2165 static void __reg_bound_offset(struct bpf_reg_state *reg)
2166 {
2167 	struct tnum var64_off = tnum_intersect(reg->var_off,
2168 					       tnum_range(reg->umin_value,
2169 							  reg->umax_value));
2170 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2171 					       tnum_range(reg->u32_min_value,
2172 							  reg->u32_max_value));
2173 
2174 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2175 }
2176 
2177 static void reg_bounds_sync(struct bpf_reg_state *reg)
2178 {
2179 	/* We might have learned new bounds from the var_off. */
2180 	__update_reg_bounds(reg);
2181 	/* We might have learned something about the sign bit. */
2182 	__reg_deduce_bounds(reg);
2183 	/* We might have learned some bits from the bounds. */
2184 	__reg_bound_offset(reg);
2185 	/* Intersecting with the old var_off might have improved our bounds
2186 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2187 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2188 	 */
2189 	__update_reg_bounds(reg);
2190 }
2191 
2192 static bool __reg32_bound_s64(s32 a)
2193 {
2194 	return a >= 0 && a <= S32_MAX;
2195 }
2196 
2197 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2198 {
2199 	reg->umin_value = reg->u32_min_value;
2200 	reg->umax_value = reg->u32_max_value;
2201 
2202 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2203 	 * be positive otherwise set to worse case bounds and refine later
2204 	 * from tnum.
2205 	 */
2206 	if (__reg32_bound_s64(reg->s32_min_value) &&
2207 	    __reg32_bound_s64(reg->s32_max_value)) {
2208 		reg->smin_value = reg->s32_min_value;
2209 		reg->smax_value = reg->s32_max_value;
2210 	} else {
2211 		reg->smin_value = 0;
2212 		reg->smax_value = U32_MAX;
2213 	}
2214 }
2215 
2216 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2217 {
2218 	/* special case when 64-bit register has upper 32-bit register
2219 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
2220 	 * allowing us to use 32-bit bounds directly,
2221 	 */
2222 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2223 		__reg_assign_32_into_64(reg);
2224 	} else {
2225 		/* Otherwise the best we can do is push lower 32bit known and
2226 		 * unknown bits into register (var_off set from jmp logic)
2227 		 * then learn as much as possible from the 64-bit tnum
2228 		 * known and unknown bits. The previous smin/smax bounds are
2229 		 * invalid here because of jmp32 compare so mark them unknown
2230 		 * so they do not impact tnum bounds calculation.
2231 		 */
2232 		__mark_reg64_unbounded(reg);
2233 	}
2234 	reg_bounds_sync(reg);
2235 }
2236 
2237 static bool __reg64_bound_s32(s64 a)
2238 {
2239 	return a >= S32_MIN && a <= S32_MAX;
2240 }
2241 
2242 static bool __reg64_bound_u32(u64 a)
2243 {
2244 	return a >= U32_MIN && a <= U32_MAX;
2245 }
2246 
2247 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2248 {
2249 	__mark_reg32_unbounded(reg);
2250 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2251 		reg->s32_min_value = (s32)reg->smin_value;
2252 		reg->s32_max_value = (s32)reg->smax_value;
2253 	}
2254 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2255 		reg->u32_min_value = (u32)reg->umin_value;
2256 		reg->u32_max_value = (u32)reg->umax_value;
2257 	}
2258 	reg_bounds_sync(reg);
2259 }
2260 
2261 /* Mark a register as having a completely unknown (scalar) value. */
2262 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2263 			       struct bpf_reg_state *reg)
2264 {
2265 	/*
2266 	 * Clear type, off, and union(map_ptr, range) and
2267 	 * padding between 'type' and union
2268 	 */
2269 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2270 	reg->type = SCALAR_VALUE;
2271 	reg->id = 0;
2272 	reg->ref_obj_id = 0;
2273 	reg->var_off = tnum_unknown;
2274 	reg->frameno = 0;
2275 	reg->precise = !env->bpf_capable;
2276 	__mark_reg_unbounded(reg);
2277 }
2278 
2279 static void mark_reg_unknown(struct bpf_verifier_env *env,
2280 			     struct bpf_reg_state *regs, u32 regno)
2281 {
2282 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2283 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2284 		/* Something bad happened, let's kill all regs except FP */
2285 		for (regno = 0; regno < BPF_REG_FP; regno++)
2286 			__mark_reg_not_init(env, regs + regno);
2287 		return;
2288 	}
2289 	__mark_reg_unknown(env, regs + regno);
2290 }
2291 
2292 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2293 				struct bpf_reg_state *reg)
2294 {
2295 	__mark_reg_unknown(env, reg);
2296 	reg->type = NOT_INIT;
2297 }
2298 
2299 static void mark_reg_not_init(struct bpf_verifier_env *env,
2300 			      struct bpf_reg_state *regs, u32 regno)
2301 {
2302 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2303 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2304 		/* Something bad happened, let's kill all regs except FP */
2305 		for (regno = 0; regno < BPF_REG_FP; regno++)
2306 			__mark_reg_not_init(env, regs + regno);
2307 		return;
2308 	}
2309 	__mark_reg_not_init(env, regs + regno);
2310 }
2311 
2312 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2313 			    struct bpf_reg_state *regs, u32 regno,
2314 			    enum bpf_reg_type reg_type,
2315 			    struct btf *btf, u32 btf_id,
2316 			    enum bpf_type_flag flag)
2317 {
2318 	if (reg_type == SCALAR_VALUE) {
2319 		mark_reg_unknown(env, regs, regno);
2320 		return;
2321 	}
2322 	mark_reg_known_zero(env, regs, regno);
2323 	regs[regno].type = PTR_TO_BTF_ID | flag;
2324 	regs[regno].btf = btf;
2325 	regs[regno].btf_id = btf_id;
2326 }
2327 
2328 #define DEF_NOT_SUBREG	(0)
2329 static void init_reg_state(struct bpf_verifier_env *env,
2330 			   struct bpf_func_state *state)
2331 {
2332 	struct bpf_reg_state *regs = state->regs;
2333 	int i;
2334 
2335 	for (i = 0; i < MAX_BPF_REG; i++) {
2336 		mark_reg_not_init(env, regs, i);
2337 		regs[i].live = REG_LIVE_NONE;
2338 		regs[i].parent = NULL;
2339 		regs[i].subreg_def = DEF_NOT_SUBREG;
2340 	}
2341 
2342 	/* frame pointer */
2343 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2344 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2345 	regs[BPF_REG_FP].frameno = state->frameno;
2346 }
2347 
2348 #define BPF_MAIN_FUNC (-1)
2349 static void init_func_state(struct bpf_verifier_env *env,
2350 			    struct bpf_func_state *state,
2351 			    int callsite, int frameno, int subprogno)
2352 {
2353 	state->callsite = callsite;
2354 	state->frameno = frameno;
2355 	state->subprogno = subprogno;
2356 	state->callback_ret_range = tnum_range(0, 0);
2357 	init_reg_state(env, state);
2358 	mark_verifier_state_scratched(env);
2359 }
2360 
2361 /* Similar to push_stack(), but for async callbacks */
2362 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2363 						int insn_idx, int prev_insn_idx,
2364 						int subprog)
2365 {
2366 	struct bpf_verifier_stack_elem *elem;
2367 	struct bpf_func_state *frame;
2368 
2369 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2370 	if (!elem)
2371 		goto err;
2372 
2373 	elem->insn_idx = insn_idx;
2374 	elem->prev_insn_idx = prev_insn_idx;
2375 	elem->next = env->head;
2376 	elem->log_pos = env->log.end_pos;
2377 	env->head = elem;
2378 	env->stack_size++;
2379 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2380 		verbose(env,
2381 			"The sequence of %d jumps is too complex for async cb.\n",
2382 			env->stack_size);
2383 		goto err;
2384 	}
2385 	/* Unlike push_stack() do not copy_verifier_state().
2386 	 * The caller state doesn't matter.
2387 	 * This is async callback. It starts in a fresh stack.
2388 	 * Initialize it similar to do_check_common().
2389 	 */
2390 	elem->st.branches = 1;
2391 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2392 	if (!frame)
2393 		goto err;
2394 	init_func_state(env, frame,
2395 			BPF_MAIN_FUNC /* callsite */,
2396 			0 /* frameno within this callchain */,
2397 			subprog /* subprog number within this prog */);
2398 	elem->st.frame[0] = frame;
2399 	return &elem->st;
2400 err:
2401 	free_verifier_state(env->cur_state, true);
2402 	env->cur_state = NULL;
2403 	/* pop all elements and return */
2404 	while (!pop_stack(env, NULL, NULL, false));
2405 	return NULL;
2406 }
2407 
2408 
2409 enum reg_arg_type {
2410 	SRC_OP,		/* register is used as source operand */
2411 	DST_OP,		/* register is used as destination operand */
2412 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2413 };
2414 
2415 static int cmp_subprogs(const void *a, const void *b)
2416 {
2417 	return ((struct bpf_subprog_info *)a)->start -
2418 	       ((struct bpf_subprog_info *)b)->start;
2419 }
2420 
2421 static int find_subprog(struct bpf_verifier_env *env, int off)
2422 {
2423 	struct bpf_subprog_info *p;
2424 
2425 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2426 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2427 	if (!p)
2428 		return -ENOENT;
2429 	return p - env->subprog_info;
2430 
2431 }
2432 
2433 static int add_subprog(struct bpf_verifier_env *env, int off)
2434 {
2435 	int insn_cnt = env->prog->len;
2436 	int ret;
2437 
2438 	if (off >= insn_cnt || off < 0) {
2439 		verbose(env, "call to invalid destination\n");
2440 		return -EINVAL;
2441 	}
2442 	ret = find_subprog(env, off);
2443 	if (ret >= 0)
2444 		return ret;
2445 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2446 		verbose(env, "too many subprograms\n");
2447 		return -E2BIG;
2448 	}
2449 	/* determine subprog starts. The end is one before the next starts */
2450 	env->subprog_info[env->subprog_cnt++].start = off;
2451 	sort(env->subprog_info, env->subprog_cnt,
2452 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2453 	return env->subprog_cnt - 1;
2454 }
2455 
2456 #define MAX_KFUNC_DESCS 256
2457 #define MAX_KFUNC_BTFS	256
2458 
2459 struct bpf_kfunc_desc {
2460 	struct btf_func_model func_model;
2461 	u32 func_id;
2462 	s32 imm;
2463 	u16 offset;
2464 	unsigned long addr;
2465 };
2466 
2467 struct bpf_kfunc_btf {
2468 	struct btf *btf;
2469 	struct module *module;
2470 	u16 offset;
2471 };
2472 
2473 struct bpf_kfunc_desc_tab {
2474 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2475 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2476 	 * available, therefore at the end of verification do_misc_fixups()
2477 	 * sorts this by imm and offset.
2478 	 */
2479 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2480 	u32 nr_descs;
2481 };
2482 
2483 struct bpf_kfunc_btf_tab {
2484 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2485 	u32 nr_descs;
2486 };
2487 
2488 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2489 {
2490 	const struct bpf_kfunc_desc *d0 = a;
2491 	const struct bpf_kfunc_desc *d1 = b;
2492 
2493 	/* func_id is not greater than BTF_MAX_TYPE */
2494 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2495 }
2496 
2497 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2498 {
2499 	const struct bpf_kfunc_btf *d0 = a;
2500 	const struct bpf_kfunc_btf *d1 = b;
2501 
2502 	return d0->offset - d1->offset;
2503 }
2504 
2505 static const struct bpf_kfunc_desc *
2506 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2507 {
2508 	struct bpf_kfunc_desc desc = {
2509 		.func_id = func_id,
2510 		.offset = offset,
2511 	};
2512 	struct bpf_kfunc_desc_tab *tab;
2513 
2514 	tab = prog->aux->kfunc_tab;
2515 	return bsearch(&desc, tab->descs, tab->nr_descs,
2516 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2517 }
2518 
2519 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2520 		       u16 btf_fd_idx, u8 **func_addr)
2521 {
2522 	const struct bpf_kfunc_desc *desc;
2523 
2524 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2525 	if (!desc)
2526 		return -EFAULT;
2527 
2528 	*func_addr = (u8 *)desc->addr;
2529 	return 0;
2530 }
2531 
2532 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2533 					 s16 offset)
2534 {
2535 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2536 	struct bpf_kfunc_btf_tab *tab;
2537 	struct bpf_kfunc_btf *b;
2538 	struct module *mod;
2539 	struct btf *btf;
2540 	int btf_fd;
2541 
2542 	tab = env->prog->aux->kfunc_btf_tab;
2543 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2544 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2545 	if (!b) {
2546 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2547 			verbose(env, "too many different module BTFs\n");
2548 			return ERR_PTR(-E2BIG);
2549 		}
2550 
2551 		if (bpfptr_is_null(env->fd_array)) {
2552 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2553 			return ERR_PTR(-EPROTO);
2554 		}
2555 
2556 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2557 					    offset * sizeof(btf_fd),
2558 					    sizeof(btf_fd)))
2559 			return ERR_PTR(-EFAULT);
2560 
2561 		btf = btf_get_by_fd(btf_fd);
2562 		if (IS_ERR(btf)) {
2563 			verbose(env, "invalid module BTF fd specified\n");
2564 			return btf;
2565 		}
2566 
2567 		if (!btf_is_module(btf)) {
2568 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2569 			btf_put(btf);
2570 			return ERR_PTR(-EINVAL);
2571 		}
2572 
2573 		mod = btf_try_get_module(btf);
2574 		if (!mod) {
2575 			btf_put(btf);
2576 			return ERR_PTR(-ENXIO);
2577 		}
2578 
2579 		b = &tab->descs[tab->nr_descs++];
2580 		b->btf = btf;
2581 		b->module = mod;
2582 		b->offset = offset;
2583 
2584 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2585 		     kfunc_btf_cmp_by_off, NULL);
2586 	}
2587 	return b->btf;
2588 }
2589 
2590 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2591 {
2592 	if (!tab)
2593 		return;
2594 
2595 	while (tab->nr_descs--) {
2596 		module_put(tab->descs[tab->nr_descs].module);
2597 		btf_put(tab->descs[tab->nr_descs].btf);
2598 	}
2599 	kfree(tab);
2600 }
2601 
2602 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2603 {
2604 	if (offset) {
2605 		if (offset < 0) {
2606 			/* In the future, this can be allowed to increase limit
2607 			 * of fd index into fd_array, interpreted as u16.
2608 			 */
2609 			verbose(env, "negative offset disallowed for kernel module function call\n");
2610 			return ERR_PTR(-EINVAL);
2611 		}
2612 
2613 		return __find_kfunc_desc_btf(env, offset);
2614 	}
2615 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2616 }
2617 
2618 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2619 {
2620 	const struct btf_type *func, *func_proto;
2621 	struct bpf_kfunc_btf_tab *btf_tab;
2622 	struct bpf_kfunc_desc_tab *tab;
2623 	struct bpf_prog_aux *prog_aux;
2624 	struct bpf_kfunc_desc *desc;
2625 	const char *func_name;
2626 	struct btf *desc_btf;
2627 	unsigned long call_imm;
2628 	unsigned long addr;
2629 	int err;
2630 
2631 	prog_aux = env->prog->aux;
2632 	tab = prog_aux->kfunc_tab;
2633 	btf_tab = prog_aux->kfunc_btf_tab;
2634 	if (!tab) {
2635 		if (!btf_vmlinux) {
2636 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2637 			return -ENOTSUPP;
2638 		}
2639 
2640 		if (!env->prog->jit_requested) {
2641 			verbose(env, "JIT is required for calling kernel function\n");
2642 			return -ENOTSUPP;
2643 		}
2644 
2645 		if (!bpf_jit_supports_kfunc_call()) {
2646 			verbose(env, "JIT does not support calling kernel function\n");
2647 			return -ENOTSUPP;
2648 		}
2649 
2650 		if (!env->prog->gpl_compatible) {
2651 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2652 			return -EINVAL;
2653 		}
2654 
2655 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2656 		if (!tab)
2657 			return -ENOMEM;
2658 		prog_aux->kfunc_tab = tab;
2659 	}
2660 
2661 	/* func_id == 0 is always invalid, but instead of returning an error, be
2662 	 * conservative and wait until the code elimination pass before returning
2663 	 * error, so that invalid calls that get pruned out can be in BPF programs
2664 	 * loaded from userspace.  It is also required that offset be untouched
2665 	 * for such calls.
2666 	 */
2667 	if (!func_id && !offset)
2668 		return 0;
2669 
2670 	if (!btf_tab && offset) {
2671 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2672 		if (!btf_tab)
2673 			return -ENOMEM;
2674 		prog_aux->kfunc_btf_tab = btf_tab;
2675 	}
2676 
2677 	desc_btf = find_kfunc_desc_btf(env, offset);
2678 	if (IS_ERR(desc_btf)) {
2679 		verbose(env, "failed to find BTF for kernel function\n");
2680 		return PTR_ERR(desc_btf);
2681 	}
2682 
2683 	if (find_kfunc_desc(env->prog, func_id, offset))
2684 		return 0;
2685 
2686 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2687 		verbose(env, "too many different kernel function calls\n");
2688 		return -E2BIG;
2689 	}
2690 
2691 	func = btf_type_by_id(desc_btf, func_id);
2692 	if (!func || !btf_type_is_func(func)) {
2693 		verbose(env, "kernel btf_id %u is not a function\n",
2694 			func_id);
2695 		return -EINVAL;
2696 	}
2697 	func_proto = btf_type_by_id(desc_btf, func->type);
2698 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2699 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2700 			func_id);
2701 		return -EINVAL;
2702 	}
2703 
2704 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2705 	addr = kallsyms_lookup_name(func_name);
2706 	if (!addr) {
2707 		verbose(env, "cannot find address for kernel function %s\n",
2708 			func_name);
2709 		return -EINVAL;
2710 	}
2711 	specialize_kfunc(env, func_id, offset, &addr);
2712 
2713 	if (bpf_jit_supports_far_kfunc_call()) {
2714 		call_imm = func_id;
2715 	} else {
2716 		call_imm = BPF_CALL_IMM(addr);
2717 		/* Check whether the relative offset overflows desc->imm */
2718 		if ((unsigned long)(s32)call_imm != call_imm) {
2719 			verbose(env, "address of kernel function %s is out of range\n",
2720 				func_name);
2721 			return -EINVAL;
2722 		}
2723 	}
2724 
2725 	if (bpf_dev_bound_kfunc_id(func_id)) {
2726 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2727 		if (err)
2728 			return err;
2729 	}
2730 
2731 	desc = &tab->descs[tab->nr_descs++];
2732 	desc->func_id = func_id;
2733 	desc->imm = call_imm;
2734 	desc->offset = offset;
2735 	desc->addr = addr;
2736 	err = btf_distill_func_proto(&env->log, desc_btf,
2737 				     func_proto, func_name,
2738 				     &desc->func_model);
2739 	if (!err)
2740 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2741 		     kfunc_desc_cmp_by_id_off, NULL);
2742 	return err;
2743 }
2744 
2745 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2746 {
2747 	const struct bpf_kfunc_desc *d0 = a;
2748 	const struct bpf_kfunc_desc *d1 = b;
2749 
2750 	if (d0->imm != d1->imm)
2751 		return d0->imm < d1->imm ? -1 : 1;
2752 	if (d0->offset != d1->offset)
2753 		return d0->offset < d1->offset ? -1 : 1;
2754 	return 0;
2755 }
2756 
2757 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2758 {
2759 	struct bpf_kfunc_desc_tab *tab;
2760 
2761 	tab = prog->aux->kfunc_tab;
2762 	if (!tab)
2763 		return;
2764 
2765 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2766 	     kfunc_desc_cmp_by_imm_off, NULL);
2767 }
2768 
2769 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2770 {
2771 	return !!prog->aux->kfunc_tab;
2772 }
2773 
2774 const struct btf_func_model *
2775 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2776 			 const struct bpf_insn *insn)
2777 {
2778 	const struct bpf_kfunc_desc desc = {
2779 		.imm = insn->imm,
2780 		.offset = insn->off,
2781 	};
2782 	const struct bpf_kfunc_desc *res;
2783 	struct bpf_kfunc_desc_tab *tab;
2784 
2785 	tab = prog->aux->kfunc_tab;
2786 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2787 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2788 
2789 	return res ? &res->func_model : NULL;
2790 }
2791 
2792 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2793 {
2794 	struct bpf_subprog_info *subprog = env->subprog_info;
2795 	struct bpf_insn *insn = env->prog->insnsi;
2796 	int i, ret, insn_cnt = env->prog->len;
2797 
2798 	/* Add entry function. */
2799 	ret = add_subprog(env, 0);
2800 	if (ret)
2801 		return ret;
2802 
2803 	for (i = 0; i < insn_cnt; i++, insn++) {
2804 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2805 		    !bpf_pseudo_kfunc_call(insn))
2806 			continue;
2807 
2808 		if (!env->bpf_capable) {
2809 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2810 			return -EPERM;
2811 		}
2812 
2813 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2814 			ret = add_subprog(env, i + insn->imm + 1);
2815 		else
2816 			ret = add_kfunc_call(env, insn->imm, insn->off);
2817 
2818 		if (ret < 0)
2819 			return ret;
2820 	}
2821 
2822 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2823 	 * logic. 'subprog_cnt' should not be increased.
2824 	 */
2825 	subprog[env->subprog_cnt].start = insn_cnt;
2826 
2827 	if (env->log.level & BPF_LOG_LEVEL2)
2828 		for (i = 0; i < env->subprog_cnt; i++)
2829 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2830 
2831 	return 0;
2832 }
2833 
2834 static int check_subprogs(struct bpf_verifier_env *env)
2835 {
2836 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2837 	struct bpf_subprog_info *subprog = env->subprog_info;
2838 	struct bpf_insn *insn = env->prog->insnsi;
2839 	int insn_cnt = env->prog->len;
2840 
2841 	/* now check that all jumps are within the same subprog */
2842 	subprog_start = subprog[cur_subprog].start;
2843 	subprog_end = subprog[cur_subprog + 1].start;
2844 	for (i = 0; i < insn_cnt; i++) {
2845 		u8 code = insn[i].code;
2846 
2847 		if (code == (BPF_JMP | BPF_CALL) &&
2848 		    insn[i].src_reg == 0 &&
2849 		    insn[i].imm == BPF_FUNC_tail_call)
2850 			subprog[cur_subprog].has_tail_call = true;
2851 		if (BPF_CLASS(code) == BPF_LD &&
2852 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2853 			subprog[cur_subprog].has_ld_abs = true;
2854 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2855 			goto next;
2856 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2857 			goto next;
2858 		off = i + insn[i].off + 1;
2859 		if (off < subprog_start || off >= subprog_end) {
2860 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2861 			return -EINVAL;
2862 		}
2863 next:
2864 		if (i == subprog_end - 1) {
2865 			/* to avoid fall-through from one subprog into another
2866 			 * the last insn of the subprog should be either exit
2867 			 * or unconditional jump back
2868 			 */
2869 			if (code != (BPF_JMP | BPF_EXIT) &&
2870 			    code != (BPF_JMP | BPF_JA)) {
2871 				verbose(env, "last insn is not an exit or jmp\n");
2872 				return -EINVAL;
2873 			}
2874 			subprog_start = subprog_end;
2875 			cur_subprog++;
2876 			if (cur_subprog < env->subprog_cnt)
2877 				subprog_end = subprog[cur_subprog + 1].start;
2878 		}
2879 	}
2880 	return 0;
2881 }
2882 
2883 /* Parentage chain of this register (or stack slot) should take care of all
2884  * issues like callee-saved registers, stack slot allocation time, etc.
2885  */
2886 static int mark_reg_read(struct bpf_verifier_env *env,
2887 			 const struct bpf_reg_state *state,
2888 			 struct bpf_reg_state *parent, u8 flag)
2889 {
2890 	bool writes = parent == state->parent; /* Observe write marks */
2891 	int cnt = 0;
2892 
2893 	while (parent) {
2894 		/* if read wasn't screened by an earlier write ... */
2895 		if (writes && state->live & REG_LIVE_WRITTEN)
2896 			break;
2897 		if (parent->live & REG_LIVE_DONE) {
2898 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2899 				reg_type_str(env, parent->type),
2900 				parent->var_off.value, parent->off);
2901 			return -EFAULT;
2902 		}
2903 		/* The first condition is more likely to be true than the
2904 		 * second, checked it first.
2905 		 */
2906 		if ((parent->live & REG_LIVE_READ) == flag ||
2907 		    parent->live & REG_LIVE_READ64)
2908 			/* The parentage chain never changes and
2909 			 * this parent was already marked as LIVE_READ.
2910 			 * There is no need to keep walking the chain again and
2911 			 * keep re-marking all parents as LIVE_READ.
2912 			 * This case happens when the same register is read
2913 			 * multiple times without writes into it in-between.
2914 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2915 			 * then no need to set the weak REG_LIVE_READ32.
2916 			 */
2917 			break;
2918 		/* ... then we depend on parent's value */
2919 		parent->live |= flag;
2920 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2921 		if (flag == REG_LIVE_READ64)
2922 			parent->live &= ~REG_LIVE_READ32;
2923 		state = parent;
2924 		parent = state->parent;
2925 		writes = true;
2926 		cnt++;
2927 	}
2928 
2929 	if (env->longest_mark_read_walk < cnt)
2930 		env->longest_mark_read_walk = cnt;
2931 	return 0;
2932 }
2933 
2934 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2935 {
2936 	struct bpf_func_state *state = func(env, reg);
2937 	int spi, ret;
2938 
2939 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
2940 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2941 	 * check_kfunc_call.
2942 	 */
2943 	if (reg->type == CONST_PTR_TO_DYNPTR)
2944 		return 0;
2945 	spi = dynptr_get_spi(env, reg);
2946 	if (spi < 0)
2947 		return spi;
2948 	/* Caller ensures dynptr is valid and initialized, which means spi is in
2949 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2950 	 * read.
2951 	 */
2952 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2953 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2954 	if (ret)
2955 		return ret;
2956 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2957 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2958 }
2959 
2960 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2961 			  int spi, int nr_slots)
2962 {
2963 	struct bpf_func_state *state = func(env, reg);
2964 	int err, i;
2965 
2966 	for (i = 0; i < nr_slots; i++) {
2967 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2968 
2969 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2970 		if (err)
2971 			return err;
2972 
2973 		mark_stack_slot_scratched(env, spi - i);
2974 	}
2975 
2976 	return 0;
2977 }
2978 
2979 /* This function is supposed to be used by the following 32-bit optimization
2980  * code only. It returns TRUE if the source or destination register operates
2981  * on 64-bit, otherwise return FALSE.
2982  */
2983 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2984 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2985 {
2986 	u8 code, class, op;
2987 
2988 	code = insn->code;
2989 	class = BPF_CLASS(code);
2990 	op = BPF_OP(code);
2991 	if (class == BPF_JMP) {
2992 		/* BPF_EXIT for "main" will reach here. Return TRUE
2993 		 * conservatively.
2994 		 */
2995 		if (op == BPF_EXIT)
2996 			return true;
2997 		if (op == BPF_CALL) {
2998 			/* BPF to BPF call will reach here because of marking
2999 			 * caller saved clobber with DST_OP_NO_MARK for which we
3000 			 * don't care the register def because they are anyway
3001 			 * marked as NOT_INIT already.
3002 			 */
3003 			if (insn->src_reg == BPF_PSEUDO_CALL)
3004 				return false;
3005 			/* Helper call will reach here because of arg type
3006 			 * check, conservatively return TRUE.
3007 			 */
3008 			if (t == SRC_OP)
3009 				return true;
3010 
3011 			return false;
3012 		}
3013 	}
3014 
3015 	if (class == BPF_ALU64 || class == BPF_JMP ||
3016 	    /* BPF_END always use BPF_ALU class. */
3017 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3018 		return true;
3019 
3020 	if (class == BPF_ALU || class == BPF_JMP32)
3021 		return false;
3022 
3023 	if (class == BPF_LDX) {
3024 		if (t != SRC_OP)
3025 			return BPF_SIZE(code) == BPF_DW;
3026 		/* LDX source must be ptr. */
3027 		return true;
3028 	}
3029 
3030 	if (class == BPF_STX) {
3031 		/* BPF_STX (including atomic variants) has multiple source
3032 		 * operands, one of which is a ptr. Check whether the caller is
3033 		 * asking about it.
3034 		 */
3035 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3036 			return true;
3037 		return BPF_SIZE(code) == BPF_DW;
3038 	}
3039 
3040 	if (class == BPF_LD) {
3041 		u8 mode = BPF_MODE(code);
3042 
3043 		/* LD_IMM64 */
3044 		if (mode == BPF_IMM)
3045 			return true;
3046 
3047 		/* Both LD_IND and LD_ABS return 32-bit data. */
3048 		if (t != SRC_OP)
3049 			return  false;
3050 
3051 		/* Implicit ctx ptr. */
3052 		if (regno == BPF_REG_6)
3053 			return true;
3054 
3055 		/* Explicit source could be any width. */
3056 		return true;
3057 	}
3058 
3059 	if (class == BPF_ST)
3060 		/* The only source register for BPF_ST is a ptr. */
3061 		return true;
3062 
3063 	/* Conservatively return true at default. */
3064 	return true;
3065 }
3066 
3067 /* Return the regno defined by the insn, or -1. */
3068 static int insn_def_regno(const struct bpf_insn *insn)
3069 {
3070 	switch (BPF_CLASS(insn->code)) {
3071 	case BPF_JMP:
3072 	case BPF_JMP32:
3073 	case BPF_ST:
3074 		return -1;
3075 	case BPF_STX:
3076 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3077 		    (insn->imm & BPF_FETCH)) {
3078 			if (insn->imm == BPF_CMPXCHG)
3079 				return BPF_REG_0;
3080 			else
3081 				return insn->src_reg;
3082 		} else {
3083 			return -1;
3084 		}
3085 	default:
3086 		return insn->dst_reg;
3087 	}
3088 }
3089 
3090 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3091 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3092 {
3093 	int dst_reg = insn_def_regno(insn);
3094 
3095 	if (dst_reg == -1)
3096 		return false;
3097 
3098 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3099 }
3100 
3101 static void mark_insn_zext(struct bpf_verifier_env *env,
3102 			   struct bpf_reg_state *reg)
3103 {
3104 	s32 def_idx = reg->subreg_def;
3105 
3106 	if (def_idx == DEF_NOT_SUBREG)
3107 		return;
3108 
3109 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3110 	/* The dst will be zero extended, so won't be sub-register anymore. */
3111 	reg->subreg_def = DEF_NOT_SUBREG;
3112 }
3113 
3114 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3115 			 enum reg_arg_type t)
3116 {
3117 	struct bpf_verifier_state *vstate = env->cur_state;
3118 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3119 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3120 	struct bpf_reg_state *reg, *regs = state->regs;
3121 	bool rw64;
3122 
3123 	if (regno >= MAX_BPF_REG) {
3124 		verbose(env, "R%d is invalid\n", regno);
3125 		return -EINVAL;
3126 	}
3127 
3128 	mark_reg_scratched(env, regno);
3129 
3130 	reg = &regs[regno];
3131 	rw64 = is_reg64(env, insn, regno, reg, t);
3132 	if (t == SRC_OP) {
3133 		/* check whether register used as source operand can be read */
3134 		if (reg->type == NOT_INIT) {
3135 			verbose(env, "R%d !read_ok\n", regno);
3136 			return -EACCES;
3137 		}
3138 		/* We don't need to worry about FP liveness because it's read-only */
3139 		if (regno == BPF_REG_FP)
3140 			return 0;
3141 
3142 		if (rw64)
3143 			mark_insn_zext(env, reg);
3144 
3145 		return mark_reg_read(env, reg, reg->parent,
3146 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3147 	} else {
3148 		/* check whether register used as dest operand can be written to */
3149 		if (regno == BPF_REG_FP) {
3150 			verbose(env, "frame pointer is read only\n");
3151 			return -EACCES;
3152 		}
3153 		reg->live |= REG_LIVE_WRITTEN;
3154 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3155 		if (t == DST_OP)
3156 			mark_reg_unknown(env, regs, regno);
3157 	}
3158 	return 0;
3159 }
3160 
3161 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3162 {
3163 	env->insn_aux_data[idx].jmp_point = true;
3164 }
3165 
3166 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3167 {
3168 	return env->insn_aux_data[insn_idx].jmp_point;
3169 }
3170 
3171 /* for any branch, call, exit record the history of jmps in the given state */
3172 static int push_jmp_history(struct bpf_verifier_env *env,
3173 			    struct bpf_verifier_state *cur)
3174 {
3175 	u32 cnt = cur->jmp_history_cnt;
3176 	struct bpf_idx_pair *p;
3177 	size_t alloc_size;
3178 
3179 	if (!is_jmp_point(env, env->insn_idx))
3180 		return 0;
3181 
3182 	cnt++;
3183 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3184 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3185 	if (!p)
3186 		return -ENOMEM;
3187 	p[cnt - 1].idx = env->insn_idx;
3188 	p[cnt - 1].prev_idx = env->prev_insn_idx;
3189 	cur->jmp_history = p;
3190 	cur->jmp_history_cnt = cnt;
3191 	return 0;
3192 }
3193 
3194 /* Backtrack one insn at a time. If idx is not at the top of recorded
3195  * history then previous instruction came from straight line execution.
3196  */
3197 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3198 			     u32 *history)
3199 {
3200 	u32 cnt = *history;
3201 
3202 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3203 		i = st->jmp_history[cnt - 1].prev_idx;
3204 		(*history)--;
3205 	} else {
3206 		i--;
3207 	}
3208 	return i;
3209 }
3210 
3211 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3212 {
3213 	const struct btf_type *func;
3214 	struct btf *desc_btf;
3215 
3216 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3217 		return NULL;
3218 
3219 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3220 	if (IS_ERR(desc_btf))
3221 		return "<error>";
3222 
3223 	func = btf_type_by_id(desc_btf, insn->imm);
3224 	return btf_name_by_offset(desc_btf, func->name_off);
3225 }
3226 
3227 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3228 {
3229 	bt->frame = frame;
3230 }
3231 
3232 static inline void bt_reset(struct backtrack_state *bt)
3233 {
3234 	struct bpf_verifier_env *env = bt->env;
3235 
3236 	memset(bt, 0, sizeof(*bt));
3237 	bt->env = env;
3238 }
3239 
3240 static inline u32 bt_empty(struct backtrack_state *bt)
3241 {
3242 	u64 mask = 0;
3243 	int i;
3244 
3245 	for (i = 0; i <= bt->frame; i++)
3246 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3247 
3248 	return mask == 0;
3249 }
3250 
3251 static inline int bt_subprog_enter(struct backtrack_state *bt)
3252 {
3253 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3254 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3255 		WARN_ONCE(1, "verifier backtracking bug");
3256 		return -EFAULT;
3257 	}
3258 	bt->frame++;
3259 	return 0;
3260 }
3261 
3262 static inline int bt_subprog_exit(struct backtrack_state *bt)
3263 {
3264 	if (bt->frame == 0) {
3265 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3266 		WARN_ONCE(1, "verifier backtracking bug");
3267 		return -EFAULT;
3268 	}
3269 	bt->frame--;
3270 	return 0;
3271 }
3272 
3273 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3274 {
3275 	bt->reg_masks[frame] |= 1 << reg;
3276 }
3277 
3278 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3279 {
3280 	bt->reg_masks[frame] &= ~(1 << reg);
3281 }
3282 
3283 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3284 {
3285 	bt_set_frame_reg(bt, bt->frame, reg);
3286 }
3287 
3288 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3289 {
3290 	bt_clear_frame_reg(bt, bt->frame, reg);
3291 }
3292 
3293 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3294 {
3295 	bt->stack_masks[frame] |= 1ull << slot;
3296 }
3297 
3298 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3299 {
3300 	bt->stack_masks[frame] &= ~(1ull << slot);
3301 }
3302 
3303 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3304 {
3305 	bt_set_frame_slot(bt, bt->frame, slot);
3306 }
3307 
3308 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3309 {
3310 	bt_clear_frame_slot(bt, bt->frame, slot);
3311 }
3312 
3313 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3314 {
3315 	return bt->reg_masks[frame];
3316 }
3317 
3318 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3319 {
3320 	return bt->reg_masks[bt->frame];
3321 }
3322 
3323 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3324 {
3325 	return bt->stack_masks[frame];
3326 }
3327 
3328 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3329 {
3330 	return bt->stack_masks[bt->frame];
3331 }
3332 
3333 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3334 {
3335 	return bt->reg_masks[bt->frame] & (1 << reg);
3336 }
3337 
3338 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3339 {
3340 	return bt->stack_masks[bt->frame] & (1ull << slot);
3341 }
3342 
3343 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3344 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3345 {
3346 	DECLARE_BITMAP(mask, 64);
3347 	bool first = true;
3348 	int i, n;
3349 
3350 	buf[0] = '\0';
3351 
3352 	bitmap_from_u64(mask, reg_mask);
3353 	for_each_set_bit(i, mask, 32) {
3354 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3355 		first = false;
3356 		buf += n;
3357 		buf_sz -= n;
3358 		if (buf_sz < 0)
3359 			break;
3360 	}
3361 }
3362 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3363 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3364 {
3365 	DECLARE_BITMAP(mask, 64);
3366 	bool first = true;
3367 	int i, n;
3368 
3369 	buf[0] = '\0';
3370 
3371 	bitmap_from_u64(mask, stack_mask);
3372 	for_each_set_bit(i, mask, 64) {
3373 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3374 		first = false;
3375 		buf += n;
3376 		buf_sz -= n;
3377 		if (buf_sz < 0)
3378 			break;
3379 	}
3380 }
3381 
3382 /* For given verifier state backtrack_insn() is called from the last insn to
3383  * the first insn. Its purpose is to compute a bitmask of registers and
3384  * stack slots that needs precision in the parent verifier state.
3385  *
3386  * @idx is an index of the instruction we are currently processing;
3387  * @subseq_idx is an index of the subsequent instruction that:
3388  *   - *would be* executed next, if jump history is viewed in forward order;
3389  *   - *was* processed previously during backtracking.
3390  */
3391 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3392 			  struct backtrack_state *bt)
3393 {
3394 	const struct bpf_insn_cbs cbs = {
3395 		.cb_call	= disasm_kfunc_name,
3396 		.cb_print	= verbose,
3397 		.private_data	= env,
3398 	};
3399 	struct bpf_insn *insn = env->prog->insnsi + idx;
3400 	u8 class = BPF_CLASS(insn->code);
3401 	u8 opcode = BPF_OP(insn->code);
3402 	u8 mode = BPF_MODE(insn->code);
3403 	u32 dreg = insn->dst_reg;
3404 	u32 sreg = insn->src_reg;
3405 	u32 spi, i;
3406 
3407 	if (insn->code == 0)
3408 		return 0;
3409 	if (env->log.level & BPF_LOG_LEVEL2) {
3410 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3411 		verbose(env, "mark_precise: frame%d: regs=%s ",
3412 			bt->frame, env->tmp_str_buf);
3413 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3414 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3415 		verbose(env, "%d: ", idx);
3416 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3417 	}
3418 
3419 	if (class == BPF_ALU || class == BPF_ALU64) {
3420 		if (!bt_is_reg_set(bt, dreg))
3421 			return 0;
3422 		if (opcode == BPF_MOV) {
3423 			if (BPF_SRC(insn->code) == BPF_X) {
3424 				/* dreg = sreg
3425 				 * dreg needs precision after this insn
3426 				 * sreg needs precision before this insn
3427 				 */
3428 				bt_clear_reg(bt, dreg);
3429 				bt_set_reg(bt, sreg);
3430 			} else {
3431 				/* dreg = K
3432 				 * dreg needs precision after this insn.
3433 				 * Corresponding register is already marked
3434 				 * as precise=true in this verifier state.
3435 				 * No further markings in parent are necessary
3436 				 */
3437 				bt_clear_reg(bt, dreg);
3438 			}
3439 		} else {
3440 			if (BPF_SRC(insn->code) == BPF_X) {
3441 				/* dreg += sreg
3442 				 * both dreg and sreg need precision
3443 				 * before this insn
3444 				 */
3445 				bt_set_reg(bt, sreg);
3446 			} /* else dreg += K
3447 			   * dreg still needs precision before this insn
3448 			   */
3449 		}
3450 	} else if (class == BPF_LDX) {
3451 		if (!bt_is_reg_set(bt, dreg))
3452 			return 0;
3453 		bt_clear_reg(bt, dreg);
3454 
3455 		/* scalars can only be spilled into stack w/o losing precision.
3456 		 * Load from any other memory can be zero extended.
3457 		 * The desire to keep that precision is already indicated
3458 		 * by 'precise' mark in corresponding register of this state.
3459 		 * No further tracking necessary.
3460 		 */
3461 		if (insn->src_reg != BPF_REG_FP)
3462 			return 0;
3463 
3464 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3465 		 * that [fp - off] slot contains scalar that needs to be
3466 		 * tracked with precision
3467 		 */
3468 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3469 		if (spi >= 64) {
3470 			verbose(env, "BUG spi %d\n", spi);
3471 			WARN_ONCE(1, "verifier backtracking bug");
3472 			return -EFAULT;
3473 		}
3474 		bt_set_slot(bt, spi);
3475 	} else if (class == BPF_STX || class == BPF_ST) {
3476 		if (bt_is_reg_set(bt, dreg))
3477 			/* stx & st shouldn't be using _scalar_ dst_reg
3478 			 * to access memory. It means backtracking
3479 			 * encountered a case of pointer subtraction.
3480 			 */
3481 			return -ENOTSUPP;
3482 		/* scalars can only be spilled into stack */
3483 		if (insn->dst_reg != BPF_REG_FP)
3484 			return 0;
3485 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3486 		if (spi >= 64) {
3487 			verbose(env, "BUG spi %d\n", spi);
3488 			WARN_ONCE(1, "verifier backtracking bug");
3489 			return -EFAULT;
3490 		}
3491 		if (!bt_is_slot_set(bt, spi))
3492 			return 0;
3493 		bt_clear_slot(bt, spi);
3494 		if (class == BPF_STX)
3495 			bt_set_reg(bt, sreg);
3496 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3497 		if (bpf_pseudo_call(insn)) {
3498 			int subprog_insn_idx, subprog;
3499 
3500 			subprog_insn_idx = idx + insn->imm + 1;
3501 			subprog = find_subprog(env, subprog_insn_idx);
3502 			if (subprog < 0)
3503 				return -EFAULT;
3504 
3505 			if (subprog_is_global(env, subprog)) {
3506 				/* check that jump history doesn't have any
3507 				 * extra instructions from subprog; the next
3508 				 * instruction after call to global subprog
3509 				 * should be literally next instruction in
3510 				 * caller program
3511 				 */
3512 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3513 				/* r1-r5 are invalidated after subprog call,
3514 				 * so for global func call it shouldn't be set
3515 				 * anymore
3516 				 */
3517 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3518 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3519 					WARN_ONCE(1, "verifier backtracking bug");
3520 					return -EFAULT;
3521 				}
3522 				/* global subprog always sets R0 */
3523 				bt_clear_reg(bt, BPF_REG_0);
3524 				return 0;
3525 			} else {
3526 				/* static subprog call instruction, which
3527 				 * means that we are exiting current subprog,
3528 				 * so only r1-r5 could be still requested as
3529 				 * precise, r0 and r6-r10 or any stack slot in
3530 				 * the current frame should be zero by now
3531 				 */
3532 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3533 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3534 					WARN_ONCE(1, "verifier backtracking bug");
3535 					return -EFAULT;
3536 				}
3537 				/* we don't track register spills perfectly,
3538 				 * so fallback to force-precise instead of failing */
3539 				if (bt_stack_mask(bt) != 0)
3540 					return -ENOTSUPP;
3541 				/* propagate r1-r5 to the caller */
3542 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3543 					if (bt_is_reg_set(bt, i)) {
3544 						bt_clear_reg(bt, i);
3545 						bt_set_frame_reg(bt, bt->frame - 1, i);
3546 					}
3547 				}
3548 				if (bt_subprog_exit(bt))
3549 					return -EFAULT;
3550 				return 0;
3551 			}
3552 		} else if ((bpf_helper_call(insn) &&
3553 			    is_callback_calling_function(insn->imm) &&
3554 			    !is_async_callback_calling_function(insn->imm)) ||
3555 			   (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3556 			/* callback-calling helper or kfunc call, which means
3557 			 * we are exiting from subprog, but unlike the subprog
3558 			 * call handling above, we shouldn't propagate
3559 			 * precision of r1-r5 (if any requested), as they are
3560 			 * not actually arguments passed directly to callback
3561 			 * subprogs
3562 			 */
3563 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3564 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3565 				WARN_ONCE(1, "verifier backtracking bug");
3566 				return -EFAULT;
3567 			}
3568 			if (bt_stack_mask(bt) != 0)
3569 				return -ENOTSUPP;
3570 			/* clear r1-r5 in callback subprog's mask */
3571 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3572 				bt_clear_reg(bt, i);
3573 			if (bt_subprog_exit(bt))
3574 				return -EFAULT;
3575 			return 0;
3576 		} else if (opcode == BPF_CALL) {
3577 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3578 			 * catch this error later. Make backtracking conservative
3579 			 * with ENOTSUPP.
3580 			 */
3581 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3582 				return -ENOTSUPP;
3583 			/* regular helper call sets R0 */
3584 			bt_clear_reg(bt, BPF_REG_0);
3585 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3586 				/* if backtracing was looking for registers R1-R5
3587 				 * they should have been found already.
3588 				 */
3589 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3590 				WARN_ONCE(1, "verifier backtracking bug");
3591 				return -EFAULT;
3592 			}
3593 		} else if (opcode == BPF_EXIT) {
3594 			bool r0_precise;
3595 
3596 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3597 				/* if backtracing was looking for registers R1-R5
3598 				 * they should have been found already.
3599 				 */
3600 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3601 				WARN_ONCE(1, "verifier backtracking bug");
3602 				return -EFAULT;
3603 			}
3604 
3605 			/* BPF_EXIT in subprog or callback always returns
3606 			 * right after the call instruction, so by checking
3607 			 * whether the instruction at subseq_idx-1 is subprog
3608 			 * call or not we can distinguish actual exit from
3609 			 * *subprog* from exit from *callback*. In the former
3610 			 * case, we need to propagate r0 precision, if
3611 			 * necessary. In the former we never do that.
3612 			 */
3613 			r0_precise = subseq_idx - 1 >= 0 &&
3614 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3615 				     bt_is_reg_set(bt, BPF_REG_0);
3616 
3617 			bt_clear_reg(bt, BPF_REG_0);
3618 			if (bt_subprog_enter(bt))
3619 				return -EFAULT;
3620 
3621 			if (r0_precise)
3622 				bt_set_reg(bt, BPF_REG_0);
3623 			/* r6-r9 and stack slots will stay set in caller frame
3624 			 * bitmasks until we return back from callee(s)
3625 			 */
3626 			return 0;
3627 		} else if (BPF_SRC(insn->code) == BPF_X) {
3628 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3629 				return 0;
3630 			/* dreg <cond> sreg
3631 			 * Both dreg and sreg need precision before
3632 			 * this insn. If only sreg was marked precise
3633 			 * before it would be equally necessary to
3634 			 * propagate it to dreg.
3635 			 */
3636 			bt_set_reg(bt, dreg);
3637 			bt_set_reg(bt, sreg);
3638 			 /* else dreg <cond> K
3639 			  * Only dreg still needs precision before
3640 			  * this insn, so for the K-based conditional
3641 			  * there is nothing new to be marked.
3642 			  */
3643 		}
3644 	} else if (class == BPF_LD) {
3645 		if (!bt_is_reg_set(bt, dreg))
3646 			return 0;
3647 		bt_clear_reg(bt, dreg);
3648 		/* It's ld_imm64 or ld_abs or ld_ind.
3649 		 * For ld_imm64 no further tracking of precision
3650 		 * into parent is necessary
3651 		 */
3652 		if (mode == BPF_IND || mode == BPF_ABS)
3653 			/* to be analyzed */
3654 			return -ENOTSUPP;
3655 	}
3656 	return 0;
3657 }
3658 
3659 /* the scalar precision tracking algorithm:
3660  * . at the start all registers have precise=false.
3661  * . scalar ranges are tracked as normal through alu and jmp insns.
3662  * . once precise value of the scalar register is used in:
3663  *   .  ptr + scalar alu
3664  *   . if (scalar cond K|scalar)
3665  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3666  *   backtrack through the verifier states and mark all registers and
3667  *   stack slots with spilled constants that these scalar regisers
3668  *   should be precise.
3669  * . during state pruning two registers (or spilled stack slots)
3670  *   are equivalent if both are not precise.
3671  *
3672  * Note the verifier cannot simply walk register parentage chain,
3673  * since many different registers and stack slots could have been
3674  * used to compute single precise scalar.
3675  *
3676  * The approach of starting with precise=true for all registers and then
3677  * backtrack to mark a register as not precise when the verifier detects
3678  * that program doesn't care about specific value (e.g., when helper
3679  * takes register as ARG_ANYTHING parameter) is not safe.
3680  *
3681  * It's ok to walk single parentage chain of the verifier states.
3682  * It's possible that this backtracking will go all the way till 1st insn.
3683  * All other branches will be explored for needing precision later.
3684  *
3685  * The backtracking needs to deal with cases like:
3686  *   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)
3687  * r9 -= r8
3688  * r5 = r9
3689  * if r5 > 0x79f goto pc+7
3690  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3691  * r5 += 1
3692  * ...
3693  * call bpf_perf_event_output#25
3694  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3695  *
3696  * and this case:
3697  * r6 = 1
3698  * call foo // uses callee's r6 inside to compute r0
3699  * r0 += r6
3700  * if r0 == 0 goto
3701  *
3702  * to track above reg_mask/stack_mask needs to be independent for each frame.
3703  *
3704  * Also if parent's curframe > frame where backtracking started,
3705  * the verifier need to mark registers in both frames, otherwise callees
3706  * may incorrectly prune callers. This is similar to
3707  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3708  *
3709  * For now backtracking falls back into conservative marking.
3710  */
3711 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3712 				     struct bpf_verifier_state *st)
3713 {
3714 	struct bpf_func_state *func;
3715 	struct bpf_reg_state *reg;
3716 	int i, j;
3717 
3718 	if (env->log.level & BPF_LOG_LEVEL2) {
3719 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3720 			st->curframe);
3721 	}
3722 
3723 	/* big hammer: mark all scalars precise in this path.
3724 	 * pop_stack may still get !precise scalars.
3725 	 * We also skip current state and go straight to first parent state,
3726 	 * because precision markings in current non-checkpointed state are
3727 	 * not needed. See why in the comment in __mark_chain_precision below.
3728 	 */
3729 	for (st = st->parent; st; st = st->parent) {
3730 		for (i = 0; i <= st->curframe; i++) {
3731 			func = st->frame[i];
3732 			for (j = 0; j < BPF_REG_FP; j++) {
3733 				reg = &func->regs[j];
3734 				if (reg->type != SCALAR_VALUE || reg->precise)
3735 					continue;
3736 				reg->precise = true;
3737 				if (env->log.level & BPF_LOG_LEVEL2) {
3738 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3739 						i, j);
3740 				}
3741 			}
3742 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3743 				if (!is_spilled_reg(&func->stack[j]))
3744 					continue;
3745 				reg = &func->stack[j].spilled_ptr;
3746 				if (reg->type != SCALAR_VALUE || reg->precise)
3747 					continue;
3748 				reg->precise = true;
3749 				if (env->log.level & BPF_LOG_LEVEL2) {
3750 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3751 						i, -(j + 1) * 8);
3752 				}
3753 			}
3754 		}
3755 	}
3756 }
3757 
3758 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3759 {
3760 	struct bpf_func_state *func;
3761 	struct bpf_reg_state *reg;
3762 	int i, j;
3763 
3764 	for (i = 0; i <= st->curframe; i++) {
3765 		func = st->frame[i];
3766 		for (j = 0; j < BPF_REG_FP; j++) {
3767 			reg = &func->regs[j];
3768 			if (reg->type != SCALAR_VALUE)
3769 				continue;
3770 			reg->precise = false;
3771 		}
3772 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3773 			if (!is_spilled_reg(&func->stack[j]))
3774 				continue;
3775 			reg = &func->stack[j].spilled_ptr;
3776 			if (reg->type != SCALAR_VALUE)
3777 				continue;
3778 			reg->precise = false;
3779 		}
3780 	}
3781 }
3782 
3783 static bool idset_contains(struct bpf_idset *s, u32 id)
3784 {
3785 	u32 i;
3786 
3787 	for (i = 0; i < s->count; ++i)
3788 		if (s->ids[i] == id)
3789 			return true;
3790 
3791 	return false;
3792 }
3793 
3794 static int idset_push(struct bpf_idset *s, u32 id)
3795 {
3796 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3797 		return -EFAULT;
3798 	s->ids[s->count++] = id;
3799 	return 0;
3800 }
3801 
3802 static void idset_reset(struct bpf_idset *s)
3803 {
3804 	s->count = 0;
3805 }
3806 
3807 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3808  * Mark all registers with these IDs as precise.
3809  */
3810 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3811 {
3812 	struct bpf_idset *precise_ids = &env->idset_scratch;
3813 	struct backtrack_state *bt = &env->bt;
3814 	struct bpf_func_state *func;
3815 	struct bpf_reg_state *reg;
3816 	DECLARE_BITMAP(mask, 64);
3817 	int i, fr;
3818 
3819 	idset_reset(precise_ids);
3820 
3821 	for (fr = bt->frame; fr >= 0; fr--) {
3822 		func = st->frame[fr];
3823 
3824 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3825 		for_each_set_bit(i, mask, 32) {
3826 			reg = &func->regs[i];
3827 			if (!reg->id || reg->type != SCALAR_VALUE)
3828 				continue;
3829 			if (idset_push(precise_ids, reg->id))
3830 				return -EFAULT;
3831 		}
3832 
3833 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3834 		for_each_set_bit(i, mask, 64) {
3835 			if (i >= func->allocated_stack / BPF_REG_SIZE)
3836 				break;
3837 			if (!is_spilled_scalar_reg(&func->stack[i]))
3838 				continue;
3839 			reg = &func->stack[i].spilled_ptr;
3840 			if (!reg->id)
3841 				continue;
3842 			if (idset_push(precise_ids, reg->id))
3843 				return -EFAULT;
3844 		}
3845 	}
3846 
3847 	for (fr = 0; fr <= st->curframe; ++fr) {
3848 		func = st->frame[fr];
3849 
3850 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
3851 			reg = &func->regs[i];
3852 			if (!reg->id)
3853 				continue;
3854 			if (!idset_contains(precise_ids, reg->id))
3855 				continue;
3856 			bt_set_frame_reg(bt, fr, i);
3857 		}
3858 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
3859 			if (!is_spilled_scalar_reg(&func->stack[i]))
3860 				continue;
3861 			reg = &func->stack[i].spilled_ptr;
3862 			if (!reg->id)
3863 				continue;
3864 			if (!idset_contains(precise_ids, reg->id))
3865 				continue;
3866 			bt_set_frame_slot(bt, fr, i);
3867 		}
3868 	}
3869 
3870 	return 0;
3871 }
3872 
3873 /*
3874  * __mark_chain_precision() backtracks BPF program instruction sequence and
3875  * chain of verifier states making sure that register *regno* (if regno >= 0)
3876  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3877  * SCALARS, as well as any other registers and slots that contribute to
3878  * a tracked state of given registers/stack slots, depending on specific BPF
3879  * assembly instructions (see backtrack_insns() for exact instruction handling
3880  * logic). This backtracking relies on recorded jmp_history and is able to
3881  * traverse entire chain of parent states. This process ends only when all the
3882  * necessary registers/slots and their transitive dependencies are marked as
3883  * precise.
3884  *
3885  * One important and subtle aspect is that precise marks *do not matter* in
3886  * the currently verified state (current state). It is important to understand
3887  * why this is the case.
3888  *
3889  * First, note that current state is the state that is not yet "checkpointed",
3890  * i.e., it is not yet put into env->explored_states, and it has no children
3891  * states as well. It's ephemeral, and can end up either a) being discarded if
3892  * compatible explored state is found at some point or BPF_EXIT instruction is
3893  * reached or b) checkpointed and put into env->explored_states, branching out
3894  * into one or more children states.
3895  *
3896  * In the former case, precise markings in current state are completely
3897  * ignored by state comparison code (see regsafe() for details). Only
3898  * checkpointed ("old") state precise markings are important, and if old
3899  * state's register/slot is precise, regsafe() assumes current state's
3900  * register/slot as precise and checks value ranges exactly and precisely. If
3901  * states turn out to be compatible, current state's necessary precise
3902  * markings and any required parent states' precise markings are enforced
3903  * after the fact with propagate_precision() logic, after the fact. But it's
3904  * important to realize that in this case, even after marking current state
3905  * registers/slots as precise, we immediately discard current state. So what
3906  * actually matters is any of the precise markings propagated into current
3907  * state's parent states, which are always checkpointed (due to b) case above).
3908  * As such, for scenario a) it doesn't matter if current state has precise
3909  * markings set or not.
3910  *
3911  * Now, for the scenario b), checkpointing and forking into child(ren)
3912  * state(s). Note that before current state gets to checkpointing step, any
3913  * processed instruction always assumes precise SCALAR register/slot
3914  * knowledge: if precise value or range is useful to prune jump branch, BPF
3915  * verifier takes this opportunity enthusiastically. Similarly, when
3916  * register's value is used to calculate offset or memory address, exact
3917  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3918  * what we mentioned above about state comparison ignoring precise markings
3919  * during state comparison, BPF verifier ignores and also assumes precise
3920  * markings *at will* during instruction verification process. But as verifier
3921  * assumes precision, it also propagates any precision dependencies across
3922  * parent states, which are not yet finalized, so can be further restricted
3923  * based on new knowledge gained from restrictions enforced by their children
3924  * states. This is so that once those parent states are finalized, i.e., when
3925  * they have no more active children state, state comparison logic in
3926  * is_state_visited() would enforce strict and precise SCALAR ranges, if
3927  * required for correctness.
3928  *
3929  * To build a bit more intuition, note also that once a state is checkpointed,
3930  * the path we took to get to that state is not important. This is crucial
3931  * property for state pruning. When state is checkpointed and finalized at
3932  * some instruction index, it can be correctly and safely used to "short
3933  * circuit" any *compatible* state that reaches exactly the same instruction
3934  * index. I.e., if we jumped to that instruction from a completely different
3935  * code path than original finalized state was derived from, it doesn't
3936  * matter, current state can be discarded because from that instruction
3937  * forward having a compatible state will ensure we will safely reach the
3938  * exit. States describe preconditions for further exploration, but completely
3939  * forget the history of how we got here.
3940  *
3941  * This also means that even if we needed precise SCALAR range to get to
3942  * finalized state, but from that point forward *that same* SCALAR register is
3943  * never used in a precise context (i.e., it's precise value is not needed for
3944  * correctness), it's correct and safe to mark such register as "imprecise"
3945  * (i.e., precise marking set to false). This is what we rely on when we do
3946  * not set precise marking in current state. If no child state requires
3947  * precision for any given SCALAR register, it's safe to dictate that it can
3948  * be imprecise. If any child state does require this register to be precise,
3949  * we'll mark it precise later retroactively during precise markings
3950  * propagation from child state to parent states.
3951  *
3952  * Skipping precise marking setting in current state is a mild version of
3953  * relying on the above observation. But we can utilize this property even
3954  * more aggressively by proactively forgetting any precise marking in the
3955  * current state (which we inherited from the parent state), right before we
3956  * checkpoint it and branch off into new child state. This is done by
3957  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3958  * finalized states which help in short circuiting more future states.
3959  */
3960 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
3961 {
3962 	struct backtrack_state *bt = &env->bt;
3963 	struct bpf_verifier_state *st = env->cur_state;
3964 	int first_idx = st->first_insn_idx;
3965 	int last_idx = env->insn_idx;
3966 	int subseq_idx = -1;
3967 	struct bpf_func_state *func;
3968 	struct bpf_reg_state *reg;
3969 	bool skip_first = true;
3970 	int i, fr, err;
3971 
3972 	if (!env->bpf_capable)
3973 		return 0;
3974 
3975 	/* set frame number from which we are starting to backtrack */
3976 	bt_init(bt, env->cur_state->curframe);
3977 
3978 	/* Do sanity checks against current state of register and/or stack
3979 	 * slot, but don't set precise flag in current state, as precision
3980 	 * tracking in the current state is unnecessary.
3981 	 */
3982 	func = st->frame[bt->frame];
3983 	if (regno >= 0) {
3984 		reg = &func->regs[regno];
3985 		if (reg->type != SCALAR_VALUE) {
3986 			WARN_ONCE(1, "backtracing misuse");
3987 			return -EFAULT;
3988 		}
3989 		bt_set_reg(bt, regno);
3990 	}
3991 
3992 	if (bt_empty(bt))
3993 		return 0;
3994 
3995 	for (;;) {
3996 		DECLARE_BITMAP(mask, 64);
3997 		u32 history = st->jmp_history_cnt;
3998 
3999 		if (env->log.level & BPF_LOG_LEVEL2) {
4000 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4001 				bt->frame, last_idx, first_idx, subseq_idx);
4002 		}
4003 
4004 		/* If some register with scalar ID is marked as precise,
4005 		 * make sure that all registers sharing this ID are also precise.
4006 		 * This is needed to estimate effect of find_equal_scalars().
4007 		 * Do this at the last instruction of each state,
4008 		 * bpf_reg_state::id fields are valid for these instructions.
4009 		 *
4010 		 * Allows to track precision in situation like below:
4011 		 *
4012 		 *     r2 = unknown value
4013 		 *     ...
4014 		 *   --- state #0 ---
4015 		 *     ...
4016 		 *     r1 = r2                 // r1 and r2 now share the same ID
4017 		 *     ...
4018 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4019 		 *     ...
4020 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4021 		 *     ...
4022 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4023 		 *     r3 = r10
4024 		 *     r3 += r1                // need to mark both r1 and r2
4025 		 */
4026 		if (mark_precise_scalar_ids(env, st))
4027 			return -EFAULT;
4028 
4029 		if (last_idx < 0) {
4030 			/* we are at the entry into subprog, which
4031 			 * is expected for global funcs, but only if
4032 			 * requested precise registers are R1-R5
4033 			 * (which are global func's input arguments)
4034 			 */
4035 			if (st->curframe == 0 &&
4036 			    st->frame[0]->subprogno > 0 &&
4037 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4038 			    bt_stack_mask(bt) == 0 &&
4039 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4040 				bitmap_from_u64(mask, bt_reg_mask(bt));
4041 				for_each_set_bit(i, mask, 32) {
4042 					reg = &st->frame[0]->regs[i];
4043 					if (reg->type != SCALAR_VALUE) {
4044 						bt_clear_reg(bt, i);
4045 						continue;
4046 					}
4047 					reg->precise = true;
4048 				}
4049 				return 0;
4050 			}
4051 
4052 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4053 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4054 			WARN_ONCE(1, "verifier backtracking bug");
4055 			return -EFAULT;
4056 		}
4057 
4058 		for (i = last_idx;;) {
4059 			if (skip_first) {
4060 				err = 0;
4061 				skip_first = false;
4062 			} else {
4063 				err = backtrack_insn(env, i, subseq_idx, bt);
4064 			}
4065 			if (err == -ENOTSUPP) {
4066 				mark_all_scalars_precise(env, env->cur_state);
4067 				bt_reset(bt);
4068 				return 0;
4069 			} else if (err) {
4070 				return err;
4071 			}
4072 			if (bt_empty(bt))
4073 				/* Found assignment(s) into tracked register in this state.
4074 				 * Since this state is already marked, just return.
4075 				 * Nothing to be tracked further in the parent state.
4076 				 */
4077 				return 0;
4078 			if (i == first_idx)
4079 				break;
4080 			subseq_idx = i;
4081 			i = get_prev_insn_idx(st, i, &history);
4082 			if (i >= env->prog->len) {
4083 				/* This can happen if backtracking reached insn 0
4084 				 * and there are still reg_mask or stack_mask
4085 				 * to backtrack.
4086 				 * It means the backtracking missed the spot where
4087 				 * particular register was initialized with a constant.
4088 				 */
4089 				verbose(env, "BUG backtracking idx %d\n", i);
4090 				WARN_ONCE(1, "verifier backtracking bug");
4091 				return -EFAULT;
4092 			}
4093 		}
4094 		st = st->parent;
4095 		if (!st)
4096 			break;
4097 
4098 		for (fr = bt->frame; fr >= 0; fr--) {
4099 			func = st->frame[fr];
4100 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4101 			for_each_set_bit(i, mask, 32) {
4102 				reg = &func->regs[i];
4103 				if (reg->type != SCALAR_VALUE) {
4104 					bt_clear_frame_reg(bt, fr, i);
4105 					continue;
4106 				}
4107 				if (reg->precise)
4108 					bt_clear_frame_reg(bt, fr, i);
4109 				else
4110 					reg->precise = true;
4111 			}
4112 
4113 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4114 			for_each_set_bit(i, mask, 64) {
4115 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4116 					/* the sequence of instructions:
4117 					 * 2: (bf) r3 = r10
4118 					 * 3: (7b) *(u64 *)(r3 -8) = r0
4119 					 * 4: (79) r4 = *(u64 *)(r10 -8)
4120 					 * doesn't contain jmps. It's backtracked
4121 					 * as a single block.
4122 					 * During backtracking insn 3 is not recognized as
4123 					 * stack access, so at the end of backtracking
4124 					 * stack slot fp-8 is still marked in stack_mask.
4125 					 * However the parent state may not have accessed
4126 					 * fp-8 and it's "unallocated" stack space.
4127 					 * In such case fallback to conservative.
4128 					 */
4129 					mark_all_scalars_precise(env, env->cur_state);
4130 					bt_reset(bt);
4131 					return 0;
4132 				}
4133 
4134 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4135 					bt_clear_frame_slot(bt, fr, i);
4136 					continue;
4137 				}
4138 				reg = &func->stack[i].spilled_ptr;
4139 				if (reg->precise)
4140 					bt_clear_frame_slot(bt, fr, i);
4141 				else
4142 					reg->precise = true;
4143 			}
4144 			if (env->log.level & BPF_LOG_LEVEL2) {
4145 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4146 					     bt_frame_reg_mask(bt, fr));
4147 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4148 					fr, env->tmp_str_buf);
4149 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4150 					       bt_frame_stack_mask(bt, fr));
4151 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4152 				print_verifier_state(env, func, true);
4153 			}
4154 		}
4155 
4156 		if (bt_empty(bt))
4157 			return 0;
4158 
4159 		subseq_idx = first_idx;
4160 		last_idx = st->last_insn_idx;
4161 		first_idx = st->first_insn_idx;
4162 	}
4163 
4164 	/* if we still have requested precise regs or slots, we missed
4165 	 * something (e.g., stack access through non-r10 register), so
4166 	 * fallback to marking all precise
4167 	 */
4168 	if (!bt_empty(bt)) {
4169 		mark_all_scalars_precise(env, env->cur_state);
4170 		bt_reset(bt);
4171 	}
4172 
4173 	return 0;
4174 }
4175 
4176 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4177 {
4178 	return __mark_chain_precision(env, regno);
4179 }
4180 
4181 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4182  * desired reg and stack masks across all relevant frames
4183  */
4184 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4185 {
4186 	return __mark_chain_precision(env, -1);
4187 }
4188 
4189 static bool is_spillable_regtype(enum bpf_reg_type type)
4190 {
4191 	switch (base_type(type)) {
4192 	case PTR_TO_MAP_VALUE:
4193 	case PTR_TO_STACK:
4194 	case PTR_TO_CTX:
4195 	case PTR_TO_PACKET:
4196 	case PTR_TO_PACKET_META:
4197 	case PTR_TO_PACKET_END:
4198 	case PTR_TO_FLOW_KEYS:
4199 	case CONST_PTR_TO_MAP:
4200 	case PTR_TO_SOCKET:
4201 	case PTR_TO_SOCK_COMMON:
4202 	case PTR_TO_TCP_SOCK:
4203 	case PTR_TO_XDP_SOCK:
4204 	case PTR_TO_BTF_ID:
4205 	case PTR_TO_BUF:
4206 	case PTR_TO_MEM:
4207 	case PTR_TO_FUNC:
4208 	case PTR_TO_MAP_KEY:
4209 		return true;
4210 	default:
4211 		return false;
4212 	}
4213 }
4214 
4215 /* Does this register contain a constant zero? */
4216 static bool register_is_null(struct bpf_reg_state *reg)
4217 {
4218 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4219 }
4220 
4221 static bool register_is_const(struct bpf_reg_state *reg)
4222 {
4223 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4224 }
4225 
4226 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4227 {
4228 	return tnum_is_unknown(reg->var_off) &&
4229 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4230 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4231 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4232 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4233 }
4234 
4235 static bool register_is_bounded(struct bpf_reg_state *reg)
4236 {
4237 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4238 }
4239 
4240 static bool __is_pointer_value(bool allow_ptr_leaks,
4241 			       const struct bpf_reg_state *reg)
4242 {
4243 	if (allow_ptr_leaks)
4244 		return false;
4245 
4246 	return reg->type != SCALAR_VALUE;
4247 }
4248 
4249 /* Copy src state preserving dst->parent and dst->live fields */
4250 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4251 {
4252 	struct bpf_reg_state *parent = dst->parent;
4253 	enum bpf_reg_liveness live = dst->live;
4254 
4255 	*dst = *src;
4256 	dst->parent = parent;
4257 	dst->live = live;
4258 }
4259 
4260 static void save_register_state(struct bpf_func_state *state,
4261 				int spi, struct bpf_reg_state *reg,
4262 				int size)
4263 {
4264 	int i;
4265 
4266 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4267 	if (size == BPF_REG_SIZE)
4268 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4269 
4270 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4271 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4272 
4273 	/* size < 8 bytes spill */
4274 	for (; i; i--)
4275 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4276 }
4277 
4278 static bool is_bpf_st_mem(struct bpf_insn *insn)
4279 {
4280 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4281 }
4282 
4283 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4284  * stack boundary and alignment are checked in check_mem_access()
4285  */
4286 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4287 				       /* stack frame we're writing to */
4288 				       struct bpf_func_state *state,
4289 				       int off, int size, int value_regno,
4290 				       int insn_idx)
4291 {
4292 	struct bpf_func_state *cur; /* state of the current function */
4293 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4294 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4295 	struct bpf_reg_state *reg = NULL;
4296 	u32 dst_reg = insn->dst_reg;
4297 
4298 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
4299 	if (err)
4300 		return err;
4301 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4302 	 * so it's aligned access and [off, off + size) are within stack limits
4303 	 */
4304 	if (!env->allow_ptr_leaks &&
4305 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
4306 	    size != BPF_REG_SIZE) {
4307 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4308 		return -EACCES;
4309 	}
4310 
4311 	cur = env->cur_state->frame[env->cur_state->curframe];
4312 	if (value_regno >= 0)
4313 		reg = &cur->regs[value_regno];
4314 	if (!env->bypass_spec_v4) {
4315 		bool sanitize = reg && is_spillable_regtype(reg->type);
4316 
4317 		for (i = 0; i < size; i++) {
4318 			u8 type = state->stack[spi].slot_type[i];
4319 
4320 			if (type != STACK_MISC && type != STACK_ZERO) {
4321 				sanitize = true;
4322 				break;
4323 			}
4324 		}
4325 
4326 		if (sanitize)
4327 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4328 	}
4329 
4330 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4331 	if (err)
4332 		return err;
4333 
4334 	mark_stack_slot_scratched(env, spi);
4335 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4336 	    !register_is_null(reg) && env->bpf_capable) {
4337 		if (dst_reg != BPF_REG_FP) {
4338 			/* The backtracking logic can only recognize explicit
4339 			 * stack slot address like [fp - 8]. Other spill of
4340 			 * scalar via different register has to be conservative.
4341 			 * Backtrack from here and mark all registers as precise
4342 			 * that contributed into 'reg' being a constant.
4343 			 */
4344 			err = mark_chain_precision(env, value_regno);
4345 			if (err)
4346 				return err;
4347 		}
4348 		save_register_state(state, spi, reg, size);
4349 		/* Break the relation on a narrowing spill. */
4350 		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4351 			state->stack[spi].spilled_ptr.id = 0;
4352 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4353 		   insn->imm != 0 && env->bpf_capable) {
4354 		struct bpf_reg_state fake_reg = {};
4355 
4356 		__mark_reg_known(&fake_reg, (u32)insn->imm);
4357 		fake_reg.type = SCALAR_VALUE;
4358 		save_register_state(state, spi, &fake_reg, size);
4359 	} else if (reg && is_spillable_regtype(reg->type)) {
4360 		/* register containing pointer is being spilled into stack */
4361 		if (size != BPF_REG_SIZE) {
4362 			verbose_linfo(env, insn_idx, "; ");
4363 			verbose(env, "invalid size of register spill\n");
4364 			return -EACCES;
4365 		}
4366 		if (state != cur && reg->type == PTR_TO_STACK) {
4367 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4368 			return -EINVAL;
4369 		}
4370 		save_register_state(state, spi, reg, size);
4371 	} else {
4372 		u8 type = STACK_MISC;
4373 
4374 		/* regular write of data into stack destroys any spilled ptr */
4375 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4376 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4377 		if (is_stack_slot_special(&state->stack[spi]))
4378 			for (i = 0; i < BPF_REG_SIZE; i++)
4379 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4380 
4381 		/* only mark the slot as written if all 8 bytes were written
4382 		 * otherwise read propagation may incorrectly stop too soon
4383 		 * when stack slots are partially written.
4384 		 * This heuristic means that read propagation will be
4385 		 * conservative, since it will add reg_live_read marks
4386 		 * to stack slots all the way to first state when programs
4387 		 * writes+reads less than 8 bytes
4388 		 */
4389 		if (size == BPF_REG_SIZE)
4390 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4391 
4392 		/* when we zero initialize stack slots mark them as such */
4393 		if ((reg && register_is_null(reg)) ||
4394 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4395 			/* backtracking doesn't work for STACK_ZERO yet. */
4396 			err = mark_chain_precision(env, value_regno);
4397 			if (err)
4398 				return err;
4399 			type = STACK_ZERO;
4400 		}
4401 
4402 		/* Mark slots affected by this stack write. */
4403 		for (i = 0; i < size; i++)
4404 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4405 				type;
4406 	}
4407 	return 0;
4408 }
4409 
4410 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4411  * known to contain a variable offset.
4412  * This function checks whether the write is permitted and conservatively
4413  * tracks the effects of the write, considering that each stack slot in the
4414  * dynamic range is potentially written to.
4415  *
4416  * 'off' includes 'regno->off'.
4417  * 'value_regno' can be -1, meaning that an unknown value is being written to
4418  * the stack.
4419  *
4420  * Spilled pointers in range are not marked as written because we don't know
4421  * what's going to be actually written. This means that read propagation for
4422  * future reads cannot be terminated by this write.
4423  *
4424  * For privileged programs, uninitialized stack slots are considered
4425  * initialized by this write (even though we don't know exactly what offsets
4426  * are going to be written to). The idea is that we don't want the verifier to
4427  * reject future reads that access slots written to through variable offsets.
4428  */
4429 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4430 				     /* func where register points to */
4431 				     struct bpf_func_state *state,
4432 				     int ptr_regno, int off, int size,
4433 				     int value_regno, int insn_idx)
4434 {
4435 	struct bpf_func_state *cur; /* state of the current function */
4436 	int min_off, max_off;
4437 	int i, err;
4438 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4439 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4440 	bool writing_zero = false;
4441 	/* set if the fact that we're writing a zero is used to let any
4442 	 * stack slots remain STACK_ZERO
4443 	 */
4444 	bool zero_used = false;
4445 
4446 	cur = env->cur_state->frame[env->cur_state->curframe];
4447 	ptr_reg = &cur->regs[ptr_regno];
4448 	min_off = ptr_reg->smin_value + off;
4449 	max_off = ptr_reg->smax_value + off + size;
4450 	if (value_regno >= 0)
4451 		value_reg = &cur->regs[value_regno];
4452 	if ((value_reg && register_is_null(value_reg)) ||
4453 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4454 		writing_zero = true;
4455 
4456 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4457 	if (err)
4458 		return err;
4459 
4460 	for (i = min_off; i < max_off; i++) {
4461 		int spi;
4462 
4463 		spi = __get_spi(i);
4464 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4465 		if (err)
4466 			return err;
4467 	}
4468 
4469 	/* Variable offset writes destroy any spilled pointers in range. */
4470 	for (i = min_off; i < max_off; i++) {
4471 		u8 new_type, *stype;
4472 		int slot, spi;
4473 
4474 		slot = -i - 1;
4475 		spi = slot / BPF_REG_SIZE;
4476 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4477 		mark_stack_slot_scratched(env, spi);
4478 
4479 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4480 			/* Reject the write if range we may write to has not
4481 			 * been initialized beforehand. If we didn't reject
4482 			 * here, the ptr status would be erased below (even
4483 			 * though not all slots are actually overwritten),
4484 			 * possibly opening the door to leaks.
4485 			 *
4486 			 * We do however catch STACK_INVALID case below, and
4487 			 * only allow reading possibly uninitialized memory
4488 			 * later for CAP_PERFMON, as the write may not happen to
4489 			 * that slot.
4490 			 */
4491 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4492 				insn_idx, i);
4493 			return -EINVAL;
4494 		}
4495 
4496 		/* Erase all spilled pointers. */
4497 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4498 
4499 		/* Update the slot type. */
4500 		new_type = STACK_MISC;
4501 		if (writing_zero && *stype == STACK_ZERO) {
4502 			new_type = STACK_ZERO;
4503 			zero_used = true;
4504 		}
4505 		/* If the slot is STACK_INVALID, we check whether it's OK to
4506 		 * pretend that it will be initialized by this write. The slot
4507 		 * might not actually be written to, and so if we mark it as
4508 		 * initialized future reads might leak uninitialized memory.
4509 		 * For privileged programs, we will accept such reads to slots
4510 		 * that may or may not be written because, if we're reject
4511 		 * them, the error would be too confusing.
4512 		 */
4513 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4514 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4515 					insn_idx, i);
4516 			return -EINVAL;
4517 		}
4518 		*stype = new_type;
4519 	}
4520 	if (zero_used) {
4521 		/* backtracking doesn't work for STACK_ZERO yet. */
4522 		err = mark_chain_precision(env, value_regno);
4523 		if (err)
4524 			return err;
4525 	}
4526 	return 0;
4527 }
4528 
4529 /* When register 'dst_regno' is assigned some values from stack[min_off,
4530  * max_off), we set the register's type according to the types of the
4531  * respective stack slots. If all the stack values are known to be zeros, then
4532  * so is the destination reg. Otherwise, the register is considered to be
4533  * SCALAR. This function does not deal with register filling; the caller must
4534  * ensure that all spilled registers in the stack range have been marked as
4535  * read.
4536  */
4537 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4538 				/* func where src register points to */
4539 				struct bpf_func_state *ptr_state,
4540 				int min_off, int max_off, int dst_regno)
4541 {
4542 	struct bpf_verifier_state *vstate = env->cur_state;
4543 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4544 	int i, slot, spi;
4545 	u8 *stype;
4546 	int zeros = 0;
4547 
4548 	for (i = min_off; i < max_off; i++) {
4549 		slot = -i - 1;
4550 		spi = slot / BPF_REG_SIZE;
4551 		mark_stack_slot_scratched(env, spi);
4552 		stype = ptr_state->stack[spi].slot_type;
4553 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4554 			break;
4555 		zeros++;
4556 	}
4557 	if (zeros == max_off - min_off) {
4558 		/* any access_size read into register is zero extended,
4559 		 * so the whole register == const_zero
4560 		 */
4561 		__mark_reg_const_zero(&state->regs[dst_regno]);
4562 		/* backtracking doesn't support STACK_ZERO yet,
4563 		 * so mark it precise here, so that later
4564 		 * backtracking can stop here.
4565 		 * Backtracking may not need this if this register
4566 		 * doesn't participate in pointer adjustment.
4567 		 * Forward propagation of precise flag is not
4568 		 * necessary either. This mark is only to stop
4569 		 * backtracking. Any register that contributed
4570 		 * to const 0 was marked precise before spill.
4571 		 */
4572 		state->regs[dst_regno].precise = true;
4573 	} else {
4574 		/* have read misc data from the stack */
4575 		mark_reg_unknown(env, state->regs, dst_regno);
4576 	}
4577 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4578 }
4579 
4580 /* Read the stack at 'off' and put the results into the register indicated by
4581  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4582  * spilled reg.
4583  *
4584  * 'dst_regno' can be -1, meaning that the read value is not going to a
4585  * register.
4586  *
4587  * The access is assumed to be within the current stack bounds.
4588  */
4589 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4590 				      /* func where src register points to */
4591 				      struct bpf_func_state *reg_state,
4592 				      int off, int size, int dst_regno)
4593 {
4594 	struct bpf_verifier_state *vstate = env->cur_state;
4595 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4596 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4597 	struct bpf_reg_state *reg;
4598 	u8 *stype, type;
4599 
4600 	stype = reg_state->stack[spi].slot_type;
4601 	reg = &reg_state->stack[spi].spilled_ptr;
4602 
4603 	mark_stack_slot_scratched(env, spi);
4604 
4605 	if (is_spilled_reg(&reg_state->stack[spi])) {
4606 		u8 spill_size = 1;
4607 
4608 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4609 			spill_size++;
4610 
4611 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4612 			if (reg->type != SCALAR_VALUE) {
4613 				verbose_linfo(env, env->insn_idx, "; ");
4614 				verbose(env, "invalid size of register fill\n");
4615 				return -EACCES;
4616 			}
4617 
4618 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4619 			if (dst_regno < 0)
4620 				return 0;
4621 
4622 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4623 				/* The earlier check_reg_arg() has decided the
4624 				 * subreg_def for this insn.  Save it first.
4625 				 */
4626 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4627 
4628 				copy_register_state(&state->regs[dst_regno], reg);
4629 				state->regs[dst_regno].subreg_def = subreg_def;
4630 			} else {
4631 				for (i = 0; i < size; i++) {
4632 					type = stype[(slot - i) % BPF_REG_SIZE];
4633 					if (type == STACK_SPILL)
4634 						continue;
4635 					if (type == STACK_MISC)
4636 						continue;
4637 					if (type == STACK_INVALID && env->allow_uninit_stack)
4638 						continue;
4639 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4640 						off, i, size);
4641 					return -EACCES;
4642 				}
4643 				mark_reg_unknown(env, state->regs, dst_regno);
4644 			}
4645 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4646 			return 0;
4647 		}
4648 
4649 		if (dst_regno >= 0) {
4650 			/* restore register state from stack */
4651 			copy_register_state(&state->regs[dst_regno], reg);
4652 			/* mark reg as written since spilled pointer state likely
4653 			 * has its liveness marks cleared by is_state_visited()
4654 			 * which resets stack/reg liveness for state transitions
4655 			 */
4656 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4657 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4658 			/* If dst_regno==-1, the caller is asking us whether
4659 			 * it is acceptable to use this value as a SCALAR_VALUE
4660 			 * (e.g. for XADD).
4661 			 * We must not allow unprivileged callers to do that
4662 			 * with spilled pointers.
4663 			 */
4664 			verbose(env, "leaking pointer from stack off %d\n",
4665 				off);
4666 			return -EACCES;
4667 		}
4668 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4669 	} else {
4670 		for (i = 0; i < size; i++) {
4671 			type = stype[(slot - i) % BPF_REG_SIZE];
4672 			if (type == STACK_MISC)
4673 				continue;
4674 			if (type == STACK_ZERO)
4675 				continue;
4676 			if (type == STACK_INVALID && env->allow_uninit_stack)
4677 				continue;
4678 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4679 				off, i, size);
4680 			return -EACCES;
4681 		}
4682 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4683 		if (dst_regno >= 0)
4684 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4685 	}
4686 	return 0;
4687 }
4688 
4689 enum bpf_access_src {
4690 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4691 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4692 };
4693 
4694 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4695 					 int regno, int off, int access_size,
4696 					 bool zero_size_allowed,
4697 					 enum bpf_access_src type,
4698 					 struct bpf_call_arg_meta *meta);
4699 
4700 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4701 {
4702 	return cur_regs(env) + regno;
4703 }
4704 
4705 /* Read the stack at 'ptr_regno + off' and put the result into the register
4706  * 'dst_regno'.
4707  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4708  * but not its variable offset.
4709  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4710  *
4711  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4712  * filling registers (i.e. reads of spilled register cannot be detected when
4713  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4714  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4715  * offset; for a fixed offset check_stack_read_fixed_off should be used
4716  * instead.
4717  */
4718 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4719 				    int ptr_regno, int off, int size, int dst_regno)
4720 {
4721 	/* The state of the source register. */
4722 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4723 	struct bpf_func_state *ptr_state = func(env, reg);
4724 	int err;
4725 	int min_off, max_off;
4726 
4727 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4728 	 */
4729 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4730 					    false, ACCESS_DIRECT, NULL);
4731 	if (err)
4732 		return err;
4733 
4734 	min_off = reg->smin_value + off;
4735 	max_off = reg->smax_value + off;
4736 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4737 	return 0;
4738 }
4739 
4740 /* check_stack_read dispatches to check_stack_read_fixed_off or
4741  * check_stack_read_var_off.
4742  *
4743  * The caller must ensure that the offset falls within the allocated stack
4744  * bounds.
4745  *
4746  * 'dst_regno' is a register which will receive the value from the stack. It
4747  * can be -1, meaning that the read value is not going to a register.
4748  */
4749 static int check_stack_read(struct bpf_verifier_env *env,
4750 			    int ptr_regno, int off, int size,
4751 			    int dst_regno)
4752 {
4753 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4754 	struct bpf_func_state *state = func(env, reg);
4755 	int err;
4756 	/* Some accesses are only permitted with a static offset. */
4757 	bool var_off = !tnum_is_const(reg->var_off);
4758 
4759 	/* The offset is required to be static when reads don't go to a
4760 	 * register, in order to not leak pointers (see
4761 	 * check_stack_read_fixed_off).
4762 	 */
4763 	if (dst_regno < 0 && var_off) {
4764 		char tn_buf[48];
4765 
4766 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4767 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4768 			tn_buf, off, size);
4769 		return -EACCES;
4770 	}
4771 	/* Variable offset is prohibited for unprivileged mode for simplicity
4772 	 * since it requires corresponding support in Spectre masking for stack
4773 	 * ALU. See also retrieve_ptr_limit(). The check in
4774 	 * check_stack_access_for_ptr_arithmetic() called by
4775 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4776 	 * with variable offsets, therefore no check is required here. Further,
4777 	 * just checking it here would be insufficient as speculative stack
4778 	 * writes could still lead to unsafe speculative behaviour.
4779 	 */
4780 	if (!var_off) {
4781 		off += reg->var_off.value;
4782 		err = check_stack_read_fixed_off(env, state, off, size,
4783 						 dst_regno);
4784 	} else {
4785 		/* Variable offset stack reads need more conservative handling
4786 		 * than fixed offset ones. Note that dst_regno >= 0 on this
4787 		 * branch.
4788 		 */
4789 		err = check_stack_read_var_off(env, ptr_regno, off, size,
4790 					       dst_regno);
4791 	}
4792 	return err;
4793 }
4794 
4795 
4796 /* check_stack_write dispatches to check_stack_write_fixed_off or
4797  * check_stack_write_var_off.
4798  *
4799  * 'ptr_regno' is the register used as a pointer into the stack.
4800  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4801  * 'value_regno' is the register whose value we're writing to the stack. It can
4802  * be -1, meaning that we're not writing from a register.
4803  *
4804  * The caller must ensure that the offset falls within the maximum stack size.
4805  */
4806 static int check_stack_write(struct bpf_verifier_env *env,
4807 			     int ptr_regno, int off, int size,
4808 			     int value_regno, int insn_idx)
4809 {
4810 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4811 	struct bpf_func_state *state = func(env, reg);
4812 	int err;
4813 
4814 	if (tnum_is_const(reg->var_off)) {
4815 		off += reg->var_off.value;
4816 		err = check_stack_write_fixed_off(env, state, off, size,
4817 						  value_regno, insn_idx);
4818 	} else {
4819 		/* Variable offset stack reads need more conservative handling
4820 		 * than fixed offset ones.
4821 		 */
4822 		err = check_stack_write_var_off(env, state,
4823 						ptr_regno, off, size,
4824 						value_regno, insn_idx);
4825 	}
4826 	return err;
4827 }
4828 
4829 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4830 				 int off, int size, enum bpf_access_type type)
4831 {
4832 	struct bpf_reg_state *regs = cur_regs(env);
4833 	struct bpf_map *map = regs[regno].map_ptr;
4834 	u32 cap = bpf_map_flags_to_cap(map);
4835 
4836 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4837 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4838 			map->value_size, off, size);
4839 		return -EACCES;
4840 	}
4841 
4842 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4843 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4844 			map->value_size, off, size);
4845 		return -EACCES;
4846 	}
4847 
4848 	return 0;
4849 }
4850 
4851 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4852 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4853 			      int off, int size, u32 mem_size,
4854 			      bool zero_size_allowed)
4855 {
4856 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4857 	struct bpf_reg_state *reg;
4858 
4859 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4860 		return 0;
4861 
4862 	reg = &cur_regs(env)[regno];
4863 	switch (reg->type) {
4864 	case PTR_TO_MAP_KEY:
4865 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4866 			mem_size, off, size);
4867 		break;
4868 	case PTR_TO_MAP_VALUE:
4869 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4870 			mem_size, off, size);
4871 		break;
4872 	case PTR_TO_PACKET:
4873 	case PTR_TO_PACKET_META:
4874 	case PTR_TO_PACKET_END:
4875 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4876 			off, size, regno, reg->id, off, mem_size);
4877 		break;
4878 	case PTR_TO_MEM:
4879 	default:
4880 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4881 			mem_size, off, size);
4882 	}
4883 
4884 	return -EACCES;
4885 }
4886 
4887 /* check read/write into a memory region with possible variable offset */
4888 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4889 				   int off, int size, u32 mem_size,
4890 				   bool zero_size_allowed)
4891 {
4892 	struct bpf_verifier_state *vstate = env->cur_state;
4893 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4894 	struct bpf_reg_state *reg = &state->regs[regno];
4895 	int err;
4896 
4897 	/* We may have adjusted the register pointing to memory region, so we
4898 	 * need to try adding each of min_value and max_value to off
4899 	 * to make sure our theoretical access will be safe.
4900 	 *
4901 	 * The minimum value is only important with signed
4902 	 * comparisons where we can't assume the floor of a
4903 	 * value is 0.  If we are using signed variables for our
4904 	 * index'es we need to make sure that whatever we use
4905 	 * will have a set floor within our range.
4906 	 */
4907 	if (reg->smin_value < 0 &&
4908 	    (reg->smin_value == S64_MIN ||
4909 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4910 	      reg->smin_value + off < 0)) {
4911 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4912 			regno);
4913 		return -EACCES;
4914 	}
4915 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
4916 				 mem_size, zero_size_allowed);
4917 	if (err) {
4918 		verbose(env, "R%d min value is outside of the allowed memory range\n",
4919 			regno);
4920 		return err;
4921 	}
4922 
4923 	/* If we haven't set a max value then we need to bail since we can't be
4924 	 * sure we won't do bad things.
4925 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
4926 	 */
4927 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4928 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4929 			regno);
4930 		return -EACCES;
4931 	}
4932 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
4933 				 mem_size, zero_size_allowed);
4934 	if (err) {
4935 		verbose(env, "R%d max value is outside of the allowed memory range\n",
4936 			regno);
4937 		return err;
4938 	}
4939 
4940 	return 0;
4941 }
4942 
4943 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4944 			       const struct bpf_reg_state *reg, int regno,
4945 			       bool fixed_off_ok)
4946 {
4947 	/* Access to this pointer-typed register or passing it to a helper
4948 	 * is only allowed in its original, unmodified form.
4949 	 */
4950 
4951 	if (reg->off < 0) {
4952 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4953 			reg_type_str(env, reg->type), regno, reg->off);
4954 		return -EACCES;
4955 	}
4956 
4957 	if (!fixed_off_ok && reg->off) {
4958 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4959 			reg_type_str(env, reg->type), regno, reg->off);
4960 		return -EACCES;
4961 	}
4962 
4963 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4964 		char tn_buf[48];
4965 
4966 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4967 		verbose(env, "variable %s access var_off=%s disallowed\n",
4968 			reg_type_str(env, reg->type), tn_buf);
4969 		return -EACCES;
4970 	}
4971 
4972 	return 0;
4973 }
4974 
4975 int check_ptr_off_reg(struct bpf_verifier_env *env,
4976 		      const struct bpf_reg_state *reg, int regno)
4977 {
4978 	return __check_ptr_off_reg(env, reg, regno, false);
4979 }
4980 
4981 static int map_kptr_match_type(struct bpf_verifier_env *env,
4982 			       struct btf_field *kptr_field,
4983 			       struct bpf_reg_state *reg, u32 regno)
4984 {
4985 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4986 	int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4987 	const char *reg_name = "";
4988 
4989 	/* Only unreferenced case accepts untrusted pointers */
4990 	if (kptr_field->type == BPF_KPTR_UNREF)
4991 		perm_flags |= PTR_UNTRUSTED;
4992 
4993 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4994 		goto bad_type;
4995 
4996 	if (!btf_is_kernel(reg->btf)) {
4997 		verbose(env, "R%d must point to kernel BTF\n", regno);
4998 		return -EINVAL;
4999 	}
5000 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5001 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5002 
5003 	/* For ref_ptr case, release function check should ensure we get one
5004 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5005 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5006 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5007 	 * reg->off and reg->ref_obj_id are not needed here.
5008 	 */
5009 	if (__check_ptr_off_reg(env, reg, regno, true))
5010 		return -EACCES;
5011 
5012 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
5013 	 * we also need to take into account the reg->off.
5014 	 *
5015 	 * We want to support cases like:
5016 	 *
5017 	 * struct foo {
5018 	 *         struct bar br;
5019 	 *         struct baz bz;
5020 	 * };
5021 	 *
5022 	 * struct foo *v;
5023 	 * v = func();	      // PTR_TO_BTF_ID
5024 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5025 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5026 	 *                    // first member type of struct after comparison fails
5027 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5028 	 *                    // to match type
5029 	 *
5030 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5031 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5032 	 * the struct to match type against first member of struct, i.e. reject
5033 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5034 	 * strict mode to true for type match.
5035 	 */
5036 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5037 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5038 				  kptr_field->type == BPF_KPTR_REF))
5039 		goto bad_type;
5040 	return 0;
5041 bad_type:
5042 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5043 		reg_type_str(env, reg->type), reg_name);
5044 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5045 	if (kptr_field->type == BPF_KPTR_UNREF)
5046 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5047 			targ_name);
5048 	else
5049 		verbose(env, "\n");
5050 	return -EINVAL;
5051 }
5052 
5053 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5054  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5055  */
5056 static bool in_rcu_cs(struct bpf_verifier_env *env)
5057 {
5058 	return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
5059 }
5060 
5061 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5062 BTF_SET_START(rcu_protected_types)
5063 BTF_ID(struct, prog_test_ref_kfunc)
5064 BTF_ID(struct, cgroup)
5065 BTF_ID(struct, bpf_cpumask)
5066 BTF_ID(struct, task_struct)
5067 BTF_SET_END(rcu_protected_types)
5068 
5069 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5070 {
5071 	if (!btf_is_kernel(btf))
5072 		return false;
5073 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5074 }
5075 
5076 static bool rcu_safe_kptr(const struct btf_field *field)
5077 {
5078 	const struct btf_field_kptr *kptr = &field->kptr;
5079 
5080 	return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5081 }
5082 
5083 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5084 				 int value_regno, int insn_idx,
5085 				 struct btf_field *kptr_field)
5086 {
5087 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5088 	int class = BPF_CLASS(insn->code);
5089 	struct bpf_reg_state *val_reg;
5090 
5091 	/* Things we already checked for in check_map_access and caller:
5092 	 *  - Reject cases where variable offset may touch kptr
5093 	 *  - size of access (must be BPF_DW)
5094 	 *  - tnum_is_const(reg->var_off)
5095 	 *  - kptr_field->offset == off + reg->var_off.value
5096 	 */
5097 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5098 	if (BPF_MODE(insn->code) != BPF_MEM) {
5099 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5100 		return -EACCES;
5101 	}
5102 
5103 	/* We only allow loading referenced kptr, since it will be marked as
5104 	 * untrusted, similar to unreferenced kptr.
5105 	 */
5106 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5107 		verbose(env, "store to referenced kptr disallowed\n");
5108 		return -EACCES;
5109 	}
5110 
5111 	if (class == BPF_LDX) {
5112 		val_reg = reg_state(env, value_regno);
5113 		/* We can simply mark the value_regno receiving the pointer
5114 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5115 		 */
5116 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5117 				kptr_field->kptr.btf_id,
5118 				rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5119 				PTR_MAYBE_NULL | MEM_RCU :
5120 				PTR_MAYBE_NULL | PTR_UNTRUSTED);
5121 		/* For mark_ptr_or_null_reg */
5122 		val_reg->id = ++env->id_gen;
5123 	} else if (class == BPF_STX) {
5124 		val_reg = reg_state(env, value_regno);
5125 		if (!register_is_null(val_reg) &&
5126 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5127 			return -EACCES;
5128 	} else if (class == BPF_ST) {
5129 		if (insn->imm) {
5130 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5131 				kptr_field->offset);
5132 			return -EACCES;
5133 		}
5134 	} else {
5135 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5136 		return -EACCES;
5137 	}
5138 	return 0;
5139 }
5140 
5141 /* check read/write into a map element with possible variable offset */
5142 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5143 			    int off, int size, bool zero_size_allowed,
5144 			    enum bpf_access_src src)
5145 {
5146 	struct bpf_verifier_state *vstate = env->cur_state;
5147 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5148 	struct bpf_reg_state *reg = &state->regs[regno];
5149 	struct bpf_map *map = reg->map_ptr;
5150 	struct btf_record *rec;
5151 	int err, i;
5152 
5153 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5154 				      zero_size_allowed);
5155 	if (err)
5156 		return err;
5157 
5158 	if (IS_ERR_OR_NULL(map->record))
5159 		return 0;
5160 	rec = map->record;
5161 	for (i = 0; i < rec->cnt; i++) {
5162 		struct btf_field *field = &rec->fields[i];
5163 		u32 p = field->offset;
5164 
5165 		/* If any part of a field  can be touched by load/store, reject
5166 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5167 		 * it is sufficient to check x1 < y2 && y1 < x2.
5168 		 */
5169 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5170 		    p < reg->umax_value + off + size) {
5171 			switch (field->type) {
5172 			case BPF_KPTR_UNREF:
5173 			case BPF_KPTR_REF:
5174 				if (src != ACCESS_DIRECT) {
5175 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5176 					return -EACCES;
5177 				}
5178 				if (!tnum_is_const(reg->var_off)) {
5179 					verbose(env, "kptr access cannot have variable offset\n");
5180 					return -EACCES;
5181 				}
5182 				if (p != off + reg->var_off.value) {
5183 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5184 						p, off + reg->var_off.value);
5185 					return -EACCES;
5186 				}
5187 				if (size != bpf_size_to_bytes(BPF_DW)) {
5188 					verbose(env, "kptr access size must be BPF_DW\n");
5189 					return -EACCES;
5190 				}
5191 				break;
5192 			default:
5193 				verbose(env, "%s cannot be accessed directly by load/store\n",
5194 					btf_field_type_name(field->type));
5195 				return -EACCES;
5196 			}
5197 		}
5198 	}
5199 	return 0;
5200 }
5201 
5202 #define MAX_PACKET_OFF 0xffff
5203 
5204 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5205 				       const struct bpf_call_arg_meta *meta,
5206 				       enum bpf_access_type t)
5207 {
5208 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5209 
5210 	switch (prog_type) {
5211 	/* Program types only with direct read access go here! */
5212 	case BPF_PROG_TYPE_LWT_IN:
5213 	case BPF_PROG_TYPE_LWT_OUT:
5214 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5215 	case BPF_PROG_TYPE_SK_REUSEPORT:
5216 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5217 	case BPF_PROG_TYPE_CGROUP_SKB:
5218 		if (t == BPF_WRITE)
5219 			return false;
5220 		fallthrough;
5221 
5222 	/* Program types with direct read + write access go here! */
5223 	case BPF_PROG_TYPE_SCHED_CLS:
5224 	case BPF_PROG_TYPE_SCHED_ACT:
5225 	case BPF_PROG_TYPE_XDP:
5226 	case BPF_PROG_TYPE_LWT_XMIT:
5227 	case BPF_PROG_TYPE_SK_SKB:
5228 	case BPF_PROG_TYPE_SK_MSG:
5229 		if (meta)
5230 			return meta->pkt_access;
5231 
5232 		env->seen_direct_write = true;
5233 		return true;
5234 
5235 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5236 		if (t == BPF_WRITE)
5237 			env->seen_direct_write = true;
5238 
5239 		return true;
5240 
5241 	default:
5242 		return false;
5243 	}
5244 }
5245 
5246 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5247 			       int size, bool zero_size_allowed)
5248 {
5249 	struct bpf_reg_state *regs = cur_regs(env);
5250 	struct bpf_reg_state *reg = &regs[regno];
5251 	int err;
5252 
5253 	/* We may have added a variable offset to the packet pointer; but any
5254 	 * reg->range we have comes after that.  We are only checking the fixed
5255 	 * offset.
5256 	 */
5257 
5258 	/* We don't allow negative numbers, because we aren't tracking enough
5259 	 * detail to prove they're safe.
5260 	 */
5261 	if (reg->smin_value < 0) {
5262 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5263 			regno);
5264 		return -EACCES;
5265 	}
5266 
5267 	err = reg->range < 0 ? -EINVAL :
5268 	      __check_mem_access(env, regno, off, size, reg->range,
5269 				 zero_size_allowed);
5270 	if (err) {
5271 		verbose(env, "R%d offset is outside of the packet\n", regno);
5272 		return err;
5273 	}
5274 
5275 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5276 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5277 	 * otherwise find_good_pkt_pointers would have refused to set range info
5278 	 * that __check_mem_access would have rejected this pkt access.
5279 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5280 	 */
5281 	env->prog->aux->max_pkt_offset =
5282 		max_t(u32, env->prog->aux->max_pkt_offset,
5283 		      off + reg->umax_value + size - 1);
5284 
5285 	return err;
5286 }
5287 
5288 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5289 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5290 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5291 			    struct btf **btf, u32 *btf_id)
5292 {
5293 	struct bpf_insn_access_aux info = {
5294 		.reg_type = *reg_type,
5295 		.log = &env->log,
5296 	};
5297 
5298 	if (env->ops->is_valid_access &&
5299 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5300 		/* A non zero info.ctx_field_size indicates that this field is a
5301 		 * candidate for later verifier transformation to load the whole
5302 		 * field and then apply a mask when accessed with a narrower
5303 		 * access than actual ctx access size. A zero info.ctx_field_size
5304 		 * will only allow for whole field access and rejects any other
5305 		 * type of narrower access.
5306 		 */
5307 		*reg_type = info.reg_type;
5308 
5309 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5310 			*btf = info.btf;
5311 			*btf_id = info.btf_id;
5312 		} else {
5313 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5314 		}
5315 		/* remember the offset of last byte accessed in ctx */
5316 		if (env->prog->aux->max_ctx_offset < off + size)
5317 			env->prog->aux->max_ctx_offset = off + size;
5318 		return 0;
5319 	}
5320 
5321 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5322 	return -EACCES;
5323 }
5324 
5325 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5326 				  int size)
5327 {
5328 	if (size < 0 || off < 0 ||
5329 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5330 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5331 			off, size);
5332 		return -EACCES;
5333 	}
5334 	return 0;
5335 }
5336 
5337 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5338 			     u32 regno, int off, int size,
5339 			     enum bpf_access_type t)
5340 {
5341 	struct bpf_reg_state *regs = cur_regs(env);
5342 	struct bpf_reg_state *reg = &regs[regno];
5343 	struct bpf_insn_access_aux info = {};
5344 	bool valid;
5345 
5346 	if (reg->smin_value < 0) {
5347 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5348 			regno);
5349 		return -EACCES;
5350 	}
5351 
5352 	switch (reg->type) {
5353 	case PTR_TO_SOCK_COMMON:
5354 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5355 		break;
5356 	case PTR_TO_SOCKET:
5357 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5358 		break;
5359 	case PTR_TO_TCP_SOCK:
5360 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5361 		break;
5362 	case PTR_TO_XDP_SOCK:
5363 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5364 		break;
5365 	default:
5366 		valid = false;
5367 	}
5368 
5369 
5370 	if (valid) {
5371 		env->insn_aux_data[insn_idx].ctx_field_size =
5372 			info.ctx_field_size;
5373 		return 0;
5374 	}
5375 
5376 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5377 		regno, reg_type_str(env, reg->type), off, size);
5378 
5379 	return -EACCES;
5380 }
5381 
5382 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5383 {
5384 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5385 }
5386 
5387 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5388 {
5389 	const struct bpf_reg_state *reg = reg_state(env, regno);
5390 
5391 	return reg->type == PTR_TO_CTX;
5392 }
5393 
5394 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5395 {
5396 	const struct bpf_reg_state *reg = reg_state(env, regno);
5397 
5398 	return type_is_sk_pointer(reg->type);
5399 }
5400 
5401 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5402 {
5403 	const struct bpf_reg_state *reg = reg_state(env, regno);
5404 
5405 	return type_is_pkt_pointer(reg->type);
5406 }
5407 
5408 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5409 {
5410 	const struct bpf_reg_state *reg = reg_state(env, regno);
5411 
5412 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5413 	return reg->type == PTR_TO_FLOW_KEYS;
5414 }
5415 
5416 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5417 #ifdef CONFIG_NET
5418 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5419 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5420 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5421 #endif
5422 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5423 };
5424 
5425 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5426 {
5427 	/* A referenced register is always trusted. */
5428 	if (reg->ref_obj_id)
5429 		return true;
5430 
5431 	/* Types listed in the reg2btf_ids are always trusted */
5432 	if (reg2btf_ids[base_type(reg->type)])
5433 		return true;
5434 
5435 	/* If a register is not referenced, it is trusted if it has the
5436 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5437 	 * other type modifiers may be safe, but we elect to take an opt-in
5438 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5439 	 * not.
5440 	 *
5441 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5442 	 * for whether a register is trusted.
5443 	 */
5444 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5445 	       !bpf_type_has_unsafe_modifiers(reg->type);
5446 }
5447 
5448 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5449 {
5450 	return reg->type & MEM_RCU;
5451 }
5452 
5453 static void clear_trusted_flags(enum bpf_type_flag *flag)
5454 {
5455 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5456 }
5457 
5458 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5459 				   const struct bpf_reg_state *reg,
5460 				   int off, int size, bool strict)
5461 {
5462 	struct tnum reg_off;
5463 	int ip_align;
5464 
5465 	/* Byte size accesses are always allowed. */
5466 	if (!strict || size == 1)
5467 		return 0;
5468 
5469 	/* For platforms that do not have a Kconfig enabling
5470 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5471 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5472 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5473 	 * to this code only in strict mode where we want to emulate
5474 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5475 	 * unconditional IP align value of '2'.
5476 	 */
5477 	ip_align = 2;
5478 
5479 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5480 	if (!tnum_is_aligned(reg_off, size)) {
5481 		char tn_buf[48];
5482 
5483 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5484 		verbose(env,
5485 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5486 			ip_align, tn_buf, reg->off, off, size);
5487 		return -EACCES;
5488 	}
5489 
5490 	return 0;
5491 }
5492 
5493 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5494 				       const struct bpf_reg_state *reg,
5495 				       const char *pointer_desc,
5496 				       int off, int size, bool strict)
5497 {
5498 	struct tnum reg_off;
5499 
5500 	/* Byte size accesses are always allowed. */
5501 	if (!strict || size == 1)
5502 		return 0;
5503 
5504 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5505 	if (!tnum_is_aligned(reg_off, size)) {
5506 		char tn_buf[48];
5507 
5508 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5509 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5510 			pointer_desc, tn_buf, reg->off, off, size);
5511 		return -EACCES;
5512 	}
5513 
5514 	return 0;
5515 }
5516 
5517 static int check_ptr_alignment(struct bpf_verifier_env *env,
5518 			       const struct bpf_reg_state *reg, int off,
5519 			       int size, bool strict_alignment_once)
5520 {
5521 	bool strict = env->strict_alignment || strict_alignment_once;
5522 	const char *pointer_desc = "";
5523 
5524 	switch (reg->type) {
5525 	case PTR_TO_PACKET:
5526 	case PTR_TO_PACKET_META:
5527 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5528 		 * right in front, treat it the very same way.
5529 		 */
5530 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5531 	case PTR_TO_FLOW_KEYS:
5532 		pointer_desc = "flow keys ";
5533 		break;
5534 	case PTR_TO_MAP_KEY:
5535 		pointer_desc = "key ";
5536 		break;
5537 	case PTR_TO_MAP_VALUE:
5538 		pointer_desc = "value ";
5539 		break;
5540 	case PTR_TO_CTX:
5541 		pointer_desc = "context ";
5542 		break;
5543 	case PTR_TO_STACK:
5544 		pointer_desc = "stack ";
5545 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5546 		 * and check_stack_read_fixed_off() relies on stack accesses being
5547 		 * aligned.
5548 		 */
5549 		strict = true;
5550 		break;
5551 	case PTR_TO_SOCKET:
5552 		pointer_desc = "sock ";
5553 		break;
5554 	case PTR_TO_SOCK_COMMON:
5555 		pointer_desc = "sock_common ";
5556 		break;
5557 	case PTR_TO_TCP_SOCK:
5558 		pointer_desc = "tcp_sock ";
5559 		break;
5560 	case PTR_TO_XDP_SOCK:
5561 		pointer_desc = "xdp_sock ";
5562 		break;
5563 	default:
5564 		break;
5565 	}
5566 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5567 					   strict);
5568 }
5569 
5570 static int update_stack_depth(struct bpf_verifier_env *env,
5571 			      const struct bpf_func_state *func,
5572 			      int off)
5573 {
5574 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
5575 
5576 	if (stack >= -off)
5577 		return 0;
5578 
5579 	/* update known max for given subprogram */
5580 	env->subprog_info[func->subprogno].stack_depth = -off;
5581 	return 0;
5582 }
5583 
5584 /* starting from main bpf function walk all instructions of the function
5585  * and recursively walk all callees that given function can call.
5586  * Ignore jump and exit insns.
5587  * Since recursion is prevented by check_cfg() this algorithm
5588  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5589  */
5590 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5591 {
5592 	struct bpf_subprog_info *subprog = env->subprog_info;
5593 	struct bpf_insn *insn = env->prog->insnsi;
5594 	int depth = 0, frame = 0, i, subprog_end;
5595 	bool tail_call_reachable = false;
5596 	int ret_insn[MAX_CALL_FRAMES];
5597 	int ret_prog[MAX_CALL_FRAMES];
5598 	int j;
5599 
5600 	i = subprog[idx].start;
5601 process_func:
5602 	/* protect against potential stack overflow that might happen when
5603 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5604 	 * depth for such case down to 256 so that the worst case scenario
5605 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5606 	 * 8k).
5607 	 *
5608 	 * To get the idea what might happen, see an example:
5609 	 * func1 -> sub rsp, 128
5610 	 *  subfunc1 -> sub rsp, 256
5611 	 *  tailcall1 -> add rsp, 256
5612 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5613 	 *   subfunc2 -> sub rsp, 64
5614 	 *   subfunc22 -> sub rsp, 128
5615 	 *   tailcall2 -> add rsp, 128
5616 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5617 	 *
5618 	 * tailcall will unwind the current stack frame but it will not get rid
5619 	 * of caller's stack as shown on the example above.
5620 	 */
5621 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5622 		verbose(env,
5623 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5624 			depth);
5625 		return -EACCES;
5626 	}
5627 	/* round up to 32-bytes, since this is granularity
5628 	 * of interpreter stack size
5629 	 */
5630 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5631 	if (depth > MAX_BPF_STACK) {
5632 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5633 			frame + 1, depth);
5634 		return -EACCES;
5635 	}
5636 continue_func:
5637 	subprog_end = subprog[idx + 1].start;
5638 	for (; i < subprog_end; i++) {
5639 		int next_insn, sidx;
5640 
5641 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5642 			continue;
5643 		/* remember insn and function to return to */
5644 		ret_insn[frame] = i + 1;
5645 		ret_prog[frame] = idx;
5646 
5647 		/* find the callee */
5648 		next_insn = i + insn[i].imm + 1;
5649 		sidx = find_subprog(env, next_insn);
5650 		if (sidx < 0) {
5651 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5652 				  next_insn);
5653 			return -EFAULT;
5654 		}
5655 		if (subprog[sidx].is_async_cb) {
5656 			if (subprog[sidx].has_tail_call) {
5657 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5658 				return -EFAULT;
5659 			}
5660 			/* async callbacks don't increase bpf prog stack size unless called directly */
5661 			if (!bpf_pseudo_call(insn + i))
5662 				continue;
5663 		}
5664 		i = next_insn;
5665 		idx = sidx;
5666 
5667 		if (subprog[idx].has_tail_call)
5668 			tail_call_reachable = true;
5669 
5670 		frame++;
5671 		if (frame >= MAX_CALL_FRAMES) {
5672 			verbose(env, "the call stack of %d frames is too deep !\n",
5673 				frame);
5674 			return -E2BIG;
5675 		}
5676 		goto process_func;
5677 	}
5678 	/* if tail call got detected across bpf2bpf calls then mark each of the
5679 	 * currently present subprog frames as tail call reachable subprogs;
5680 	 * this info will be utilized by JIT so that we will be preserving the
5681 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5682 	 */
5683 	if (tail_call_reachable)
5684 		for (j = 0; j < frame; j++)
5685 			subprog[ret_prog[j]].tail_call_reachable = true;
5686 	if (subprog[0].tail_call_reachable)
5687 		env->prog->aux->tail_call_reachable = true;
5688 
5689 	/* end of for() loop means the last insn of the 'subprog'
5690 	 * was reached. Doesn't matter whether it was JA or EXIT
5691 	 */
5692 	if (frame == 0)
5693 		return 0;
5694 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5695 	frame--;
5696 	i = ret_insn[frame];
5697 	idx = ret_prog[frame];
5698 	goto continue_func;
5699 }
5700 
5701 static int check_max_stack_depth(struct bpf_verifier_env *env)
5702 {
5703 	struct bpf_subprog_info *si = env->subprog_info;
5704 	int ret;
5705 
5706 	for (int i = 0; i < env->subprog_cnt; i++) {
5707 		if (!i || si[i].is_async_cb) {
5708 			ret = check_max_stack_depth_subprog(env, i);
5709 			if (ret < 0)
5710 				return ret;
5711 		}
5712 		continue;
5713 	}
5714 	return 0;
5715 }
5716 
5717 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5718 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5719 				  const struct bpf_insn *insn, int idx)
5720 {
5721 	int start = idx + insn->imm + 1, subprog;
5722 
5723 	subprog = find_subprog(env, start);
5724 	if (subprog < 0) {
5725 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5726 			  start);
5727 		return -EFAULT;
5728 	}
5729 	return env->subprog_info[subprog].stack_depth;
5730 }
5731 #endif
5732 
5733 static int __check_buffer_access(struct bpf_verifier_env *env,
5734 				 const char *buf_info,
5735 				 const struct bpf_reg_state *reg,
5736 				 int regno, int off, int size)
5737 {
5738 	if (off < 0) {
5739 		verbose(env,
5740 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5741 			regno, buf_info, off, size);
5742 		return -EACCES;
5743 	}
5744 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5745 		char tn_buf[48];
5746 
5747 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5748 		verbose(env,
5749 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5750 			regno, off, tn_buf);
5751 		return -EACCES;
5752 	}
5753 
5754 	return 0;
5755 }
5756 
5757 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5758 				  const struct bpf_reg_state *reg,
5759 				  int regno, int off, int size)
5760 {
5761 	int err;
5762 
5763 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5764 	if (err)
5765 		return err;
5766 
5767 	if (off + size > env->prog->aux->max_tp_access)
5768 		env->prog->aux->max_tp_access = off + size;
5769 
5770 	return 0;
5771 }
5772 
5773 static int check_buffer_access(struct bpf_verifier_env *env,
5774 			       const struct bpf_reg_state *reg,
5775 			       int regno, int off, int size,
5776 			       bool zero_size_allowed,
5777 			       u32 *max_access)
5778 {
5779 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5780 	int err;
5781 
5782 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5783 	if (err)
5784 		return err;
5785 
5786 	if (off + size > *max_access)
5787 		*max_access = off + size;
5788 
5789 	return 0;
5790 }
5791 
5792 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5793 static void zext_32_to_64(struct bpf_reg_state *reg)
5794 {
5795 	reg->var_off = tnum_subreg(reg->var_off);
5796 	__reg_assign_32_into_64(reg);
5797 }
5798 
5799 /* truncate register to smaller size (in bytes)
5800  * must be called with size < BPF_REG_SIZE
5801  */
5802 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5803 {
5804 	u64 mask;
5805 
5806 	/* clear high bits in bit representation */
5807 	reg->var_off = tnum_cast(reg->var_off, size);
5808 
5809 	/* fix arithmetic bounds */
5810 	mask = ((u64)1 << (size * 8)) - 1;
5811 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5812 		reg->umin_value &= mask;
5813 		reg->umax_value &= mask;
5814 	} else {
5815 		reg->umin_value = 0;
5816 		reg->umax_value = mask;
5817 	}
5818 	reg->smin_value = reg->umin_value;
5819 	reg->smax_value = reg->umax_value;
5820 
5821 	/* If size is smaller than 32bit register the 32bit register
5822 	 * values are also truncated so we push 64-bit bounds into
5823 	 * 32-bit bounds. Above were truncated < 32-bits already.
5824 	 */
5825 	if (size >= 4)
5826 		return;
5827 	__reg_combine_64_into_32(reg);
5828 }
5829 
5830 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5831 {
5832 	/* A map is considered read-only if the following condition are true:
5833 	 *
5834 	 * 1) BPF program side cannot change any of the map content. The
5835 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5836 	 *    and was set at map creation time.
5837 	 * 2) The map value(s) have been initialized from user space by a
5838 	 *    loader and then "frozen", such that no new map update/delete
5839 	 *    operations from syscall side are possible for the rest of
5840 	 *    the map's lifetime from that point onwards.
5841 	 * 3) Any parallel/pending map update/delete operations from syscall
5842 	 *    side have been completed. Only after that point, it's safe to
5843 	 *    assume that map value(s) are immutable.
5844 	 */
5845 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
5846 	       READ_ONCE(map->frozen) &&
5847 	       !bpf_map_write_active(map);
5848 }
5849 
5850 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
5851 {
5852 	void *ptr;
5853 	u64 addr;
5854 	int err;
5855 
5856 	err = map->ops->map_direct_value_addr(map, &addr, off);
5857 	if (err)
5858 		return err;
5859 	ptr = (void *)(long)addr + off;
5860 
5861 	switch (size) {
5862 	case sizeof(u8):
5863 		*val = (u64)*(u8 *)ptr;
5864 		break;
5865 	case sizeof(u16):
5866 		*val = (u64)*(u16 *)ptr;
5867 		break;
5868 	case sizeof(u32):
5869 		*val = (u64)*(u32 *)ptr;
5870 		break;
5871 	case sizeof(u64):
5872 		*val = *(u64 *)ptr;
5873 		break;
5874 	default:
5875 		return -EINVAL;
5876 	}
5877 	return 0;
5878 }
5879 
5880 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
5881 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
5882 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
5883 
5884 /*
5885  * Allow list few fields as RCU trusted or full trusted.
5886  * This logic doesn't allow mix tagging and will be removed once GCC supports
5887  * btf_type_tag.
5888  */
5889 
5890 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
5891 BTF_TYPE_SAFE_RCU(struct task_struct) {
5892 	const cpumask_t *cpus_ptr;
5893 	struct css_set __rcu *cgroups;
5894 	struct task_struct __rcu *real_parent;
5895 	struct task_struct *group_leader;
5896 };
5897 
5898 BTF_TYPE_SAFE_RCU(struct cgroup) {
5899 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
5900 	struct kernfs_node *kn;
5901 };
5902 
5903 BTF_TYPE_SAFE_RCU(struct css_set) {
5904 	struct cgroup *dfl_cgrp;
5905 };
5906 
5907 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
5908 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
5909 	struct file __rcu *exe_file;
5910 };
5911 
5912 /* skb->sk, req->sk are not RCU protected, but we mark them as such
5913  * because bpf prog accessible sockets are SOCK_RCU_FREE.
5914  */
5915 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
5916 	struct sock *sk;
5917 };
5918 
5919 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
5920 	struct sock *sk;
5921 };
5922 
5923 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5924 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
5925 	struct seq_file *seq;
5926 };
5927 
5928 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
5929 	struct bpf_iter_meta *meta;
5930 	struct task_struct *task;
5931 };
5932 
5933 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5934 	struct file *file;
5935 };
5936 
5937 BTF_TYPE_SAFE_TRUSTED(struct file) {
5938 	struct inode *f_inode;
5939 };
5940 
5941 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
5942 	/* no negative dentry-s in places where bpf can see it */
5943 	struct inode *d_inode;
5944 };
5945 
5946 BTF_TYPE_SAFE_TRUSTED(struct socket) {
5947 	struct sock *sk;
5948 };
5949 
5950 static bool type_is_rcu(struct bpf_verifier_env *env,
5951 			struct bpf_reg_state *reg,
5952 			const char *field_name, u32 btf_id)
5953 {
5954 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5955 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
5956 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
5957 
5958 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
5959 }
5960 
5961 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
5962 				struct bpf_reg_state *reg,
5963 				const char *field_name, u32 btf_id)
5964 {
5965 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
5966 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
5967 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
5968 
5969 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
5970 }
5971 
5972 static bool type_is_trusted(struct bpf_verifier_env *env,
5973 			    struct bpf_reg_state *reg,
5974 			    const char *field_name, u32 btf_id)
5975 {
5976 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5977 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5978 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5979 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5980 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
5981 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
5982 
5983 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
5984 }
5985 
5986 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5987 				   struct bpf_reg_state *regs,
5988 				   int regno, int off, int size,
5989 				   enum bpf_access_type atype,
5990 				   int value_regno)
5991 {
5992 	struct bpf_reg_state *reg = regs + regno;
5993 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5994 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5995 	const char *field_name = NULL;
5996 	enum bpf_type_flag flag = 0;
5997 	u32 btf_id = 0;
5998 	int ret;
5999 
6000 	if (!env->allow_ptr_leaks) {
6001 		verbose(env,
6002 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6003 			tname);
6004 		return -EPERM;
6005 	}
6006 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6007 		verbose(env,
6008 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6009 			tname);
6010 		return -EINVAL;
6011 	}
6012 	if (off < 0) {
6013 		verbose(env,
6014 			"R%d is ptr_%s invalid negative access: off=%d\n",
6015 			regno, tname, off);
6016 		return -EACCES;
6017 	}
6018 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6019 		char tn_buf[48];
6020 
6021 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6022 		verbose(env,
6023 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6024 			regno, tname, off, tn_buf);
6025 		return -EACCES;
6026 	}
6027 
6028 	if (reg->type & MEM_USER) {
6029 		verbose(env,
6030 			"R%d is ptr_%s access user memory: off=%d\n",
6031 			regno, tname, off);
6032 		return -EACCES;
6033 	}
6034 
6035 	if (reg->type & MEM_PERCPU) {
6036 		verbose(env,
6037 			"R%d is ptr_%s access percpu memory: off=%d\n",
6038 			regno, tname, off);
6039 		return -EACCES;
6040 	}
6041 
6042 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6043 		if (!btf_is_kernel(reg->btf)) {
6044 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6045 			return -EFAULT;
6046 		}
6047 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6048 	} else {
6049 		/* Writes are permitted with default btf_struct_access for
6050 		 * program allocated objects (which always have ref_obj_id > 0),
6051 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6052 		 */
6053 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6054 			verbose(env, "only read is supported\n");
6055 			return -EACCES;
6056 		}
6057 
6058 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6059 		    !reg->ref_obj_id) {
6060 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6061 			return -EFAULT;
6062 		}
6063 
6064 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6065 	}
6066 
6067 	if (ret < 0)
6068 		return ret;
6069 
6070 	if (ret != PTR_TO_BTF_ID) {
6071 		/* just mark; */
6072 
6073 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6074 		/* If this is an untrusted pointer, all pointers formed by walking it
6075 		 * also inherit the untrusted flag.
6076 		 */
6077 		flag = PTR_UNTRUSTED;
6078 
6079 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6080 		/* By default any pointer obtained from walking a trusted pointer is no
6081 		 * longer trusted, unless the field being accessed has explicitly been
6082 		 * marked as inheriting its parent's state of trust (either full or RCU).
6083 		 * For example:
6084 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6085 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6086 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6087 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6088 		 *
6089 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6090 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6091 		 */
6092 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6093 			flag |= PTR_TRUSTED;
6094 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6095 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6096 				/* ignore __rcu tag and mark it MEM_RCU */
6097 				flag |= MEM_RCU;
6098 			} else if (flag & MEM_RCU ||
6099 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6100 				/* __rcu tagged pointers can be NULL */
6101 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6102 
6103 				/* We always trust them */
6104 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6105 				    flag & PTR_UNTRUSTED)
6106 					flag &= ~PTR_UNTRUSTED;
6107 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6108 				/* keep as-is */
6109 			} else {
6110 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6111 				clear_trusted_flags(&flag);
6112 			}
6113 		} else {
6114 			/*
6115 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6116 			 * aggressively mark as untrusted otherwise such
6117 			 * pointers will be plain PTR_TO_BTF_ID without flags
6118 			 * and will be allowed to be passed into helpers for
6119 			 * compat reasons.
6120 			 */
6121 			flag = PTR_UNTRUSTED;
6122 		}
6123 	} else {
6124 		/* Old compat. Deprecated */
6125 		clear_trusted_flags(&flag);
6126 	}
6127 
6128 	if (atype == BPF_READ && value_regno >= 0)
6129 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6130 
6131 	return 0;
6132 }
6133 
6134 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6135 				   struct bpf_reg_state *regs,
6136 				   int regno, int off, int size,
6137 				   enum bpf_access_type atype,
6138 				   int value_regno)
6139 {
6140 	struct bpf_reg_state *reg = regs + regno;
6141 	struct bpf_map *map = reg->map_ptr;
6142 	struct bpf_reg_state map_reg;
6143 	enum bpf_type_flag flag = 0;
6144 	const struct btf_type *t;
6145 	const char *tname;
6146 	u32 btf_id;
6147 	int ret;
6148 
6149 	if (!btf_vmlinux) {
6150 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6151 		return -ENOTSUPP;
6152 	}
6153 
6154 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6155 		verbose(env, "map_ptr access not supported for map type %d\n",
6156 			map->map_type);
6157 		return -ENOTSUPP;
6158 	}
6159 
6160 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6161 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6162 
6163 	if (!env->allow_ptr_leaks) {
6164 		verbose(env,
6165 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6166 			tname);
6167 		return -EPERM;
6168 	}
6169 
6170 	if (off < 0) {
6171 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6172 			regno, tname, off);
6173 		return -EACCES;
6174 	}
6175 
6176 	if (atype != BPF_READ) {
6177 		verbose(env, "only read from %s is supported\n", tname);
6178 		return -EACCES;
6179 	}
6180 
6181 	/* Simulate access to a PTR_TO_BTF_ID */
6182 	memset(&map_reg, 0, sizeof(map_reg));
6183 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6184 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6185 	if (ret < 0)
6186 		return ret;
6187 
6188 	if (value_regno >= 0)
6189 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6190 
6191 	return 0;
6192 }
6193 
6194 /* Check that the stack access at the given offset is within bounds. The
6195  * maximum valid offset is -1.
6196  *
6197  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6198  * -state->allocated_stack for reads.
6199  */
6200 static int check_stack_slot_within_bounds(int off,
6201 					  struct bpf_func_state *state,
6202 					  enum bpf_access_type t)
6203 {
6204 	int min_valid_off;
6205 
6206 	if (t == BPF_WRITE)
6207 		min_valid_off = -MAX_BPF_STACK;
6208 	else
6209 		min_valid_off = -state->allocated_stack;
6210 
6211 	if (off < min_valid_off || off > -1)
6212 		return -EACCES;
6213 	return 0;
6214 }
6215 
6216 /* Check that the stack access at 'regno + off' falls within the maximum stack
6217  * bounds.
6218  *
6219  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6220  */
6221 static int check_stack_access_within_bounds(
6222 		struct bpf_verifier_env *env,
6223 		int regno, int off, int access_size,
6224 		enum bpf_access_src src, enum bpf_access_type type)
6225 {
6226 	struct bpf_reg_state *regs = cur_regs(env);
6227 	struct bpf_reg_state *reg = regs + regno;
6228 	struct bpf_func_state *state = func(env, reg);
6229 	int min_off, max_off;
6230 	int err;
6231 	char *err_extra;
6232 
6233 	if (src == ACCESS_HELPER)
6234 		/* We don't know if helpers are reading or writing (or both). */
6235 		err_extra = " indirect access to";
6236 	else if (type == BPF_READ)
6237 		err_extra = " read from";
6238 	else
6239 		err_extra = " write to";
6240 
6241 	if (tnum_is_const(reg->var_off)) {
6242 		min_off = reg->var_off.value + off;
6243 		if (access_size > 0)
6244 			max_off = min_off + access_size - 1;
6245 		else
6246 			max_off = min_off;
6247 	} else {
6248 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6249 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6250 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6251 				err_extra, regno);
6252 			return -EACCES;
6253 		}
6254 		min_off = reg->smin_value + off;
6255 		if (access_size > 0)
6256 			max_off = reg->smax_value + off + access_size - 1;
6257 		else
6258 			max_off = min_off;
6259 	}
6260 
6261 	err = check_stack_slot_within_bounds(min_off, state, type);
6262 	if (!err)
6263 		err = check_stack_slot_within_bounds(max_off, state, type);
6264 
6265 	if (err) {
6266 		if (tnum_is_const(reg->var_off)) {
6267 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6268 				err_extra, regno, off, access_size);
6269 		} else {
6270 			char tn_buf[48];
6271 
6272 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6273 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6274 				err_extra, regno, tn_buf, access_size);
6275 		}
6276 	}
6277 	return err;
6278 }
6279 
6280 /* check whether memory at (regno + off) is accessible for t = (read | write)
6281  * if t==write, value_regno is a register which value is stored into memory
6282  * if t==read, value_regno is a register which will receive the value from memory
6283  * if t==write && value_regno==-1, some unknown value is stored into memory
6284  * if t==read && value_regno==-1, don't care what we read from memory
6285  */
6286 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6287 			    int off, int bpf_size, enum bpf_access_type t,
6288 			    int value_regno, bool strict_alignment_once)
6289 {
6290 	struct bpf_reg_state *regs = cur_regs(env);
6291 	struct bpf_reg_state *reg = regs + regno;
6292 	struct bpf_func_state *state;
6293 	int size, err = 0;
6294 
6295 	size = bpf_size_to_bytes(bpf_size);
6296 	if (size < 0)
6297 		return size;
6298 
6299 	/* alignment checks will add in reg->off themselves */
6300 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6301 	if (err)
6302 		return err;
6303 
6304 	/* for access checks, reg->off is just part of off */
6305 	off += reg->off;
6306 
6307 	if (reg->type == PTR_TO_MAP_KEY) {
6308 		if (t == BPF_WRITE) {
6309 			verbose(env, "write to change key R%d not allowed\n", regno);
6310 			return -EACCES;
6311 		}
6312 
6313 		err = check_mem_region_access(env, regno, off, size,
6314 					      reg->map_ptr->key_size, false);
6315 		if (err)
6316 			return err;
6317 		if (value_regno >= 0)
6318 			mark_reg_unknown(env, regs, value_regno);
6319 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6320 		struct btf_field *kptr_field = NULL;
6321 
6322 		if (t == BPF_WRITE && value_regno >= 0 &&
6323 		    is_pointer_value(env, value_regno)) {
6324 			verbose(env, "R%d leaks addr into map\n", value_regno);
6325 			return -EACCES;
6326 		}
6327 		err = check_map_access_type(env, regno, off, size, t);
6328 		if (err)
6329 			return err;
6330 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6331 		if (err)
6332 			return err;
6333 		if (tnum_is_const(reg->var_off))
6334 			kptr_field = btf_record_find(reg->map_ptr->record,
6335 						     off + reg->var_off.value, BPF_KPTR);
6336 		if (kptr_field) {
6337 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6338 		} else if (t == BPF_READ && value_regno >= 0) {
6339 			struct bpf_map *map = reg->map_ptr;
6340 
6341 			/* if map is read-only, track its contents as scalars */
6342 			if (tnum_is_const(reg->var_off) &&
6343 			    bpf_map_is_rdonly(map) &&
6344 			    map->ops->map_direct_value_addr) {
6345 				int map_off = off + reg->var_off.value;
6346 				u64 val = 0;
6347 
6348 				err = bpf_map_direct_read(map, map_off, size,
6349 							  &val);
6350 				if (err)
6351 					return err;
6352 
6353 				regs[value_regno].type = SCALAR_VALUE;
6354 				__mark_reg_known(&regs[value_regno], val);
6355 			} else {
6356 				mark_reg_unknown(env, regs, value_regno);
6357 			}
6358 		}
6359 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6360 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6361 
6362 		if (type_may_be_null(reg->type)) {
6363 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6364 				reg_type_str(env, reg->type));
6365 			return -EACCES;
6366 		}
6367 
6368 		if (t == BPF_WRITE && rdonly_mem) {
6369 			verbose(env, "R%d cannot write into %s\n",
6370 				regno, reg_type_str(env, reg->type));
6371 			return -EACCES;
6372 		}
6373 
6374 		if (t == BPF_WRITE && value_regno >= 0 &&
6375 		    is_pointer_value(env, value_regno)) {
6376 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6377 			return -EACCES;
6378 		}
6379 
6380 		err = check_mem_region_access(env, regno, off, size,
6381 					      reg->mem_size, false);
6382 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6383 			mark_reg_unknown(env, regs, value_regno);
6384 	} else if (reg->type == PTR_TO_CTX) {
6385 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6386 		struct btf *btf = NULL;
6387 		u32 btf_id = 0;
6388 
6389 		if (t == BPF_WRITE && value_regno >= 0 &&
6390 		    is_pointer_value(env, value_regno)) {
6391 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6392 			return -EACCES;
6393 		}
6394 
6395 		err = check_ptr_off_reg(env, reg, regno);
6396 		if (err < 0)
6397 			return err;
6398 
6399 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6400 				       &btf_id);
6401 		if (err)
6402 			verbose_linfo(env, insn_idx, "; ");
6403 		if (!err && t == BPF_READ && value_regno >= 0) {
6404 			/* ctx access returns either a scalar, or a
6405 			 * PTR_TO_PACKET[_META,_END]. In the latter
6406 			 * case, we know the offset is zero.
6407 			 */
6408 			if (reg_type == SCALAR_VALUE) {
6409 				mark_reg_unknown(env, regs, value_regno);
6410 			} else {
6411 				mark_reg_known_zero(env, regs,
6412 						    value_regno);
6413 				if (type_may_be_null(reg_type))
6414 					regs[value_regno].id = ++env->id_gen;
6415 				/* A load of ctx field could have different
6416 				 * actual load size with the one encoded in the
6417 				 * insn. When the dst is PTR, it is for sure not
6418 				 * a sub-register.
6419 				 */
6420 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6421 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6422 					regs[value_regno].btf = btf;
6423 					regs[value_regno].btf_id = btf_id;
6424 				}
6425 			}
6426 			regs[value_regno].type = reg_type;
6427 		}
6428 
6429 	} else if (reg->type == PTR_TO_STACK) {
6430 		/* Basic bounds checks. */
6431 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6432 		if (err)
6433 			return err;
6434 
6435 		state = func(env, reg);
6436 		err = update_stack_depth(env, state, off);
6437 		if (err)
6438 			return err;
6439 
6440 		if (t == BPF_READ)
6441 			err = check_stack_read(env, regno, off, size,
6442 					       value_regno);
6443 		else
6444 			err = check_stack_write(env, regno, off, size,
6445 						value_regno, insn_idx);
6446 	} else if (reg_is_pkt_pointer(reg)) {
6447 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6448 			verbose(env, "cannot write into packet\n");
6449 			return -EACCES;
6450 		}
6451 		if (t == BPF_WRITE && value_regno >= 0 &&
6452 		    is_pointer_value(env, value_regno)) {
6453 			verbose(env, "R%d leaks addr into packet\n",
6454 				value_regno);
6455 			return -EACCES;
6456 		}
6457 		err = check_packet_access(env, regno, off, size, false);
6458 		if (!err && t == BPF_READ && value_regno >= 0)
6459 			mark_reg_unknown(env, regs, value_regno);
6460 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6461 		if (t == BPF_WRITE && value_regno >= 0 &&
6462 		    is_pointer_value(env, value_regno)) {
6463 			verbose(env, "R%d leaks addr into flow keys\n",
6464 				value_regno);
6465 			return -EACCES;
6466 		}
6467 
6468 		err = check_flow_keys_access(env, off, size);
6469 		if (!err && t == BPF_READ && value_regno >= 0)
6470 			mark_reg_unknown(env, regs, value_regno);
6471 	} else if (type_is_sk_pointer(reg->type)) {
6472 		if (t == BPF_WRITE) {
6473 			verbose(env, "R%d cannot write into %s\n",
6474 				regno, reg_type_str(env, reg->type));
6475 			return -EACCES;
6476 		}
6477 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6478 		if (!err && value_regno >= 0)
6479 			mark_reg_unknown(env, regs, value_regno);
6480 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6481 		err = check_tp_buffer_access(env, reg, regno, off, size);
6482 		if (!err && t == BPF_READ && value_regno >= 0)
6483 			mark_reg_unknown(env, regs, value_regno);
6484 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6485 		   !type_may_be_null(reg->type)) {
6486 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6487 					      value_regno);
6488 	} else if (reg->type == CONST_PTR_TO_MAP) {
6489 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6490 					      value_regno);
6491 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6492 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6493 		u32 *max_access;
6494 
6495 		if (rdonly_mem) {
6496 			if (t == BPF_WRITE) {
6497 				verbose(env, "R%d cannot write into %s\n",
6498 					regno, reg_type_str(env, reg->type));
6499 				return -EACCES;
6500 			}
6501 			max_access = &env->prog->aux->max_rdonly_access;
6502 		} else {
6503 			max_access = &env->prog->aux->max_rdwr_access;
6504 		}
6505 
6506 		err = check_buffer_access(env, reg, regno, off, size, false,
6507 					  max_access);
6508 
6509 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6510 			mark_reg_unknown(env, regs, value_regno);
6511 	} else {
6512 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6513 			reg_type_str(env, reg->type));
6514 		return -EACCES;
6515 	}
6516 
6517 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6518 	    regs[value_regno].type == SCALAR_VALUE) {
6519 		/* b/h/w load zero-extends, mark upper bits as known 0 */
6520 		coerce_reg_to_size(&regs[value_regno], size);
6521 	}
6522 	return err;
6523 }
6524 
6525 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6526 {
6527 	int load_reg;
6528 	int err;
6529 
6530 	switch (insn->imm) {
6531 	case BPF_ADD:
6532 	case BPF_ADD | BPF_FETCH:
6533 	case BPF_AND:
6534 	case BPF_AND | BPF_FETCH:
6535 	case BPF_OR:
6536 	case BPF_OR | BPF_FETCH:
6537 	case BPF_XOR:
6538 	case BPF_XOR | BPF_FETCH:
6539 	case BPF_XCHG:
6540 	case BPF_CMPXCHG:
6541 		break;
6542 	default:
6543 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6544 		return -EINVAL;
6545 	}
6546 
6547 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6548 		verbose(env, "invalid atomic operand size\n");
6549 		return -EINVAL;
6550 	}
6551 
6552 	/* check src1 operand */
6553 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6554 	if (err)
6555 		return err;
6556 
6557 	/* check src2 operand */
6558 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6559 	if (err)
6560 		return err;
6561 
6562 	if (insn->imm == BPF_CMPXCHG) {
6563 		/* Check comparison of R0 with memory location */
6564 		const u32 aux_reg = BPF_REG_0;
6565 
6566 		err = check_reg_arg(env, aux_reg, SRC_OP);
6567 		if (err)
6568 			return err;
6569 
6570 		if (is_pointer_value(env, aux_reg)) {
6571 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6572 			return -EACCES;
6573 		}
6574 	}
6575 
6576 	if (is_pointer_value(env, insn->src_reg)) {
6577 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6578 		return -EACCES;
6579 	}
6580 
6581 	if (is_ctx_reg(env, insn->dst_reg) ||
6582 	    is_pkt_reg(env, insn->dst_reg) ||
6583 	    is_flow_key_reg(env, insn->dst_reg) ||
6584 	    is_sk_reg(env, insn->dst_reg)) {
6585 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6586 			insn->dst_reg,
6587 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6588 		return -EACCES;
6589 	}
6590 
6591 	if (insn->imm & BPF_FETCH) {
6592 		if (insn->imm == BPF_CMPXCHG)
6593 			load_reg = BPF_REG_0;
6594 		else
6595 			load_reg = insn->src_reg;
6596 
6597 		/* check and record load of old value */
6598 		err = check_reg_arg(env, load_reg, DST_OP);
6599 		if (err)
6600 			return err;
6601 	} else {
6602 		/* This instruction accesses a memory location but doesn't
6603 		 * actually load it into a register.
6604 		 */
6605 		load_reg = -1;
6606 	}
6607 
6608 	/* Check whether we can read the memory, with second call for fetch
6609 	 * case to simulate the register fill.
6610 	 */
6611 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6612 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
6613 	if (!err && load_reg >= 0)
6614 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6615 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
6616 				       true);
6617 	if (err)
6618 		return err;
6619 
6620 	/* Check whether we can write into the same memory. */
6621 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6622 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
6623 	if (err)
6624 		return err;
6625 
6626 	return 0;
6627 }
6628 
6629 /* When register 'regno' is used to read the stack (either directly or through
6630  * a helper function) make sure that it's within stack boundary and, depending
6631  * on the access type, that all elements of the stack are initialized.
6632  *
6633  * 'off' includes 'regno->off', but not its dynamic part (if any).
6634  *
6635  * All registers that have been spilled on the stack in the slots within the
6636  * read offsets are marked as read.
6637  */
6638 static int check_stack_range_initialized(
6639 		struct bpf_verifier_env *env, int regno, int off,
6640 		int access_size, bool zero_size_allowed,
6641 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6642 {
6643 	struct bpf_reg_state *reg = reg_state(env, regno);
6644 	struct bpf_func_state *state = func(env, reg);
6645 	int err, min_off, max_off, i, j, slot, spi;
6646 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6647 	enum bpf_access_type bounds_check_type;
6648 	/* Some accesses can write anything into the stack, others are
6649 	 * read-only.
6650 	 */
6651 	bool clobber = false;
6652 
6653 	if (access_size == 0 && !zero_size_allowed) {
6654 		verbose(env, "invalid zero-sized read\n");
6655 		return -EACCES;
6656 	}
6657 
6658 	if (type == ACCESS_HELPER) {
6659 		/* The bounds checks for writes are more permissive than for
6660 		 * reads. However, if raw_mode is not set, we'll do extra
6661 		 * checks below.
6662 		 */
6663 		bounds_check_type = BPF_WRITE;
6664 		clobber = true;
6665 	} else {
6666 		bounds_check_type = BPF_READ;
6667 	}
6668 	err = check_stack_access_within_bounds(env, regno, off, access_size,
6669 					       type, bounds_check_type);
6670 	if (err)
6671 		return err;
6672 
6673 
6674 	if (tnum_is_const(reg->var_off)) {
6675 		min_off = max_off = reg->var_off.value + off;
6676 	} else {
6677 		/* Variable offset is prohibited for unprivileged mode for
6678 		 * simplicity since it requires corresponding support in
6679 		 * Spectre masking for stack ALU.
6680 		 * See also retrieve_ptr_limit().
6681 		 */
6682 		if (!env->bypass_spec_v1) {
6683 			char tn_buf[48];
6684 
6685 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6686 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6687 				regno, err_extra, tn_buf);
6688 			return -EACCES;
6689 		}
6690 		/* Only initialized buffer on stack is allowed to be accessed
6691 		 * with variable offset. With uninitialized buffer it's hard to
6692 		 * guarantee that whole memory is marked as initialized on
6693 		 * helper return since specific bounds are unknown what may
6694 		 * cause uninitialized stack leaking.
6695 		 */
6696 		if (meta && meta->raw_mode)
6697 			meta = NULL;
6698 
6699 		min_off = reg->smin_value + off;
6700 		max_off = reg->smax_value + off;
6701 	}
6702 
6703 	if (meta && meta->raw_mode) {
6704 		/* Ensure we won't be overwriting dynptrs when simulating byte
6705 		 * by byte access in check_helper_call using meta.access_size.
6706 		 * This would be a problem if we have a helper in the future
6707 		 * which takes:
6708 		 *
6709 		 *	helper(uninit_mem, len, dynptr)
6710 		 *
6711 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6712 		 * may end up writing to dynptr itself when touching memory from
6713 		 * arg 1. This can be relaxed on a case by case basis for known
6714 		 * safe cases, but reject due to the possibilitiy of aliasing by
6715 		 * default.
6716 		 */
6717 		for (i = min_off; i < max_off + access_size; i++) {
6718 			int stack_off = -i - 1;
6719 
6720 			spi = __get_spi(i);
6721 			/* raw_mode may write past allocated_stack */
6722 			if (state->allocated_stack <= stack_off)
6723 				continue;
6724 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6725 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6726 				return -EACCES;
6727 			}
6728 		}
6729 		meta->access_size = access_size;
6730 		meta->regno = regno;
6731 		return 0;
6732 	}
6733 
6734 	for (i = min_off; i < max_off + access_size; i++) {
6735 		u8 *stype;
6736 
6737 		slot = -i - 1;
6738 		spi = slot / BPF_REG_SIZE;
6739 		if (state->allocated_stack <= slot)
6740 			goto err;
6741 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6742 		if (*stype == STACK_MISC)
6743 			goto mark;
6744 		if ((*stype == STACK_ZERO) ||
6745 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6746 			if (clobber) {
6747 				/* helper can write anything into the stack */
6748 				*stype = STACK_MISC;
6749 			}
6750 			goto mark;
6751 		}
6752 
6753 		if (is_spilled_reg(&state->stack[spi]) &&
6754 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6755 		     env->allow_ptr_leaks)) {
6756 			if (clobber) {
6757 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6758 				for (j = 0; j < BPF_REG_SIZE; j++)
6759 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6760 			}
6761 			goto mark;
6762 		}
6763 
6764 err:
6765 		if (tnum_is_const(reg->var_off)) {
6766 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6767 				err_extra, regno, min_off, i - min_off, access_size);
6768 		} else {
6769 			char tn_buf[48];
6770 
6771 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6772 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6773 				err_extra, regno, tn_buf, i - min_off, access_size);
6774 		}
6775 		return -EACCES;
6776 mark:
6777 		/* reading any byte out of 8-byte 'spill_slot' will cause
6778 		 * the whole slot to be marked as 'read'
6779 		 */
6780 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
6781 			      state->stack[spi].spilled_ptr.parent,
6782 			      REG_LIVE_READ64);
6783 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6784 		 * be sure that whether stack slot is written to or not. Hence,
6785 		 * we must still conservatively propagate reads upwards even if
6786 		 * helper may write to the entire memory range.
6787 		 */
6788 	}
6789 	return update_stack_depth(env, state, min_off);
6790 }
6791 
6792 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6793 				   int access_size, bool zero_size_allowed,
6794 				   struct bpf_call_arg_meta *meta)
6795 {
6796 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6797 	u32 *max_access;
6798 
6799 	switch (base_type(reg->type)) {
6800 	case PTR_TO_PACKET:
6801 	case PTR_TO_PACKET_META:
6802 		return check_packet_access(env, regno, reg->off, access_size,
6803 					   zero_size_allowed);
6804 	case PTR_TO_MAP_KEY:
6805 		if (meta && meta->raw_mode) {
6806 			verbose(env, "R%d cannot write into %s\n", regno,
6807 				reg_type_str(env, reg->type));
6808 			return -EACCES;
6809 		}
6810 		return check_mem_region_access(env, regno, reg->off, access_size,
6811 					       reg->map_ptr->key_size, false);
6812 	case PTR_TO_MAP_VALUE:
6813 		if (check_map_access_type(env, regno, reg->off, access_size,
6814 					  meta && meta->raw_mode ? BPF_WRITE :
6815 					  BPF_READ))
6816 			return -EACCES;
6817 		return check_map_access(env, regno, reg->off, access_size,
6818 					zero_size_allowed, ACCESS_HELPER);
6819 	case PTR_TO_MEM:
6820 		if (type_is_rdonly_mem(reg->type)) {
6821 			if (meta && meta->raw_mode) {
6822 				verbose(env, "R%d cannot write into %s\n", regno,
6823 					reg_type_str(env, reg->type));
6824 				return -EACCES;
6825 			}
6826 		}
6827 		return check_mem_region_access(env, regno, reg->off,
6828 					       access_size, reg->mem_size,
6829 					       zero_size_allowed);
6830 	case PTR_TO_BUF:
6831 		if (type_is_rdonly_mem(reg->type)) {
6832 			if (meta && meta->raw_mode) {
6833 				verbose(env, "R%d cannot write into %s\n", regno,
6834 					reg_type_str(env, reg->type));
6835 				return -EACCES;
6836 			}
6837 
6838 			max_access = &env->prog->aux->max_rdonly_access;
6839 		} else {
6840 			max_access = &env->prog->aux->max_rdwr_access;
6841 		}
6842 		return check_buffer_access(env, reg, regno, reg->off,
6843 					   access_size, zero_size_allowed,
6844 					   max_access);
6845 	case PTR_TO_STACK:
6846 		return check_stack_range_initialized(
6847 				env,
6848 				regno, reg->off, access_size,
6849 				zero_size_allowed, ACCESS_HELPER, meta);
6850 	case PTR_TO_BTF_ID:
6851 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
6852 					       access_size, BPF_READ, -1);
6853 	case PTR_TO_CTX:
6854 		/* in case the function doesn't know how to access the context,
6855 		 * (because we are in a program of type SYSCALL for example), we
6856 		 * can not statically check its size.
6857 		 * Dynamically check it now.
6858 		 */
6859 		if (!env->ops->convert_ctx_access) {
6860 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
6861 			int offset = access_size - 1;
6862 
6863 			/* Allow zero-byte read from PTR_TO_CTX */
6864 			if (access_size == 0)
6865 				return zero_size_allowed ? 0 : -EACCES;
6866 
6867 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
6868 						atype, -1, false);
6869 		}
6870 
6871 		fallthrough;
6872 	default: /* scalar_value or invalid ptr */
6873 		/* Allow zero-byte read from NULL, regardless of pointer type */
6874 		if (zero_size_allowed && access_size == 0 &&
6875 		    register_is_null(reg))
6876 			return 0;
6877 
6878 		verbose(env, "R%d type=%s ", regno,
6879 			reg_type_str(env, reg->type));
6880 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
6881 		return -EACCES;
6882 	}
6883 }
6884 
6885 static int check_mem_size_reg(struct bpf_verifier_env *env,
6886 			      struct bpf_reg_state *reg, u32 regno,
6887 			      bool zero_size_allowed,
6888 			      struct bpf_call_arg_meta *meta)
6889 {
6890 	int err;
6891 
6892 	/* This is used to refine r0 return value bounds for helpers
6893 	 * that enforce this value as an upper bound on return values.
6894 	 * See do_refine_retval_range() for helpers that can refine
6895 	 * the return value. C type of helper is u32 so we pull register
6896 	 * bound from umax_value however, if negative verifier errors
6897 	 * out. Only upper bounds can be learned because retval is an
6898 	 * int type and negative retvals are allowed.
6899 	 */
6900 	meta->msize_max_value = reg->umax_value;
6901 
6902 	/* The register is SCALAR_VALUE; the access check
6903 	 * happens using its boundaries.
6904 	 */
6905 	if (!tnum_is_const(reg->var_off))
6906 		/* For unprivileged variable accesses, disable raw
6907 		 * mode so that the program is required to
6908 		 * initialize all the memory that the helper could
6909 		 * just partially fill up.
6910 		 */
6911 		meta = NULL;
6912 
6913 	if (reg->smin_value < 0) {
6914 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
6915 			regno);
6916 		return -EACCES;
6917 	}
6918 
6919 	if (reg->umin_value == 0) {
6920 		err = check_helper_mem_access(env, regno - 1, 0,
6921 					      zero_size_allowed,
6922 					      meta);
6923 		if (err)
6924 			return err;
6925 	}
6926 
6927 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
6928 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
6929 			regno);
6930 		return -EACCES;
6931 	}
6932 	err = check_helper_mem_access(env, regno - 1,
6933 				      reg->umax_value,
6934 				      zero_size_allowed, meta);
6935 	if (!err)
6936 		err = mark_chain_precision(env, regno);
6937 	return err;
6938 }
6939 
6940 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6941 		   u32 regno, u32 mem_size)
6942 {
6943 	bool may_be_null = type_may_be_null(reg->type);
6944 	struct bpf_reg_state saved_reg;
6945 	struct bpf_call_arg_meta meta;
6946 	int err;
6947 
6948 	if (register_is_null(reg))
6949 		return 0;
6950 
6951 	memset(&meta, 0, sizeof(meta));
6952 	/* Assuming that the register contains a value check if the memory
6953 	 * access is safe. Temporarily save and restore the register's state as
6954 	 * the conversion shouldn't be visible to a caller.
6955 	 */
6956 	if (may_be_null) {
6957 		saved_reg = *reg;
6958 		mark_ptr_not_null_reg(reg);
6959 	}
6960 
6961 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
6962 	/* Check access for BPF_WRITE */
6963 	meta.raw_mode = true;
6964 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
6965 
6966 	if (may_be_null)
6967 		*reg = saved_reg;
6968 
6969 	return err;
6970 }
6971 
6972 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6973 				    u32 regno)
6974 {
6975 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
6976 	bool may_be_null = type_may_be_null(mem_reg->type);
6977 	struct bpf_reg_state saved_reg;
6978 	struct bpf_call_arg_meta meta;
6979 	int err;
6980 
6981 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
6982 
6983 	memset(&meta, 0, sizeof(meta));
6984 
6985 	if (may_be_null) {
6986 		saved_reg = *mem_reg;
6987 		mark_ptr_not_null_reg(mem_reg);
6988 	}
6989 
6990 	err = check_mem_size_reg(env, reg, regno, true, &meta);
6991 	/* Check access for BPF_WRITE */
6992 	meta.raw_mode = true;
6993 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
6994 
6995 	if (may_be_null)
6996 		*mem_reg = saved_reg;
6997 	return err;
6998 }
6999 
7000 /* Implementation details:
7001  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7002  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7003  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7004  * Two separate bpf_obj_new will also have different reg->id.
7005  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7006  * clears reg->id after value_or_null->value transition, since the verifier only
7007  * cares about the range of access to valid map value pointer and doesn't care
7008  * about actual address of the map element.
7009  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7010  * reg->id > 0 after value_or_null->value transition. By doing so
7011  * two bpf_map_lookups will be considered two different pointers that
7012  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7013  * returned from bpf_obj_new.
7014  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7015  * dead-locks.
7016  * Since only one bpf_spin_lock is allowed the checks are simpler than
7017  * reg_is_refcounted() logic. The verifier needs to remember only
7018  * one spin_lock instead of array of acquired_refs.
7019  * cur_state->active_lock remembers which map value element or allocated
7020  * object got locked and clears it after bpf_spin_unlock.
7021  */
7022 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7023 			     bool is_lock)
7024 {
7025 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7026 	struct bpf_verifier_state *cur = env->cur_state;
7027 	bool is_const = tnum_is_const(reg->var_off);
7028 	u64 val = reg->var_off.value;
7029 	struct bpf_map *map = NULL;
7030 	struct btf *btf = NULL;
7031 	struct btf_record *rec;
7032 
7033 	if (!is_const) {
7034 		verbose(env,
7035 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7036 			regno);
7037 		return -EINVAL;
7038 	}
7039 	if (reg->type == PTR_TO_MAP_VALUE) {
7040 		map = reg->map_ptr;
7041 		if (!map->btf) {
7042 			verbose(env,
7043 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7044 				map->name);
7045 			return -EINVAL;
7046 		}
7047 	} else {
7048 		btf = reg->btf;
7049 	}
7050 
7051 	rec = reg_btf_record(reg);
7052 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7053 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7054 			map ? map->name : "kptr");
7055 		return -EINVAL;
7056 	}
7057 	if (rec->spin_lock_off != val + reg->off) {
7058 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7059 			val + reg->off, rec->spin_lock_off);
7060 		return -EINVAL;
7061 	}
7062 	if (is_lock) {
7063 		if (cur->active_lock.ptr) {
7064 			verbose(env,
7065 				"Locking two bpf_spin_locks are not allowed\n");
7066 			return -EINVAL;
7067 		}
7068 		if (map)
7069 			cur->active_lock.ptr = map;
7070 		else
7071 			cur->active_lock.ptr = btf;
7072 		cur->active_lock.id = reg->id;
7073 	} else {
7074 		void *ptr;
7075 
7076 		if (map)
7077 			ptr = map;
7078 		else
7079 			ptr = btf;
7080 
7081 		if (!cur->active_lock.ptr) {
7082 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7083 			return -EINVAL;
7084 		}
7085 		if (cur->active_lock.ptr != ptr ||
7086 		    cur->active_lock.id != reg->id) {
7087 			verbose(env, "bpf_spin_unlock of different lock\n");
7088 			return -EINVAL;
7089 		}
7090 
7091 		invalidate_non_owning_refs(env);
7092 
7093 		cur->active_lock.ptr = NULL;
7094 		cur->active_lock.id = 0;
7095 	}
7096 	return 0;
7097 }
7098 
7099 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7100 			      struct bpf_call_arg_meta *meta)
7101 {
7102 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7103 	bool is_const = tnum_is_const(reg->var_off);
7104 	struct bpf_map *map = reg->map_ptr;
7105 	u64 val = reg->var_off.value;
7106 
7107 	if (!is_const) {
7108 		verbose(env,
7109 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7110 			regno);
7111 		return -EINVAL;
7112 	}
7113 	if (!map->btf) {
7114 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7115 			map->name);
7116 		return -EINVAL;
7117 	}
7118 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7119 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7120 		return -EINVAL;
7121 	}
7122 	if (map->record->timer_off != val + reg->off) {
7123 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7124 			val + reg->off, map->record->timer_off);
7125 		return -EINVAL;
7126 	}
7127 	if (meta->map_ptr) {
7128 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7129 		return -EFAULT;
7130 	}
7131 	meta->map_uid = reg->map_uid;
7132 	meta->map_ptr = map;
7133 	return 0;
7134 }
7135 
7136 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7137 			     struct bpf_call_arg_meta *meta)
7138 {
7139 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7140 	struct bpf_map *map_ptr = reg->map_ptr;
7141 	struct btf_field *kptr_field;
7142 	u32 kptr_off;
7143 
7144 	if (!tnum_is_const(reg->var_off)) {
7145 		verbose(env,
7146 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7147 			regno);
7148 		return -EINVAL;
7149 	}
7150 	if (!map_ptr->btf) {
7151 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7152 			map_ptr->name);
7153 		return -EINVAL;
7154 	}
7155 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7156 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7157 		return -EINVAL;
7158 	}
7159 
7160 	meta->map_ptr = map_ptr;
7161 	kptr_off = reg->off + reg->var_off.value;
7162 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7163 	if (!kptr_field) {
7164 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7165 		return -EACCES;
7166 	}
7167 	if (kptr_field->type != BPF_KPTR_REF) {
7168 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7169 		return -EACCES;
7170 	}
7171 	meta->kptr_field = kptr_field;
7172 	return 0;
7173 }
7174 
7175 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7176  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7177  *
7178  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7179  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7180  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7181  *
7182  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7183  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7184  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7185  * mutate the view of the dynptr and also possibly destroy it. In the latter
7186  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7187  * memory that dynptr points to.
7188  *
7189  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7190  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7191  * readonly dynptr view yet, hence only the first case is tracked and checked.
7192  *
7193  * This is consistent with how C applies the const modifier to a struct object,
7194  * where the pointer itself inside bpf_dynptr becomes const but not what it
7195  * points to.
7196  *
7197  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7198  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7199  */
7200 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7201 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7202 {
7203 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7204 	int err;
7205 
7206 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7207 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7208 	 */
7209 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7210 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7211 		return -EFAULT;
7212 	}
7213 
7214 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7215 	 *		 constructing a mutable bpf_dynptr object.
7216 	 *
7217 	 *		 Currently, this is only possible with PTR_TO_STACK
7218 	 *		 pointing to a region of at least 16 bytes which doesn't
7219 	 *		 contain an existing bpf_dynptr.
7220 	 *
7221 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7222 	 *		 mutated or destroyed. However, the memory it points to
7223 	 *		 may be mutated.
7224 	 *
7225 	 *  None       - Points to a initialized dynptr that can be mutated and
7226 	 *		 destroyed, including mutation of the memory it points
7227 	 *		 to.
7228 	 */
7229 	if (arg_type & MEM_UNINIT) {
7230 		int i;
7231 
7232 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7233 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7234 			return -EINVAL;
7235 		}
7236 
7237 		/* we write BPF_DW bits (8 bytes) at a time */
7238 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7239 			err = check_mem_access(env, insn_idx, regno,
7240 					       i, BPF_DW, BPF_WRITE, -1, false);
7241 			if (err)
7242 				return err;
7243 		}
7244 
7245 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7246 	} else /* MEM_RDONLY and None case from above */ {
7247 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7248 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7249 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7250 			return -EINVAL;
7251 		}
7252 
7253 		if (!is_dynptr_reg_valid_init(env, reg)) {
7254 			verbose(env,
7255 				"Expected an initialized dynptr as arg #%d\n",
7256 				regno);
7257 			return -EINVAL;
7258 		}
7259 
7260 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7261 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7262 			verbose(env,
7263 				"Expected a dynptr of type %s as arg #%d\n",
7264 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7265 			return -EINVAL;
7266 		}
7267 
7268 		err = mark_dynptr_read(env, reg);
7269 	}
7270 	return err;
7271 }
7272 
7273 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7274 {
7275 	struct bpf_func_state *state = func(env, reg);
7276 
7277 	return state->stack[spi].spilled_ptr.ref_obj_id;
7278 }
7279 
7280 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7281 {
7282 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7283 }
7284 
7285 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7286 {
7287 	return meta->kfunc_flags & KF_ITER_NEW;
7288 }
7289 
7290 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7291 {
7292 	return meta->kfunc_flags & KF_ITER_NEXT;
7293 }
7294 
7295 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7296 {
7297 	return meta->kfunc_flags & KF_ITER_DESTROY;
7298 }
7299 
7300 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7301 {
7302 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7303 	 * kfunc is iter state pointer
7304 	 */
7305 	return arg == 0 && is_iter_kfunc(meta);
7306 }
7307 
7308 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7309 			    struct bpf_kfunc_call_arg_meta *meta)
7310 {
7311 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7312 	const struct btf_type *t;
7313 	const struct btf_param *arg;
7314 	int spi, err, i, nr_slots;
7315 	u32 btf_id;
7316 
7317 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7318 	arg = &btf_params(meta->func_proto)[0];
7319 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7320 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7321 	nr_slots = t->size / BPF_REG_SIZE;
7322 
7323 	if (is_iter_new_kfunc(meta)) {
7324 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7325 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7326 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7327 				iter_type_str(meta->btf, btf_id), regno);
7328 			return -EINVAL;
7329 		}
7330 
7331 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7332 			err = check_mem_access(env, insn_idx, regno,
7333 					       i, BPF_DW, BPF_WRITE, -1, false);
7334 			if (err)
7335 				return err;
7336 		}
7337 
7338 		err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7339 		if (err)
7340 			return err;
7341 	} else {
7342 		/* iter_next() or iter_destroy() expect initialized iter state*/
7343 		if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7344 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7345 				iter_type_str(meta->btf, btf_id), regno);
7346 			return -EINVAL;
7347 		}
7348 
7349 		spi = iter_get_spi(env, reg, nr_slots);
7350 		if (spi < 0)
7351 			return spi;
7352 
7353 		err = mark_iter_read(env, reg, spi, nr_slots);
7354 		if (err)
7355 			return err;
7356 
7357 		/* remember meta->iter info for process_iter_next_call() */
7358 		meta->iter.spi = spi;
7359 		meta->iter.frameno = reg->frameno;
7360 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7361 
7362 		if (is_iter_destroy_kfunc(meta)) {
7363 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7364 			if (err)
7365 				return err;
7366 		}
7367 	}
7368 
7369 	return 0;
7370 }
7371 
7372 /* process_iter_next_call() is called when verifier gets to iterator's next
7373  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7374  * to it as just "iter_next()" in comments below.
7375  *
7376  * BPF verifier relies on a crucial contract for any iter_next()
7377  * implementation: it should *eventually* return NULL, and once that happens
7378  * it should keep returning NULL. That is, once iterator exhausts elements to
7379  * iterate, it should never reset or spuriously return new elements.
7380  *
7381  * With the assumption of such contract, process_iter_next_call() simulates
7382  * a fork in the verifier state to validate loop logic correctness and safety
7383  * without having to simulate infinite amount of iterations.
7384  *
7385  * In current state, we first assume that iter_next() returned NULL and
7386  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7387  * conditions we should not form an infinite loop and should eventually reach
7388  * exit.
7389  *
7390  * Besides that, we also fork current state and enqueue it for later
7391  * verification. In a forked state we keep iterator state as ACTIVE
7392  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7393  * also bump iteration depth to prevent erroneous infinite loop detection
7394  * later on (see iter_active_depths_differ() comment for details). In this
7395  * state we assume that we'll eventually loop back to another iter_next()
7396  * calls (it could be in exactly same location or in some other instruction,
7397  * it doesn't matter, we don't make any unnecessary assumptions about this,
7398  * everything revolves around iterator state in a stack slot, not which
7399  * instruction is calling iter_next()). When that happens, we either will come
7400  * to iter_next() with equivalent state and can conclude that next iteration
7401  * will proceed in exactly the same way as we just verified, so it's safe to
7402  * assume that loop converges. If not, we'll go on another iteration
7403  * simulation with a different input state, until all possible starting states
7404  * are validated or we reach maximum number of instructions limit.
7405  *
7406  * This way, we will either exhaustively discover all possible input states
7407  * that iterator loop can start with and eventually will converge, or we'll
7408  * effectively regress into bounded loop simulation logic and either reach
7409  * maximum number of instructions if loop is not provably convergent, or there
7410  * is some statically known limit on number of iterations (e.g., if there is
7411  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7412  *
7413  * One very subtle but very important aspect is that we *always* simulate NULL
7414  * condition first (as the current state) before we simulate non-NULL case.
7415  * This has to do with intricacies of scalar precision tracking. By simulating
7416  * "exit condition" of iter_next() returning NULL first, we make sure all the
7417  * relevant precision marks *that will be set **after** we exit iterator loop*
7418  * are propagated backwards to common parent state of NULL and non-NULL
7419  * branches. Thanks to that, state equivalence checks done later in forked
7420  * state, when reaching iter_next() for ACTIVE iterator, can assume that
7421  * precision marks are finalized and won't change. Because simulating another
7422  * ACTIVE iterator iteration won't change them (because given same input
7423  * states we'll end up with exactly same output states which we are currently
7424  * comparing; and verification after the loop already propagated back what
7425  * needs to be **additionally** tracked as precise). It's subtle, grok
7426  * precision tracking for more intuitive understanding.
7427  */
7428 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7429 				  struct bpf_kfunc_call_arg_meta *meta)
7430 {
7431 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7432 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7433 	struct bpf_reg_state *cur_iter, *queued_iter;
7434 	int iter_frameno = meta->iter.frameno;
7435 	int iter_spi = meta->iter.spi;
7436 
7437 	BTF_TYPE_EMIT(struct bpf_iter);
7438 
7439 	cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7440 
7441 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7442 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7443 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7444 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7445 		return -EFAULT;
7446 	}
7447 
7448 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7449 		/* branch out active iter state */
7450 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7451 		if (!queued_st)
7452 			return -ENOMEM;
7453 
7454 		queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7455 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7456 		queued_iter->iter.depth++;
7457 
7458 		queued_fr = queued_st->frame[queued_st->curframe];
7459 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7460 	}
7461 
7462 	/* switch to DRAINED state, but keep the depth unchanged */
7463 	/* mark current iter state as drained and assume returned NULL */
7464 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7465 	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7466 
7467 	return 0;
7468 }
7469 
7470 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7471 {
7472 	return type == ARG_CONST_SIZE ||
7473 	       type == ARG_CONST_SIZE_OR_ZERO;
7474 }
7475 
7476 static bool arg_type_is_release(enum bpf_arg_type type)
7477 {
7478 	return type & OBJ_RELEASE;
7479 }
7480 
7481 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7482 {
7483 	return base_type(type) == ARG_PTR_TO_DYNPTR;
7484 }
7485 
7486 static int int_ptr_type_to_size(enum bpf_arg_type type)
7487 {
7488 	if (type == ARG_PTR_TO_INT)
7489 		return sizeof(u32);
7490 	else if (type == ARG_PTR_TO_LONG)
7491 		return sizeof(u64);
7492 
7493 	return -EINVAL;
7494 }
7495 
7496 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7497 				 const struct bpf_call_arg_meta *meta,
7498 				 enum bpf_arg_type *arg_type)
7499 {
7500 	if (!meta->map_ptr) {
7501 		/* kernel subsystem misconfigured verifier */
7502 		verbose(env, "invalid map_ptr to access map->type\n");
7503 		return -EACCES;
7504 	}
7505 
7506 	switch (meta->map_ptr->map_type) {
7507 	case BPF_MAP_TYPE_SOCKMAP:
7508 	case BPF_MAP_TYPE_SOCKHASH:
7509 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7510 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7511 		} else {
7512 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
7513 			return -EINVAL;
7514 		}
7515 		break;
7516 	case BPF_MAP_TYPE_BLOOM_FILTER:
7517 		if (meta->func_id == BPF_FUNC_map_peek_elem)
7518 			*arg_type = ARG_PTR_TO_MAP_VALUE;
7519 		break;
7520 	default:
7521 		break;
7522 	}
7523 	return 0;
7524 }
7525 
7526 struct bpf_reg_types {
7527 	const enum bpf_reg_type types[10];
7528 	u32 *btf_id;
7529 };
7530 
7531 static const struct bpf_reg_types sock_types = {
7532 	.types = {
7533 		PTR_TO_SOCK_COMMON,
7534 		PTR_TO_SOCKET,
7535 		PTR_TO_TCP_SOCK,
7536 		PTR_TO_XDP_SOCK,
7537 	},
7538 };
7539 
7540 #ifdef CONFIG_NET
7541 static const struct bpf_reg_types btf_id_sock_common_types = {
7542 	.types = {
7543 		PTR_TO_SOCK_COMMON,
7544 		PTR_TO_SOCKET,
7545 		PTR_TO_TCP_SOCK,
7546 		PTR_TO_XDP_SOCK,
7547 		PTR_TO_BTF_ID,
7548 		PTR_TO_BTF_ID | PTR_TRUSTED,
7549 	},
7550 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7551 };
7552 #endif
7553 
7554 static const struct bpf_reg_types mem_types = {
7555 	.types = {
7556 		PTR_TO_STACK,
7557 		PTR_TO_PACKET,
7558 		PTR_TO_PACKET_META,
7559 		PTR_TO_MAP_KEY,
7560 		PTR_TO_MAP_VALUE,
7561 		PTR_TO_MEM,
7562 		PTR_TO_MEM | MEM_RINGBUF,
7563 		PTR_TO_BUF,
7564 		PTR_TO_BTF_ID | PTR_TRUSTED,
7565 	},
7566 };
7567 
7568 static const struct bpf_reg_types int_ptr_types = {
7569 	.types = {
7570 		PTR_TO_STACK,
7571 		PTR_TO_PACKET,
7572 		PTR_TO_PACKET_META,
7573 		PTR_TO_MAP_KEY,
7574 		PTR_TO_MAP_VALUE,
7575 	},
7576 };
7577 
7578 static const struct bpf_reg_types spin_lock_types = {
7579 	.types = {
7580 		PTR_TO_MAP_VALUE,
7581 		PTR_TO_BTF_ID | MEM_ALLOC,
7582 	}
7583 };
7584 
7585 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7586 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7587 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7588 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7589 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7590 static const struct bpf_reg_types btf_ptr_types = {
7591 	.types = {
7592 		PTR_TO_BTF_ID,
7593 		PTR_TO_BTF_ID | PTR_TRUSTED,
7594 		PTR_TO_BTF_ID | MEM_RCU,
7595 	},
7596 };
7597 static const struct bpf_reg_types percpu_btf_ptr_types = {
7598 	.types = {
7599 		PTR_TO_BTF_ID | MEM_PERCPU,
7600 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7601 	}
7602 };
7603 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7604 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7605 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7606 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7607 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7608 static const struct bpf_reg_types dynptr_types = {
7609 	.types = {
7610 		PTR_TO_STACK,
7611 		CONST_PTR_TO_DYNPTR,
7612 	}
7613 };
7614 
7615 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7616 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
7617 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
7618 	[ARG_CONST_SIZE]		= &scalar_types,
7619 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
7620 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
7621 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
7622 	[ARG_PTR_TO_CTX]		= &context_types,
7623 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
7624 #ifdef CONFIG_NET
7625 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
7626 #endif
7627 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
7628 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
7629 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
7630 	[ARG_PTR_TO_MEM]		= &mem_types,
7631 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
7632 	[ARG_PTR_TO_INT]		= &int_ptr_types,
7633 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
7634 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
7635 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
7636 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
7637 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
7638 	[ARG_PTR_TO_TIMER]		= &timer_types,
7639 	[ARG_PTR_TO_KPTR]		= &kptr_types,
7640 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
7641 };
7642 
7643 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7644 			  enum bpf_arg_type arg_type,
7645 			  const u32 *arg_btf_id,
7646 			  struct bpf_call_arg_meta *meta)
7647 {
7648 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7649 	enum bpf_reg_type expected, type = reg->type;
7650 	const struct bpf_reg_types *compatible;
7651 	int i, j;
7652 
7653 	compatible = compatible_reg_types[base_type(arg_type)];
7654 	if (!compatible) {
7655 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7656 		return -EFAULT;
7657 	}
7658 
7659 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7660 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7661 	 *
7662 	 * Same for MAYBE_NULL:
7663 	 *
7664 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7665 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7666 	 *
7667 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7668 	 *
7669 	 * Therefore we fold these flags depending on the arg_type before comparison.
7670 	 */
7671 	if (arg_type & MEM_RDONLY)
7672 		type &= ~MEM_RDONLY;
7673 	if (arg_type & PTR_MAYBE_NULL)
7674 		type &= ~PTR_MAYBE_NULL;
7675 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
7676 		type &= ~DYNPTR_TYPE_FLAG_MASK;
7677 
7678 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
7679 		type &= ~MEM_ALLOC;
7680 
7681 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7682 		expected = compatible->types[i];
7683 		if (expected == NOT_INIT)
7684 			break;
7685 
7686 		if (type == expected)
7687 			goto found;
7688 	}
7689 
7690 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7691 	for (j = 0; j + 1 < i; j++)
7692 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7693 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7694 	return -EACCES;
7695 
7696 found:
7697 	if (base_type(reg->type) != PTR_TO_BTF_ID)
7698 		return 0;
7699 
7700 	if (compatible == &mem_types) {
7701 		if (!(arg_type & MEM_RDONLY)) {
7702 			verbose(env,
7703 				"%s() may write into memory pointed by R%d type=%s\n",
7704 				func_id_name(meta->func_id),
7705 				regno, reg_type_str(env, reg->type));
7706 			return -EACCES;
7707 		}
7708 		return 0;
7709 	}
7710 
7711 	switch ((int)reg->type) {
7712 	case PTR_TO_BTF_ID:
7713 	case PTR_TO_BTF_ID | PTR_TRUSTED:
7714 	case PTR_TO_BTF_ID | MEM_RCU:
7715 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7716 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7717 	{
7718 		/* For bpf_sk_release, it needs to match against first member
7719 		 * 'struct sock_common', hence make an exception for it. This
7720 		 * allows bpf_sk_release to work for multiple socket types.
7721 		 */
7722 		bool strict_type_match = arg_type_is_release(arg_type) &&
7723 					 meta->func_id != BPF_FUNC_sk_release;
7724 
7725 		if (type_may_be_null(reg->type) &&
7726 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7727 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7728 			return -EACCES;
7729 		}
7730 
7731 		if (!arg_btf_id) {
7732 			if (!compatible->btf_id) {
7733 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7734 				return -EFAULT;
7735 			}
7736 			arg_btf_id = compatible->btf_id;
7737 		}
7738 
7739 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
7740 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7741 				return -EACCES;
7742 		} else {
7743 			if (arg_btf_id == BPF_PTR_POISON) {
7744 				verbose(env, "verifier internal error:");
7745 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7746 					regno);
7747 				return -EACCES;
7748 			}
7749 
7750 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7751 						  btf_vmlinux, *arg_btf_id,
7752 						  strict_type_match)) {
7753 				verbose(env, "R%d is of type %s but %s is expected\n",
7754 					regno, btf_type_name(reg->btf, reg->btf_id),
7755 					btf_type_name(btf_vmlinux, *arg_btf_id));
7756 				return -EACCES;
7757 			}
7758 		}
7759 		break;
7760 	}
7761 	case PTR_TO_BTF_ID | MEM_ALLOC:
7762 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7763 		    meta->func_id != BPF_FUNC_kptr_xchg) {
7764 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7765 			return -EFAULT;
7766 		}
7767 		/* Handled by helper specific checks */
7768 		break;
7769 	case PTR_TO_BTF_ID | MEM_PERCPU:
7770 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7771 		/* Handled by helper specific checks */
7772 		break;
7773 	default:
7774 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7775 		return -EFAULT;
7776 	}
7777 	return 0;
7778 }
7779 
7780 static struct btf_field *
7781 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7782 {
7783 	struct btf_field *field;
7784 	struct btf_record *rec;
7785 
7786 	rec = reg_btf_record(reg);
7787 	if (!rec)
7788 		return NULL;
7789 
7790 	field = btf_record_find(rec, off, fields);
7791 	if (!field)
7792 		return NULL;
7793 
7794 	return field;
7795 }
7796 
7797 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7798 			   const struct bpf_reg_state *reg, int regno,
7799 			   enum bpf_arg_type arg_type)
7800 {
7801 	u32 type = reg->type;
7802 
7803 	/* When referenced register is passed to release function, its fixed
7804 	 * offset must be 0.
7805 	 *
7806 	 * We will check arg_type_is_release reg has ref_obj_id when storing
7807 	 * meta->release_regno.
7808 	 */
7809 	if (arg_type_is_release(arg_type)) {
7810 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7811 		 * may not directly point to the object being released, but to
7812 		 * dynptr pointing to such object, which might be at some offset
7813 		 * on the stack. In that case, we simply to fallback to the
7814 		 * default handling.
7815 		 */
7816 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7817 			return 0;
7818 
7819 		if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7820 			if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7821 				return __check_ptr_off_reg(env, reg, regno, true);
7822 
7823 			verbose(env, "R%d must have zero offset when passed to release func\n",
7824 				regno);
7825 			verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
7826 				btf_type_name(reg->btf, reg->btf_id), reg->off);
7827 			return -EINVAL;
7828 		}
7829 
7830 		/* Doing check_ptr_off_reg check for the offset will catch this
7831 		 * because fixed_off_ok is false, but checking here allows us
7832 		 * to give the user a better error message.
7833 		 */
7834 		if (reg->off) {
7835 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7836 				regno);
7837 			return -EINVAL;
7838 		}
7839 		return __check_ptr_off_reg(env, reg, regno, false);
7840 	}
7841 
7842 	switch (type) {
7843 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
7844 	case PTR_TO_STACK:
7845 	case PTR_TO_PACKET:
7846 	case PTR_TO_PACKET_META:
7847 	case PTR_TO_MAP_KEY:
7848 	case PTR_TO_MAP_VALUE:
7849 	case PTR_TO_MEM:
7850 	case PTR_TO_MEM | MEM_RDONLY:
7851 	case PTR_TO_MEM | MEM_RINGBUF:
7852 	case PTR_TO_BUF:
7853 	case PTR_TO_BUF | MEM_RDONLY:
7854 	case SCALAR_VALUE:
7855 		return 0;
7856 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
7857 	 * fixed offset.
7858 	 */
7859 	case PTR_TO_BTF_ID:
7860 	case PTR_TO_BTF_ID | MEM_ALLOC:
7861 	case PTR_TO_BTF_ID | PTR_TRUSTED:
7862 	case PTR_TO_BTF_ID | MEM_RCU:
7863 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
7864 		/* When referenced PTR_TO_BTF_ID is passed to release function,
7865 		 * its fixed offset must be 0. In the other cases, fixed offset
7866 		 * can be non-zero. This was already checked above. So pass
7867 		 * fixed_off_ok as true to allow fixed offset for all other
7868 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
7869 		 * still need to do checks instead of returning.
7870 		 */
7871 		return __check_ptr_off_reg(env, reg, regno, true);
7872 	default:
7873 		return __check_ptr_off_reg(env, reg, regno, false);
7874 	}
7875 }
7876 
7877 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
7878 						const struct bpf_func_proto *fn,
7879 						struct bpf_reg_state *regs)
7880 {
7881 	struct bpf_reg_state *state = NULL;
7882 	int i;
7883 
7884 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
7885 		if (arg_type_is_dynptr(fn->arg_type[i])) {
7886 			if (state) {
7887 				verbose(env, "verifier internal error: multiple dynptr args\n");
7888 				return NULL;
7889 			}
7890 			state = &regs[BPF_REG_1 + i];
7891 		}
7892 
7893 	if (!state)
7894 		verbose(env, "verifier internal error: no dynptr arg found\n");
7895 
7896 	return state;
7897 }
7898 
7899 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7900 {
7901 	struct bpf_func_state *state = func(env, reg);
7902 	int spi;
7903 
7904 	if (reg->type == CONST_PTR_TO_DYNPTR)
7905 		return reg->id;
7906 	spi = dynptr_get_spi(env, reg);
7907 	if (spi < 0)
7908 		return spi;
7909 	return state->stack[spi].spilled_ptr.id;
7910 }
7911 
7912 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7913 {
7914 	struct bpf_func_state *state = func(env, reg);
7915 	int spi;
7916 
7917 	if (reg->type == CONST_PTR_TO_DYNPTR)
7918 		return reg->ref_obj_id;
7919 	spi = dynptr_get_spi(env, reg);
7920 	if (spi < 0)
7921 		return spi;
7922 	return state->stack[spi].spilled_ptr.ref_obj_id;
7923 }
7924 
7925 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
7926 					    struct bpf_reg_state *reg)
7927 {
7928 	struct bpf_func_state *state = func(env, reg);
7929 	int spi;
7930 
7931 	if (reg->type == CONST_PTR_TO_DYNPTR)
7932 		return reg->dynptr.type;
7933 
7934 	spi = __get_spi(reg->off);
7935 	if (spi < 0) {
7936 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
7937 		return BPF_DYNPTR_TYPE_INVALID;
7938 	}
7939 
7940 	return state->stack[spi].spilled_ptr.dynptr.type;
7941 }
7942 
7943 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
7944 			  struct bpf_call_arg_meta *meta,
7945 			  const struct bpf_func_proto *fn,
7946 			  int insn_idx)
7947 {
7948 	u32 regno = BPF_REG_1 + arg;
7949 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7950 	enum bpf_arg_type arg_type = fn->arg_type[arg];
7951 	enum bpf_reg_type type = reg->type;
7952 	u32 *arg_btf_id = NULL;
7953 	int err = 0;
7954 
7955 	if (arg_type == ARG_DONTCARE)
7956 		return 0;
7957 
7958 	err = check_reg_arg(env, regno, SRC_OP);
7959 	if (err)
7960 		return err;
7961 
7962 	if (arg_type == ARG_ANYTHING) {
7963 		if (is_pointer_value(env, regno)) {
7964 			verbose(env, "R%d leaks addr into helper function\n",
7965 				regno);
7966 			return -EACCES;
7967 		}
7968 		return 0;
7969 	}
7970 
7971 	if (type_is_pkt_pointer(type) &&
7972 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
7973 		verbose(env, "helper access to the packet is not allowed\n");
7974 		return -EACCES;
7975 	}
7976 
7977 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
7978 		err = resolve_map_arg_type(env, meta, &arg_type);
7979 		if (err)
7980 			return err;
7981 	}
7982 
7983 	if (register_is_null(reg) && type_may_be_null(arg_type))
7984 		/* A NULL register has a SCALAR_VALUE type, so skip
7985 		 * type checking.
7986 		 */
7987 		goto skip_type_check;
7988 
7989 	/* arg_btf_id and arg_size are in a union. */
7990 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
7991 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
7992 		arg_btf_id = fn->arg_btf_id[arg];
7993 
7994 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
7995 	if (err)
7996 		return err;
7997 
7998 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
7999 	if (err)
8000 		return err;
8001 
8002 skip_type_check:
8003 	if (arg_type_is_release(arg_type)) {
8004 		if (arg_type_is_dynptr(arg_type)) {
8005 			struct bpf_func_state *state = func(env, reg);
8006 			int spi;
8007 
8008 			/* Only dynptr created on stack can be released, thus
8009 			 * the get_spi and stack state checks for spilled_ptr
8010 			 * should only be done before process_dynptr_func for
8011 			 * PTR_TO_STACK.
8012 			 */
8013 			if (reg->type == PTR_TO_STACK) {
8014 				spi = dynptr_get_spi(env, reg);
8015 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8016 					verbose(env, "arg %d is an unacquired reference\n", regno);
8017 					return -EINVAL;
8018 				}
8019 			} else {
8020 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8021 				return -EINVAL;
8022 			}
8023 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8024 			verbose(env, "R%d must be referenced when passed to release function\n",
8025 				regno);
8026 			return -EINVAL;
8027 		}
8028 		if (meta->release_regno) {
8029 			verbose(env, "verifier internal error: more than one release argument\n");
8030 			return -EFAULT;
8031 		}
8032 		meta->release_regno = regno;
8033 	}
8034 
8035 	if (reg->ref_obj_id) {
8036 		if (meta->ref_obj_id) {
8037 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8038 				regno, reg->ref_obj_id,
8039 				meta->ref_obj_id);
8040 			return -EFAULT;
8041 		}
8042 		meta->ref_obj_id = reg->ref_obj_id;
8043 	}
8044 
8045 	switch (base_type(arg_type)) {
8046 	case ARG_CONST_MAP_PTR:
8047 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8048 		if (meta->map_ptr) {
8049 			/* Use map_uid (which is unique id of inner map) to reject:
8050 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8051 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8052 			 * if (inner_map1 && inner_map2) {
8053 			 *     timer = bpf_map_lookup_elem(inner_map1);
8054 			 *     if (timer)
8055 			 *         // mismatch would have been allowed
8056 			 *         bpf_timer_init(timer, inner_map2);
8057 			 * }
8058 			 *
8059 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8060 			 */
8061 			if (meta->map_ptr != reg->map_ptr ||
8062 			    meta->map_uid != reg->map_uid) {
8063 				verbose(env,
8064 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8065 					meta->map_uid, reg->map_uid);
8066 				return -EINVAL;
8067 			}
8068 		}
8069 		meta->map_ptr = reg->map_ptr;
8070 		meta->map_uid = reg->map_uid;
8071 		break;
8072 	case ARG_PTR_TO_MAP_KEY:
8073 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8074 		 * check that [key, key + map->key_size) are within
8075 		 * stack limits and initialized
8076 		 */
8077 		if (!meta->map_ptr) {
8078 			/* in function declaration map_ptr must come before
8079 			 * map_key, so that it's verified and known before
8080 			 * we have to check map_key here. Otherwise it means
8081 			 * that kernel subsystem misconfigured verifier
8082 			 */
8083 			verbose(env, "invalid map_ptr to access map->key\n");
8084 			return -EACCES;
8085 		}
8086 		err = check_helper_mem_access(env, regno,
8087 					      meta->map_ptr->key_size, false,
8088 					      NULL);
8089 		break;
8090 	case ARG_PTR_TO_MAP_VALUE:
8091 		if (type_may_be_null(arg_type) && register_is_null(reg))
8092 			return 0;
8093 
8094 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8095 		 * check [value, value + map->value_size) validity
8096 		 */
8097 		if (!meta->map_ptr) {
8098 			/* kernel subsystem misconfigured verifier */
8099 			verbose(env, "invalid map_ptr to access map->value\n");
8100 			return -EACCES;
8101 		}
8102 		meta->raw_mode = arg_type & MEM_UNINIT;
8103 		err = check_helper_mem_access(env, regno,
8104 					      meta->map_ptr->value_size, false,
8105 					      meta);
8106 		break;
8107 	case ARG_PTR_TO_PERCPU_BTF_ID:
8108 		if (!reg->btf_id) {
8109 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8110 			return -EACCES;
8111 		}
8112 		meta->ret_btf = reg->btf;
8113 		meta->ret_btf_id = reg->btf_id;
8114 		break;
8115 	case ARG_PTR_TO_SPIN_LOCK:
8116 		if (in_rbtree_lock_required_cb(env)) {
8117 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8118 			return -EACCES;
8119 		}
8120 		if (meta->func_id == BPF_FUNC_spin_lock) {
8121 			err = process_spin_lock(env, regno, true);
8122 			if (err)
8123 				return err;
8124 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8125 			err = process_spin_lock(env, regno, false);
8126 			if (err)
8127 				return err;
8128 		} else {
8129 			verbose(env, "verifier internal error\n");
8130 			return -EFAULT;
8131 		}
8132 		break;
8133 	case ARG_PTR_TO_TIMER:
8134 		err = process_timer_func(env, regno, meta);
8135 		if (err)
8136 			return err;
8137 		break;
8138 	case ARG_PTR_TO_FUNC:
8139 		meta->subprogno = reg->subprogno;
8140 		break;
8141 	case ARG_PTR_TO_MEM:
8142 		/* The access to this pointer is only checked when we hit the
8143 		 * next is_mem_size argument below.
8144 		 */
8145 		meta->raw_mode = arg_type & MEM_UNINIT;
8146 		if (arg_type & MEM_FIXED_SIZE) {
8147 			err = check_helper_mem_access(env, regno,
8148 						      fn->arg_size[arg], false,
8149 						      meta);
8150 		}
8151 		break;
8152 	case ARG_CONST_SIZE:
8153 		err = check_mem_size_reg(env, reg, regno, false, meta);
8154 		break;
8155 	case ARG_CONST_SIZE_OR_ZERO:
8156 		err = check_mem_size_reg(env, reg, regno, true, meta);
8157 		break;
8158 	case ARG_PTR_TO_DYNPTR:
8159 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8160 		if (err)
8161 			return err;
8162 		break;
8163 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8164 		if (!tnum_is_const(reg->var_off)) {
8165 			verbose(env, "R%d is not a known constant'\n",
8166 				regno);
8167 			return -EACCES;
8168 		}
8169 		meta->mem_size = reg->var_off.value;
8170 		err = mark_chain_precision(env, regno);
8171 		if (err)
8172 			return err;
8173 		break;
8174 	case ARG_PTR_TO_INT:
8175 	case ARG_PTR_TO_LONG:
8176 	{
8177 		int size = int_ptr_type_to_size(arg_type);
8178 
8179 		err = check_helper_mem_access(env, regno, size, false, meta);
8180 		if (err)
8181 			return err;
8182 		err = check_ptr_alignment(env, reg, 0, size, true);
8183 		break;
8184 	}
8185 	case ARG_PTR_TO_CONST_STR:
8186 	{
8187 		struct bpf_map *map = reg->map_ptr;
8188 		int map_off;
8189 		u64 map_addr;
8190 		char *str_ptr;
8191 
8192 		if (!bpf_map_is_rdonly(map)) {
8193 			verbose(env, "R%d does not point to a readonly map'\n", regno);
8194 			return -EACCES;
8195 		}
8196 
8197 		if (!tnum_is_const(reg->var_off)) {
8198 			verbose(env, "R%d is not a constant address'\n", regno);
8199 			return -EACCES;
8200 		}
8201 
8202 		if (!map->ops->map_direct_value_addr) {
8203 			verbose(env, "no direct value access support for this map type\n");
8204 			return -EACCES;
8205 		}
8206 
8207 		err = check_map_access(env, regno, reg->off,
8208 				       map->value_size - reg->off, false,
8209 				       ACCESS_HELPER);
8210 		if (err)
8211 			return err;
8212 
8213 		map_off = reg->off + reg->var_off.value;
8214 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8215 		if (err) {
8216 			verbose(env, "direct value access on string failed\n");
8217 			return err;
8218 		}
8219 
8220 		str_ptr = (char *)(long)(map_addr);
8221 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8222 			verbose(env, "string is not zero-terminated\n");
8223 			return -EINVAL;
8224 		}
8225 		break;
8226 	}
8227 	case ARG_PTR_TO_KPTR:
8228 		err = process_kptr_func(env, regno, meta);
8229 		if (err)
8230 			return err;
8231 		break;
8232 	}
8233 
8234 	return err;
8235 }
8236 
8237 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8238 {
8239 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8240 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8241 
8242 	if (func_id != BPF_FUNC_map_update_elem)
8243 		return false;
8244 
8245 	/* It's not possible to get access to a locked struct sock in these
8246 	 * contexts, so updating is safe.
8247 	 */
8248 	switch (type) {
8249 	case BPF_PROG_TYPE_TRACING:
8250 		if (eatype == BPF_TRACE_ITER)
8251 			return true;
8252 		break;
8253 	case BPF_PROG_TYPE_SOCKET_FILTER:
8254 	case BPF_PROG_TYPE_SCHED_CLS:
8255 	case BPF_PROG_TYPE_SCHED_ACT:
8256 	case BPF_PROG_TYPE_XDP:
8257 	case BPF_PROG_TYPE_SK_REUSEPORT:
8258 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8259 	case BPF_PROG_TYPE_SK_LOOKUP:
8260 		return true;
8261 	default:
8262 		break;
8263 	}
8264 
8265 	verbose(env, "cannot update sockmap in this context\n");
8266 	return false;
8267 }
8268 
8269 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8270 {
8271 	return env->prog->jit_requested &&
8272 	       bpf_jit_supports_subprog_tailcalls();
8273 }
8274 
8275 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8276 					struct bpf_map *map, int func_id)
8277 {
8278 	if (!map)
8279 		return 0;
8280 
8281 	/* We need a two way check, first is from map perspective ... */
8282 	switch (map->map_type) {
8283 	case BPF_MAP_TYPE_PROG_ARRAY:
8284 		if (func_id != BPF_FUNC_tail_call)
8285 			goto error;
8286 		break;
8287 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8288 		if (func_id != BPF_FUNC_perf_event_read &&
8289 		    func_id != BPF_FUNC_perf_event_output &&
8290 		    func_id != BPF_FUNC_skb_output &&
8291 		    func_id != BPF_FUNC_perf_event_read_value &&
8292 		    func_id != BPF_FUNC_xdp_output)
8293 			goto error;
8294 		break;
8295 	case BPF_MAP_TYPE_RINGBUF:
8296 		if (func_id != BPF_FUNC_ringbuf_output &&
8297 		    func_id != BPF_FUNC_ringbuf_reserve &&
8298 		    func_id != BPF_FUNC_ringbuf_query &&
8299 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8300 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8301 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8302 			goto error;
8303 		break;
8304 	case BPF_MAP_TYPE_USER_RINGBUF:
8305 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8306 			goto error;
8307 		break;
8308 	case BPF_MAP_TYPE_STACK_TRACE:
8309 		if (func_id != BPF_FUNC_get_stackid)
8310 			goto error;
8311 		break;
8312 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8313 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8314 		    func_id != BPF_FUNC_current_task_under_cgroup)
8315 			goto error;
8316 		break;
8317 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8318 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8319 		if (func_id != BPF_FUNC_get_local_storage)
8320 			goto error;
8321 		break;
8322 	case BPF_MAP_TYPE_DEVMAP:
8323 	case BPF_MAP_TYPE_DEVMAP_HASH:
8324 		if (func_id != BPF_FUNC_redirect_map &&
8325 		    func_id != BPF_FUNC_map_lookup_elem)
8326 			goto error;
8327 		break;
8328 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8329 	 * appear.
8330 	 */
8331 	case BPF_MAP_TYPE_CPUMAP:
8332 		if (func_id != BPF_FUNC_redirect_map)
8333 			goto error;
8334 		break;
8335 	case BPF_MAP_TYPE_XSKMAP:
8336 		if (func_id != BPF_FUNC_redirect_map &&
8337 		    func_id != BPF_FUNC_map_lookup_elem)
8338 			goto error;
8339 		break;
8340 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8341 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8342 		if (func_id != BPF_FUNC_map_lookup_elem)
8343 			goto error;
8344 		break;
8345 	case BPF_MAP_TYPE_SOCKMAP:
8346 		if (func_id != BPF_FUNC_sk_redirect_map &&
8347 		    func_id != BPF_FUNC_sock_map_update &&
8348 		    func_id != BPF_FUNC_map_delete_elem &&
8349 		    func_id != BPF_FUNC_msg_redirect_map &&
8350 		    func_id != BPF_FUNC_sk_select_reuseport &&
8351 		    func_id != BPF_FUNC_map_lookup_elem &&
8352 		    !may_update_sockmap(env, func_id))
8353 			goto error;
8354 		break;
8355 	case BPF_MAP_TYPE_SOCKHASH:
8356 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8357 		    func_id != BPF_FUNC_sock_hash_update &&
8358 		    func_id != BPF_FUNC_map_delete_elem &&
8359 		    func_id != BPF_FUNC_msg_redirect_hash &&
8360 		    func_id != BPF_FUNC_sk_select_reuseport &&
8361 		    func_id != BPF_FUNC_map_lookup_elem &&
8362 		    !may_update_sockmap(env, func_id))
8363 			goto error;
8364 		break;
8365 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8366 		if (func_id != BPF_FUNC_sk_select_reuseport)
8367 			goto error;
8368 		break;
8369 	case BPF_MAP_TYPE_QUEUE:
8370 	case BPF_MAP_TYPE_STACK:
8371 		if (func_id != BPF_FUNC_map_peek_elem &&
8372 		    func_id != BPF_FUNC_map_pop_elem &&
8373 		    func_id != BPF_FUNC_map_push_elem)
8374 			goto error;
8375 		break;
8376 	case BPF_MAP_TYPE_SK_STORAGE:
8377 		if (func_id != BPF_FUNC_sk_storage_get &&
8378 		    func_id != BPF_FUNC_sk_storage_delete &&
8379 		    func_id != BPF_FUNC_kptr_xchg)
8380 			goto error;
8381 		break;
8382 	case BPF_MAP_TYPE_INODE_STORAGE:
8383 		if (func_id != BPF_FUNC_inode_storage_get &&
8384 		    func_id != BPF_FUNC_inode_storage_delete &&
8385 		    func_id != BPF_FUNC_kptr_xchg)
8386 			goto error;
8387 		break;
8388 	case BPF_MAP_TYPE_TASK_STORAGE:
8389 		if (func_id != BPF_FUNC_task_storage_get &&
8390 		    func_id != BPF_FUNC_task_storage_delete &&
8391 		    func_id != BPF_FUNC_kptr_xchg)
8392 			goto error;
8393 		break;
8394 	case BPF_MAP_TYPE_CGRP_STORAGE:
8395 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8396 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8397 		    func_id != BPF_FUNC_kptr_xchg)
8398 			goto error;
8399 		break;
8400 	case BPF_MAP_TYPE_BLOOM_FILTER:
8401 		if (func_id != BPF_FUNC_map_peek_elem &&
8402 		    func_id != BPF_FUNC_map_push_elem)
8403 			goto error;
8404 		break;
8405 	default:
8406 		break;
8407 	}
8408 
8409 	/* ... and second from the function itself. */
8410 	switch (func_id) {
8411 	case BPF_FUNC_tail_call:
8412 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8413 			goto error;
8414 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8415 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8416 			return -EINVAL;
8417 		}
8418 		break;
8419 	case BPF_FUNC_perf_event_read:
8420 	case BPF_FUNC_perf_event_output:
8421 	case BPF_FUNC_perf_event_read_value:
8422 	case BPF_FUNC_skb_output:
8423 	case BPF_FUNC_xdp_output:
8424 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8425 			goto error;
8426 		break;
8427 	case BPF_FUNC_ringbuf_output:
8428 	case BPF_FUNC_ringbuf_reserve:
8429 	case BPF_FUNC_ringbuf_query:
8430 	case BPF_FUNC_ringbuf_reserve_dynptr:
8431 	case BPF_FUNC_ringbuf_submit_dynptr:
8432 	case BPF_FUNC_ringbuf_discard_dynptr:
8433 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8434 			goto error;
8435 		break;
8436 	case BPF_FUNC_user_ringbuf_drain:
8437 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8438 			goto error;
8439 		break;
8440 	case BPF_FUNC_get_stackid:
8441 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8442 			goto error;
8443 		break;
8444 	case BPF_FUNC_current_task_under_cgroup:
8445 	case BPF_FUNC_skb_under_cgroup:
8446 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8447 			goto error;
8448 		break;
8449 	case BPF_FUNC_redirect_map:
8450 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8451 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8452 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8453 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8454 			goto error;
8455 		break;
8456 	case BPF_FUNC_sk_redirect_map:
8457 	case BPF_FUNC_msg_redirect_map:
8458 	case BPF_FUNC_sock_map_update:
8459 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8460 			goto error;
8461 		break;
8462 	case BPF_FUNC_sk_redirect_hash:
8463 	case BPF_FUNC_msg_redirect_hash:
8464 	case BPF_FUNC_sock_hash_update:
8465 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8466 			goto error;
8467 		break;
8468 	case BPF_FUNC_get_local_storage:
8469 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8470 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8471 			goto error;
8472 		break;
8473 	case BPF_FUNC_sk_select_reuseport:
8474 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8475 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8476 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8477 			goto error;
8478 		break;
8479 	case BPF_FUNC_map_pop_elem:
8480 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8481 		    map->map_type != BPF_MAP_TYPE_STACK)
8482 			goto error;
8483 		break;
8484 	case BPF_FUNC_map_peek_elem:
8485 	case BPF_FUNC_map_push_elem:
8486 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8487 		    map->map_type != BPF_MAP_TYPE_STACK &&
8488 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8489 			goto error;
8490 		break;
8491 	case BPF_FUNC_map_lookup_percpu_elem:
8492 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8493 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8494 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8495 			goto error;
8496 		break;
8497 	case BPF_FUNC_sk_storage_get:
8498 	case BPF_FUNC_sk_storage_delete:
8499 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8500 			goto error;
8501 		break;
8502 	case BPF_FUNC_inode_storage_get:
8503 	case BPF_FUNC_inode_storage_delete:
8504 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8505 			goto error;
8506 		break;
8507 	case BPF_FUNC_task_storage_get:
8508 	case BPF_FUNC_task_storage_delete:
8509 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8510 			goto error;
8511 		break;
8512 	case BPF_FUNC_cgrp_storage_get:
8513 	case BPF_FUNC_cgrp_storage_delete:
8514 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8515 			goto error;
8516 		break;
8517 	default:
8518 		break;
8519 	}
8520 
8521 	return 0;
8522 error:
8523 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
8524 		map->map_type, func_id_name(func_id), func_id);
8525 	return -EINVAL;
8526 }
8527 
8528 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8529 {
8530 	int count = 0;
8531 
8532 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8533 		count++;
8534 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8535 		count++;
8536 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8537 		count++;
8538 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8539 		count++;
8540 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8541 		count++;
8542 
8543 	/* We only support one arg being in raw mode at the moment,
8544 	 * which is sufficient for the helper functions we have
8545 	 * right now.
8546 	 */
8547 	return count <= 1;
8548 }
8549 
8550 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8551 {
8552 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8553 	bool has_size = fn->arg_size[arg] != 0;
8554 	bool is_next_size = false;
8555 
8556 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8557 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8558 
8559 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8560 		return is_next_size;
8561 
8562 	return has_size == is_next_size || is_next_size == is_fixed;
8563 }
8564 
8565 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8566 {
8567 	/* bpf_xxx(..., buf, len) call will access 'len'
8568 	 * bytes from memory 'buf'. Both arg types need
8569 	 * to be paired, so make sure there's no buggy
8570 	 * helper function specification.
8571 	 */
8572 	if (arg_type_is_mem_size(fn->arg1_type) ||
8573 	    check_args_pair_invalid(fn, 0) ||
8574 	    check_args_pair_invalid(fn, 1) ||
8575 	    check_args_pair_invalid(fn, 2) ||
8576 	    check_args_pair_invalid(fn, 3) ||
8577 	    check_args_pair_invalid(fn, 4))
8578 		return false;
8579 
8580 	return true;
8581 }
8582 
8583 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8584 {
8585 	int i;
8586 
8587 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8588 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8589 			return !!fn->arg_btf_id[i];
8590 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8591 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
8592 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8593 		    /* arg_btf_id and arg_size are in a union. */
8594 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8595 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8596 			return false;
8597 	}
8598 
8599 	return true;
8600 }
8601 
8602 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8603 {
8604 	return check_raw_mode_ok(fn) &&
8605 	       check_arg_pair_ok(fn) &&
8606 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
8607 }
8608 
8609 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8610  * are now invalid, so turn them into unknown SCALAR_VALUE.
8611  *
8612  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8613  * since these slices point to packet data.
8614  */
8615 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8616 {
8617 	struct bpf_func_state *state;
8618 	struct bpf_reg_state *reg;
8619 
8620 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8621 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8622 			mark_reg_invalid(env, reg);
8623 	}));
8624 }
8625 
8626 enum {
8627 	AT_PKT_END = -1,
8628 	BEYOND_PKT_END = -2,
8629 };
8630 
8631 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8632 {
8633 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8634 	struct bpf_reg_state *reg = &state->regs[regn];
8635 
8636 	if (reg->type != PTR_TO_PACKET)
8637 		/* PTR_TO_PACKET_META is not supported yet */
8638 		return;
8639 
8640 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8641 	 * How far beyond pkt_end it goes is unknown.
8642 	 * if (!range_open) it's the case of pkt >= pkt_end
8643 	 * if (range_open) it's the case of pkt > pkt_end
8644 	 * hence this pointer is at least 1 byte bigger than pkt_end
8645 	 */
8646 	if (range_open)
8647 		reg->range = BEYOND_PKT_END;
8648 	else
8649 		reg->range = AT_PKT_END;
8650 }
8651 
8652 /* The pointer with the specified id has released its reference to kernel
8653  * resources. Identify all copies of the same pointer and clear the reference.
8654  */
8655 static int release_reference(struct bpf_verifier_env *env,
8656 			     int ref_obj_id)
8657 {
8658 	struct bpf_func_state *state;
8659 	struct bpf_reg_state *reg;
8660 	int err;
8661 
8662 	err = release_reference_state(cur_func(env), ref_obj_id);
8663 	if (err)
8664 		return err;
8665 
8666 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8667 		if (reg->ref_obj_id == ref_obj_id)
8668 			mark_reg_invalid(env, reg);
8669 	}));
8670 
8671 	return 0;
8672 }
8673 
8674 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8675 {
8676 	struct bpf_func_state *unused;
8677 	struct bpf_reg_state *reg;
8678 
8679 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8680 		if (type_is_non_owning_ref(reg->type))
8681 			mark_reg_invalid(env, reg);
8682 	}));
8683 }
8684 
8685 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8686 				    struct bpf_reg_state *regs)
8687 {
8688 	int i;
8689 
8690 	/* after the call registers r0 - r5 were scratched */
8691 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8692 		mark_reg_not_init(env, regs, caller_saved[i]);
8693 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8694 	}
8695 }
8696 
8697 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8698 				   struct bpf_func_state *caller,
8699 				   struct bpf_func_state *callee,
8700 				   int insn_idx);
8701 
8702 static int set_callee_state(struct bpf_verifier_env *env,
8703 			    struct bpf_func_state *caller,
8704 			    struct bpf_func_state *callee, int insn_idx);
8705 
8706 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8707 			     int *insn_idx, int subprog,
8708 			     set_callee_state_fn set_callee_state_cb)
8709 {
8710 	struct bpf_verifier_state *state = env->cur_state;
8711 	struct bpf_func_state *caller, *callee;
8712 	int err;
8713 
8714 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8715 		verbose(env, "the call stack of %d frames is too deep\n",
8716 			state->curframe + 2);
8717 		return -E2BIG;
8718 	}
8719 
8720 	caller = state->frame[state->curframe];
8721 	if (state->frame[state->curframe + 1]) {
8722 		verbose(env, "verifier bug. Frame %d already allocated\n",
8723 			state->curframe + 1);
8724 		return -EFAULT;
8725 	}
8726 
8727 	err = btf_check_subprog_call(env, subprog, caller->regs);
8728 	if (err == -EFAULT)
8729 		return err;
8730 	if (subprog_is_global(env, subprog)) {
8731 		if (err) {
8732 			verbose(env, "Caller passes invalid args into func#%d\n",
8733 				subprog);
8734 			return err;
8735 		} else {
8736 			if (env->log.level & BPF_LOG_LEVEL)
8737 				verbose(env,
8738 					"Func#%d is global and valid. Skipping.\n",
8739 					subprog);
8740 			clear_caller_saved_regs(env, caller->regs);
8741 
8742 			/* All global functions return a 64-bit SCALAR_VALUE */
8743 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
8744 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8745 
8746 			/* continue with next insn after call */
8747 			return 0;
8748 		}
8749 	}
8750 
8751 	/* set_callee_state is used for direct subprog calls, but we are
8752 	 * interested in validating only BPF helpers that can call subprogs as
8753 	 * callbacks
8754 	 */
8755 	if (set_callee_state_cb != set_callee_state) {
8756 		if (bpf_pseudo_kfunc_call(insn) &&
8757 		    !is_callback_calling_kfunc(insn->imm)) {
8758 			verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8759 				func_id_name(insn->imm), insn->imm);
8760 			return -EFAULT;
8761 		} else if (!bpf_pseudo_kfunc_call(insn) &&
8762 			   !is_callback_calling_function(insn->imm)) { /* helper */
8763 			verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8764 				func_id_name(insn->imm), insn->imm);
8765 			return -EFAULT;
8766 		}
8767 	}
8768 
8769 	if (insn->code == (BPF_JMP | BPF_CALL) &&
8770 	    insn->src_reg == 0 &&
8771 	    insn->imm == BPF_FUNC_timer_set_callback) {
8772 		struct bpf_verifier_state *async_cb;
8773 
8774 		/* there is no real recursion here. timer callbacks are async */
8775 		env->subprog_info[subprog].is_async_cb = true;
8776 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8777 					 *insn_idx, subprog);
8778 		if (!async_cb)
8779 			return -EFAULT;
8780 		callee = async_cb->frame[0];
8781 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
8782 
8783 		/* Convert bpf_timer_set_callback() args into timer callback args */
8784 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
8785 		if (err)
8786 			return err;
8787 
8788 		clear_caller_saved_regs(env, caller->regs);
8789 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
8790 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8791 		/* continue with next insn after call */
8792 		return 0;
8793 	}
8794 
8795 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8796 	if (!callee)
8797 		return -ENOMEM;
8798 	state->frame[state->curframe + 1] = callee;
8799 
8800 	/* callee cannot access r0, r6 - r9 for reading and has to write
8801 	 * into its own stack before reading from it.
8802 	 * callee can read/write into caller's stack
8803 	 */
8804 	init_func_state(env, callee,
8805 			/* remember the callsite, it will be used by bpf_exit */
8806 			*insn_idx /* callsite */,
8807 			state->curframe + 1 /* frameno within this callchain */,
8808 			subprog /* subprog number within this prog */);
8809 
8810 	/* Transfer references to the callee */
8811 	err = copy_reference_state(callee, caller);
8812 	if (err)
8813 		goto err_out;
8814 
8815 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
8816 	if (err)
8817 		goto err_out;
8818 
8819 	clear_caller_saved_regs(env, caller->regs);
8820 
8821 	/* only increment it after check_reg_arg() finished */
8822 	state->curframe++;
8823 
8824 	/* and go analyze first insn of the callee */
8825 	*insn_idx = env->subprog_info[subprog].start - 1;
8826 
8827 	if (env->log.level & BPF_LOG_LEVEL) {
8828 		verbose(env, "caller:\n");
8829 		print_verifier_state(env, caller, true);
8830 		verbose(env, "callee:\n");
8831 		print_verifier_state(env, callee, true);
8832 	}
8833 	return 0;
8834 
8835 err_out:
8836 	free_func_state(callee);
8837 	state->frame[state->curframe + 1] = NULL;
8838 	return err;
8839 }
8840 
8841 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8842 				   struct bpf_func_state *caller,
8843 				   struct bpf_func_state *callee)
8844 {
8845 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8846 	 *      void *callback_ctx, u64 flags);
8847 	 * callback_fn(struct bpf_map *map, void *key, void *value,
8848 	 *      void *callback_ctx);
8849 	 */
8850 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8851 
8852 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8853 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8854 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8855 
8856 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8857 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8858 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8859 
8860 	/* pointer to stack or null */
8861 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
8862 
8863 	/* unused */
8864 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8865 	return 0;
8866 }
8867 
8868 static int set_callee_state(struct bpf_verifier_env *env,
8869 			    struct bpf_func_state *caller,
8870 			    struct bpf_func_state *callee, int insn_idx)
8871 {
8872 	int i;
8873 
8874 	/* copy r1 - r5 args that callee can access.  The copy includes parent
8875 	 * pointers, which connects us up to the liveness chain
8876 	 */
8877 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
8878 		callee->regs[i] = caller->regs[i];
8879 	return 0;
8880 }
8881 
8882 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8883 			   int *insn_idx)
8884 {
8885 	int subprog, target_insn;
8886 
8887 	target_insn = *insn_idx + insn->imm + 1;
8888 	subprog = find_subprog(env, target_insn);
8889 	if (subprog < 0) {
8890 		verbose(env, "verifier bug. No program starts at insn %d\n",
8891 			target_insn);
8892 		return -EFAULT;
8893 	}
8894 
8895 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
8896 }
8897 
8898 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
8899 				       struct bpf_func_state *caller,
8900 				       struct bpf_func_state *callee,
8901 				       int insn_idx)
8902 {
8903 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
8904 	struct bpf_map *map;
8905 	int err;
8906 
8907 	if (bpf_map_ptr_poisoned(insn_aux)) {
8908 		verbose(env, "tail_call abusing map_ptr\n");
8909 		return -EINVAL;
8910 	}
8911 
8912 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
8913 	if (!map->ops->map_set_for_each_callback_args ||
8914 	    !map->ops->map_for_each_callback) {
8915 		verbose(env, "callback function not allowed for map\n");
8916 		return -ENOTSUPP;
8917 	}
8918 
8919 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
8920 	if (err)
8921 		return err;
8922 
8923 	callee->in_callback_fn = true;
8924 	callee->callback_ret_range = tnum_range(0, 1);
8925 	return 0;
8926 }
8927 
8928 static int set_loop_callback_state(struct bpf_verifier_env *env,
8929 				   struct bpf_func_state *caller,
8930 				   struct bpf_func_state *callee,
8931 				   int insn_idx)
8932 {
8933 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
8934 	 *	    u64 flags);
8935 	 * callback_fn(u32 index, void *callback_ctx);
8936 	 */
8937 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
8938 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8939 
8940 	/* unused */
8941 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8942 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8943 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8944 
8945 	callee->in_callback_fn = true;
8946 	callee->callback_ret_range = tnum_range(0, 1);
8947 	return 0;
8948 }
8949 
8950 static int set_timer_callback_state(struct bpf_verifier_env *env,
8951 				    struct bpf_func_state *caller,
8952 				    struct bpf_func_state *callee,
8953 				    int insn_idx)
8954 {
8955 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
8956 
8957 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
8958 	 * callback_fn(struct bpf_map *map, void *key, void *value);
8959 	 */
8960 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
8961 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
8962 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
8963 
8964 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8965 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8966 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
8967 
8968 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8969 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8970 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
8971 
8972 	/* unused */
8973 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8974 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8975 	callee->in_async_callback_fn = true;
8976 	callee->callback_ret_range = tnum_range(0, 1);
8977 	return 0;
8978 }
8979 
8980 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
8981 				       struct bpf_func_state *caller,
8982 				       struct bpf_func_state *callee,
8983 				       int insn_idx)
8984 {
8985 	/* bpf_find_vma(struct task_struct *task, u64 addr,
8986 	 *               void *callback_fn, void *callback_ctx, u64 flags)
8987 	 * (callback_fn)(struct task_struct *task,
8988 	 *               struct vm_area_struct *vma, void *callback_ctx);
8989 	 */
8990 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8991 
8992 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
8993 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8994 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
8995 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
8996 
8997 	/* pointer to stack or null */
8998 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
8999 
9000 	/* unused */
9001 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9002 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9003 	callee->in_callback_fn = true;
9004 	callee->callback_ret_range = tnum_range(0, 1);
9005 	return 0;
9006 }
9007 
9008 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9009 					   struct bpf_func_state *caller,
9010 					   struct bpf_func_state *callee,
9011 					   int insn_idx)
9012 {
9013 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9014 	 *			  callback_ctx, u64 flags);
9015 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9016 	 */
9017 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9018 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9019 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9020 
9021 	/* unused */
9022 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9023 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9024 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9025 
9026 	callee->in_callback_fn = true;
9027 	callee->callback_ret_range = tnum_range(0, 1);
9028 	return 0;
9029 }
9030 
9031 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9032 					 struct bpf_func_state *caller,
9033 					 struct bpf_func_state *callee,
9034 					 int insn_idx)
9035 {
9036 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9037 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9038 	 *
9039 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9040 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9041 	 * by this point, so look at 'root'
9042 	 */
9043 	struct btf_field *field;
9044 
9045 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9046 				      BPF_RB_ROOT);
9047 	if (!field || !field->graph_root.value_btf_id)
9048 		return -EFAULT;
9049 
9050 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9051 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9052 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9053 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9054 
9055 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9056 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9057 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9058 	callee->in_callback_fn = true;
9059 	callee->callback_ret_range = tnum_range(0, 1);
9060 	return 0;
9061 }
9062 
9063 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9064 
9065 /* Are we currently verifying the callback for a rbtree helper that must
9066  * be called with lock held? If so, no need to complain about unreleased
9067  * lock
9068  */
9069 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9070 {
9071 	struct bpf_verifier_state *state = env->cur_state;
9072 	struct bpf_insn *insn = env->prog->insnsi;
9073 	struct bpf_func_state *callee;
9074 	int kfunc_btf_id;
9075 
9076 	if (!state->curframe)
9077 		return false;
9078 
9079 	callee = state->frame[state->curframe];
9080 
9081 	if (!callee->in_callback_fn)
9082 		return false;
9083 
9084 	kfunc_btf_id = insn[callee->callsite].imm;
9085 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9086 }
9087 
9088 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9089 {
9090 	struct bpf_verifier_state *state = env->cur_state;
9091 	struct bpf_func_state *caller, *callee;
9092 	struct bpf_reg_state *r0;
9093 	int err;
9094 
9095 	callee = state->frame[state->curframe];
9096 	r0 = &callee->regs[BPF_REG_0];
9097 	if (r0->type == PTR_TO_STACK) {
9098 		/* technically it's ok to return caller's stack pointer
9099 		 * (or caller's caller's pointer) back to the caller,
9100 		 * since these pointers are valid. Only current stack
9101 		 * pointer will be invalid as soon as function exits,
9102 		 * but let's be conservative
9103 		 */
9104 		verbose(env, "cannot return stack pointer to the caller\n");
9105 		return -EINVAL;
9106 	}
9107 
9108 	caller = state->frame[state->curframe - 1];
9109 	if (callee->in_callback_fn) {
9110 		/* enforce R0 return value range [0, 1]. */
9111 		struct tnum range = callee->callback_ret_range;
9112 
9113 		if (r0->type != SCALAR_VALUE) {
9114 			verbose(env, "R0 not a scalar value\n");
9115 			return -EACCES;
9116 		}
9117 		if (!tnum_in(range, r0->var_off)) {
9118 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9119 			return -EINVAL;
9120 		}
9121 	} else {
9122 		/* return to the caller whatever r0 had in the callee */
9123 		caller->regs[BPF_REG_0] = *r0;
9124 	}
9125 
9126 	/* callback_fn frame should have released its own additions to parent's
9127 	 * reference state at this point, or check_reference_leak would
9128 	 * complain, hence it must be the same as the caller. There is no need
9129 	 * to copy it back.
9130 	 */
9131 	if (!callee->in_callback_fn) {
9132 		/* Transfer references to the caller */
9133 		err = copy_reference_state(caller, callee);
9134 		if (err)
9135 			return err;
9136 	}
9137 
9138 	*insn_idx = callee->callsite + 1;
9139 	if (env->log.level & BPF_LOG_LEVEL) {
9140 		verbose(env, "returning from callee:\n");
9141 		print_verifier_state(env, callee, true);
9142 		verbose(env, "to caller at %d:\n", *insn_idx);
9143 		print_verifier_state(env, caller, true);
9144 	}
9145 	/* clear everything in the callee */
9146 	free_func_state(callee);
9147 	state->frame[state->curframe--] = NULL;
9148 	return 0;
9149 }
9150 
9151 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9152 				   int func_id,
9153 				   struct bpf_call_arg_meta *meta)
9154 {
9155 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9156 
9157 	if (ret_type != RET_INTEGER)
9158 		return;
9159 
9160 	switch (func_id) {
9161 	case BPF_FUNC_get_stack:
9162 	case BPF_FUNC_get_task_stack:
9163 	case BPF_FUNC_probe_read_str:
9164 	case BPF_FUNC_probe_read_kernel_str:
9165 	case BPF_FUNC_probe_read_user_str:
9166 		ret_reg->smax_value = meta->msize_max_value;
9167 		ret_reg->s32_max_value = meta->msize_max_value;
9168 		ret_reg->smin_value = -MAX_ERRNO;
9169 		ret_reg->s32_min_value = -MAX_ERRNO;
9170 		reg_bounds_sync(ret_reg);
9171 		break;
9172 	case BPF_FUNC_get_smp_processor_id:
9173 		ret_reg->umax_value = nr_cpu_ids - 1;
9174 		ret_reg->u32_max_value = nr_cpu_ids - 1;
9175 		ret_reg->smax_value = nr_cpu_ids - 1;
9176 		ret_reg->s32_max_value = nr_cpu_ids - 1;
9177 		ret_reg->umin_value = 0;
9178 		ret_reg->u32_min_value = 0;
9179 		ret_reg->smin_value = 0;
9180 		ret_reg->s32_min_value = 0;
9181 		reg_bounds_sync(ret_reg);
9182 		break;
9183 	}
9184 }
9185 
9186 static int
9187 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9188 		int func_id, int insn_idx)
9189 {
9190 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9191 	struct bpf_map *map = meta->map_ptr;
9192 
9193 	if (func_id != BPF_FUNC_tail_call &&
9194 	    func_id != BPF_FUNC_map_lookup_elem &&
9195 	    func_id != BPF_FUNC_map_update_elem &&
9196 	    func_id != BPF_FUNC_map_delete_elem &&
9197 	    func_id != BPF_FUNC_map_push_elem &&
9198 	    func_id != BPF_FUNC_map_pop_elem &&
9199 	    func_id != BPF_FUNC_map_peek_elem &&
9200 	    func_id != BPF_FUNC_for_each_map_elem &&
9201 	    func_id != BPF_FUNC_redirect_map &&
9202 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9203 		return 0;
9204 
9205 	if (map == NULL) {
9206 		verbose(env, "kernel subsystem misconfigured verifier\n");
9207 		return -EINVAL;
9208 	}
9209 
9210 	/* In case of read-only, some additional restrictions
9211 	 * need to be applied in order to prevent altering the
9212 	 * state of the map from program side.
9213 	 */
9214 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9215 	    (func_id == BPF_FUNC_map_delete_elem ||
9216 	     func_id == BPF_FUNC_map_update_elem ||
9217 	     func_id == BPF_FUNC_map_push_elem ||
9218 	     func_id == BPF_FUNC_map_pop_elem)) {
9219 		verbose(env, "write into map forbidden\n");
9220 		return -EACCES;
9221 	}
9222 
9223 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9224 		bpf_map_ptr_store(aux, meta->map_ptr,
9225 				  !meta->map_ptr->bypass_spec_v1);
9226 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9227 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9228 				  !meta->map_ptr->bypass_spec_v1);
9229 	return 0;
9230 }
9231 
9232 static int
9233 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9234 		int func_id, int insn_idx)
9235 {
9236 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9237 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9238 	struct bpf_map *map = meta->map_ptr;
9239 	u64 val, max;
9240 	int err;
9241 
9242 	if (func_id != BPF_FUNC_tail_call)
9243 		return 0;
9244 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9245 		verbose(env, "kernel subsystem misconfigured verifier\n");
9246 		return -EINVAL;
9247 	}
9248 
9249 	reg = &regs[BPF_REG_3];
9250 	val = reg->var_off.value;
9251 	max = map->max_entries;
9252 
9253 	if (!(register_is_const(reg) && val < max)) {
9254 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9255 		return 0;
9256 	}
9257 
9258 	err = mark_chain_precision(env, BPF_REG_3);
9259 	if (err)
9260 		return err;
9261 	if (bpf_map_key_unseen(aux))
9262 		bpf_map_key_store(aux, val);
9263 	else if (!bpf_map_key_poisoned(aux) &&
9264 		  bpf_map_key_immediate(aux) != val)
9265 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9266 	return 0;
9267 }
9268 
9269 static int check_reference_leak(struct bpf_verifier_env *env)
9270 {
9271 	struct bpf_func_state *state = cur_func(env);
9272 	bool refs_lingering = false;
9273 	int i;
9274 
9275 	if (state->frameno && !state->in_callback_fn)
9276 		return 0;
9277 
9278 	for (i = 0; i < state->acquired_refs; i++) {
9279 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9280 			continue;
9281 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9282 			state->refs[i].id, state->refs[i].insn_idx);
9283 		refs_lingering = true;
9284 	}
9285 	return refs_lingering ? -EINVAL : 0;
9286 }
9287 
9288 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9289 				   struct bpf_reg_state *regs)
9290 {
9291 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9292 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9293 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9294 	struct bpf_bprintf_data data = {};
9295 	int err, fmt_map_off, num_args;
9296 	u64 fmt_addr;
9297 	char *fmt;
9298 
9299 	/* data must be an array of u64 */
9300 	if (data_len_reg->var_off.value % 8)
9301 		return -EINVAL;
9302 	num_args = data_len_reg->var_off.value / 8;
9303 
9304 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9305 	 * and map_direct_value_addr is set.
9306 	 */
9307 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9308 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9309 						  fmt_map_off);
9310 	if (err) {
9311 		verbose(env, "verifier bug\n");
9312 		return -EFAULT;
9313 	}
9314 	fmt = (char *)(long)fmt_addr + fmt_map_off;
9315 
9316 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9317 	 * can focus on validating the format specifiers.
9318 	 */
9319 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9320 	if (err < 0)
9321 		verbose(env, "Invalid format string\n");
9322 
9323 	return err;
9324 }
9325 
9326 static int check_get_func_ip(struct bpf_verifier_env *env)
9327 {
9328 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9329 	int func_id = BPF_FUNC_get_func_ip;
9330 
9331 	if (type == BPF_PROG_TYPE_TRACING) {
9332 		if (!bpf_prog_has_trampoline(env->prog)) {
9333 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9334 				func_id_name(func_id), func_id);
9335 			return -ENOTSUPP;
9336 		}
9337 		return 0;
9338 	} else if (type == BPF_PROG_TYPE_KPROBE) {
9339 		return 0;
9340 	}
9341 
9342 	verbose(env, "func %s#%d not supported for program type %d\n",
9343 		func_id_name(func_id), func_id, type);
9344 	return -ENOTSUPP;
9345 }
9346 
9347 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9348 {
9349 	return &env->insn_aux_data[env->insn_idx];
9350 }
9351 
9352 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9353 {
9354 	struct bpf_reg_state *regs = cur_regs(env);
9355 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9356 	bool reg_is_null = register_is_null(reg);
9357 
9358 	if (reg_is_null)
9359 		mark_chain_precision(env, BPF_REG_4);
9360 
9361 	return reg_is_null;
9362 }
9363 
9364 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9365 {
9366 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9367 
9368 	if (!state->initialized) {
9369 		state->initialized = 1;
9370 		state->fit_for_inline = loop_flag_is_zero(env);
9371 		state->callback_subprogno = subprogno;
9372 		return;
9373 	}
9374 
9375 	if (!state->fit_for_inline)
9376 		return;
9377 
9378 	state->fit_for_inline = (loop_flag_is_zero(env) &&
9379 				 state->callback_subprogno == subprogno);
9380 }
9381 
9382 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9383 			     int *insn_idx_p)
9384 {
9385 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9386 	const struct bpf_func_proto *fn = NULL;
9387 	enum bpf_return_type ret_type;
9388 	enum bpf_type_flag ret_flag;
9389 	struct bpf_reg_state *regs;
9390 	struct bpf_call_arg_meta meta;
9391 	int insn_idx = *insn_idx_p;
9392 	bool changes_data;
9393 	int i, err, func_id;
9394 
9395 	/* find function prototype */
9396 	func_id = insn->imm;
9397 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9398 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9399 			func_id);
9400 		return -EINVAL;
9401 	}
9402 
9403 	if (env->ops->get_func_proto)
9404 		fn = env->ops->get_func_proto(func_id, env->prog);
9405 	if (!fn) {
9406 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9407 			func_id);
9408 		return -EINVAL;
9409 	}
9410 
9411 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9412 	if (!env->prog->gpl_compatible && fn->gpl_only) {
9413 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9414 		return -EINVAL;
9415 	}
9416 
9417 	if (fn->allowed && !fn->allowed(env->prog)) {
9418 		verbose(env, "helper call is not allowed in probe\n");
9419 		return -EINVAL;
9420 	}
9421 
9422 	if (!env->prog->aux->sleepable && fn->might_sleep) {
9423 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
9424 		return -EINVAL;
9425 	}
9426 
9427 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
9428 	changes_data = bpf_helper_changes_pkt_data(fn->func);
9429 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9430 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9431 			func_id_name(func_id), func_id);
9432 		return -EINVAL;
9433 	}
9434 
9435 	memset(&meta, 0, sizeof(meta));
9436 	meta.pkt_access = fn->pkt_access;
9437 
9438 	err = check_func_proto(fn, func_id);
9439 	if (err) {
9440 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9441 			func_id_name(func_id), func_id);
9442 		return err;
9443 	}
9444 
9445 	if (env->cur_state->active_rcu_lock) {
9446 		if (fn->might_sleep) {
9447 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9448 				func_id_name(func_id), func_id);
9449 			return -EINVAL;
9450 		}
9451 
9452 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9453 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9454 	}
9455 
9456 	meta.func_id = func_id;
9457 	/* check args */
9458 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9459 		err = check_func_arg(env, i, &meta, fn, insn_idx);
9460 		if (err)
9461 			return err;
9462 	}
9463 
9464 	err = record_func_map(env, &meta, func_id, insn_idx);
9465 	if (err)
9466 		return err;
9467 
9468 	err = record_func_key(env, &meta, func_id, insn_idx);
9469 	if (err)
9470 		return err;
9471 
9472 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
9473 	 * is inferred from register state.
9474 	 */
9475 	for (i = 0; i < meta.access_size; i++) {
9476 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9477 				       BPF_WRITE, -1, false);
9478 		if (err)
9479 			return err;
9480 	}
9481 
9482 	regs = cur_regs(env);
9483 
9484 	if (meta.release_regno) {
9485 		err = -EINVAL;
9486 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9487 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9488 		 * is safe to do directly.
9489 		 */
9490 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9491 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9492 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9493 				return -EFAULT;
9494 			}
9495 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
9496 		} else if (meta.ref_obj_id) {
9497 			err = release_reference(env, meta.ref_obj_id);
9498 		} else if (register_is_null(&regs[meta.release_regno])) {
9499 			/* meta.ref_obj_id can only be 0 if register that is meant to be
9500 			 * released is NULL, which must be > R0.
9501 			 */
9502 			err = 0;
9503 		}
9504 		if (err) {
9505 			verbose(env, "func %s#%d reference has not been acquired before\n",
9506 				func_id_name(func_id), func_id);
9507 			return err;
9508 		}
9509 	}
9510 
9511 	switch (func_id) {
9512 	case BPF_FUNC_tail_call:
9513 		err = check_reference_leak(env);
9514 		if (err) {
9515 			verbose(env, "tail_call would lead to reference leak\n");
9516 			return err;
9517 		}
9518 		break;
9519 	case BPF_FUNC_get_local_storage:
9520 		/* check that flags argument in get_local_storage(map, flags) is 0,
9521 		 * this is required because get_local_storage() can't return an error.
9522 		 */
9523 		if (!register_is_null(&regs[BPF_REG_2])) {
9524 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9525 			return -EINVAL;
9526 		}
9527 		break;
9528 	case BPF_FUNC_for_each_map_elem:
9529 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9530 					set_map_elem_callback_state);
9531 		break;
9532 	case BPF_FUNC_timer_set_callback:
9533 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9534 					set_timer_callback_state);
9535 		break;
9536 	case BPF_FUNC_find_vma:
9537 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9538 					set_find_vma_callback_state);
9539 		break;
9540 	case BPF_FUNC_snprintf:
9541 		err = check_bpf_snprintf_call(env, regs);
9542 		break;
9543 	case BPF_FUNC_loop:
9544 		update_loop_inline_state(env, meta.subprogno);
9545 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9546 					set_loop_callback_state);
9547 		break;
9548 	case BPF_FUNC_dynptr_from_mem:
9549 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9550 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9551 				reg_type_str(env, regs[BPF_REG_1].type));
9552 			return -EACCES;
9553 		}
9554 		break;
9555 	case BPF_FUNC_set_retval:
9556 		if (prog_type == BPF_PROG_TYPE_LSM &&
9557 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9558 			if (!env->prog->aux->attach_func_proto->type) {
9559 				/* Make sure programs that attach to void
9560 				 * hooks don't try to modify return value.
9561 				 */
9562 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9563 				return -EINVAL;
9564 			}
9565 		}
9566 		break;
9567 	case BPF_FUNC_dynptr_data:
9568 	{
9569 		struct bpf_reg_state *reg;
9570 		int id, ref_obj_id;
9571 
9572 		reg = get_dynptr_arg_reg(env, fn, regs);
9573 		if (!reg)
9574 			return -EFAULT;
9575 
9576 
9577 		if (meta.dynptr_id) {
9578 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9579 			return -EFAULT;
9580 		}
9581 		if (meta.ref_obj_id) {
9582 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9583 			return -EFAULT;
9584 		}
9585 
9586 		id = dynptr_id(env, reg);
9587 		if (id < 0) {
9588 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9589 			return id;
9590 		}
9591 
9592 		ref_obj_id = dynptr_ref_obj_id(env, reg);
9593 		if (ref_obj_id < 0) {
9594 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9595 			return ref_obj_id;
9596 		}
9597 
9598 		meta.dynptr_id = id;
9599 		meta.ref_obj_id = ref_obj_id;
9600 
9601 		break;
9602 	}
9603 	case BPF_FUNC_dynptr_write:
9604 	{
9605 		enum bpf_dynptr_type dynptr_type;
9606 		struct bpf_reg_state *reg;
9607 
9608 		reg = get_dynptr_arg_reg(env, fn, regs);
9609 		if (!reg)
9610 			return -EFAULT;
9611 
9612 		dynptr_type = dynptr_get_type(env, reg);
9613 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9614 			return -EFAULT;
9615 
9616 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9617 			/* this will trigger clear_all_pkt_pointers(), which will
9618 			 * invalidate all dynptr slices associated with the skb
9619 			 */
9620 			changes_data = true;
9621 
9622 		break;
9623 	}
9624 	case BPF_FUNC_user_ringbuf_drain:
9625 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9626 					set_user_ringbuf_callback_state);
9627 		break;
9628 	}
9629 
9630 	if (err)
9631 		return err;
9632 
9633 	/* reset caller saved regs */
9634 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9635 		mark_reg_not_init(env, regs, caller_saved[i]);
9636 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9637 	}
9638 
9639 	/* helper call returns 64-bit value. */
9640 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9641 
9642 	/* update return register (already marked as written above) */
9643 	ret_type = fn->ret_type;
9644 	ret_flag = type_flag(ret_type);
9645 
9646 	switch (base_type(ret_type)) {
9647 	case RET_INTEGER:
9648 		/* sets type to SCALAR_VALUE */
9649 		mark_reg_unknown(env, regs, BPF_REG_0);
9650 		break;
9651 	case RET_VOID:
9652 		regs[BPF_REG_0].type = NOT_INIT;
9653 		break;
9654 	case RET_PTR_TO_MAP_VALUE:
9655 		/* There is no offset yet applied, variable or fixed */
9656 		mark_reg_known_zero(env, regs, BPF_REG_0);
9657 		/* remember map_ptr, so that check_map_access()
9658 		 * can check 'value_size' boundary of memory access
9659 		 * to map element returned from bpf_map_lookup_elem()
9660 		 */
9661 		if (meta.map_ptr == NULL) {
9662 			verbose(env,
9663 				"kernel subsystem misconfigured verifier\n");
9664 			return -EINVAL;
9665 		}
9666 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
9667 		regs[BPF_REG_0].map_uid = meta.map_uid;
9668 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9669 		if (!type_may_be_null(ret_type) &&
9670 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9671 			regs[BPF_REG_0].id = ++env->id_gen;
9672 		}
9673 		break;
9674 	case RET_PTR_TO_SOCKET:
9675 		mark_reg_known_zero(env, regs, BPF_REG_0);
9676 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9677 		break;
9678 	case RET_PTR_TO_SOCK_COMMON:
9679 		mark_reg_known_zero(env, regs, BPF_REG_0);
9680 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9681 		break;
9682 	case RET_PTR_TO_TCP_SOCK:
9683 		mark_reg_known_zero(env, regs, BPF_REG_0);
9684 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9685 		break;
9686 	case RET_PTR_TO_MEM:
9687 		mark_reg_known_zero(env, regs, BPF_REG_0);
9688 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9689 		regs[BPF_REG_0].mem_size = meta.mem_size;
9690 		break;
9691 	case RET_PTR_TO_MEM_OR_BTF_ID:
9692 	{
9693 		const struct btf_type *t;
9694 
9695 		mark_reg_known_zero(env, regs, BPF_REG_0);
9696 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9697 		if (!btf_type_is_struct(t)) {
9698 			u32 tsize;
9699 			const struct btf_type *ret;
9700 			const char *tname;
9701 
9702 			/* resolve the type size of ksym. */
9703 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9704 			if (IS_ERR(ret)) {
9705 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9706 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
9707 					tname, PTR_ERR(ret));
9708 				return -EINVAL;
9709 			}
9710 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9711 			regs[BPF_REG_0].mem_size = tsize;
9712 		} else {
9713 			/* MEM_RDONLY may be carried from ret_flag, but it
9714 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9715 			 * it will confuse the check of PTR_TO_BTF_ID in
9716 			 * check_mem_access().
9717 			 */
9718 			ret_flag &= ~MEM_RDONLY;
9719 
9720 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9721 			regs[BPF_REG_0].btf = meta.ret_btf;
9722 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9723 		}
9724 		break;
9725 	}
9726 	case RET_PTR_TO_BTF_ID:
9727 	{
9728 		struct btf *ret_btf;
9729 		int ret_btf_id;
9730 
9731 		mark_reg_known_zero(env, regs, BPF_REG_0);
9732 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9733 		if (func_id == BPF_FUNC_kptr_xchg) {
9734 			ret_btf = meta.kptr_field->kptr.btf;
9735 			ret_btf_id = meta.kptr_field->kptr.btf_id;
9736 			if (!btf_is_kernel(ret_btf))
9737 				regs[BPF_REG_0].type |= MEM_ALLOC;
9738 		} else {
9739 			if (fn->ret_btf_id == BPF_PTR_POISON) {
9740 				verbose(env, "verifier internal error:");
9741 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9742 					func_id_name(func_id));
9743 				return -EINVAL;
9744 			}
9745 			ret_btf = btf_vmlinux;
9746 			ret_btf_id = *fn->ret_btf_id;
9747 		}
9748 		if (ret_btf_id == 0) {
9749 			verbose(env, "invalid return type %u of func %s#%d\n",
9750 				base_type(ret_type), func_id_name(func_id),
9751 				func_id);
9752 			return -EINVAL;
9753 		}
9754 		regs[BPF_REG_0].btf = ret_btf;
9755 		regs[BPF_REG_0].btf_id = ret_btf_id;
9756 		break;
9757 	}
9758 	default:
9759 		verbose(env, "unknown return type %u of func %s#%d\n",
9760 			base_type(ret_type), func_id_name(func_id), func_id);
9761 		return -EINVAL;
9762 	}
9763 
9764 	if (type_may_be_null(regs[BPF_REG_0].type))
9765 		regs[BPF_REG_0].id = ++env->id_gen;
9766 
9767 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9768 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9769 			func_id_name(func_id), func_id);
9770 		return -EFAULT;
9771 	}
9772 
9773 	if (is_dynptr_ref_function(func_id))
9774 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9775 
9776 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9777 		/* For release_reference() */
9778 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9779 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
9780 		int id = acquire_reference_state(env, insn_idx);
9781 
9782 		if (id < 0)
9783 			return id;
9784 		/* For mark_ptr_or_null_reg() */
9785 		regs[BPF_REG_0].id = id;
9786 		/* For release_reference() */
9787 		regs[BPF_REG_0].ref_obj_id = id;
9788 	}
9789 
9790 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9791 
9792 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9793 	if (err)
9794 		return err;
9795 
9796 	if ((func_id == BPF_FUNC_get_stack ||
9797 	     func_id == BPF_FUNC_get_task_stack) &&
9798 	    !env->prog->has_callchain_buf) {
9799 		const char *err_str;
9800 
9801 #ifdef CONFIG_PERF_EVENTS
9802 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
9803 		err_str = "cannot get callchain buffer for func %s#%d\n";
9804 #else
9805 		err = -ENOTSUPP;
9806 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9807 #endif
9808 		if (err) {
9809 			verbose(env, err_str, func_id_name(func_id), func_id);
9810 			return err;
9811 		}
9812 
9813 		env->prog->has_callchain_buf = true;
9814 	}
9815 
9816 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9817 		env->prog->call_get_stack = true;
9818 
9819 	if (func_id == BPF_FUNC_get_func_ip) {
9820 		if (check_get_func_ip(env))
9821 			return -ENOTSUPP;
9822 		env->prog->call_get_func_ip = true;
9823 	}
9824 
9825 	if (changes_data)
9826 		clear_all_pkt_pointers(env);
9827 	return 0;
9828 }
9829 
9830 /* mark_btf_func_reg_size() is used when the reg size is determined by
9831  * the BTF func_proto's return value size and argument.
9832  */
9833 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9834 				   size_t reg_size)
9835 {
9836 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
9837 
9838 	if (regno == BPF_REG_0) {
9839 		/* Function return value */
9840 		reg->live |= REG_LIVE_WRITTEN;
9841 		reg->subreg_def = reg_size == sizeof(u64) ?
9842 			DEF_NOT_SUBREG : env->insn_idx + 1;
9843 	} else {
9844 		/* Function argument */
9845 		if (reg_size == sizeof(u64)) {
9846 			mark_insn_zext(env, reg);
9847 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9848 		} else {
9849 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
9850 		}
9851 	}
9852 }
9853 
9854 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
9855 {
9856 	return meta->kfunc_flags & KF_ACQUIRE;
9857 }
9858 
9859 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
9860 {
9861 	return meta->kfunc_flags & KF_RELEASE;
9862 }
9863 
9864 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
9865 {
9866 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
9867 }
9868 
9869 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
9870 {
9871 	return meta->kfunc_flags & KF_SLEEPABLE;
9872 }
9873 
9874 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
9875 {
9876 	return meta->kfunc_flags & KF_DESTRUCTIVE;
9877 }
9878 
9879 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
9880 {
9881 	return meta->kfunc_flags & KF_RCU;
9882 }
9883 
9884 static bool __kfunc_param_match_suffix(const struct btf *btf,
9885 				       const struct btf_param *arg,
9886 				       const char *suffix)
9887 {
9888 	int suffix_len = strlen(suffix), len;
9889 	const char *param_name;
9890 
9891 	/* In the future, this can be ported to use BTF tagging */
9892 	param_name = btf_name_by_offset(btf, arg->name_off);
9893 	if (str_is_empty(param_name))
9894 		return false;
9895 	len = strlen(param_name);
9896 	if (len < suffix_len)
9897 		return false;
9898 	param_name += len - suffix_len;
9899 	return !strncmp(param_name, suffix, suffix_len);
9900 }
9901 
9902 static bool is_kfunc_arg_mem_size(const struct btf *btf,
9903 				  const struct btf_param *arg,
9904 				  const struct bpf_reg_state *reg)
9905 {
9906 	const struct btf_type *t;
9907 
9908 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9909 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9910 		return false;
9911 
9912 	return __kfunc_param_match_suffix(btf, arg, "__sz");
9913 }
9914 
9915 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
9916 					const struct btf_param *arg,
9917 					const struct bpf_reg_state *reg)
9918 {
9919 	const struct btf_type *t;
9920 
9921 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9922 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9923 		return false;
9924 
9925 	return __kfunc_param_match_suffix(btf, arg, "__szk");
9926 }
9927 
9928 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
9929 {
9930 	return __kfunc_param_match_suffix(btf, arg, "__opt");
9931 }
9932 
9933 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
9934 {
9935 	return __kfunc_param_match_suffix(btf, arg, "__k");
9936 }
9937 
9938 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
9939 {
9940 	return __kfunc_param_match_suffix(btf, arg, "__ign");
9941 }
9942 
9943 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
9944 {
9945 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
9946 }
9947 
9948 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
9949 {
9950 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
9951 }
9952 
9953 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
9954 {
9955 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
9956 }
9957 
9958 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
9959 					  const struct btf_param *arg,
9960 					  const char *name)
9961 {
9962 	int len, target_len = strlen(name);
9963 	const char *param_name;
9964 
9965 	param_name = btf_name_by_offset(btf, arg->name_off);
9966 	if (str_is_empty(param_name))
9967 		return false;
9968 	len = strlen(param_name);
9969 	if (len != target_len)
9970 		return false;
9971 	if (strcmp(param_name, name))
9972 		return false;
9973 
9974 	return true;
9975 }
9976 
9977 enum {
9978 	KF_ARG_DYNPTR_ID,
9979 	KF_ARG_LIST_HEAD_ID,
9980 	KF_ARG_LIST_NODE_ID,
9981 	KF_ARG_RB_ROOT_ID,
9982 	KF_ARG_RB_NODE_ID,
9983 };
9984 
9985 BTF_ID_LIST(kf_arg_btf_ids)
9986 BTF_ID(struct, bpf_dynptr_kern)
9987 BTF_ID(struct, bpf_list_head)
9988 BTF_ID(struct, bpf_list_node)
9989 BTF_ID(struct, bpf_rb_root)
9990 BTF_ID(struct, bpf_rb_node)
9991 
9992 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
9993 				    const struct btf_param *arg, int type)
9994 {
9995 	const struct btf_type *t;
9996 	u32 res_id;
9997 
9998 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9999 	if (!t)
10000 		return false;
10001 	if (!btf_type_is_ptr(t))
10002 		return false;
10003 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10004 	if (!t)
10005 		return false;
10006 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10007 }
10008 
10009 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10010 {
10011 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10012 }
10013 
10014 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10015 {
10016 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10017 }
10018 
10019 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10020 {
10021 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10022 }
10023 
10024 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10025 {
10026 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10027 }
10028 
10029 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10030 {
10031 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10032 }
10033 
10034 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10035 				  const struct btf_param *arg)
10036 {
10037 	const struct btf_type *t;
10038 
10039 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10040 	if (!t)
10041 		return false;
10042 
10043 	return true;
10044 }
10045 
10046 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10047 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10048 					const struct btf *btf,
10049 					const struct btf_type *t, int rec)
10050 {
10051 	const struct btf_type *member_type;
10052 	const struct btf_member *member;
10053 	u32 i;
10054 
10055 	if (!btf_type_is_struct(t))
10056 		return false;
10057 
10058 	for_each_member(i, t, member) {
10059 		const struct btf_array *array;
10060 
10061 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10062 		if (btf_type_is_struct(member_type)) {
10063 			if (rec >= 3) {
10064 				verbose(env, "max struct nesting depth exceeded\n");
10065 				return false;
10066 			}
10067 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10068 				return false;
10069 			continue;
10070 		}
10071 		if (btf_type_is_array(member_type)) {
10072 			array = btf_array(member_type);
10073 			if (!array->nelems)
10074 				return false;
10075 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10076 			if (!btf_type_is_scalar(member_type))
10077 				return false;
10078 			continue;
10079 		}
10080 		if (!btf_type_is_scalar(member_type))
10081 			return false;
10082 	}
10083 	return true;
10084 }
10085 
10086 enum kfunc_ptr_arg_type {
10087 	KF_ARG_PTR_TO_CTX,
10088 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10089 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10090 	KF_ARG_PTR_TO_DYNPTR,
10091 	KF_ARG_PTR_TO_ITER,
10092 	KF_ARG_PTR_TO_LIST_HEAD,
10093 	KF_ARG_PTR_TO_LIST_NODE,
10094 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10095 	KF_ARG_PTR_TO_MEM,
10096 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10097 	KF_ARG_PTR_TO_CALLBACK,
10098 	KF_ARG_PTR_TO_RB_ROOT,
10099 	KF_ARG_PTR_TO_RB_NODE,
10100 };
10101 
10102 enum special_kfunc_type {
10103 	KF_bpf_obj_new_impl,
10104 	KF_bpf_obj_drop_impl,
10105 	KF_bpf_refcount_acquire_impl,
10106 	KF_bpf_list_push_front_impl,
10107 	KF_bpf_list_push_back_impl,
10108 	KF_bpf_list_pop_front,
10109 	KF_bpf_list_pop_back,
10110 	KF_bpf_cast_to_kern_ctx,
10111 	KF_bpf_rdonly_cast,
10112 	KF_bpf_rcu_read_lock,
10113 	KF_bpf_rcu_read_unlock,
10114 	KF_bpf_rbtree_remove,
10115 	KF_bpf_rbtree_add_impl,
10116 	KF_bpf_rbtree_first,
10117 	KF_bpf_dynptr_from_skb,
10118 	KF_bpf_dynptr_from_xdp,
10119 	KF_bpf_dynptr_slice,
10120 	KF_bpf_dynptr_slice_rdwr,
10121 	KF_bpf_dynptr_clone,
10122 };
10123 
10124 BTF_SET_START(special_kfunc_set)
10125 BTF_ID(func, bpf_obj_new_impl)
10126 BTF_ID(func, bpf_obj_drop_impl)
10127 BTF_ID(func, bpf_refcount_acquire_impl)
10128 BTF_ID(func, bpf_list_push_front_impl)
10129 BTF_ID(func, bpf_list_push_back_impl)
10130 BTF_ID(func, bpf_list_pop_front)
10131 BTF_ID(func, bpf_list_pop_back)
10132 BTF_ID(func, bpf_cast_to_kern_ctx)
10133 BTF_ID(func, bpf_rdonly_cast)
10134 BTF_ID(func, bpf_rbtree_remove)
10135 BTF_ID(func, bpf_rbtree_add_impl)
10136 BTF_ID(func, bpf_rbtree_first)
10137 BTF_ID(func, bpf_dynptr_from_skb)
10138 BTF_ID(func, bpf_dynptr_from_xdp)
10139 BTF_ID(func, bpf_dynptr_slice)
10140 BTF_ID(func, bpf_dynptr_slice_rdwr)
10141 BTF_ID(func, bpf_dynptr_clone)
10142 BTF_SET_END(special_kfunc_set)
10143 
10144 BTF_ID_LIST(special_kfunc_list)
10145 BTF_ID(func, bpf_obj_new_impl)
10146 BTF_ID(func, bpf_obj_drop_impl)
10147 BTF_ID(func, bpf_refcount_acquire_impl)
10148 BTF_ID(func, bpf_list_push_front_impl)
10149 BTF_ID(func, bpf_list_push_back_impl)
10150 BTF_ID(func, bpf_list_pop_front)
10151 BTF_ID(func, bpf_list_pop_back)
10152 BTF_ID(func, bpf_cast_to_kern_ctx)
10153 BTF_ID(func, bpf_rdonly_cast)
10154 BTF_ID(func, bpf_rcu_read_lock)
10155 BTF_ID(func, bpf_rcu_read_unlock)
10156 BTF_ID(func, bpf_rbtree_remove)
10157 BTF_ID(func, bpf_rbtree_add_impl)
10158 BTF_ID(func, bpf_rbtree_first)
10159 BTF_ID(func, bpf_dynptr_from_skb)
10160 BTF_ID(func, bpf_dynptr_from_xdp)
10161 BTF_ID(func, bpf_dynptr_slice)
10162 BTF_ID(func, bpf_dynptr_slice_rdwr)
10163 BTF_ID(func, bpf_dynptr_clone)
10164 
10165 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10166 {
10167 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10168 	    meta->arg_owning_ref) {
10169 		return false;
10170 	}
10171 
10172 	return meta->kfunc_flags & KF_RET_NULL;
10173 }
10174 
10175 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10176 {
10177 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10178 }
10179 
10180 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10181 {
10182 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10183 }
10184 
10185 static enum kfunc_ptr_arg_type
10186 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10187 		       struct bpf_kfunc_call_arg_meta *meta,
10188 		       const struct btf_type *t, const struct btf_type *ref_t,
10189 		       const char *ref_tname, const struct btf_param *args,
10190 		       int argno, int nargs)
10191 {
10192 	u32 regno = argno + 1;
10193 	struct bpf_reg_state *regs = cur_regs(env);
10194 	struct bpf_reg_state *reg = &regs[regno];
10195 	bool arg_mem_size = false;
10196 
10197 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10198 		return KF_ARG_PTR_TO_CTX;
10199 
10200 	/* In this function, we verify the kfunc's BTF as per the argument type,
10201 	 * leaving the rest of the verification with respect to the register
10202 	 * type to our caller. When a set of conditions hold in the BTF type of
10203 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10204 	 */
10205 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10206 		return KF_ARG_PTR_TO_CTX;
10207 
10208 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10209 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10210 
10211 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10212 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10213 
10214 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10215 		return KF_ARG_PTR_TO_DYNPTR;
10216 
10217 	if (is_kfunc_arg_iter(meta, argno))
10218 		return KF_ARG_PTR_TO_ITER;
10219 
10220 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10221 		return KF_ARG_PTR_TO_LIST_HEAD;
10222 
10223 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10224 		return KF_ARG_PTR_TO_LIST_NODE;
10225 
10226 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10227 		return KF_ARG_PTR_TO_RB_ROOT;
10228 
10229 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10230 		return KF_ARG_PTR_TO_RB_NODE;
10231 
10232 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10233 		if (!btf_type_is_struct(ref_t)) {
10234 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10235 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10236 			return -EINVAL;
10237 		}
10238 		return KF_ARG_PTR_TO_BTF_ID;
10239 	}
10240 
10241 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10242 		return KF_ARG_PTR_TO_CALLBACK;
10243 
10244 
10245 	if (argno + 1 < nargs &&
10246 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10247 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10248 		arg_mem_size = true;
10249 
10250 	/* This is the catch all argument type of register types supported by
10251 	 * check_helper_mem_access. However, we only allow when argument type is
10252 	 * pointer to scalar, or struct composed (recursively) of scalars. When
10253 	 * arg_mem_size is true, the pointer can be void *.
10254 	 */
10255 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10256 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10257 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10258 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10259 		return -EINVAL;
10260 	}
10261 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10262 }
10263 
10264 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10265 					struct bpf_reg_state *reg,
10266 					const struct btf_type *ref_t,
10267 					const char *ref_tname, u32 ref_id,
10268 					struct bpf_kfunc_call_arg_meta *meta,
10269 					int argno)
10270 {
10271 	const struct btf_type *reg_ref_t;
10272 	bool strict_type_match = false;
10273 	const struct btf *reg_btf;
10274 	const char *reg_ref_tname;
10275 	u32 reg_ref_id;
10276 
10277 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
10278 		reg_btf = reg->btf;
10279 		reg_ref_id = reg->btf_id;
10280 	} else {
10281 		reg_btf = btf_vmlinux;
10282 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10283 	}
10284 
10285 	/* Enforce strict type matching for calls to kfuncs that are acquiring
10286 	 * or releasing a reference, or are no-cast aliases. We do _not_
10287 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10288 	 * as we want to enable BPF programs to pass types that are bitwise
10289 	 * equivalent without forcing them to explicitly cast with something
10290 	 * like bpf_cast_to_kern_ctx().
10291 	 *
10292 	 * For example, say we had a type like the following:
10293 	 *
10294 	 * struct bpf_cpumask {
10295 	 *	cpumask_t cpumask;
10296 	 *	refcount_t usage;
10297 	 * };
10298 	 *
10299 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10300 	 * to a struct cpumask, so it would be safe to pass a struct
10301 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10302 	 *
10303 	 * The philosophy here is similar to how we allow scalars of different
10304 	 * types to be passed to kfuncs as long as the size is the same. The
10305 	 * only difference here is that we're simply allowing
10306 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10307 	 * resolve types.
10308 	 */
10309 	if (is_kfunc_acquire(meta) ||
10310 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
10311 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10312 		strict_type_match = true;
10313 
10314 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10315 
10316 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10317 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10318 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10319 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10320 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10321 			btf_type_str(reg_ref_t), reg_ref_tname);
10322 		return -EINVAL;
10323 	}
10324 	return 0;
10325 }
10326 
10327 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10328 {
10329 	struct bpf_verifier_state *state = env->cur_state;
10330 
10331 	if (!state->active_lock.ptr) {
10332 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10333 		return -EFAULT;
10334 	}
10335 
10336 	if (type_flag(reg->type) & NON_OWN_REF) {
10337 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10338 		return -EFAULT;
10339 	}
10340 
10341 	reg->type |= NON_OWN_REF;
10342 	return 0;
10343 }
10344 
10345 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10346 {
10347 	struct bpf_func_state *state, *unused;
10348 	struct bpf_reg_state *reg;
10349 	int i;
10350 
10351 	state = cur_func(env);
10352 
10353 	if (!ref_obj_id) {
10354 		verbose(env, "verifier internal error: ref_obj_id is zero for "
10355 			     "owning -> non-owning conversion\n");
10356 		return -EFAULT;
10357 	}
10358 
10359 	for (i = 0; i < state->acquired_refs; i++) {
10360 		if (state->refs[i].id != ref_obj_id)
10361 			continue;
10362 
10363 		/* Clear ref_obj_id here so release_reference doesn't clobber
10364 		 * the whole reg
10365 		 */
10366 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10367 			if (reg->ref_obj_id == ref_obj_id) {
10368 				reg->ref_obj_id = 0;
10369 				ref_set_non_owning(env, reg);
10370 			}
10371 		}));
10372 		return 0;
10373 	}
10374 
10375 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10376 	return -EFAULT;
10377 }
10378 
10379 /* Implementation details:
10380  *
10381  * Each register points to some region of memory, which we define as an
10382  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10383  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10384  * allocation. The lock and the data it protects are colocated in the same
10385  * memory region.
10386  *
10387  * Hence, everytime a register holds a pointer value pointing to such
10388  * allocation, the verifier preserves a unique reg->id for it.
10389  *
10390  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10391  * bpf_spin_lock is called.
10392  *
10393  * To enable this, lock state in the verifier captures two values:
10394  *	active_lock.ptr = Register's type specific pointer
10395  *	active_lock.id  = A unique ID for each register pointer value
10396  *
10397  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10398  * supported register types.
10399  *
10400  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10401  * allocated objects is the reg->btf pointer.
10402  *
10403  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10404  * can establish the provenance of the map value statically for each distinct
10405  * lookup into such maps. They always contain a single map value hence unique
10406  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10407  *
10408  * So, in case of global variables, they use array maps with max_entries = 1,
10409  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10410  * into the same map value as max_entries is 1, as described above).
10411  *
10412  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10413  * outer map pointer (in verifier context), but each lookup into an inner map
10414  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10415  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10416  * will get different reg->id assigned to each lookup, hence different
10417  * active_lock.id.
10418  *
10419  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10420  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10421  * returned from bpf_obj_new. Each allocation receives a new reg->id.
10422  */
10423 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10424 {
10425 	void *ptr;
10426 	u32 id;
10427 
10428 	switch ((int)reg->type) {
10429 	case PTR_TO_MAP_VALUE:
10430 		ptr = reg->map_ptr;
10431 		break;
10432 	case PTR_TO_BTF_ID | MEM_ALLOC:
10433 		ptr = reg->btf;
10434 		break;
10435 	default:
10436 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
10437 		return -EFAULT;
10438 	}
10439 	id = reg->id;
10440 
10441 	if (!env->cur_state->active_lock.ptr)
10442 		return -EINVAL;
10443 	if (env->cur_state->active_lock.ptr != ptr ||
10444 	    env->cur_state->active_lock.id != id) {
10445 		verbose(env, "held lock and object are not in the same allocation\n");
10446 		return -EINVAL;
10447 	}
10448 	return 0;
10449 }
10450 
10451 static bool is_bpf_list_api_kfunc(u32 btf_id)
10452 {
10453 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10454 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10455 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10456 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10457 }
10458 
10459 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10460 {
10461 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10462 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10463 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10464 }
10465 
10466 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10467 {
10468 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10469 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10470 }
10471 
10472 static bool is_callback_calling_kfunc(u32 btf_id)
10473 {
10474 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10475 }
10476 
10477 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10478 {
10479 	return is_bpf_rbtree_api_kfunc(btf_id);
10480 }
10481 
10482 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10483 					  enum btf_field_type head_field_type,
10484 					  u32 kfunc_btf_id)
10485 {
10486 	bool ret;
10487 
10488 	switch (head_field_type) {
10489 	case BPF_LIST_HEAD:
10490 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10491 		break;
10492 	case BPF_RB_ROOT:
10493 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10494 		break;
10495 	default:
10496 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10497 			btf_field_type_name(head_field_type));
10498 		return false;
10499 	}
10500 
10501 	if (!ret)
10502 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10503 			btf_field_type_name(head_field_type));
10504 	return ret;
10505 }
10506 
10507 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10508 					  enum btf_field_type node_field_type,
10509 					  u32 kfunc_btf_id)
10510 {
10511 	bool ret;
10512 
10513 	switch (node_field_type) {
10514 	case BPF_LIST_NODE:
10515 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10516 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10517 		break;
10518 	case BPF_RB_NODE:
10519 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10520 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10521 		break;
10522 	default:
10523 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10524 			btf_field_type_name(node_field_type));
10525 		return false;
10526 	}
10527 
10528 	if (!ret)
10529 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10530 			btf_field_type_name(node_field_type));
10531 	return ret;
10532 }
10533 
10534 static int
10535 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10536 				   struct bpf_reg_state *reg, u32 regno,
10537 				   struct bpf_kfunc_call_arg_meta *meta,
10538 				   enum btf_field_type head_field_type,
10539 				   struct btf_field **head_field)
10540 {
10541 	const char *head_type_name;
10542 	struct btf_field *field;
10543 	struct btf_record *rec;
10544 	u32 head_off;
10545 
10546 	if (meta->btf != btf_vmlinux) {
10547 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10548 		return -EFAULT;
10549 	}
10550 
10551 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10552 		return -EFAULT;
10553 
10554 	head_type_name = btf_field_type_name(head_field_type);
10555 	if (!tnum_is_const(reg->var_off)) {
10556 		verbose(env,
10557 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
10558 			regno, head_type_name);
10559 		return -EINVAL;
10560 	}
10561 
10562 	rec = reg_btf_record(reg);
10563 	head_off = reg->off + reg->var_off.value;
10564 	field = btf_record_find(rec, head_off, head_field_type);
10565 	if (!field) {
10566 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10567 		return -EINVAL;
10568 	}
10569 
10570 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10571 	if (check_reg_allocation_locked(env, reg)) {
10572 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10573 			rec->spin_lock_off, head_type_name);
10574 		return -EINVAL;
10575 	}
10576 
10577 	if (*head_field) {
10578 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10579 		return -EFAULT;
10580 	}
10581 	*head_field = field;
10582 	return 0;
10583 }
10584 
10585 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10586 					   struct bpf_reg_state *reg, u32 regno,
10587 					   struct bpf_kfunc_call_arg_meta *meta)
10588 {
10589 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10590 							  &meta->arg_list_head.field);
10591 }
10592 
10593 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10594 					     struct bpf_reg_state *reg, u32 regno,
10595 					     struct bpf_kfunc_call_arg_meta *meta)
10596 {
10597 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10598 							  &meta->arg_rbtree_root.field);
10599 }
10600 
10601 static int
10602 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10603 				   struct bpf_reg_state *reg, u32 regno,
10604 				   struct bpf_kfunc_call_arg_meta *meta,
10605 				   enum btf_field_type head_field_type,
10606 				   enum btf_field_type node_field_type,
10607 				   struct btf_field **node_field)
10608 {
10609 	const char *node_type_name;
10610 	const struct btf_type *et, *t;
10611 	struct btf_field *field;
10612 	u32 node_off;
10613 
10614 	if (meta->btf != btf_vmlinux) {
10615 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10616 		return -EFAULT;
10617 	}
10618 
10619 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10620 		return -EFAULT;
10621 
10622 	node_type_name = btf_field_type_name(node_field_type);
10623 	if (!tnum_is_const(reg->var_off)) {
10624 		verbose(env,
10625 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
10626 			regno, node_type_name);
10627 		return -EINVAL;
10628 	}
10629 
10630 	node_off = reg->off + reg->var_off.value;
10631 	field = reg_find_field_offset(reg, node_off, node_field_type);
10632 	if (!field || field->offset != node_off) {
10633 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10634 		return -EINVAL;
10635 	}
10636 
10637 	field = *node_field;
10638 
10639 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10640 	t = btf_type_by_id(reg->btf, reg->btf_id);
10641 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10642 				  field->graph_root.value_btf_id, true)) {
10643 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10644 			"in struct %s, but arg is at offset=%d in struct %s\n",
10645 			btf_field_type_name(head_field_type),
10646 			btf_field_type_name(node_field_type),
10647 			field->graph_root.node_offset,
10648 			btf_name_by_offset(field->graph_root.btf, et->name_off),
10649 			node_off, btf_name_by_offset(reg->btf, t->name_off));
10650 		return -EINVAL;
10651 	}
10652 	meta->arg_btf = reg->btf;
10653 	meta->arg_btf_id = reg->btf_id;
10654 
10655 	if (node_off != field->graph_root.node_offset) {
10656 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10657 			node_off, btf_field_type_name(node_field_type),
10658 			field->graph_root.node_offset,
10659 			btf_name_by_offset(field->graph_root.btf, et->name_off));
10660 		return -EINVAL;
10661 	}
10662 
10663 	return 0;
10664 }
10665 
10666 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10667 					   struct bpf_reg_state *reg, u32 regno,
10668 					   struct bpf_kfunc_call_arg_meta *meta)
10669 {
10670 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10671 						  BPF_LIST_HEAD, BPF_LIST_NODE,
10672 						  &meta->arg_list_head.field);
10673 }
10674 
10675 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10676 					     struct bpf_reg_state *reg, u32 regno,
10677 					     struct bpf_kfunc_call_arg_meta *meta)
10678 {
10679 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10680 						  BPF_RB_ROOT, BPF_RB_NODE,
10681 						  &meta->arg_rbtree_root.field);
10682 }
10683 
10684 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10685 			    int insn_idx)
10686 {
10687 	const char *func_name = meta->func_name, *ref_tname;
10688 	const struct btf *btf = meta->btf;
10689 	const struct btf_param *args;
10690 	struct btf_record *rec;
10691 	u32 i, nargs;
10692 	int ret;
10693 
10694 	args = (const struct btf_param *)(meta->func_proto + 1);
10695 	nargs = btf_type_vlen(meta->func_proto);
10696 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10697 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10698 			MAX_BPF_FUNC_REG_ARGS);
10699 		return -EINVAL;
10700 	}
10701 
10702 	/* Check that BTF function arguments match actual types that the
10703 	 * verifier sees.
10704 	 */
10705 	for (i = 0; i < nargs; i++) {
10706 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
10707 		const struct btf_type *t, *ref_t, *resolve_ret;
10708 		enum bpf_arg_type arg_type = ARG_DONTCARE;
10709 		u32 regno = i + 1, ref_id, type_size;
10710 		bool is_ret_buf_sz = false;
10711 		int kf_arg_type;
10712 
10713 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10714 
10715 		if (is_kfunc_arg_ignore(btf, &args[i]))
10716 			continue;
10717 
10718 		if (btf_type_is_scalar(t)) {
10719 			if (reg->type != SCALAR_VALUE) {
10720 				verbose(env, "R%d is not a scalar\n", regno);
10721 				return -EINVAL;
10722 			}
10723 
10724 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10725 				if (meta->arg_constant.found) {
10726 					verbose(env, "verifier internal error: only one constant argument permitted\n");
10727 					return -EFAULT;
10728 				}
10729 				if (!tnum_is_const(reg->var_off)) {
10730 					verbose(env, "R%d must be a known constant\n", regno);
10731 					return -EINVAL;
10732 				}
10733 				ret = mark_chain_precision(env, regno);
10734 				if (ret < 0)
10735 					return ret;
10736 				meta->arg_constant.found = true;
10737 				meta->arg_constant.value = reg->var_off.value;
10738 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10739 				meta->r0_rdonly = true;
10740 				is_ret_buf_sz = true;
10741 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10742 				is_ret_buf_sz = true;
10743 			}
10744 
10745 			if (is_ret_buf_sz) {
10746 				if (meta->r0_size) {
10747 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10748 					return -EINVAL;
10749 				}
10750 
10751 				if (!tnum_is_const(reg->var_off)) {
10752 					verbose(env, "R%d is not a const\n", regno);
10753 					return -EINVAL;
10754 				}
10755 
10756 				meta->r0_size = reg->var_off.value;
10757 				ret = mark_chain_precision(env, regno);
10758 				if (ret)
10759 					return ret;
10760 			}
10761 			continue;
10762 		}
10763 
10764 		if (!btf_type_is_ptr(t)) {
10765 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10766 			return -EINVAL;
10767 		}
10768 
10769 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10770 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
10771 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10772 			return -EACCES;
10773 		}
10774 
10775 		if (reg->ref_obj_id) {
10776 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
10777 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10778 					regno, reg->ref_obj_id,
10779 					meta->ref_obj_id);
10780 				return -EFAULT;
10781 			}
10782 			meta->ref_obj_id = reg->ref_obj_id;
10783 			if (is_kfunc_release(meta))
10784 				meta->release_regno = regno;
10785 		}
10786 
10787 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10788 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10789 
10790 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10791 		if (kf_arg_type < 0)
10792 			return kf_arg_type;
10793 
10794 		switch (kf_arg_type) {
10795 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10796 		case KF_ARG_PTR_TO_BTF_ID:
10797 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10798 				break;
10799 
10800 			if (!is_trusted_reg(reg)) {
10801 				if (!is_kfunc_rcu(meta)) {
10802 					verbose(env, "R%d must be referenced or trusted\n", regno);
10803 					return -EINVAL;
10804 				}
10805 				if (!is_rcu_reg(reg)) {
10806 					verbose(env, "R%d must be a rcu pointer\n", regno);
10807 					return -EINVAL;
10808 				}
10809 			}
10810 
10811 			fallthrough;
10812 		case KF_ARG_PTR_TO_CTX:
10813 			/* Trusted arguments have the same offset checks as release arguments */
10814 			arg_type |= OBJ_RELEASE;
10815 			break;
10816 		case KF_ARG_PTR_TO_DYNPTR:
10817 		case KF_ARG_PTR_TO_ITER:
10818 		case KF_ARG_PTR_TO_LIST_HEAD:
10819 		case KF_ARG_PTR_TO_LIST_NODE:
10820 		case KF_ARG_PTR_TO_RB_ROOT:
10821 		case KF_ARG_PTR_TO_RB_NODE:
10822 		case KF_ARG_PTR_TO_MEM:
10823 		case KF_ARG_PTR_TO_MEM_SIZE:
10824 		case KF_ARG_PTR_TO_CALLBACK:
10825 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10826 			/* Trusted by default */
10827 			break;
10828 		default:
10829 			WARN_ON_ONCE(1);
10830 			return -EFAULT;
10831 		}
10832 
10833 		if (is_kfunc_release(meta) && reg->ref_obj_id)
10834 			arg_type |= OBJ_RELEASE;
10835 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10836 		if (ret < 0)
10837 			return ret;
10838 
10839 		switch (kf_arg_type) {
10840 		case KF_ARG_PTR_TO_CTX:
10841 			if (reg->type != PTR_TO_CTX) {
10842 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10843 				return -EINVAL;
10844 			}
10845 
10846 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10847 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10848 				if (ret < 0)
10849 					return -EINVAL;
10850 				meta->ret_btf_id  = ret;
10851 			}
10852 			break;
10853 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10854 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10855 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
10856 				return -EINVAL;
10857 			}
10858 			if (!reg->ref_obj_id) {
10859 				verbose(env, "allocated object must be referenced\n");
10860 				return -EINVAL;
10861 			}
10862 			if (meta->btf == btf_vmlinux &&
10863 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10864 				meta->arg_btf = reg->btf;
10865 				meta->arg_btf_id = reg->btf_id;
10866 			}
10867 			break;
10868 		case KF_ARG_PTR_TO_DYNPTR:
10869 		{
10870 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
10871 			int clone_ref_obj_id = 0;
10872 
10873 			if (reg->type != PTR_TO_STACK &&
10874 			    reg->type != CONST_PTR_TO_DYNPTR) {
10875 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
10876 				return -EINVAL;
10877 			}
10878 
10879 			if (reg->type == CONST_PTR_TO_DYNPTR)
10880 				dynptr_arg_type |= MEM_RDONLY;
10881 
10882 			if (is_kfunc_arg_uninit(btf, &args[i]))
10883 				dynptr_arg_type |= MEM_UNINIT;
10884 
10885 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
10886 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
10887 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
10888 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
10889 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
10890 				   (dynptr_arg_type & MEM_UNINIT)) {
10891 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
10892 
10893 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
10894 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
10895 					return -EFAULT;
10896 				}
10897 
10898 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
10899 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
10900 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
10901 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
10902 					return -EFAULT;
10903 				}
10904 			}
10905 
10906 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
10907 			if (ret < 0)
10908 				return ret;
10909 
10910 			if (!(dynptr_arg_type & MEM_UNINIT)) {
10911 				int id = dynptr_id(env, reg);
10912 
10913 				if (id < 0) {
10914 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10915 					return id;
10916 				}
10917 				meta->initialized_dynptr.id = id;
10918 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
10919 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
10920 			}
10921 
10922 			break;
10923 		}
10924 		case KF_ARG_PTR_TO_ITER:
10925 			ret = process_iter_arg(env, regno, insn_idx, meta);
10926 			if (ret < 0)
10927 				return ret;
10928 			break;
10929 		case KF_ARG_PTR_TO_LIST_HEAD:
10930 			if (reg->type != PTR_TO_MAP_VALUE &&
10931 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10932 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10933 				return -EINVAL;
10934 			}
10935 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10936 				verbose(env, "allocated object must be referenced\n");
10937 				return -EINVAL;
10938 			}
10939 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
10940 			if (ret < 0)
10941 				return ret;
10942 			break;
10943 		case KF_ARG_PTR_TO_RB_ROOT:
10944 			if (reg->type != PTR_TO_MAP_VALUE &&
10945 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10946 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10947 				return -EINVAL;
10948 			}
10949 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10950 				verbose(env, "allocated object must be referenced\n");
10951 				return -EINVAL;
10952 			}
10953 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
10954 			if (ret < 0)
10955 				return ret;
10956 			break;
10957 		case KF_ARG_PTR_TO_LIST_NODE:
10958 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10959 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
10960 				return -EINVAL;
10961 			}
10962 			if (!reg->ref_obj_id) {
10963 				verbose(env, "allocated object must be referenced\n");
10964 				return -EINVAL;
10965 			}
10966 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
10967 			if (ret < 0)
10968 				return ret;
10969 			break;
10970 		case KF_ARG_PTR_TO_RB_NODE:
10971 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
10972 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
10973 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
10974 					return -EINVAL;
10975 				}
10976 				if (in_rbtree_lock_required_cb(env)) {
10977 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
10978 					return -EINVAL;
10979 				}
10980 			} else {
10981 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10982 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
10983 					return -EINVAL;
10984 				}
10985 				if (!reg->ref_obj_id) {
10986 					verbose(env, "allocated object must be referenced\n");
10987 					return -EINVAL;
10988 				}
10989 			}
10990 
10991 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
10992 			if (ret < 0)
10993 				return ret;
10994 			break;
10995 		case KF_ARG_PTR_TO_BTF_ID:
10996 			/* Only base_type is checked, further checks are done here */
10997 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
10998 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
10999 			    !reg2btf_ids[base_type(reg->type)]) {
11000 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11001 				verbose(env, "expected %s or socket\n",
11002 					reg_type_str(env, base_type(reg->type) |
11003 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11004 				return -EINVAL;
11005 			}
11006 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11007 			if (ret < 0)
11008 				return ret;
11009 			break;
11010 		case KF_ARG_PTR_TO_MEM:
11011 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11012 			if (IS_ERR(resolve_ret)) {
11013 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11014 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11015 				return -EINVAL;
11016 			}
11017 			ret = check_mem_reg(env, reg, regno, type_size);
11018 			if (ret < 0)
11019 				return ret;
11020 			break;
11021 		case KF_ARG_PTR_TO_MEM_SIZE:
11022 		{
11023 			struct bpf_reg_state *buff_reg = &regs[regno];
11024 			const struct btf_param *buff_arg = &args[i];
11025 			struct bpf_reg_state *size_reg = &regs[regno + 1];
11026 			const struct btf_param *size_arg = &args[i + 1];
11027 
11028 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11029 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11030 				if (ret < 0) {
11031 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11032 					return ret;
11033 				}
11034 			}
11035 
11036 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11037 				if (meta->arg_constant.found) {
11038 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11039 					return -EFAULT;
11040 				}
11041 				if (!tnum_is_const(size_reg->var_off)) {
11042 					verbose(env, "R%d must be a known constant\n", regno + 1);
11043 					return -EINVAL;
11044 				}
11045 				meta->arg_constant.found = true;
11046 				meta->arg_constant.value = size_reg->var_off.value;
11047 			}
11048 
11049 			/* Skip next '__sz' or '__szk' argument */
11050 			i++;
11051 			break;
11052 		}
11053 		case KF_ARG_PTR_TO_CALLBACK:
11054 			meta->subprogno = reg->subprogno;
11055 			break;
11056 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11057 			if (!type_is_ptr_alloc_obj(reg->type)) {
11058 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11059 				return -EINVAL;
11060 			}
11061 			if (!type_is_non_owning_ref(reg->type))
11062 				meta->arg_owning_ref = true;
11063 
11064 			rec = reg_btf_record(reg);
11065 			if (!rec) {
11066 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
11067 				return -EFAULT;
11068 			}
11069 
11070 			if (rec->refcount_off < 0) {
11071 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11072 				return -EINVAL;
11073 			}
11074 			if (rec->refcount_off >= 0) {
11075 				verbose(env, "bpf_refcount_acquire calls are disabled for now\n");
11076 				return -EINVAL;
11077 			}
11078 			meta->arg_btf = reg->btf;
11079 			meta->arg_btf_id = reg->btf_id;
11080 			break;
11081 		}
11082 	}
11083 
11084 	if (is_kfunc_release(meta) && !meta->release_regno) {
11085 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11086 			func_name);
11087 		return -EINVAL;
11088 	}
11089 
11090 	return 0;
11091 }
11092 
11093 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11094 			    struct bpf_insn *insn,
11095 			    struct bpf_kfunc_call_arg_meta *meta,
11096 			    const char **kfunc_name)
11097 {
11098 	const struct btf_type *func, *func_proto;
11099 	u32 func_id, *kfunc_flags;
11100 	const char *func_name;
11101 	struct btf *desc_btf;
11102 
11103 	if (kfunc_name)
11104 		*kfunc_name = NULL;
11105 
11106 	if (!insn->imm)
11107 		return -EINVAL;
11108 
11109 	desc_btf = find_kfunc_desc_btf(env, insn->off);
11110 	if (IS_ERR(desc_btf))
11111 		return PTR_ERR(desc_btf);
11112 
11113 	func_id = insn->imm;
11114 	func = btf_type_by_id(desc_btf, func_id);
11115 	func_name = btf_name_by_offset(desc_btf, func->name_off);
11116 	if (kfunc_name)
11117 		*kfunc_name = func_name;
11118 	func_proto = btf_type_by_id(desc_btf, func->type);
11119 
11120 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11121 	if (!kfunc_flags) {
11122 		return -EACCES;
11123 	}
11124 
11125 	memset(meta, 0, sizeof(*meta));
11126 	meta->btf = desc_btf;
11127 	meta->func_id = func_id;
11128 	meta->kfunc_flags = *kfunc_flags;
11129 	meta->func_proto = func_proto;
11130 	meta->func_name = func_name;
11131 
11132 	return 0;
11133 }
11134 
11135 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11136 			    int *insn_idx_p)
11137 {
11138 	const struct btf_type *t, *ptr_type;
11139 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
11140 	struct bpf_reg_state *regs = cur_regs(env);
11141 	const char *func_name, *ptr_type_name;
11142 	bool sleepable, rcu_lock, rcu_unlock;
11143 	struct bpf_kfunc_call_arg_meta meta;
11144 	struct bpf_insn_aux_data *insn_aux;
11145 	int err, insn_idx = *insn_idx_p;
11146 	const struct btf_param *args;
11147 	const struct btf_type *ret_t;
11148 	struct btf *desc_btf;
11149 
11150 	/* skip for now, but return error when we find this in fixup_kfunc_call */
11151 	if (!insn->imm)
11152 		return 0;
11153 
11154 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11155 	if (err == -EACCES && func_name)
11156 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
11157 	if (err)
11158 		return err;
11159 	desc_btf = meta.btf;
11160 	insn_aux = &env->insn_aux_data[insn_idx];
11161 
11162 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11163 
11164 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11165 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11166 		return -EACCES;
11167 	}
11168 
11169 	sleepable = is_kfunc_sleepable(&meta);
11170 	if (sleepable && !env->prog->aux->sleepable) {
11171 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11172 		return -EACCES;
11173 	}
11174 
11175 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11176 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11177 
11178 	if (env->cur_state->active_rcu_lock) {
11179 		struct bpf_func_state *state;
11180 		struct bpf_reg_state *reg;
11181 
11182 		if (rcu_lock) {
11183 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11184 			return -EINVAL;
11185 		} else if (rcu_unlock) {
11186 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11187 				if (reg->type & MEM_RCU) {
11188 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11189 					reg->type |= PTR_UNTRUSTED;
11190 				}
11191 			}));
11192 			env->cur_state->active_rcu_lock = false;
11193 		} else if (sleepable) {
11194 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11195 			return -EACCES;
11196 		}
11197 	} else if (rcu_lock) {
11198 		env->cur_state->active_rcu_lock = true;
11199 	} else if (rcu_unlock) {
11200 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11201 		return -EINVAL;
11202 	}
11203 
11204 	/* Check the arguments */
11205 	err = check_kfunc_args(env, &meta, insn_idx);
11206 	if (err < 0)
11207 		return err;
11208 	/* In case of release function, we get register number of refcounted
11209 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11210 	 */
11211 	if (meta.release_regno) {
11212 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11213 		if (err) {
11214 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11215 				func_name, meta.func_id);
11216 			return err;
11217 		}
11218 	}
11219 
11220 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11221 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11222 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11223 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11224 		insn_aux->insert_off = regs[BPF_REG_2].off;
11225 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11226 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11227 		if (err) {
11228 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11229 				func_name, meta.func_id);
11230 			return err;
11231 		}
11232 
11233 		err = release_reference(env, release_ref_obj_id);
11234 		if (err) {
11235 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11236 				func_name, meta.func_id);
11237 			return err;
11238 		}
11239 	}
11240 
11241 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11242 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11243 					set_rbtree_add_callback_state);
11244 		if (err) {
11245 			verbose(env, "kfunc %s#%d failed callback verification\n",
11246 				func_name, meta.func_id);
11247 			return err;
11248 		}
11249 	}
11250 
11251 	for (i = 0; i < CALLER_SAVED_REGS; i++)
11252 		mark_reg_not_init(env, regs, caller_saved[i]);
11253 
11254 	/* Check return type */
11255 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11256 
11257 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11258 		/* Only exception is bpf_obj_new_impl */
11259 		if (meta.btf != btf_vmlinux ||
11260 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11261 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11262 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11263 			return -EINVAL;
11264 		}
11265 	}
11266 
11267 	if (btf_type_is_scalar(t)) {
11268 		mark_reg_unknown(env, regs, BPF_REG_0);
11269 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11270 	} else if (btf_type_is_ptr(t)) {
11271 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11272 
11273 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11274 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11275 				struct btf *ret_btf;
11276 				u32 ret_btf_id;
11277 
11278 				if (unlikely(!bpf_global_ma_set))
11279 					return -ENOMEM;
11280 
11281 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11282 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11283 					return -EINVAL;
11284 				}
11285 
11286 				ret_btf = env->prog->aux->btf;
11287 				ret_btf_id = meta.arg_constant.value;
11288 
11289 				/* This may be NULL due to user not supplying a BTF */
11290 				if (!ret_btf) {
11291 					verbose(env, "bpf_obj_new requires prog BTF\n");
11292 					return -EINVAL;
11293 				}
11294 
11295 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11296 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
11297 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11298 					return -EINVAL;
11299 				}
11300 
11301 				mark_reg_known_zero(env, regs, BPF_REG_0);
11302 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11303 				regs[BPF_REG_0].btf = ret_btf;
11304 				regs[BPF_REG_0].btf_id = ret_btf_id;
11305 
11306 				insn_aux->obj_new_size = ret_t->size;
11307 				insn_aux->kptr_struct_meta =
11308 					btf_find_struct_meta(ret_btf, ret_btf_id);
11309 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11310 				mark_reg_known_zero(env, regs, BPF_REG_0);
11311 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11312 				regs[BPF_REG_0].btf = meta.arg_btf;
11313 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11314 
11315 				insn_aux->kptr_struct_meta =
11316 					btf_find_struct_meta(meta.arg_btf,
11317 							     meta.arg_btf_id);
11318 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11319 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11320 				struct btf_field *field = meta.arg_list_head.field;
11321 
11322 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11323 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11324 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11325 				struct btf_field *field = meta.arg_rbtree_root.field;
11326 
11327 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11328 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11329 				mark_reg_known_zero(env, regs, BPF_REG_0);
11330 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11331 				regs[BPF_REG_0].btf = desc_btf;
11332 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11333 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11334 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11335 				if (!ret_t || !btf_type_is_struct(ret_t)) {
11336 					verbose(env,
11337 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11338 					return -EINVAL;
11339 				}
11340 
11341 				mark_reg_known_zero(env, regs, BPF_REG_0);
11342 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11343 				regs[BPF_REG_0].btf = desc_btf;
11344 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11345 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11346 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11347 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11348 
11349 				mark_reg_known_zero(env, regs, BPF_REG_0);
11350 
11351 				if (!meta.arg_constant.found) {
11352 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11353 					return -EFAULT;
11354 				}
11355 
11356 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11357 
11358 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11359 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11360 
11361 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11362 					regs[BPF_REG_0].type |= MEM_RDONLY;
11363 				} else {
11364 					/* this will set env->seen_direct_write to true */
11365 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11366 						verbose(env, "the prog does not allow writes to packet data\n");
11367 						return -EINVAL;
11368 					}
11369 				}
11370 
11371 				if (!meta.initialized_dynptr.id) {
11372 					verbose(env, "verifier internal error: no dynptr id\n");
11373 					return -EFAULT;
11374 				}
11375 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11376 
11377 				/* we don't need to set BPF_REG_0's ref obj id
11378 				 * because packet slices are not refcounted (see
11379 				 * dynptr_type_refcounted)
11380 				 */
11381 			} else {
11382 				verbose(env, "kernel function %s unhandled dynamic return type\n",
11383 					meta.func_name);
11384 				return -EFAULT;
11385 			}
11386 		} else if (!__btf_type_is_struct(ptr_type)) {
11387 			if (!meta.r0_size) {
11388 				__u32 sz;
11389 
11390 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11391 					meta.r0_size = sz;
11392 					meta.r0_rdonly = true;
11393 				}
11394 			}
11395 			if (!meta.r0_size) {
11396 				ptr_type_name = btf_name_by_offset(desc_btf,
11397 								   ptr_type->name_off);
11398 				verbose(env,
11399 					"kernel function %s returns pointer type %s %s is not supported\n",
11400 					func_name,
11401 					btf_type_str(ptr_type),
11402 					ptr_type_name);
11403 				return -EINVAL;
11404 			}
11405 
11406 			mark_reg_known_zero(env, regs, BPF_REG_0);
11407 			regs[BPF_REG_0].type = PTR_TO_MEM;
11408 			regs[BPF_REG_0].mem_size = meta.r0_size;
11409 
11410 			if (meta.r0_rdonly)
11411 				regs[BPF_REG_0].type |= MEM_RDONLY;
11412 
11413 			/* Ensures we don't access the memory after a release_reference() */
11414 			if (meta.ref_obj_id)
11415 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11416 		} else {
11417 			mark_reg_known_zero(env, regs, BPF_REG_0);
11418 			regs[BPF_REG_0].btf = desc_btf;
11419 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11420 			regs[BPF_REG_0].btf_id = ptr_type_id;
11421 		}
11422 
11423 		if (is_kfunc_ret_null(&meta)) {
11424 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11425 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11426 			regs[BPF_REG_0].id = ++env->id_gen;
11427 		}
11428 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11429 		if (is_kfunc_acquire(&meta)) {
11430 			int id = acquire_reference_state(env, insn_idx);
11431 
11432 			if (id < 0)
11433 				return id;
11434 			if (is_kfunc_ret_null(&meta))
11435 				regs[BPF_REG_0].id = id;
11436 			regs[BPF_REG_0].ref_obj_id = id;
11437 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11438 			ref_set_non_owning(env, &regs[BPF_REG_0]);
11439 		}
11440 
11441 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
11442 			regs[BPF_REG_0].id = ++env->id_gen;
11443 	} else if (btf_type_is_void(t)) {
11444 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11445 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11446 				insn_aux->kptr_struct_meta =
11447 					btf_find_struct_meta(meta.arg_btf,
11448 							     meta.arg_btf_id);
11449 			}
11450 		}
11451 	}
11452 
11453 	nargs = btf_type_vlen(meta.func_proto);
11454 	args = (const struct btf_param *)(meta.func_proto + 1);
11455 	for (i = 0; i < nargs; i++) {
11456 		u32 regno = i + 1;
11457 
11458 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11459 		if (btf_type_is_ptr(t))
11460 			mark_btf_func_reg_size(env, regno, sizeof(void *));
11461 		else
11462 			/* scalar. ensured by btf_check_kfunc_arg_match() */
11463 			mark_btf_func_reg_size(env, regno, t->size);
11464 	}
11465 
11466 	if (is_iter_next_kfunc(&meta)) {
11467 		err = process_iter_next_call(env, insn_idx, &meta);
11468 		if (err)
11469 			return err;
11470 	}
11471 
11472 	return 0;
11473 }
11474 
11475 static bool signed_add_overflows(s64 a, s64 b)
11476 {
11477 	/* Do the add in u64, where overflow is well-defined */
11478 	s64 res = (s64)((u64)a + (u64)b);
11479 
11480 	if (b < 0)
11481 		return res > a;
11482 	return res < a;
11483 }
11484 
11485 static bool signed_add32_overflows(s32 a, s32 b)
11486 {
11487 	/* Do the add in u32, where overflow is well-defined */
11488 	s32 res = (s32)((u32)a + (u32)b);
11489 
11490 	if (b < 0)
11491 		return res > a;
11492 	return res < a;
11493 }
11494 
11495 static bool signed_sub_overflows(s64 a, s64 b)
11496 {
11497 	/* Do the sub in u64, where overflow is well-defined */
11498 	s64 res = (s64)((u64)a - (u64)b);
11499 
11500 	if (b < 0)
11501 		return res < a;
11502 	return res > a;
11503 }
11504 
11505 static bool signed_sub32_overflows(s32 a, s32 b)
11506 {
11507 	/* Do the sub in u32, where overflow is well-defined */
11508 	s32 res = (s32)((u32)a - (u32)b);
11509 
11510 	if (b < 0)
11511 		return res < a;
11512 	return res > a;
11513 }
11514 
11515 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11516 				  const struct bpf_reg_state *reg,
11517 				  enum bpf_reg_type type)
11518 {
11519 	bool known = tnum_is_const(reg->var_off);
11520 	s64 val = reg->var_off.value;
11521 	s64 smin = reg->smin_value;
11522 
11523 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11524 		verbose(env, "math between %s pointer and %lld is not allowed\n",
11525 			reg_type_str(env, type), val);
11526 		return false;
11527 	}
11528 
11529 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11530 		verbose(env, "%s pointer offset %d is not allowed\n",
11531 			reg_type_str(env, type), reg->off);
11532 		return false;
11533 	}
11534 
11535 	if (smin == S64_MIN) {
11536 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11537 			reg_type_str(env, type));
11538 		return false;
11539 	}
11540 
11541 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11542 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
11543 			smin, reg_type_str(env, type));
11544 		return false;
11545 	}
11546 
11547 	return true;
11548 }
11549 
11550 enum {
11551 	REASON_BOUNDS	= -1,
11552 	REASON_TYPE	= -2,
11553 	REASON_PATHS	= -3,
11554 	REASON_LIMIT	= -4,
11555 	REASON_STACK	= -5,
11556 };
11557 
11558 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11559 			      u32 *alu_limit, bool mask_to_left)
11560 {
11561 	u32 max = 0, ptr_limit = 0;
11562 
11563 	switch (ptr_reg->type) {
11564 	case PTR_TO_STACK:
11565 		/* Offset 0 is out-of-bounds, but acceptable start for the
11566 		 * left direction, see BPF_REG_FP. Also, unknown scalar
11567 		 * offset where we would need to deal with min/max bounds is
11568 		 * currently prohibited for unprivileged.
11569 		 */
11570 		max = MAX_BPF_STACK + mask_to_left;
11571 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11572 		break;
11573 	case PTR_TO_MAP_VALUE:
11574 		max = ptr_reg->map_ptr->value_size;
11575 		ptr_limit = (mask_to_left ?
11576 			     ptr_reg->smin_value :
11577 			     ptr_reg->umax_value) + ptr_reg->off;
11578 		break;
11579 	default:
11580 		return REASON_TYPE;
11581 	}
11582 
11583 	if (ptr_limit >= max)
11584 		return REASON_LIMIT;
11585 	*alu_limit = ptr_limit;
11586 	return 0;
11587 }
11588 
11589 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11590 				    const struct bpf_insn *insn)
11591 {
11592 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11593 }
11594 
11595 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11596 				       u32 alu_state, u32 alu_limit)
11597 {
11598 	/* If we arrived here from different branches with different
11599 	 * state or limits to sanitize, then this won't work.
11600 	 */
11601 	if (aux->alu_state &&
11602 	    (aux->alu_state != alu_state ||
11603 	     aux->alu_limit != alu_limit))
11604 		return REASON_PATHS;
11605 
11606 	/* Corresponding fixup done in do_misc_fixups(). */
11607 	aux->alu_state = alu_state;
11608 	aux->alu_limit = alu_limit;
11609 	return 0;
11610 }
11611 
11612 static int sanitize_val_alu(struct bpf_verifier_env *env,
11613 			    struct bpf_insn *insn)
11614 {
11615 	struct bpf_insn_aux_data *aux = cur_aux(env);
11616 
11617 	if (can_skip_alu_sanitation(env, insn))
11618 		return 0;
11619 
11620 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11621 }
11622 
11623 static bool sanitize_needed(u8 opcode)
11624 {
11625 	return opcode == BPF_ADD || opcode == BPF_SUB;
11626 }
11627 
11628 struct bpf_sanitize_info {
11629 	struct bpf_insn_aux_data aux;
11630 	bool mask_to_left;
11631 };
11632 
11633 static struct bpf_verifier_state *
11634 sanitize_speculative_path(struct bpf_verifier_env *env,
11635 			  const struct bpf_insn *insn,
11636 			  u32 next_idx, u32 curr_idx)
11637 {
11638 	struct bpf_verifier_state *branch;
11639 	struct bpf_reg_state *regs;
11640 
11641 	branch = push_stack(env, next_idx, curr_idx, true);
11642 	if (branch && insn) {
11643 		regs = branch->frame[branch->curframe]->regs;
11644 		if (BPF_SRC(insn->code) == BPF_K) {
11645 			mark_reg_unknown(env, regs, insn->dst_reg);
11646 		} else if (BPF_SRC(insn->code) == BPF_X) {
11647 			mark_reg_unknown(env, regs, insn->dst_reg);
11648 			mark_reg_unknown(env, regs, insn->src_reg);
11649 		}
11650 	}
11651 	return branch;
11652 }
11653 
11654 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11655 			    struct bpf_insn *insn,
11656 			    const struct bpf_reg_state *ptr_reg,
11657 			    const struct bpf_reg_state *off_reg,
11658 			    struct bpf_reg_state *dst_reg,
11659 			    struct bpf_sanitize_info *info,
11660 			    const bool commit_window)
11661 {
11662 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11663 	struct bpf_verifier_state *vstate = env->cur_state;
11664 	bool off_is_imm = tnum_is_const(off_reg->var_off);
11665 	bool off_is_neg = off_reg->smin_value < 0;
11666 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
11667 	u8 opcode = BPF_OP(insn->code);
11668 	u32 alu_state, alu_limit;
11669 	struct bpf_reg_state tmp;
11670 	bool ret;
11671 	int err;
11672 
11673 	if (can_skip_alu_sanitation(env, insn))
11674 		return 0;
11675 
11676 	/* We already marked aux for masking from non-speculative
11677 	 * paths, thus we got here in the first place. We only care
11678 	 * to explore bad access from here.
11679 	 */
11680 	if (vstate->speculative)
11681 		goto do_sim;
11682 
11683 	if (!commit_window) {
11684 		if (!tnum_is_const(off_reg->var_off) &&
11685 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11686 			return REASON_BOUNDS;
11687 
11688 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
11689 				     (opcode == BPF_SUB && !off_is_neg);
11690 	}
11691 
11692 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11693 	if (err < 0)
11694 		return err;
11695 
11696 	if (commit_window) {
11697 		/* In commit phase we narrow the masking window based on
11698 		 * the observed pointer move after the simulated operation.
11699 		 */
11700 		alu_state = info->aux.alu_state;
11701 		alu_limit = abs(info->aux.alu_limit - alu_limit);
11702 	} else {
11703 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11704 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11705 		alu_state |= ptr_is_dst_reg ?
11706 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11707 
11708 		/* Limit pruning on unknown scalars to enable deep search for
11709 		 * potential masking differences from other program paths.
11710 		 */
11711 		if (!off_is_imm)
11712 			env->explore_alu_limits = true;
11713 	}
11714 
11715 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11716 	if (err < 0)
11717 		return err;
11718 do_sim:
11719 	/* If we're in commit phase, we're done here given we already
11720 	 * pushed the truncated dst_reg into the speculative verification
11721 	 * stack.
11722 	 *
11723 	 * Also, when register is a known constant, we rewrite register-based
11724 	 * operation to immediate-based, and thus do not need masking (and as
11725 	 * a consequence, do not need to simulate the zero-truncation either).
11726 	 */
11727 	if (commit_window || off_is_imm)
11728 		return 0;
11729 
11730 	/* Simulate and find potential out-of-bounds access under
11731 	 * speculative execution from truncation as a result of
11732 	 * masking when off was not within expected range. If off
11733 	 * sits in dst, then we temporarily need to move ptr there
11734 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
11735 	 * for cases where we use K-based arithmetic in one direction
11736 	 * and truncated reg-based in the other in order to explore
11737 	 * bad access.
11738 	 */
11739 	if (!ptr_is_dst_reg) {
11740 		tmp = *dst_reg;
11741 		copy_register_state(dst_reg, ptr_reg);
11742 	}
11743 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11744 					env->insn_idx);
11745 	if (!ptr_is_dst_reg && ret)
11746 		*dst_reg = tmp;
11747 	return !ret ? REASON_STACK : 0;
11748 }
11749 
11750 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11751 {
11752 	struct bpf_verifier_state *vstate = env->cur_state;
11753 
11754 	/* If we simulate paths under speculation, we don't update the
11755 	 * insn as 'seen' such that when we verify unreachable paths in
11756 	 * the non-speculative domain, sanitize_dead_code() can still
11757 	 * rewrite/sanitize them.
11758 	 */
11759 	if (!vstate->speculative)
11760 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11761 }
11762 
11763 static int sanitize_err(struct bpf_verifier_env *env,
11764 			const struct bpf_insn *insn, int reason,
11765 			const struct bpf_reg_state *off_reg,
11766 			const struct bpf_reg_state *dst_reg)
11767 {
11768 	static const char *err = "pointer arithmetic with it prohibited for !root";
11769 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11770 	u32 dst = insn->dst_reg, src = insn->src_reg;
11771 
11772 	switch (reason) {
11773 	case REASON_BOUNDS:
11774 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11775 			off_reg == dst_reg ? dst : src, err);
11776 		break;
11777 	case REASON_TYPE:
11778 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11779 			off_reg == dst_reg ? src : dst, err);
11780 		break;
11781 	case REASON_PATHS:
11782 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11783 			dst, op, err);
11784 		break;
11785 	case REASON_LIMIT:
11786 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11787 			dst, op, err);
11788 		break;
11789 	case REASON_STACK:
11790 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11791 			dst, err);
11792 		break;
11793 	default:
11794 		verbose(env, "verifier internal error: unknown reason (%d)\n",
11795 			reason);
11796 		break;
11797 	}
11798 
11799 	return -EACCES;
11800 }
11801 
11802 /* check that stack access falls within stack limits and that 'reg' doesn't
11803  * have a variable offset.
11804  *
11805  * Variable offset is prohibited for unprivileged mode for simplicity since it
11806  * requires corresponding support in Spectre masking for stack ALU.  See also
11807  * retrieve_ptr_limit().
11808  *
11809  *
11810  * 'off' includes 'reg->off'.
11811  */
11812 static int check_stack_access_for_ptr_arithmetic(
11813 				struct bpf_verifier_env *env,
11814 				int regno,
11815 				const struct bpf_reg_state *reg,
11816 				int off)
11817 {
11818 	if (!tnum_is_const(reg->var_off)) {
11819 		char tn_buf[48];
11820 
11821 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11822 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11823 			regno, tn_buf, off);
11824 		return -EACCES;
11825 	}
11826 
11827 	if (off >= 0 || off < -MAX_BPF_STACK) {
11828 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
11829 			"prohibited for !root; off=%d\n", regno, off);
11830 		return -EACCES;
11831 	}
11832 
11833 	return 0;
11834 }
11835 
11836 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11837 				 const struct bpf_insn *insn,
11838 				 const struct bpf_reg_state *dst_reg)
11839 {
11840 	u32 dst = insn->dst_reg;
11841 
11842 	/* For unprivileged we require that resulting offset must be in bounds
11843 	 * in order to be able to sanitize access later on.
11844 	 */
11845 	if (env->bypass_spec_v1)
11846 		return 0;
11847 
11848 	switch (dst_reg->type) {
11849 	case PTR_TO_STACK:
11850 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
11851 					dst_reg->off + dst_reg->var_off.value))
11852 			return -EACCES;
11853 		break;
11854 	case PTR_TO_MAP_VALUE:
11855 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
11856 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
11857 				"prohibited for !root\n", dst);
11858 			return -EACCES;
11859 		}
11860 		break;
11861 	default:
11862 		break;
11863 	}
11864 
11865 	return 0;
11866 }
11867 
11868 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
11869  * Caller should also handle BPF_MOV case separately.
11870  * If we return -EACCES, caller may want to try again treating pointer as a
11871  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
11872  */
11873 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
11874 				   struct bpf_insn *insn,
11875 				   const struct bpf_reg_state *ptr_reg,
11876 				   const struct bpf_reg_state *off_reg)
11877 {
11878 	struct bpf_verifier_state *vstate = env->cur_state;
11879 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
11880 	struct bpf_reg_state *regs = state->regs, *dst_reg;
11881 	bool known = tnum_is_const(off_reg->var_off);
11882 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
11883 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
11884 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
11885 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
11886 	struct bpf_sanitize_info info = {};
11887 	u8 opcode = BPF_OP(insn->code);
11888 	u32 dst = insn->dst_reg;
11889 	int ret;
11890 
11891 	dst_reg = &regs[dst];
11892 
11893 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
11894 	    smin_val > smax_val || umin_val > umax_val) {
11895 		/* Taint dst register if offset had invalid bounds derived from
11896 		 * e.g. dead branches.
11897 		 */
11898 		__mark_reg_unknown(env, dst_reg);
11899 		return 0;
11900 	}
11901 
11902 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
11903 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
11904 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11905 			__mark_reg_unknown(env, dst_reg);
11906 			return 0;
11907 		}
11908 
11909 		verbose(env,
11910 			"R%d 32-bit pointer arithmetic prohibited\n",
11911 			dst);
11912 		return -EACCES;
11913 	}
11914 
11915 	if (ptr_reg->type & PTR_MAYBE_NULL) {
11916 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
11917 			dst, reg_type_str(env, ptr_reg->type));
11918 		return -EACCES;
11919 	}
11920 
11921 	switch (base_type(ptr_reg->type)) {
11922 	case CONST_PTR_TO_MAP:
11923 		/* smin_val represents the known value */
11924 		if (known && smin_val == 0 && opcode == BPF_ADD)
11925 			break;
11926 		fallthrough;
11927 	case PTR_TO_PACKET_END:
11928 	case PTR_TO_SOCKET:
11929 	case PTR_TO_SOCK_COMMON:
11930 	case PTR_TO_TCP_SOCK:
11931 	case PTR_TO_XDP_SOCK:
11932 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
11933 			dst, reg_type_str(env, ptr_reg->type));
11934 		return -EACCES;
11935 	default:
11936 		break;
11937 	}
11938 
11939 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
11940 	 * The id may be overwritten later if we create a new variable offset.
11941 	 */
11942 	dst_reg->type = ptr_reg->type;
11943 	dst_reg->id = ptr_reg->id;
11944 
11945 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
11946 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
11947 		return -EINVAL;
11948 
11949 	/* pointer types do not carry 32-bit bounds at the moment. */
11950 	__mark_reg32_unbounded(dst_reg);
11951 
11952 	if (sanitize_needed(opcode)) {
11953 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
11954 				       &info, false);
11955 		if (ret < 0)
11956 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
11957 	}
11958 
11959 	switch (opcode) {
11960 	case BPF_ADD:
11961 		/* We can take a fixed offset as long as it doesn't overflow
11962 		 * the s32 'off' field
11963 		 */
11964 		if (known && (ptr_reg->off + smin_val ==
11965 			      (s64)(s32)(ptr_reg->off + smin_val))) {
11966 			/* pointer += K.  Accumulate it into fixed offset */
11967 			dst_reg->smin_value = smin_ptr;
11968 			dst_reg->smax_value = smax_ptr;
11969 			dst_reg->umin_value = umin_ptr;
11970 			dst_reg->umax_value = umax_ptr;
11971 			dst_reg->var_off = ptr_reg->var_off;
11972 			dst_reg->off = ptr_reg->off + smin_val;
11973 			dst_reg->raw = ptr_reg->raw;
11974 			break;
11975 		}
11976 		/* A new variable offset is created.  Note that off_reg->off
11977 		 * == 0, since it's a scalar.
11978 		 * dst_reg gets the pointer type and since some positive
11979 		 * integer value was added to the pointer, give it a new 'id'
11980 		 * if it's a PTR_TO_PACKET.
11981 		 * this creates a new 'base' pointer, off_reg (variable) gets
11982 		 * added into the variable offset, and we copy the fixed offset
11983 		 * from ptr_reg.
11984 		 */
11985 		if (signed_add_overflows(smin_ptr, smin_val) ||
11986 		    signed_add_overflows(smax_ptr, smax_val)) {
11987 			dst_reg->smin_value = S64_MIN;
11988 			dst_reg->smax_value = S64_MAX;
11989 		} else {
11990 			dst_reg->smin_value = smin_ptr + smin_val;
11991 			dst_reg->smax_value = smax_ptr + smax_val;
11992 		}
11993 		if (umin_ptr + umin_val < umin_ptr ||
11994 		    umax_ptr + umax_val < umax_ptr) {
11995 			dst_reg->umin_value = 0;
11996 			dst_reg->umax_value = U64_MAX;
11997 		} else {
11998 			dst_reg->umin_value = umin_ptr + umin_val;
11999 			dst_reg->umax_value = umax_ptr + umax_val;
12000 		}
12001 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12002 		dst_reg->off = ptr_reg->off;
12003 		dst_reg->raw = ptr_reg->raw;
12004 		if (reg_is_pkt_pointer(ptr_reg)) {
12005 			dst_reg->id = ++env->id_gen;
12006 			/* something was added to pkt_ptr, set range to zero */
12007 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12008 		}
12009 		break;
12010 	case BPF_SUB:
12011 		if (dst_reg == off_reg) {
12012 			/* scalar -= pointer.  Creates an unknown scalar */
12013 			verbose(env, "R%d tried to subtract pointer from scalar\n",
12014 				dst);
12015 			return -EACCES;
12016 		}
12017 		/* We don't allow subtraction from FP, because (according to
12018 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
12019 		 * be able to deal with it.
12020 		 */
12021 		if (ptr_reg->type == PTR_TO_STACK) {
12022 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
12023 				dst);
12024 			return -EACCES;
12025 		}
12026 		if (known && (ptr_reg->off - smin_val ==
12027 			      (s64)(s32)(ptr_reg->off - smin_val))) {
12028 			/* pointer -= K.  Subtract it from fixed offset */
12029 			dst_reg->smin_value = smin_ptr;
12030 			dst_reg->smax_value = smax_ptr;
12031 			dst_reg->umin_value = umin_ptr;
12032 			dst_reg->umax_value = umax_ptr;
12033 			dst_reg->var_off = ptr_reg->var_off;
12034 			dst_reg->id = ptr_reg->id;
12035 			dst_reg->off = ptr_reg->off - smin_val;
12036 			dst_reg->raw = ptr_reg->raw;
12037 			break;
12038 		}
12039 		/* A new variable offset is created.  If the subtrahend is known
12040 		 * nonnegative, then any reg->range we had before is still good.
12041 		 */
12042 		if (signed_sub_overflows(smin_ptr, smax_val) ||
12043 		    signed_sub_overflows(smax_ptr, smin_val)) {
12044 			/* Overflow possible, we know nothing */
12045 			dst_reg->smin_value = S64_MIN;
12046 			dst_reg->smax_value = S64_MAX;
12047 		} else {
12048 			dst_reg->smin_value = smin_ptr - smax_val;
12049 			dst_reg->smax_value = smax_ptr - smin_val;
12050 		}
12051 		if (umin_ptr < umax_val) {
12052 			/* Overflow possible, we know nothing */
12053 			dst_reg->umin_value = 0;
12054 			dst_reg->umax_value = U64_MAX;
12055 		} else {
12056 			/* Cannot overflow (as long as bounds are consistent) */
12057 			dst_reg->umin_value = umin_ptr - umax_val;
12058 			dst_reg->umax_value = umax_ptr - umin_val;
12059 		}
12060 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12061 		dst_reg->off = ptr_reg->off;
12062 		dst_reg->raw = ptr_reg->raw;
12063 		if (reg_is_pkt_pointer(ptr_reg)) {
12064 			dst_reg->id = ++env->id_gen;
12065 			/* something was added to pkt_ptr, set range to zero */
12066 			if (smin_val < 0)
12067 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12068 		}
12069 		break;
12070 	case BPF_AND:
12071 	case BPF_OR:
12072 	case BPF_XOR:
12073 		/* bitwise ops on pointers are troublesome, prohibit. */
12074 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12075 			dst, bpf_alu_string[opcode >> 4]);
12076 		return -EACCES;
12077 	default:
12078 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
12079 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12080 			dst, bpf_alu_string[opcode >> 4]);
12081 		return -EACCES;
12082 	}
12083 
12084 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12085 		return -EINVAL;
12086 	reg_bounds_sync(dst_reg);
12087 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12088 		return -EACCES;
12089 	if (sanitize_needed(opcode)) {
12090 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12091 				       &info, true);
12092 		if (ret < 0)
12093 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12094 	}
12095 
12096 	return 0;
12097 }
12098 
12099 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12100 				 struct bpf_reg_state *src_reg)
12101 {
12102 	s32 smin_val = src_reg->s32_min_value;
12103 	s32 smax_val = src_reg->s32_max_value;
12104 	u32 umin_val = src_reg->u32_min_value;
12105 	u32 umax_val = src_reg->u32_max_value;
12106 
12107 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12108 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12109 		dst_reg->s32_min_value = S32_MIN;
12110 		dst_reg->s32_max_value = S32_MAX;
12111 	} else {
12112 		dst_reg->s32_min_value += smin_val;
12113 		dst_reg->s32_max_value += smax_val;
12114 	}
12115 	if (dst_reg->u32_min_value + umin_val < umin_val ||
12116 	    dst_reg->u32_max_value + umax_val < umax_val) {
12117 		dst_reg->u32_min_value = 0;
12118 		dst_reg->u32_max_value = U32_MAX;
12119 	} else {
12120 		dst_reg->u32_min_value += umin_val;
12121 		dst_reg->u32_max_value += umax_val;
12122 	}
12123 }
12124 
12125 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12126 			       struct bpf_reg_state *src_reg)
12127 {
12128 	s64 smin_val = src_reg->smin_value;
12129 	s64 smax_val = src_reg->smax_value;
12130 	u64 umin_val = src_reg->umin_value;
12131 	u64 umax_val = src_reg->umax_value;
12132 
12133 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12134 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
12135 		dst_reg->smin_value = S64_MIN;
12136 		dst_reg->smax_value = S64_MAX;
12137 	} else {
12138 		dst_reg->smin_value += smin_val;
12139 		dst_reg->smax_value += smax_val;
12140 	}
12141 	if (dst_reg->umin_value + umin_val < umin_val ||
12142 	    dst_reg->umax_value + umax_val < umax_val) {
12143 		dst_reg->umin_value = 0;
12144 		dst_reg->umax_value = U64_MAX;
12145 	} else {
12146 		dst_reg->umin_value += umin_val;
12147 		dst_reg->umax_value += umax_val;
12148 	}
12149 }
12150 
12151 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12152 				 struct bpf_reg_state *src_reg)
12153 {
12154 	s32 smin_val = src_reg->s32_min_value;
12155 	s32 smax_val = src_reg->s32_max_value;
12156 	u32 umin_val = src_reg->u32_min_value;
12157 	u32 umax_val = src_reg->u32_max_value;
12158 
12159 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12160 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12161 		/* Overflow possible, we know nothing */
12162 		dst_reg->s32_min_value = S32_MIN;
12163 		dst_reg->s32_max_value = S32_MAX;
12164 	} else {
12165 		dst_reg->s32_min_value -= smax_val;
12166 		dst_reg->s32_max_value -= smin_val;
12167 	}
12168 	if (dst_reg->u32_min_value < umax_val) {
12169 		/* Overflow possible, we know nothing */
12170 		dst_reg->u32_min_value = 0;
12171 		dst_reg->u32_max_value = U32_MAX;
12172 	} else {
12173 		/* Cannot overflow (as long as bounds are consistent) */
12174 		dst_reg->u32_min_value -= umax_val;
12175 		dst_reg->u32_max_value -= umin_val;
12176 	}
12177 }
12178 
12179 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12180 			       struct bpf_reg_state *src_reg)
12181 {
12182 	s64 smin_val = src_reg->smin_value;
12183 	s64 smax_val = src_reg->smax_value;
12184 	u64 umin_val = src_reg->umin_value;
12185 	u64 umax_val = src_reg->umax_value;
12186 
12187 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12188 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12189 		/* Overflow possible, we know nothing */
12190 		dst_reg->smin_value = S64_MIN;
12191 		dst_reg->smax_value = S64_MAX;
12192 	} else {
12193 		dst_reg->smin_value -= smax_val;
12194 		dst_reg->smax_value -= smin_val;
12195 	}
12196 	if (dst_reg->umin_value < umax_val) {
12197 		/* Overflow possible, we know nothing */
12198 		dst_reg->umin_value = 0;
12199 		dst_reg->umax_value = U64_MAX;
12200 	} else {
12201 		/* Cannot overflow (as long as bounds are consistent) */
12202 		dst_reg->umin_value -= umax_val;
12203 		dst_reg->umax_value -= umin_val;
12204 	}
12205 }
12206 
12207 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12208 				 struct bpf_reg_state *src_reg)
12209 {
12210 	s32 smin_val = src_reg->s32_min_value;
12211 	u32 umin_val = src_reg->u32_min_value;
12212 	u32 umax_val = src_reg->u32_max_value;
12213 
12214 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12215 		/* Ain't nobody got time to multiply that sign */
12216 		__mark_reg32_unbounded(dst_reg);
12217 		return;
12218 	}
12219 	/* Both values are positive, so we can work with unsigned and
12220 	 * copy the result to signed (unless it exceeds S32_MAX).
12221 	 */
12222 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12223 		/* Potential overflow, we know nothing */
12224 		__mark_reg32_unbounded(dst_reg);
12225 		return;
12226 	}
12227 	dst_reg->u32_min_value *= umin_val;
12228 	dst_reg->u32_max_value *= umax_val;
12229 	if (dst_reg->u32_max_value > S32_MAX) {
12230 		/* Overflow possible, we know nothing */
12231 		dst_reg->s32_min_value = S32_MIN;
12232 		dst_reg->s32_max_value = S32_MAX;
12233 	} else {
12234 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12235 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12236 	}
12237 }
12238 
12239 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12240 			       struct bpf_reg_state *src_reg)
12241 {
12242 	s64 smin_val = src_reg->smin_value;
12243 	u64 umin_val = src_reg->umin_value;
12244 	u64 umax_val = src_reg->umax_value;
12245 
12246 	if (smin_val < 0 || dst_reg->smin_value < 0) {
12247 		/* Ain't nobody got time to multiply that sign */
12248 		__mark_reg64_unbounded(dst_reg);
12249 		return;
12250 	}
12251 	/* Both values are positive, so we can work with unsigned and
12252 	 * copy the result to signed (unless it exceeds S64_MAX).
12253 	 */
12254 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12255 		/* Potential overflow, we know nothing */
12256 		__mark_reg64_unbounded(dst_reg);
12257 		return;
12258 	}
12259 	dst_reg->umin_value *= umin_val;
12260 	dst_reg->umax_value *= umax_val;
12261 	if (dst_reg->umax_value > S64_MAX) {
12262 		/* Overflow possible, we know nothing */
12263 		dst_reg->smin_value = S64_MIN;
12264 		dst_reg->smax_value = S64_MAX;
12265 	} else {
12266 		dst_reg->smin_value = dst_reg->umin_value;
12267 		dst_reg->smax_value = dst_reg->umax_value;
12268 	}
12269 }
12270 
12271 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12272 				 struct bpf_reg_state *src_reg)
12273 {
12274 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12275 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12276 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12277 	s32 smin_val = src_reg->s32_min_value;
12278 	u32 umax_val = src_reg->u32_max_value;
12279 
12280 	if (src_known && dst_known) {
12281 		__mark_reg32_known(dst_reg, var32_off.value);
12282 		return;
12283 	}
12284 
12285 	/* We get our minimum from the var_off, since that's inherently
12286 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12287 	 */
12288 	dst_reg->u32_min_value = var32_off.value;
12289 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12290 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12291 		/* Lose signed bounds when ANDing negative numbers,
12292 		 * ain't nobody got time for that.
12293 		 */
12294 		dst_reg->s32_min_value = S32_MIN;
12295 		dst_reg->s32_max_value = S32_MAX;
12296 	} else {
12297 		/* ANDing two positives gives a positive, so safe to
12298 		 * cast result into s64.
12299 		 */
12300 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12301 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12302 	}
12303 }
12304 
12305 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12306 			       struct bpf_reg_state *src_reg)
12307 {
12308 	bool src_known = tnum_is_const(src_reg->var_off);
12309 	bool dst_known = tnum_is_const(dst_reg->var_off);
12310 	s64 smin_val = src_reg->smin_value;
12311 	u64 umax_val = src_reg->umax_value;
12312 
12313 	if (src_known && dst_known) {
12314 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12315 		return;
12316 	}
12317 
12318 	/* We get our minimum from the var_off, since that's inherently
12319 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12320 	 */
12321 	dst_reg->umin_value = dst_reg->var_off.value;
12322 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12323 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12324 		/* Lose signed bounds when ANDing negative numbers,
12325 		 * ain't nobody got time for that.
12326 		 */
12327 		dst_reg->smin_value = S64_MIN;
12328 		dst_reg->smax_value = S64_MAX;
12329 	} else {
12330 		/* ANDing two positives gives a positive, so safe to
12331 		 * cast result into s64.
12332 		 */
12333 		dst_reg->smin_value = dst_reg->umin_value;
12334 		dst_reg->smax_value = dst_reg->umax_value;
12335 	}
12336 	/* We may learn something more from the var_off */
12337 	__update_reg_bounds(dst_reg);
12338 }
12339 
12340 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12341 				struct bpf_reg_state *src_reg)
12342 {
12343 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12344 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12345 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12346 	s32 smin_val = src_reg->s32_min_value;
12347 	u32 umin_val = src_reg->u32_min_value;
12348 
12349 	if (src_known && dst_known) {
12350 		__mark_reg32_known(dst_reg, var32_off.value);
12351 		return;
12352 	}
12353 
12354 	/* We get our maximum from the var_off, and our minimum is the
12355 	 * maximum of the operands' minima
12356 	 */
12357 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12358 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12359 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12360 		/* Lose signed bounds when ORing negative numbers,
12361 		 * ain't nobody got time for that.
12362 		 */
12363 		dst_reg->s32_min_value = S32_MIN;
12364 		dst_reg->s32_max_value = S32_MAX;
12365 	} else {
12366 		/* ORing two positives gives a positive, so safe to
12367 		 * cast result into s64.
12368 		 */
12369 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12370 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12371 	}
12372 }
12373 
12374 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12375 			      struct bpf_reg_state *src_reg)
12376 {
12377 	bool src_known = tnum_is_const(src_reg->var_off);
12378 	bool dst_known = tnum_is_const(dst_reg->var_off);
12379 	s64 smin_val = src_reg->smin_value;
12380 	u64 umin_val = src_reg->umin_value;
12381 
12382 	if (src_known && dst_known) {
12383 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12384 		return;
12385 	}
12386 
12387 	/* We get our maximum from the var_off, and our minimum is the
12388 	 * maximum of the operands' minima
12389 	 */
12390 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12391 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12392 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12393 		/* Lose signed bounds when ORing negative numbers,
12394 		 * ain't nobody got time for that.
12395 		 */
12396 		dst_reg->smin_value = S64_MIN;
12397 		dst_reg->smax_value = S64_MAX;
12398 	} else {
12399 		/* ORing two positives gives a positive, so safe to
12400 		 * cast result into s64.
12401 		 */
12402 		dst_reg->smin_value = dst_reg->umin_value;
12403 		dst_reg->smax_value = dst_reg->umax_value;
12404 	}
12405 	/* We may learn something more from the var_off */
12406 	__update_reg_bounds(dst_reg);
12407 }
12408 
12409 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12410 				 struct bpf_reg_state *src_reg)
12411 {
12412 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12413 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12414 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12415 	s32 smin_val = src_reg->s32_min_value;
12416 
12417 	if (src_known && dst_known) {
12418 		__mark_reg32_known(dst_reg, var32_off.value);
12419 		return;
12420 	}
12421 
12422 	/* We get both minimum and maximum from the var32_off. */
12423 	dst_reg->u32_min_value = var32_off.value;
12424 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12425 
12426 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12427 		/* XORing two positive sign numbers gives a positive,
12428 		 * so safe to cast u32 result into s32.
12429 		 */
12430 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12431 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12432 	} else {
12433 		dst_reg->s32_min_value = S32_MIN;
12434 		dst_reg->s32_max_value = S32_MAX;
12435 	}
12436 }
12437 
12438 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12439 			       struct bpf_reg_state *src_reg)
12440 {
12441 	bool src_known = tnum_is_const(src_reg->var_off);
12442 	bool dst_known = tnum_is_const(dst_reg->var_off);
12443 	s64 smin_val = src_reg->smin_value;
12444 
12445 	if (src_known && dst_known) {
12446 		/* dst_reg->var_off.value has been updated earlier */
12447 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12448 		return;
12449 	}
12450 
12451 	/* We get both minimum and maximum from the var_off. */
12452 	dst_reg->umin_value = dst_reg->var_off.value;
12453 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12454 
12455 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12456 		/* XORing two positive sign numbers gives a positive,
12457 		 * so safe to cast u64 result into s64.
12458 		 */
12459 		dst_reg->smin_value = dst_reg->umin_value;
12460 		dst_reg->smax_value = dst_reg->umax_value;
12461 	} else {
12462 		dst_reg->smin_value = S64_MIN;
12463 		dst_reg->smax_value = S64_MAX;
12464 	}
12465 
12466 	__update_reg_bounds(dst_reg);
12467 }
12468 
12469 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12470 				   u64 umin_val, u64 umax_val)
12471 {
12472 	/* We lose all sign bit information (except what we can pick
12473 	 * up from var_off)
12474 	 */
12475 	dst_reg->s32_min_value = S32_MIN;
12476 	dst_reg->s32_max_value = S32_MAX;
12477 	/* If we might shift our top bit out, then we know nothing */
12478 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12479 		dst_reg->u32_min_value = 0;
12480 		dst_reg->u32_max_value = U32_MAX;
12481 	} else {
12482 		dst_reg->u32_min_value <<= umin_val;
12483 		dst_reg->u32_max_value <<= umax_val;
12484 	}
12485 }
12486 
12487 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12488 				 struct bpf_reg_state *src_reg)
12489 {
12490 	u32 umax_val = src_reg->u32_max_value;
12491 	u32 umin_val = src_reg->u32_min_value;
12492 	/* u32 alu operation will zext upper bits */
12493 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
12494 
12495 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12496 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12497 	/* Not required but being careful mark reg64 bounds as unknown so
12498 	 * that we are forced to pick them up from tnum and zext later and
12499 	 * if some path skips this step we are still safe.
12500 	 */
12501 	__mark_reg64_unbounded(dst_reg);
12502 	__update_reg32_bounds(dst_reg);
12503 }
12504 
12505 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12506 				   u64 umin_val, u64 umax_val)
12507 {
12508 	/* Special case <<32 because it is a common compiler pattern to sign
12509 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12510 	 * positive we know this shift will also be positive so we can track
12511 	 * bounds correctly. Otherwise we lose all sign bit information except
12512 	 * what we can pick up from var_off. Perhaps we can generalize this
12513 	 * later to shifts of any length.
12514 	 */
12515 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12516 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12517 	else
12518 		dst_reg->smax_value = S64_MAX;
12519 
12520 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12521 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12522 	else
12523 		dst_reg->smin_value = S64_MIN;
12524 
12525 	/* If we might shift our top bit out, then we know nothing */
12526 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12527 		dst_reg->umin_value = 0;
12528 		dst_reg->umax_value = U64_MAX;
12529 	} else {
12530 		dst_reg->umin_value <<= umin_val;
12531 		dst_reg->umax_value <<= umax_val;
12532 	}
12533 }
12534 
12535 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12536 			       struct bpf_reg_state *src_reg)
12537 {
12538 	u64 umax_val = src_reg->umax_value;
12539 	u64 umin_val = src_reg->umin_value;
12540 
12541 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
12542 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12543 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12544 
12545 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12546 	/* We may learn something more from the var_off */
12547 	__update_reg_bounds(dst_reg);
12548 }
12549 
12550 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12551 				 struct bpf_reg_state *src_reg)
12552 {
12553 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
12554 	u32 umax_val = src_reg->u32_max_value;
12555 	u32 umin_val = src_reg->u32_min_value;
12556 
12557 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12558 	 * be negative, then either:
12559 	 * 1) src_reg might be zero, so the sign bit of the result is
12560 	 *    unknown, so we lose our signed bounds
12561 	 * 2) it's known negative, thus the unsigned bounds capture the
12562 	 *    signed bounds
12563 	 * 3) the signed bounds cross zero, so they tell us nothing
12564 	 *    about the result
12565 	 * If the value in dst_reg is known nonnegative, then again the
12566 	 * unsigned bounds capture the signed bounds.
12567 	 * Thus, in all cases it suffices to blow away our signed bounds
12568 	 * and rely on inferring new ones from the unsigned bounds and
12569 	 * var_off of the result.
12570 	 */
12571 	dst_reg->s32_min_value = S32_MIN;
12572 	dst_reg->s32_max_value = S32_MAX;
12573 
12574 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
12575 	dst_reg->u32_min_value >>= umax_val;
12576 	dst_reg->u32_max_value >>= umin_val;
12577 
12578 	__mark_reg64_unbounded(dst_reg);
12579 	__update_reg32_bounds(dst_reg);
12580 }
12581 
12582 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12583 			       struct bpf_reg_state *src_reg)
12584 {
12585 	u64 umax_val = src_reg->umax_value;
12586 	u64 umin_val = src_reg->umin_value;
12587 
12588 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12589 	 * be negative, then either:
12590 	 * 1) src_reg might be zero, so the sign bit of the result is
12591 	 *    unknown, so we lose our signed bounds
12592 	 * 2) it's known negative, thus the unsigned bounds capture the
12593 	 *    signed bounds
12594 	 * 3) the signed bounds cross zero, so they tell us nothing
12595 	 *    about the result
12596 	 * If the value in dst_reg is known nonnegative, then again the
12597 	 * unsigned bounds capture the signed bounds.
12598 	 * Thus, in all cases it suffices to blow away our signed bounds
12599 	 * and rely on inferring new ones from the unsigned bounds and
12600 	 * var_off of the result.
12601 	 */
12602 	dst_reg->smin_value = S64_MIN;
12603 	dst_reg->smax_value = S64_MAX;
12604 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12605 	dst_reg->umin_value >>= umax_val;
12606 	dst_reg->umax_value >>= umin_val;
12607 
12608 	/* Its not easy to operate on alu32 bounds here because it depends
12609 	 * on bits being shifted in. Take easy way out and mark unbounded
12610 	 * so we can recalculate later from tnum.
12611 	 */
12612 	__mark_reg32_unbounded(dst_reg);
12613 	__update_reg_bounds(dst_reg);
12614 }
12615 
12616 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12617 				  struct bpf_reg_state *src_reg)
12618 {
12619 	u64 umin_val = src_reg->u32_min_value;
12620 
12621 	/* Upon reaching here, src_known is true and
12622 	 * umax_val is equal to umin_val.
12623 	 */
12624 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12625 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12626 
12627 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12628 
12629 	/* blow away the dst_reg umin_value/umax_value and rely on
12630 	 * dst_reg var_off to refine the result.
12631 	 */
12632 	dst_reg->u32_min_value = 0;
12633 	dst_reg->u32_max_value = U32_MAX;
12634 
12635 	__mark_reg64_unbounded(dst_reg);
12636 	__update_reg32_bounds(dst_reg);
12637 }
12638 
12639 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12640 				struct bpf_reg_state *src_reg)
12641 {
12642 	u64 umin_val = src_reg->umin_value;
12643 
12644 	/* Upon reaching here, src_known is true and umax_val is equal
12645 	 * to umin_val.
12646 	 */
12647 	dst_reg->smin_value >>= umin_val;
12648 	dst_reg->smax_value >>= umin_val;
12649 
12650 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12651 
12652 	/* blow away the dst_reg umin_value/umax_value and rely on
12653 	 * dst_reg var_off to refine the result.
12654 	 */
12655 	dst_reg->umin_value = 0;
12656 	dst_reg->umax_value = U64_MAX;
12657 
12658 	/* Its not easy to operate on alu32 bounds here because it depends
12659 	 * on bits being shifted in from upper 32-bits. Take easy way out
12660 	 * and mark unbounded so we can recalculate later from tnum.
12661 	 */
12662 	__mark_reg32_unbounded(dst_reg);
12663 	__update_reg_bounds(dst_reg);
12664 }
12665 
12666 /* WARNING: This function does calculations on 64-bit values, but the actual
12667  * execution may occur on 32-bit values. Therefore, things like bitshifts
12668  * need extra checks in the 32-bit case.
12669  */
12670 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12671 				      struct bpf_insn *insn,
12672 				      struct bpf_reg_state *dst_reg,
12673 				      struct bpf_reg_state src_reg)
12674 {
12675 	struct bpf_reg_state *regs = cur_regs(env);
12676 	u8 opcode = BPF_OP(insn->code);
12677 	bool src_known;
12678 	s64 smin_val, smax_val;
12679 	u64 umin_val, umax_val;
12680 	s32 s32_min_val, s32_max_val;
12681 	u32 u32_min_val, u32_max_val;
12682 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12683 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12684 	int ret;
12685 
12686 	smin_val = src_reg.smin_value;
12687 	smax_val = src_reg.smax_value;
12688 	umin_val = src_reg.umin_value;
12689 	umax_val = src_reg.umax_value;
12690 
12691 	s32_min_val = src_reg.s32_min_value;
12692 	s32_max_val = src_reg.s32_max_value;
12693 	u32_min_val = src_reg.u32_min_value;
12694 	u32_max_val = src_reg.u32_max_value;
12695 
12696 	if (alu32) {
12697 		src_known = tnum_subreg_is_const(src_reg.var_off);
12698 		if ((src_known &&
12699 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12700 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12701 			/* Taint dst register if offset had invalid bounds
12702 			 * derived from e.g. dead branches.
12703 			 */
12704 			__mark_reg_unknown(env, dst_reg);
12705 			return 0;
12706 		}
12707 	} else {
12708 		src_known = tnum_is_const(src_reg.var_off);
12709 		if ((src_known &&
12710 		     (smin_val != smax_val || umin_val != umax_val)) ||
12711 		    smin_val > smax_val || umin_val > umax_val) {
12712 			/* Taint dst register if offset had invalid bounds
12713 			 * derived from e.g. dead branches.
12714 			 */
12715 			__mark_reg_unknown(env, dst_reg);
12716 			return 0;
12717 		}
12718 	}
12719 
12720 	if (!src_known &&
12721 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12722 		__mark_reg_unknown(env, dst_reg);
12723 		return 0;
12724 	}
12725 
12726 	if (sanitize_needed(opcode)) {
12727 		ret = sanitize_val_alu(env, insn);
12728 		if (ret < 0)
12729 			return sanitize_err(env, insn, ret, NULL, NULL);
12730 	}
12731 
12732 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12733 	 * There are two classes of instructions: The first class we track both
12734 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
12735 	 * greatest amount of precision when alu operations are mixed with jmp32
12736 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12737 	 * and BPF_OR. This is possible because these ops have fairly easy to
12738 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12739 	 * See alu32 verifier tests for examples. The second class of
12740 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12741 	 * with regards to tracking sign/unsigned bounds because the bits may
12742 	 * cross subreg boundaries in the alu64 case. When this happens we mark
12743 	 * the reg unbounded in the subreg bound space and use the resulting
12744 	 * tnum to calculate an approximation of the sign/unsigned bounds.
12745 	 */
12746 	switch (opcode) {
12747 	case BPF_ADD:
12748 		scalar32_min_max_add(dst_reg, &src_reg);
12749 		scalar_min_max_add(dst_reg, &src_reg);
12750 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12751 		break;
12752 	case BPF_SUB:
12753 		scalar32_min_max_sub(dst_reg, &src_reg);
12754 		scalar_min_max_sub(dst_reg, &src_reg);
12755 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12756 		break;
12757 	case BPF_MUL:
12758 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12759 		scalar32_min_max_mul(dst_reg, &src_reg);
12760 		scalar_min_max_mul(dst_reg, &src_reg);
12761 		break;
12762 	case BPF_AND:
12763 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12764 		scalar32_min_max_and(dst_reg, &src_reg);
12765 		scalar_min_max_and(dst_reg, &src_reg);
12766 		break;
12767 	case BPF_OR:
12768 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12769 		scalar32_min_max_or(dst_reg, &src_reg);
12770 		scalar_min_max_or(dst_reg, &src_reg);
12771 		break;
12772 	case BPF_XOR:
12773 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12774 		scalar32_min_max_xor(dst_reg, &src_reg);
12775 		scalar_min_max_xor(dst_reg, &src_reg);
12776 		break;
12777 	case BPF_LSH:
12778 		if (umax_val >= insn_bitness) {
12779 			/* Shifts greater than 31 or 63 are undefined.
12780 			 * This includes shifts by a negative number.
12781 			 */
12782 			mark_reg_unknown(env, regs, insn->dst_reg);
12783 			break;
12784 		}
12785 		if (alu32)
12786 			scalar32_min_max_lsh(dst_reg, &src_reg);
12787 		else
12788 			scalar_min_max_lsh(dst_reg, &src_reg);
12789 		break;
12790 	case BPF_RSH:
12791 		if (umax_val >= insn_bitness) {
12792 			/* Shifts greater than 31 or 63 are undefined.
12793 			 * This includes shifts by a negative number.
12794 			 */
12795 			mark_reg_unknown(env, regs, insn->dst_reg);
12796 			break;
12797 		}
12798 		if (alu32)
12799 			scalar32_min_max_rsh(dst_reg, &src_reg);
12800 		else
12801 			scalar_min_max_rsh(dst_reg, &src_reg);
12802 		break;
12803 	case BPF_ARSH:
12804 		if (umax_val >= insn_bitness) {
12805 			/* Shifts greater than 31 or 63 are undefined.
12806 			 * This includes shifts by a negative number.
12807 			 */
12808 			mark_reg_unknown(env, regs, insn->dst_reg);
12809 			break;
12810 		}
12811 		if (alu32)
12812 			scalar32_min_max_arsh(dst_reg, &src_reg);
12813 		else
12814 			scalar_min_max_arsh(dst_reg, &src_reg);
12815 		break;
12816 	default:
12817 		mark_reg_unknown(env, regs, insn->dst_reg);
12818 		break;
12819 	}
12820 
12821 	/* ALU32 ops are zero extended into 64bit register */
12822 	if (alu32)
12823 		zext_32_to_64(dst_reg);
12824 	reg_bounds_sync(dst_reg);
12825 	return 0;
12826 }
12827 
12828 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12829  * and var_off.
12830  */
12831 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12832 				   struct bpf_insn *insn)
12833 {
12834 	struct bpf_verifier_state *vstate = env->cur_state;
12835 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12836 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12837 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12838 	u8 opcode = BPF_OP(insn->code);
12839 	int err;
12840 
12841 	dst_reg = &regs[insn->dst_reg];
12842 	src_reg = NULL;
12843 	if (dst_reg->type != SCALAR_VALUE)
12844 		ptr_reg = dst_reg;
12845 	else
12846 		/* Make sure ID is cleared otherwise dst_reg min/max could be
12847 		 * incorrectly propagated into other registers by find_equal_scalars()
12848 		 */
12849 		dst_reg->id = 0;
12850 	if (BPF_SRC(insn->code) == BPF_X) {
12851 		src_reg = &regs[insn->src_reg];
12852 		if (src_reg->type != SCALAR_VALUE) {
12853 			if (dst_reg->type != SCALAR_VALUE) {
12854 				/* Combining two pointers by any ALU op yields
12855 				 * an arbitrary scalar. Disallow all math except
12856 				 * pointer subtraction
12857 				 */
12858 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12859 					mark_reg_unknown(env, regs, insn->dst_reg);
12860 					return 0;
12861 				}
12862 				verbose(env, "R%d pointer %s pointer prohibited\n",
12863 					insn->dst_reg,
12864 					bpf_alu_string[opcode >> 4]);
12865 				return -EACCES;
12866 			} else {
12867 				/* scalar += pointer
12868 				 * This is legal, but we have to reverse our
12869 				 * src/dest handling in computing the range
12870 				 */
12871 				err = mark_chain_precision(env, insn->dst_reg);
12872 				if (err)
12873 					return err;
12874 				return adjust_ptr_min_max_vals(env, insn,
12875 							       src_reg, dst_reg);
12876 			}
12877 		} else if (ptr_reg) {
12878 			/* pointer += scalar */
12879 			err = mark_chain_precision(env, insn->src_reg);
12880 			if (err)
12881 				return err;
12882 			return adjust_ptr_min_max_vals(env, insn,
12883 						       dst_reg, src_reg);
12884 		} else if (dst_reg->precise) {
12885 			/* if dst_reg is precise, src_reg should be precise as well */
12886 			err = mark_chain_precision(env, insn->src_reg);
12887 			if (err)
12888 				return err;
12889 		}
12890 	} else {
12891 		/* Pretend the src is a reg with a known value, since we only
12892 		 * need to be able to read from this state.
12893 		 */
12894 		off_reg.type = SCALAR_VALUE;
12895 		__mark_reg_known(&off_reg, insn->imm);
12896 		src_reg = &off_reg;
12897 		if (ptr_reg) /* pointer += K */
12898 			return adjust_ptr_min_max_vals(env, insn,
12899 						       ptr_reg, src_reg);
12900 	}
12901 
12902 	/* Got here implies adding two SCALAR_VALUEs */
12903 	if (WARN_ON_ONCE(ptr_reg)) {
12904 		print_verifier_state(env, state, true);
12905 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
12906 		return -EINVAL;
12907 	}
12908 	if (WARN_ON(!src_reg)) {
12909 		print_verifier_state(env, state, true);
12910 		verbose(env, "verifier internal error: no src_reg\n");
12911 		return -EINVAL;
12912 	}
12913 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
12914 }
12915 
12916 /* check validity of 32-bit and 64-bit arithmetic operations */
12917 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
12918 {
12919 	struct bpf_reg_state *regs = cur_regs(env);
12920 	u8 opcode = BPF_OP(insn->code);
12921 	int err;
12922 
12923 	if (opcode == BPF_END || opcode == BPF_NEG) {
12924 		if (opcode == BPF_NEG) {
12925 			if (BPF_SRC(insn->code) != BPF_K ||
12926 			    insn->src_reg != BPF_REG_0 ||
12927 			    insn->off != 0 || insn->imm != 0) {
12928 				verbose(env, "BPF_NEG uses reserved fields\n");
12929 				return -EINVAL;
12930 			}
12931 		} else {
12932 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
12933 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
12934 			    BPF_CLASS(insn->code) == BPF_ALU64) {
12935 				verbose(env, "BPF_END uses reserved fields\n");
12936 				return -EINVAL;
12937 			}
12938 		}
12939 
12940 		/* check src operand */
12941 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12942 		if (err)
12943 			return err;
12944 
12945 		if (is_pointer_value(env, insn->dst_reg)) {
12946 			verbose(env, "R%d pointer arithmetic prohibited\n",
12947 				insn->dst_reg);
12948 			return -EACCES;
12949 		}
12950 
12951 		/* check dest operand */
12952 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
12953 		if (err)
12954 			return err;
12955 
12956 	} else if (opcode == BPF_MOV) {
12957 
12958 		if (BPF_SRC(insn->code) == BPF_X) {
12959 			if (insn->imm != 0 || insn->off != 0) {
12960 				verbose(env, "BPF_MOV uses reserved fields\n");
12961 				return -EINVAL;
12962 			}
12963 
12964 			/* check src operand */
12965 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12966 			if (err)
12967 				return err;
12968 		} else {
12969 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
12970 				verbose(env, "BPF_MOV uses reserved fields\n");
12971 				return -EINVAL;
12972 			}
12973 		}
12974 
12975 		/* check dest operand, mark as required later */
12976 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12977 		if (err)
12978 			return err;
12979 
12980 		if (BPF_SRC(insn->code) == BPF_X) {
12981 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
12982 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
12983 			bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
12984 				       !tnum_is_const(src_reg->var_off);
12985 
12986 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
12987 				/* case: R1 = R2
12988 				 * copy register state to dest reg
12989 				 */
12990 				if (need_id)
12991 					/* Assign src and dst registers the same ID
12992 					 * that will be used by find_equal_scalars()
12993 					 * to propagate min/max range.
12994 					 */
12995 					src_reg->id = ++env->id_gen;
12996 				copy_register_state(dst_reg, src_reg);
12997 				dst_reg->live |= REG_LIVE_WRITTEN;
12998 				dst_reg->subreg_def = DEF_NOT_SUBREG;
12999 			} else {
13000 				/* R1 = (u32) R2 */
13001 				if (is_pointer_value(env, insn->src_reg)) {
13002 					verbose(env,
13003 						"R%d partial copy of pointer\n",
13004 						insn->src_reg);
13005 					return -EACCES;
13006 				} else if (src_reg->type == SCALAR_VALUE) {
13007 					bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13008 
13009 					if (is_src_reg_u32 && need_id)
13010 						src_reg->id = ++env->id_gen;
13011 					copy_register_state(dst_reg, src_reg);
13012 					/* Make sure ID is cleared if src_reg is not in u32 range otherwise
13013 					 * dst_reg min/max could be incorrectly
13014 					 * propagated into src_reg by find_equal_scalars()
13015 					 */
13016 					if (!is_src_reg_u32)
13017 						dst_reg->id = 0;
13018 					dst_reg->live |= REG_LIVE_WRITTEN;
13019 					dst_reg->subreg_def = env->insn_idx + 1;
13020 				} else {
13021 					mark_reg_unknown(env, regs,
13022 							 insn->dst_reg);
13023 				}
13024 				zext_32_to_64(dst_reg);
13025 				reg_bounds_sync(dst_reg);
13026 			}
13027 		} else {
13028 			/* case: R = imm
13029 			 * remember the value we stored into this reg
13030 			 */
13031 			/* clear any state __mark_reg_known doesn't set */
13032 			mark_reg_unknown(env, regs, insn->dst_reg);
13033 			regs[insn->dst_reg].type = SCALAR_VALUE;
13034 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13035 				__mark_reg_known(regs + insn->dst_reg,
13036 						 insn->imm);
13037 			} else {
13038 				__mark_reg_known(regs + insn->dst_reg,
13039 						 (u32)insn->imm);
13040 			}
13041 		}
13042 
13043 	} else if (opcode > BPF_END) {
13044 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13045 		return -EINVAL;
13046 
13047 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
13048 
13049 		if (BPF_SRC(insn->code) == BPF_X) {
13050 			if (insn->imm != 0 || insn->off != 0) {
13051 				verbose(env, "BPF_ALU uses reserved fields\n");
13052 				return -EINVAL;
13053 			}
13054 			/* check src1 operand */
13055 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13056 			if (err)
13057 				return err;
13058 		} else {
13059 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13060 				verbose(env, "BPF_ALU uses reserved fields\n");
13061 				return -EINVAL;
13062 			}
13063 		}
13064 
13065 		/* check src2 operand */
13066 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13067 		if (err)
13068 			return err;
13069 
13070 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13071 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13072 			verbose(env, "div by zero\n");
13073 			return -EINVAL;
13074 		}
13075 
13076 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13077 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13078 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13079 
13080 			if (insn->imm < 0 || insn->imm >= size) {
13081 				verbose(env, "invalid shift %d\n", insn->imm);
13082 				return -EINVAL;
13083 			}
13084 		}
13085 
13086 		/* check dest operand */
13087 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13088 		if (err)
13089 			return err;
13090 
13091 		return adjust_reg_min_max_vals(env, insn);
13092 	}
13093 
13094 	return 0;
13095 }
13096 
13097 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13098 				   struct bpf_reg_state *dst_reg,
13099 				   enum bpf_reg_type type,
13100 				   bool range_right_open)
13101 {
13102 	struct bpf_func_state *state;
13103 	struct bpf_reg_state *reg;
13104 	int new_range;
13105 
13106 	if (dst_reg->off < 0 ||
13107 	    (dst_reg->off == 0 && range_right_open))
13108 		/* This doesn't give us any range */
13109 		return;
13110 
13111 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
13112 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13113 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
13114 		 * than pkt_end, but that's because it's also less than pkt.
13115 		 */
13116 		return;
13117 
13118 	new_range = dst_reg->off;
13119 	if (range_right_open)
13120 		new_range++;
13121 
13122 	/* Examples for register markings:
13123 	 *
13124 	 * pkt_data in dst register:
13125 	 *
13126 	 *   r2 = r3;
13127 	 *   r2 += 8;
13128 	 *   if (r2 > pkt_end) goto <handle exception>
13129 	 *   <access okay>
13130 	 *
13131 	 *   r2 = r3;
13132 	 *   r2 += 8;
13133 	 *   if (r2 < pkt_end) goto <access okay>
13134 	 *   <handle exception>
13135 	 *
13136 	 *   Where:
13137 	 *     r2 == dst_reg, pkt_end == src_reg
13138 	 *     r2=pkt(id=n,off=8,r=0)
13139 	 *     r3=pkt(id=n,off=0,r=0)
13140 	 *
13141 	 * pkt_data in src register:
13142 	 *
13143 	 *   r2 = r3;
13144 	 *   r2 += 8;
13145 	 *   if (pkt_end >= r2) goto <access okay>
13146 	 *   <handle exception>
13147 	 *
13148 	 *   r2 = r3;
13149 	 *   r2 += 8;
13150 	 *   if (pkt_end <= r2) goto <handle exception>
13151 	 *   <access okay>
13152 	 *
13153 	 *   Where:
13154 	 *     pkt_end == dst_reg, r2 == src_reg
13155 	 *     r2=pkt(id=n,off=8,r=0)
13156 	 *     r3=pkt(id=n,off=0,r=0)
13157 	 *
13158 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13159 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13160 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
13161 	 * the check.
13162 	 */
13163 
13164 	/* If our ids match, then we must have the same max_value.  And we
13165 	 * don't care about the other reg's fixed offset, since if it's too big
13166 	 * the range won't allow anything.
13167 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13168 	 */
13169 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13170 		if (reg->type == type && reg->id == dst_reg->id)
13171 			/* keep the maximum range already checked */
13172 			reg->range = max(reg->range, new_range);
13173 	}));
13174 }
13175 
13176 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13177 {
13178 	struct tnum subreg = tnum_subreg(reg->var_off);
13179 	s32 sval = (s32)val;
13180 
13181 	switch (opcode) {
13182 	case BPF_JEQ:
13183 		if (tnum_is_const(subreg))
13184 			return !!tnum_equals_const(subreg, val);
13185 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13186 			return 0;
13187 		break;
13188 	case BPF_JNE:
13189 		if (tnum_is_const(subreg))
13190 			return !tnum_equals_const(subreg, val);
13191 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13192 			return 1;
13193 		break;
13194 	case BPF_JSET:
13195 		if ((~subreg.mask & subreg.value) & val)
13196 			return 1;
13197 		if (!((subreg.mask | subreg.value) & val))
13198 			return 0;
13199 		break;
13200 	case BPF_JGT:
13201 		if (reg->u32_min_value > val)
13202 			return 1;
13203 		else if (reg->u32_max_value <= val)
13204 			return 0;
13205 		break;
13206 	case BPF_JSGT:
13207 		if (reg->s32_min_value > sval)
13208 			return 1;
13209 		else if (reg->s32_max_value <= sval)
13210 			return 0;
13211 		break;
13212 	case BPF_JLT:
13213 		if (reg->u32_max_value < val)
13214 			return 1;
13215 		else if (reg->u32_min_value >= val)
13216 			return 0;
13217 		break;
13218 	case BPF_JSLT:
13219 		if (reg->s32_max_value < sval)
13220 			return 1;
13221 		else if (reg->s32_min_value >= sval)
13222 			return 0;
13223 		break;
13224 	case BPF_JGE:
13225 		if (reg->u32_min_value >= val)
13226 			return 1;
13227 		else if (reg->u32_max_value < val)
13228 			return 0;
13229 		break;
13230 	case BPF_JSGE:
13231 		if (reg->s32_min_value >= sval)
13232 			return 1;
13233 		else if (reg->s32_max_value < sval)
13234 			return 0;
13235 		break;
13236 	case BPF_JLE:
13237 		if (reg->u32_max_value <= val)
13238 			return 1;
13239 		else if (reg->u32_min_value > val)
13240 			return 0;
13241 		break;
13242 	case BPF_JSLE:
13243 		if (reg->s32_max_value <= sval)
13244 			return 1;
13245 		else if (reg->s32_min_value > sval)
13246 			return 0;
13247 		break;
13248 	}
13249 
13250 	return -1;
13251 }
13252 
13253 
13254 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13255 {
13256 	s64 sval = (s64)val;
13257 
13258 	switch (opcode) {
13259 	case BPF_JEQ:
13260 		if (tnum_is_const(reg->var_off))
13261 			return !!tnum_equals_const(reg->var_off, val);
13262 		else if (val < reg->umin_value || val > reg->umax_value)
13263 			return 0;
13264 		break;
13265 	case BPF_JNE:
13266 		if (tnum_is_const(reg->var_off))
13267 			return !tnum_equals_const(reg->var_off, val);
13268 		else if (val < reg->umin_value || val > reg->umax_value)
13269 			return 1;
13270 		break;
13271 	case BPF_JSET:
13272 		if ((~reg->var_off.mask & reg->var_off.value) & val)
13273 			return 1;
13274 		if (!((reg->var_off.mask | reg->var_off.value) & val))
13275 			return 0;
13276 		break;
13277 	case BPF_JGT:
13278 		if (reg->umin_value > val)
13279 			return 1;
13280 		else if (reg->umax_value <= val)
13281 			return 0;
13282 		break;
13283 	case BPF_JSGT:
13284 		if (reg->smin_value > sval)
13285 			return 1;
13286 		else if (reg->smax_value <= sval)
13287 			return 0;
13288 		break;
13289 	case BPF_JLT:
13290 		if (reg->umax_value < val)
13291 			return 1;
13292 		else if (reg->umin_value >= val)
13293 			return 0;
13294 		break;
13295 	case BPF_JSLT:
13296 		if (reg->smax_value < sval)
13297 			return 1;
13298 		else if (reg->smin_value >= sval)
13299 			return 0;
13300 		break;
13301 	case BPF_JGE:
13302 		if (reg->umin_value >= val)
13303 			return 1;
13304 		else if (reg->umax_value < val)
13305 			return 0;
13306 		break;
13307 	case BPF_JSGE:
13308 		if (reg->smin_value >= sval)
13309 			return 1;
13310 		else if (reg->smax_value < sval)
13311 			return 0;
13312 		break;
13313 	case BPF_JLE:
13314 		if (reg->umax_value <= val)
13315 			return 1;
13316 		else if (reg->umin_value > val)
13317 			return 0;
13318 		break;
13319 	case BPF_JSLE:
13320 		if (reg->smax_value <= sval)
13321 			return 1;
13322 		else if (reg->smin_value > sval)
13323 			return 0;
13324 		break;
13325 	}
13326 
13327 	return -1;
13328 }
13329 
13330 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13331  * and return:
13332  *  1 - branch will be taken and "goto target" will be executed
13333  *  0 - branch will not be taken and fall-through to next insn
13334  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13335  *      range [0,10]
13336  */
13337 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13338 			   bool is_jmp32)
13339 {
13340 	if (__is_pointer_value(false, reg)) {
13341 		if (!reg_not_null(reg))
13342 			return -1;
13343 
13344 		/* If pointer is valid tests against zero will fail so we can
13345 		 * use this to direct branch taken.
13346 		 */
13347 		if (val != 0)
13348 			return -1;
13349 
13350 		switch (opcode) {
13351 		case BPF_JEQ:
13352 			return 0;
13353 		case BPF_JNE:
13354 			return 1;
13355 		default:
13356 			return -1;
13357 		}
13358 	}
13359 
13360 	if (is_jmp32)
13361 		return is_branch32_taken(reg, val, opcode);
13362 	return is_branch64_taken(reg, val, opcode);
13363 }
13364 
13365 static int flip_opcode(u32 opcode)
13366 {
13367 	/* How can we transform "a <op> b" into "b <op> a"? */
13368 	static const u8 opcode_flip[16] = {
13369 		/* these stay the same */
13370 		[BPF_JEQ  >> 4] = BPF_JEQ,
13371 		[BPF_JNE  >> 4] = BPF_JNE,
13372 		[BPF_JSET >> 4] = BPF_JSET,
13373 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
13374 		[BPF_JGE  >> 4] = BPF_JLE,
13375 		[BPF_JGT  >> 4] = BPF_JLT,
13376 		[BPF_JLE  >> 4] = BPF_JGE,
13377 		[BPF_JLT  >> 4] = BPF_JGT,
13378 		[BPF_JSGE >> 4] = BPF_JSLE,
13379 		[BPF_JSGT >> 4] = BPF_JSLT,
13380 		[BPF_JSLE >> 4] = BPF_JSGE,
13381 		[BPF_JSLT >> 4] = BPF_JSGT
13382 	};
13383 	return opcode_flip[opcode >> 4];
13384 }
13385 
13386 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13387 				   struct bpf_reg_state *src_reg,
13388 				   u8 opcode)
13389 {
13390 	struct bpf_reg_state *pkt;
13391 
13392 	if (src_reg->type == PTR_TO_PACKET_END) {
13393 		pkt = dst_reg;
13394 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
13395 		pkt = src_reg;
13396 		opcode = flip_opcode(opcode);
13397 	} else {
13398 		return -1;
13399 	}
13400 
13401 	if (pkt->range >= 0)
13402 		return -1;
13403 
13404 	switch (opcode) {
13405 	case BPF_JLE:
13406 		/* pkt <= pkt_end */
13407 		fallthrough;
13408 	case BPF_JGT:
13409 		/* pkt > pkt_end */
13410 		if (pkt->range == BEYOND_PKT_END)
13411 			/* pkt has at last one extra byte beyond pkt_end */
13412 			return opcode == BPF_JGT;
13413 		break;
13414 	case BPF_JLT:
13415 		/* pkt < pkt_end */
13416 		fallthrough;
13417 	case BPF_JGE:
13418 		/* pkt >= pkt_end */
13419 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13420 			return opcode == BPF_JGE;
13421 		break;
13422 	}
13423 	return -1;
13424 }
13425 
13426 /* Adjusts the register min/max values in the case that the dst_reg is the
13427  * variable register that we are working on, and src_reg is a constant or we're
13428  * simply doing a BPF_K check.
13429  * In JEQ/JNE cases we also adjust the var_off values.
13430  */
13431 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13432 			    struct bpf_reg_state *false_reg,
13433 			    u64 val, u32 val32,
13434 			    u8 opcode, bool is_jmp32)
13435 {
13436 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
13437 	struct tnum false_64off = false_reg->var_off;
13438 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
13439 	struct tnum true_64off = true_reg->var_off;
13440 	s64 sval = (s64)val;
13441 	s32 sval32 = (s32)val32;
13442 
13443 	/* If the dst_reg is a pointer, we can't learn anything about its
13444 	 * variable offset from the compare (unless src_reg were a pointer into
13445 	 * the same object, but we don't bother with that.
13446 	 * Since false_reg and true_reg have the same type by construction, we
13447 	 * only need to check one of them for pointerness.
13448 	 */
13449 	if (__is_pointer_value(false, false_reg))
13450 		return;
13451 
13452 	switch (opcode) {
13453 	/* JEQ/JNE comparison doesn't change the register equivalence.
13454 	 *
13455 	 * r1 = r2;
13456 	 * if (r1 == 42) goto label;
13457 	 * ...
13458 	 * label: // here both r1 and r2 are known to be 42.
13459 	 *
13460 	 * Hence when marking register as known preserve it's ID.
13461 	 */
13462 	case BPF_JEQ:
13463 		if (is_jmp32) {
13464 			__mark_reg32_known(true_reg, val32);
13465 			true_32off = tnum_subreg(true_reg->var_off);
13466 		} else {
13467 			___mark_reg_known(true_reg, val);
13468 			true_64off = true_reg->var_off;
13469 		}
13470 		break;
13471 	case BPF_JNE:
13472 		if (is_jmp32) {
13473 			__mark_reg32_known(false_reg, val32);
13474 			false_32off = tnum_subreg(false_reg->var_off);
13475 		} else {
13476 			___mark_reg_known(false_reg, val);
13477 			false_64off = false_reg->var_off;
13478 		}
13479 		break;
13480 	case BPF_JSET:
13481 		if (is_jmp32) {
13482 			false_32off = tnum_and(false_32off, tnum_const(~val32));
13483 			if (is_power_of_2(val32))
13484 				true_32off = tnum_or(true_32off,
13485 						     tnum_const(val32));
13486 		} else {
13487 			false_64off = tnum_and(false_64off, tnum_const(~val));
13488 			if (is_power_of_2(val))
13489 				true_64off = tnum_or(true_64off,
13490 						     tnum_const(val));
13491 		}
13492 		break;
13493 	case BPF_JGE:
13494 	case BPF_JGT:
13495 	{
13496 		if (is_jmp32) {
13497 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
13498 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13499 
13500 			false_reg->u32_max_value = min(false_reg->u32_max_value,
13501 						       false_umax);
13502 			true_reg->u32_min_value = max(true_reg->u32_min_value,
13503 						      true_umin);
13504 		} else {
13505 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
13506 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13507 
13508 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
13509 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
13510 		}
13511 		break;
13512 	}
13513 	case BPF_JSGE:
13514 	case BPF_JSGT:
13515 	{
13516 		if (is_jmp32) {
13517 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
13518 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13519 
13520 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13521 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13522 		} else {
13523 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
13524 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13525 
13526 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
13527 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
13528 		}
13529 		break;
13530 	}
13531 	case BPF_JLE:
13532 	case BPF_JLT:
13533 	{
13534 		if (is_jmp32) {
13535 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
13536 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13537 
13538 			false_reg->u32_min_value = max(false_reg->u32_min_value,
13539 						       false_umin);
13540 			true_reg->u32_max_value = min(true_reg->u32_max_value,
13541 						      true_umax);
13542 		} else {
13543 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
13544 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13545 
13546 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
13547 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
13548 		}
13549 		break;
13550 	}
13551 	case BPF_JSLE:
13552 	case BPF_JSLT:
13553 	{
13554 		if (is_jmp32) {
13555 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
13556 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13557 
13558 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13559 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13560 		} else {
13561 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
13562 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13563 
13564 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
13565 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
13566 		}
13567 		break;
13568 	}
13569 	default:
13570 		return;
13571 	}
13572 
13573 	if (is_jmp32) {
13574 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13575 					     tnum_subreg(false_32off));
13576 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13577 					    tnum_subreg(true_32off));
13578 		__reg_combine_32_into_64(false_reg);
13579 		__reg_combine_32_into_64(true_reg);
13580 	} else {
13581 		false_reg->var_off = false_64off;
13582 		true_reg->var_off = true_64off;
13583 		__reg_combine_64_into_32(false_reg);
13584 		__reg_combine_64_into_32(true_reg);
13585 	}
13586 }
13587 
13588 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13589  * the variable reg.
13590  */
13591 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13592 				struct bpf_reg_state *false_reg,
13593 				u64 val, u32 val32,
13594 				u8 opcode, bool is_jmp32)
13595 {
13596 	opcode = flip_opcode(opcode);
13597 	/* This uses zero as "not present in table"; luckily the zero opcode,
13598 	 * BPF_JA, can't get here.
13599 	 */
13600 	if (opcode)
13601 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13602 }
13603 
13604 /* Regs are known to be equal, so intersect their min/max/var_off */
13605 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13606 				  struct bpf_reg_state *dst_reg)
13607 {
13608 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13609 							dst_reg->umin_value);
13610 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13611 							dst_reg->umax_value);
13612 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13613 							dst_reg->smin_value);
13614 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13615 							dst_reg->smax_value);
13616 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13617 							     dst_reg->var_off);
13618 	reg_bounds_sync(src_reg);
13619 	reg_bounds_sync(dst_reg);
13620 }
13621 
13622 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13623 				struct bpf_reg_state *true_dst,
13624 				struct bpf_reg_state *false_src,
13625 				struct bpf_reg_state *false_dst,
13626 				u8 opcode)
13627 {
13628 	switch (opcode) {
13629 	case BPF_JEQ:
13630 		__reg_combine_min_max(true_src, true_dst);
13631 		break;
13632 	case BPF_JNE:
13633 		__reg_combine_min_max(false_src, false_dst);
13634 		break;
13635 	}
13636 }
13637 
13638 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13639 				 struct bpf_reg_state *reg, u32 id,
13640 				 bool is_null)
13641 {
13642 	if (type_may_be_null(reg->type) && reg->id == id &&
13643 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13644 		/* Old offset (both fixed and variable parts) should have been
13645 		 * known-zero, because we don't allow pointer arithmetic on
13646 		 * pointers that might be NULL. If we see this happening, don't
13647 		 * convert the register.
13648 		 *
13649 		 * But in some cases, some helpers that return local kptrs
13650 		 * advance offset for the returned pointer. In those cases, it
13651 		 * is fine to expect to see reg->off.
13652 		 */
13653 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13654 			return;
13655 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13656 		    WARN_ON_ONCE(reg->off))
13657 			return;
13658 
13659 		if (is_null) {
13660 			reg->type = SCALAR_VALUE;
13661 			/* We don't need id and ref_obj_id from this point
13662 			 * onwards anymore, thus we should better reset it,
13663 			 * so that state pruning has chances to take effect.
13664 			 */
13665 			reg->id = 0;
13666 			reg->ref_obj_id = 0;
13667 
13668 			return;
13669 		}
13670 
13671 		mark_ptr_not_null_reg(reg);
13672 
13673 		if (!reg_may_point_to_spin_lock(reg)) {
13674 			/* For not-NULL ptr, reg->ref_obj_id will be reset
13675 			 * in release_reference().
13676 			 *
13677 			 * reg->id is still used by spin_lock ptr. Other
13678 			 * than spin_lock ptr type, reg->id can be reset.
13679 			 */
13680 			reg->id = 0;
13681 		}
13682 	}
13683 }
13684 
13685 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13686  * be folded together at some point.
13687  */
13688 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13689 				  bool is_null)
13690 {
13691 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13692 	struct bpf_reg_state *regs = state->regs, *reg;
13693 	u32 ref_obj_id = regs[regno].ref_obj_id;
13694 	u32 id = regs[regno].id;
13695 
13696 	if (ref_obj_id && ref_obj_id == id && is_null)
13697 		/* regs[regno] is in the " == NULL" branch.
13698 		 * No one could have freed the reference state before
13699 		 * doing the NULL check.
13700 		 */
13701 		WARN_ON_ONCE(release_reference_state(state, id));
13702 
13703 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13704 		mark_ptr_or_null_reg(state, reg, id, is_null);
13705 	}));
13706 }
13707 
13708 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13709 				   struct bpf_reg_state *dst_reg,
13710 				   struct bpf_reg_state *src_reg,
13711 				   struct bpf_verifier_state *this_branch,
13712 				   struct bpf_verifier_state *other_branch)
13713 {
13714 	if (BPF_SRC(insn->code) != BPF_X)
13715 		return false;
13716 
13717 	/* Pointers are always 64-bit. */
13718 	if (BPF_CLASS(insn->code) == BPF_JMP32)
13719 		return false;
13720 
13721 	switch (BPF_OP(insn->code)) {
13722 	case BPF_JGT:
13723 		if ((dst_reg->type == PTR_TO_PACKET &&
13724 		     src_reg->type == PTR_TO_PACKET_END) ||
13725 		    (dst_reg->type == PTR_TO_PACKET_META &&
13726 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13727 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13728 			find_good_pkt_pointers(this_branch, dst_reg,
13729 					       dst_reg->type, false);
13730 			mark_pkt_end(other_branch, insn->dst_reg, true);
13731 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13732 			    src_reg->type == PTR_TO_PACKET) ||
13733 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13734 			    src_reg->type == PTR_TO_PACKET_META)) {
13735 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
13736 			find_good_pkt_pointers(other_branch, src_reg,
13737 					       src_reg->type, true);
13738 			mark_pkt_end(this_branch, insn->src_reg, false);
13739 		} else {
13740 			return false;
13741 		}
13742 		break;
13743 	case BPF_JLT:
13744 		if ((dst_reg->type == PTR_TO_PACKET &&
13745 		     src_reg->type == PTR_TO_PACKET_END) ||
13746 		    (dst_reg->type == PTR_TO_PACKET_META &&
13747 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13748 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13749 			find_good_pkt_pointers(other_branch, dst_reg,
13750 					       dst_reg->type, true);
13751 			mark_pkt_end(this_branch, insn->dst_reg, false);
13752 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13753 			    src_reg->type == PTR_TO_PACKET) ||
13754 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13755 			    src_reg->type == PTR_TO_PACKET_META)) {
13756 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
13757 			find_good_pkt_pointers(this_branch, src_reg,
13758 					       src_reg->type, false);
13759 			mark_pkt_end(other_branch, insn->src_reg, true);
13760 		} else {
13761 			return false;
13762 		}
13763 		break;
13764 	case BPF_JGE:
13765 		if ((dst_reg->type == PTR_TO_PACKET &&
13766 		     src_reg->type == PTR_TO_PACKET_END) ||
13767 		    (dst_reg->type == PTR_TO_PACKET_META &&
13768 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13769 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13770 			find_good_pkt_pointers(this_branch, dst_reg,
13771 					       dst_reg->type, true);
13772 			mark_pkt_end(other_branch, insn->dst_reg, false);
13773 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13774 			    src_reg->type == PTR_TO_PACKET) ||
13775 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13776 			    src_reg->type == PTR_TO_PACKET_META)) {
13777 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13778 			find_good_pkt_pointers(other_branch, src_reg,
13779 					       src_reg->type, false);
13780 			mark_pkt_end(this_branch, insn->src_reg, true);
13781 		} else {
13782 			return false;
13783 		}
13784 		break;
13785 	case BPF_JLE:
13786 		if ((dst_reg->type == PTR_TO_PACKET &&
13787 		     src_reg->type == PTR_TO_PACKET_END) ||
13788 		    (dst_reg->type == PTR_TO_PACKET_META &&
13789 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13790 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13791 			find_good_pkt_pointers(other_branch, dst_reg,
13792 					       dst_reg->type, false);
13793 			mark_pkt_end(this_branch, insn->dst_reg, true);
13794 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13795 			    src_reg->type == PTR_TO_PACKET) ||
13796 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13797 			    src_reg->type == PTR_TO_PACKET_META)) {
13798 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13799 			find_good_pkt_pointers(this_branch, src_reg,
13800 					       src_reg->type, true);
13801 			mark_pkt_end(other_branch, insn->src_reg, false);
13802 		} else {
13803 			return false;
13804 		}
13805 		break;
13806 	default:
13807 		return false;
13808 	}
13809 
13810 	return true;
13811 }
13812 
13813 static void find_equal_scalars(struct bpf_verifier_state *vstate,
13814 			       struct bpf_reg_state *known_reg)
13815 {
13816 	struct bpf_func_state *state;
13817 	struct bpf_reg_state *reg;
13818 
13819 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13820 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
13821 			copy_register_state(reg, known_reg);
13822 	}));
13823 }
13824 
13825 static int check_cond_jmp_op(struct bpf_verifier_env *env,
13826 			     struct bpf_insn *insn, int *insn_idx)
13827 {
13828 	struct bpf_verifier_state *this_branch = env->cur_state;
13829 	struct bpf_verifier_state *other_branch;
13830 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
13831 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
13832 	struct bpf_reg_state *eq_branch_regs;
13833 	u8 opcode = BPF_OP(insn->code);
13834 	bool is_jmp32;
13835 	int pred = -1;
13836 	int err;
13837 
13838 	/* Only conditional jumps are expected to reach here. */
13839 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
13840 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
13841 		return -EINVAL;
13842 	}
13843 
13844 	if (BPF_SRC(insn->code) == BPF_X) {
13845 		if (insn->imm != 0) {
13846 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13847 			return -EINVAL;
13848 		}
13849 
13850 		/* check src1 operand */
13851 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
13852 		if (err)
13853 			return err;
13854 
13855 		if (is_pointer_value(env, insn->src_reg)) {
13856 			verbose(env, "R%d pointer comparison prohibited\n",
13857 				insn->src_reg);
13858 			return -EACCES;
13859 		}
13860 		src_reg = &regs[insn->src_reg];
13861 	} else {
13862 		if (insn->src_reg != BPF_REG_0) {
13863 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13864 			return -EINVAL;
13865 		}
13866 	}
13867 
13868 	/* check src2 operand */
13869 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13870 	if (err)
13871 		return err;
13872 
13873 	dst_reg = &regs[insn->dst_reg];
13874 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
13875 
13876 	if (BPF_SRC(insn->code) == BPF_K) {
13877 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
13878 	} else if (src_reg->type == SCALAR_VALUE &&
13879 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
13880 		pred = is_branch_taken(dst_reg,
13881 				       tnum_subreg(src_reg->var_off).value,
13882 				       opcode,
13883 				       is_jmp32);
13884 	} else if (src_reg->type == SCALAR_VALUE &&
13885 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
13886 		pred = is_branch_taken(dst_reg,
13887 				       src_reg->var_off.value,
13888 				       opcode,
13889 				       is_jmp32);
13890 	} else if (dst_reg->type == SCALAR_VALUE &&
13891 		   is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
13892 		pred = is_branch_taken(src_reg,
13893 				       tnum_subreg(dst_reg->var_off).value,
13894 				       flip_opcode(opcode),
13895 				       is_jmp32);
13896 	} else if (dst_reg->type == SCALAR_VALUE &&
13897 		   !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
13898 		pred = is_branch_taken(src_reg,
13899 				       dst_reg->var_off.value,
13900 				       flip_opcode(opcode),
13901 				       is_jmp32);
13902 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
13903 		   reg_is_pkt_pointer_any(src_reg) &&
13904 		   !is_jmp32) {
13905 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
13906 	}
13907 
13908 	if (pred >= 0) {
13909 		/* If we get here with a dst_reg pointer type it is because
13910 		 * above is_branch_taken() special cased the 0 comparison.
13911 		 */
13912 		if (!__is_pointer_value(false, dst_reg))
13913 			err = mark_chain_precision(env, insn->dst_reg);
13914 		if (BPF_SRC(insn->code) == BPF_X && !err &&
13915 		    !__is_pointer_value(false, src_reg))
13916 			err = mark_chain_precision(env, insn->src_reg);
13917 		if (err)
13918 			return err;
13919 	}
13920 
13921 	if (pred == 1) {
13922 		/* Only follow the goto, ignore fall-through. If needed, push
13923 		 * the fall-through branch for simulation under speculative
13924 		 * execution.
13925 		 */
13926 		if (!env->bypass_spec_v1 &&
13927 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
13928 					       *insn_idx))
13929 			return -EFAULT;
13930 		*insn_idx += insn->off;
13931 		return 0;
13932 	} else if (pred == 0) {
13933 		/* Only follow the fall-through branch, since that's where the
13934 		 * program will go. If needed, push the goto branch for
13935 		 * simulation under speculative execution.
13936 		 */
13937 		if (!env->bypass_spec_v1 &&
13938 		    !sanitize_speculative_path(env, insn,
13939 					       *insn_idx + insn->off + 1,
13940 					       *insn_idx))
13941 			return -EFAULT;
13942 		return 0;
13943 	}
13944 
13945 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
13946 				  false);
13947 	if (!other_branch)
13948 		return -EFAULT;
13949 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
13950 
13951 	/* detect if we are comparing against a constant value so we can adjust
13952 	 * our min/max values for our dst register.
13953 	 * this is only legit if both are scalars (or pointers to the same
13954 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
13955 	 * because otherwise the different base pointers mean the offsets aren't
13956 	 * comparable.
13957 	 */
13958 	if (BPF_SRC(insn->code) == BPF_X) {
13959 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
13960 
13961 		if (dst_reg->type == SCALAR_VALUE &&
13962 		    src_reg->type == SCALAR_VALUE) {
13963 			if (tnum_is_const(src_reg->var_off) ||
13964 			    (is_jmp32 &&
13965 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
13966 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
13967 						dst_reg,
13968 						src_reg->var_off.value,
13969 						tnum_subreg(src_reg->var_off).value,
13970 						opcode, is_jmp32);
13971 			else if (tnum_is_const(dst_reg->var_off) ||
13972 				 (is_jmp32 &&
13973 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
13974 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
13975 						    src_reg,
13976 						    dst_reg->var_off.value,
13977 						    tnum_subreg(dst_reg->var_off).value,
13978 						    opcode, is_jmp32);
13979 			else if (!is_jmp32 &&
13980 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
13981 				/* Comparing for equality, we can combine knowledge */
13982 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
13983 						    &other_branch_regs[insn->dst_reg],
13984 						    src_reg, dst_reg, opcode);
13985 			if (src_reg->id &&
13986 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
13987 				find_equal_scalars(this_branch, src_reg);
13988 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
13989 			}
13990 
13991 		}
13992 	} else if (dst_reg->type == SCALAR_VALUE) {
13993 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
13994 					dst_reg, insn->imm, (u32)insn->imm,
13995 					opcode, is_jmp32);
13996 	}
13997 
13998 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
13999 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14000 		find_equal_scalars(this_branch, dst_reg);
14001 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14002 	}
14003 
14004 	/* if one pointer register is compared to another pointer
14005 	 * register check if PTR_MAYBE_NULL could be lifted.
14006 	 * E.g. register A - maybe null
14007 	 *      register B - not null
14008 	 * for JNE A, B, ... - A is not null in the false branch;
14009 	 * for JEQ A, B, ... - A is not null in the true branch.
14010 	 *
14011 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
14012 	 * not need to be null checked by the BPF program, i.e.,
14013 	 * could be null even without PTR_MAYBE_NULL marking, so
14014 	 * only propagate nullness when neither reg is that type.
14015 	 */
14016 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14017 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14018 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14019 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
14020 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14021 		eq_branch_regs = NULL;
14022 		switch (opcode) {
14023 		case BPF_JEQ:
14024 			eq_branch_regs = other_branch_regs;
14025 			break;
14026 		case BPF_JNE:
14027 			eq_branch_regs = regs;
14028 			break;
14029 		default:
14030 			/* do nothing */
14031 			break;
14032 		}
14033 		if (eq_branch_regs) {
14034 			if (type_may_be_null(src_reg->type))
14035 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14036 			else
14037 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14038 		}
14039 	}
14040 
14041 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14042 	 * NOTE: these optimizations below are related with pointer comparison
14043 	 *       which will never be JMP32.
14044 	 */
14045 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14046 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14047 	    type_may_be_null(dst_reg->type)) {
14048 		/* Mark all identical registers in each branch as either
14049 		 * safe or unknown depending R == 0 or R != 0 conditional.
14050 		 */
14051 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14052 				      opcode == BPF_JNE);
14053 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14054 				      opcode == BPF_JEQ);
14055 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14056 					   this_branch, other_branch) &&
14057 		   is_pointer_value(env, insn->dst_reg)) {
14058 		verbose(env, "R%d pointer comparison prohibited\n",
14059 			insn->dst_reg);
14060 		return -EACCES;
14061 	}
14062 	if (env->log.level & BPF_LOG_LEVEL)
14063 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
14064 	return 0;
14065 }
14066 
14067 /* verify BPF_LD_IMM64 instruction */
14068 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14069 {
14070 	struct bpf_insn_aux_data *aux = cur_aux(env);
14071 	struct bpf_reg_state *regs = cur_regs(env);
14072 	struct bpf_reg_state *dst_reg;
14073 	struct bpf_map *map;
14074 	int err;
14075 
14076 	if (BPF_SIZE(insn->code) != BPF_DW) {
14077 		verbose(env, "invalid BPF_LD_IMM insn\n");
14078 		return -EINVAL;
14079 	}
14080 	if (insn->off != 0) {
14081 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14082 		return -EINVAL;
14083 	}
14084 
14085 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
14086 	if (err)
14087 		return err;
14088 
14089 	dst_reg = &regs[insn->dst_reg];
14090 	if (insn->src_reg == 0) {
14091 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14092 
14093 		dst_reg->type = SCALAR_VALUE;
14094 		__mark_reg_known(&regs[insn->dst_reg], imm);
14095 		return 0;
14096 	}
14097 
14098 	/* All special src_reg cases are listed below. From this point onwards
14099 	 * we either succeed and assign a corresponding dst_reg->type after
14100 	 * zeroing the offset, or fail and reject the program.
14101 	 */
14102 	mark_reg_known_zero(env, regs, insn->dst_reg);
14103 
14104 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14105 		dst_reg->type = aux->btf_var.reg_type;
14106 		switch (base_type(dst_reg->type)) {
14107 		case PTR_TO_MEM:
14108 			dst_reg->mem_size = aux->btf_var.mem_size;
14109 			break;
14110 		case PTR_TO_BTF_ID:
14111 			dst_reg->btf = aux->btf_var.btf;
14112 			dst_reg->btf_id = aux->btf_var.btf_id;
14113 			break;
14114 		default:
14115 			verbose(env, "bpf verifier is misconfigured\n");
14116 			return -EFAULT;
14117 		}
14118 		return 0;
14119 	}
14120 
14121 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
14122 		struct bpf_prog_aux *aux = env->prog->aux;
14123 		u32 subprogno = find_subprog(env,
14124 					     env->insn_idx + insn->imm + 1);
14125 
14126 		if (!aux->func_info) {
14127 			verbose(env, "missing btf func_info\n");
14128 			return -EINVAL;
14129 		}
14130 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14131 			verbose(env, "callback function not static\n");
14132 			return -EINVAL;
14133 		}
14134 
14135 		dst_reg->type = PTR_TO_FUNC;
14136 		dst_reg->subprogno = subprogno;
14137 		return 0;
14138 	}
14139 
14140 	map = env->used_maps[aux->map_index];
14141 	dst_reg->map_ptr = map;
14142 
14143 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14144 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14145 		dst_reg->type = PTR_TO_MAP_VALUE;
14146 		dst_reg->off = aux->map_off;
14147 		WARN_ON_ONCE(map->max_entries != 1);
14148 		/* We want reg->id to be same (0) as map_value is not distinct */
14149 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14150 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14151 		dst_reg->type = CONST_PTR_TO_MAP;
14152 	} else {
14153 		verbose(env, "bpf verifier is misconfigured\n");
14154 		return -EINVAL;
14155 	}
14156 
14157 	return 0;
14158 }
14159 
14160 static bool may_access_skb(enum bpf_prog_type type)
14161 {
14162 	switch (type) {
14163 	case BPF_PROG_TYPE_SOCKET_FILTER:
14164 	case BPF_PROG_TYPE_SCHED_CLS:
14165 	case BPF_PROG_TYPE_SCHED_ACT:
14166 		return true;
14167 	default:
14168 		return false;
14169 	}
14170 }
14171 
14172 /* verify safety of LD_ABS|LD_IND instructions:
14173  * - they can only appear in the programs where ctx == skb
14174  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14175  *   preserve R6-R9, and store return value into R0
14176  *
14177  * Implicit input:
14178  *   ctx == skb == R6 == CTX
14179  *
14180  * Explicit input:
14181  *   SRC == any register
14182  *   IMM == 32-bit immediate
14183  *
14184  * Output:
14185  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14186  */
14187 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14188 {
14189 	struct bpf_reg_state *regs = cur_regs(env);
14190 	static const int ctx_reg = BPF_REG_6;
14191 	u8 mode = BPF_MODE(insn->code);
14192 	int i, err;
14193 
14194 	if (!may_access_skb(resolve_prog_type(env->prog))) {
14195 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14196 		return -EINVAL;
14197 	}
14198 
14199 	if (!env->ops->gen_ld_abs) {
14200 		verbose(env, "bpf verifier is misconfigured\n");
14201 		return -EINVAL;
14202 	}
14203 
14204 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14205 	    BPF_SIZE(insn->code) == BPF_DW ||
14206 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14207 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14208 		return -EINVAL;
14209 	}
14210 
14211 	/* check whether implicit source operand (register R6) is readable */
14212 	err = check_reg_arg(env, ctx_reg, SRC_OP);
14213 	if (err)
14214 		return err;
14215 
14216 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14217 	 * gen_ld_abs() may terminate the program at runtime, leading to
14218 	 * reference leak.
14219 	 */
14220 	err = check_reference_leak(env);
14221 	if (err) {
14222 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14223 		return err;
14224 	}
14225 
14226 	if (env->cur_state->active_lock.ptr) {
14227 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14228 		return -EINVAL;
14229 	}
14230 
14231 	if (env->cur_state->active_rcu_lock) {
14232 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14233 		return -EINVAL;
14234 	}
14235 
14236 	if (regs[ctx_reg].type != PTR_TO_CTX) {
14237 		verbose(env,
14238 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14239 		return -EINVAL;
14240 	}
14241 
14242 	if (mode == BPF_IND) {
14243 		/* check explicit source operand */
14244 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14245 		if (err)
14246 			return err;
14247 	}
14248 
14249 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14250 	if (err < 0)
14251 		return err;
14252 
14253 	/* reset caller saved regs to unreadable */
14254 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14255 		mark_reg_not_init(env, regs, caller_saved[i]);
14256 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14257 	}
14258 
14259 	/* mark destination R0 register as readable, since it contains
14260 	 * the value fetched from the packet.
14261 	 * Already marked as written above.
14262 	 */
14263 	mark_reg_unknown(env, regs, BPF_REG_0);
14264 	/* ld_abs load up to 32-bit skb data. */
14265 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14266 	return 0;
14267 }
14268 
14269 static int check_return_code(struct bpf_verifier_env *env)
14270 {
14271 	struct tnum enforce_attach_type_range = tnum_unknown;
14272 	const struct bpf_prog *prog = env->prog;
14273 	struct bpf_reg_state *reg;
14274 	struct tnum range = tnum_range(0, 1);
14275 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14276 	int err;
14277 	struct bpf_func_state *frame = env->cur_state->frame[0];
14278 	const bool is_subprog = frame->subprogno;
14279 
14280 	/* LSM and struct_ops func-ptr's return type could be "void" */
14281 	if (!is_subprog) {
14282 		switch (prog_type) {
14283 		case BPF_PROG_TYPE_LSM:
14284 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
14285 				/* See below, can be 0 or 0-1 depending on hook. */
14286 				break;
14287 			fallthrough;
14288 		case BPF_PROG_TYPE_STRUCT_OPS:
14289 			if (!prog->aux->attach_func_proto->type)
14290 				return 0;
14291 			break;
14292 		default:
14293 			break;
14294 		}
14295 	}
14296 
14297 	/* eBPF calling convention is such that R0 is used
14298 	 * to return the value from eBPF program.
14299 	 * Make sure that it's readable at this time
14300 	 * of bpf_exit, which means that program wrote
14301 	 * something into it earlier
14302 	 */
14303 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14304 	if (err)
14305 		return err;
14306 
14307 	if (is_pointer_value(env, BPF_REG_0)) {
14308 		verbose(env, "R0 leaks addr as return value\n");
14309 		return -EACCES;
14310 	}
14311 
14312 	reg = cur_regs(env) + BPF_REG_0;
14313 
14314 	if (frame->in_async_callback_fn) {
14315 		/* enforce return zero from async callbacks like timer */
14316 		if (reg->type != SCALAR_VALUE) {
14317 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14318 				reg_type_str(env, reg->type));
14319 			return -EINVAL;
14320 		}
14321 
14322 		if (!tnum_in(tnum_const(0), reg->var_off)) {
14323 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
14324 			return -EINVAL;
14325 		}
14326 		return 0;
14327 	}
14328 
14329 	if (is_subprog) {
14330 		if (reg->type != SCALAR_VALUE) {
14331 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14332 				reg_type_str(env, reg->type));
14333 			return -EINVAL;
14334 		}
14335 		return 0;
14336 	}
14337 
14338 	switch (prog_type) {
14339 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14340 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14341 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14342 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14343 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14344 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14345 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14346 			range = tnum_range(1, 1);
14347 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14348 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14349 			range = tnum_range(0, 3);
14350 		break;
14351 	case BPF_PROG_TYPE_CGROUP_SKB:
14352 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14353 			range = tnum_range(0, 3);
14354 			enforce_attach_type_range = tnum_range(2, 3);
14355 		}
14356 		break;
14357 	case BPF_PROG_TYPE_CGROUP_SOCK:
14358 	case BPF_PROG_TYPE_SOCK_OPS:
14359 	case BPF_PROG_TYPE_CGROUP_DEVICE:
14360 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
14361 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14362 		break;
14363 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
14364 		if (!env->prog->aux->attach_btf_id)
14365 			return 0;
14366 		range = tnum_const(0);
14367 		break;
14368 	case BPF_PROG_TYPE_TRACING:
14369 		switch (env->prog->expected_attach_type) {
14370 		case BPF_TRACE_FENTRY:
14371 		case BPF_TRACE_FEXIT:
14372 			range = tnum_const(0);
14373 			break;
14374 		case BPF_TRACE_RAW_TP:
14375 		case BPF_MODIFY_RETURN:
14376 			return 0;
14377 		case BPF_TRACE_ITER:
14378 			break;
14379 		default:
14380 			return -ENOTSUPP;
14381 		}
14382 		break;
14383 	case BPF_PROG_TYPE_SK_LOOKUP:
14384 		range = tnum_range(SK_DROP, SK_PASS);
14385 		break;
14386 
14387 	case BPF_PROG_TYPE_LSM:
14388 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14389 			/* Regular BPF_PROG_TYPE_LSM programs can return
14390 			 * any value.
14391 			 */
14392 			return 0;
14393 		}
14394 		if (!env->prog->aux->attach_func_proto->type) {
14395 			/* Make sure programs that attach to void
14396 			 * hooks don't try to modify return value.
14397 			 */
14398 			range = tnum_range(1, 1);
14399 		}
14400 		break;
14401 
14402 	case BPF_PROG_TYPE_NETFILTER:
14403 		range = tnum_range(NF_DROP, NF_ACCEPT);
14404 		break;
14405 	case BPF_PROG_TYPE_EXT:
14406 		/* freplace program can return anything as its return value
14407 		 * depends on the to-be-replaced kernel func or bpf program.
14408 		 */
14409 	default:
14410 		return 0;
14411 	}
14412 
14413 	if (reg->type != SCALAR_VALUE) {
14414 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14415 			reg_type_str(env, reg->type));
14416 		return -EINVAL;
14417 	}
14418 
14419 	if (!tnum_in(range, reg->var_off)) {
14420 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14421 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14422 		    prog_type == BPF_PROG_TYPE_LSM &&
14423 		    !prog->aux->attach_func_proto->type)
14424 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14425 		return -EINVAL;
14426 	}
14427 
14428 	if (!tnum_is_unknown(enforce_attach_type_range) &&
14429 	    tnum_in(enforce_attach_type_range, reg->var_off))
14430 		env->prog->enforce_expected_attach_type = 1;
14431 	return 0;
14432 }
14433 
14434 /* non-recursive DFS pseudo code
14435  * 1  procedure DFS-iterative(G,v):
14436  * 2      label v as discovered
14437  * 3      let S be a stack
14438  * 4      S.push(v)
14439  * 5      while S is not empty
14440  * 6            t <- S.peek()
14441  * 7            if t is what we're looking for:
14442  * 8                return t
14443  * 9            for all edges e in G.adjacentEdges(t) do
14444  * 10               if edge e is already labelled
14445  * 11                   continue with the next edge
14446  * 12               w <- G.adjacentVertex(t,e)
14447  * 13               if vertex w is not discovered and not explored
14448  * 14                   label e as tree-edge
14449  * 15                   label w as discovered
14450  * 16                   S.push(w)
14451  * 17                   continue at 5
14452  * 18               else if vertex w is discovered
14453  * 19                   label e as back-edge
14454  * 20               else
14455  * 21                   // vertex w is explored
14456  * 22                   label e as forward- or cross-edge
14457  * 23           label t as explored
14458  * 24           S.pop()
14459  *
14460  * convention:
14461  * 0x10 - discovered
14462  * 0x11 - discovered and fall-through edge labelled
14463  * 0x12 - discovered and fall-through and branch edges labelled
14464  * 0x20 - explored
14465  */
14466 
14467 enum {
14468 	DISCOVERED = 0x10,
14469 	EXPLORED = 0x20,
14470 	FALLTHROUGH = 1,
14471 	BRANCH = 2,
14472 };
14473 
14474 static u32 state_htab_size(struct bpf_verifier_env *env)
14475 {
14476 	return env->prog->len;
14477 }
14478 
14479 static struct bpf_verifier_state_list **explored_state(
14480 					struct bpf_verifier_env *env,
14481 					int idx)
14482 {
14483 	struct bpf_verifier_state *cur = env->cur_state;
14484 	struct bpf_func_state *state = cur->frame[cur->curframe];
14485 
14486 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
14487 }
14488 
14489 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14490 {
14491 	env->insn_aux_data[idx].prune_point = true;
14492 }
14493 
14494 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14495 {
14496 	return env->insn_aux_data[insn_idx].prune_point;
14497 }
14498 
14499 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14500 {
14501 	env->insn_aux_data[idx].force_checkpoint = true;
14502 }
14503 
14504 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14505 {
14506 	return env->insn_aux_data[insn_idx].force_checkpoint;
14507 }
14508 
14509 
14510 enum {
14511 	DONE_EXPLORING = 0,
14512 	KEEP_EXPLORING = 1,
14513 };
14514 
14515 /* t, w, e - match pseudo-code above:
14516  * t - index of current instruction
14517  * w - next instruction
14518  * e - edge
14519  */
14520 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
14521 		     bool loop_ok)
14522 {
14523 	int *insn_stack = env->cfg.insn_stack;
14524 	int *insn_state = env->cfg.insn_state;
14525 
14526 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14527 		return DONE_EXPLORING;
14528 
14529 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14530 		return DONE_EXPLORING;
14531 
14532 	if (w < 0 || w >= env->prog->len) {
14533 		verbose_linfo(env, t, "%d: ", t);
14534 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
14535 		return -EINVAL;
14536 	}
14537 
14538 	if (e == BRANCH) {
14539 		/* mark branch target for state pruning */
14540 		mark_prune_point(env, w);
14541 		mark_jmp_point(env, w);
14542 	}
14543 
14544 	if (insn_state[w] == 0) {
14545 		/* tree-edge */
14546 		insn_state[t] = DISCOVERED | e;
14547 		insn_state[w] = DISCOVERED;
14548 		if (env->cfg.cur_stack >= env->prog->len)
14549 			return -E2BIG;
14550 		insn_stack[env->cfg.cur_stack++] = w;
14551 		return KEEP_EXPLORING;
14552 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14553 		if (loop_ok && env->bpf_capable)
14554 			return DONE_EXPLORING;
14555 		verbose_linfo(env, t, "%d: ", t);
14556 		verbose_linfo(env, w, "%d: ", w);
14557 		verbose(env, "back-edge from insn %d to %d\n", t, w);
14558 		return -EINVAL;
14559 	} else if (insn_state[w] == EXPLORED) {
14560 		/* forward- or cross-edge */
14561 		insn_state[t] = DISCOVERED | e;
14562 	} else {
14563 		verbose(env, "insn state internal bug\n");
14564 		return -EFAULT;
14565 	}
14566 	return DONE_EXPLORING;
14567 }
14568 
14569 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14570 				struct bpf_verifier_env *env,
14571 				bool visit_callee)
14572 {
14573 	int ret;
14574 
14575 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
14576 	if (ret)
14577 		return ret;
14578 
14579 	mark_prune_point(env, t + 1);
14580 	/* when we exit from subprog, we need to record non-linear history */
14581 	mark_jmp_point(env, t + 1);
14582 
14583 	if (visit_callee) {
14584 		mark_prune_point(env, t);
14585 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
14586 				/* It's ok to allow recursion from CFG point of
14587 				 * view. __check_func_call() will do the actual
14588 				 * check.
14589 				 */
14590 				bpf_pseudo_func(insns + t));
14591 	}
14592 	return ret;
14593 }
14594 
14595 /* Visits the instruction at index t and returns one of the following:
14596  *  < 0 - an error occurred
14597  *  DONE_EXPLORING - the instruction was fully explored
14598  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
14599  */
14600 static int visit_insn(int t, struct bpf_verifier_env *env)
14601 {
14602 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14603 	int ret;
14604 
14605 	if (bpf_pseudo_func(insn))
14606 		return visit_func_call_insn(t, insns, env, true);
14607 
14608 	/* All non-branch instructions have a single fall-through edge. */
14609 	if (BPF_CLASS(insn->code) != BPF_JMP &&
14610 	    BPF_CLASS(insn->code) != BPF_JMP32)
14611 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
14612 
14613 	switch (BPF_OP(insn->code)) {
14614 	case BPF_EXIT:
14615 		return DONE_EXPLORING;
14616 
14617 	case BPF_CALL:
14618 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14619 			/* Mark this call insn as a prune point to trigger
14620 			 * is_state_visited() check before call itself is
14621 			 * processed by __check_func_call(). Otherwise new
14622 			 * async state will be pushed for further exploration.
14623 			 */
14624 			mark_prune_point(env, t);
14625 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14626 			struct bpf_kfunc_call_arg_meta meta;
14627 
14628 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14629 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
14630 				mark_prune_point(env, t);
14631 				/* Checking and saving state checkpoints at iter_next() call
14632 				 * is crucial for fast convergence of open-coded iterator loop
14633 				 * logic, so we need to force it. If we don't do that,
14634 				 * is_state_visited() might skip saving a checkpoint, causing
14635 				 * unnecessarily long sequence of not checkpointed
14636 				 * instructions and jumps, leading to exhaustion of jump
14637 				 * history buffer, and potentially other undesired outcomes.
14638 				 * It is expected that with correct open-coded iterators
14639 				 * convergence will happen quickly, so we don't run a risk of
14640 				 * exhausting memory.
14641 				 */
14642 				mark_force_checkpoint(env, t);
14643 			}
14644 		}
14645 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14646 
14647 	case BPF_JA:
14648 		if (BPF_SRC(insn->code) != BPF_K)
14649 			return -EINVAL;
14650 
14651 		/* unconditional jump with single edge */
14652 		ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
14653 				true);
14654 		if (ret)
14655 			return ret;
14656 
14657 		mark_prune_point(env, t + insn->off + 1);
14658 		mark_jmp_point(env, t + insn->off + 1);
14659 
14660 		return ret;
14661 
14662 	default:
14663 		/* conditional jump with two edges */
14664 		mark_prune_point(env, t);
14665 
14666 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14667 		if (ret)
14668 			return ret;
14669 
14670 		return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14671 	}
14672 }
14673 
14674 /* non-recursive depth-first-search to detect loops in BPF program
14675  * loop == back-edge in directed graph
14676  */
14677 static int check_cfg(struct bpf_verifier_env *env)
14678 {
14679 	int insn_cnt = env->prog->len;
14680 	int *insn_stack, *insn_state;
14681 	int ret = 0;
14682 	int i;
14683 
14684 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14685 	if (!insn_state)
14686 		return -ENOMEM;
14687 
14688 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14689 	if (!insn_stack) {
14690 		kvfree(insn_state);
14691 		return -ENOMEM;
14692 	}
14693 
14694 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14695 	insn_stack[0] = 0; /* 0 is the first instruction */
14696 	env->cfg.cur_stack = 1;
14697 
14698 	while (env->cfg.cur_stack > 0) {
14699 		int t = insn_stack[env->cfg.cur_stack - 1];
14700 
14701 		ret = visit_insn(t, env);
14702 		switch (ret) {
14703 		case DONE_EXPLORING:
14704 			insn_state[t] = EXPLORED;
14705 			env->cfg.cur_stack--;
14706 			break;
14707 		case KEEP_EXPLORING:
14708 			break;
14709 		default:
14710 			if (ret > 0) {
14711 				verbose(env, "visit_insn internal bug\n");
14712 				ret = -EFAULT;
14713 			}
14714 			goto err_free;
14715 		}
14716 	}
14717 
14718 	if (env->cfg.cur_stack < 0) {
14719 		verbose(env, "pop stack internal bug\n");
14720 		ret = -EFAULT;
14721 		goto err_free;
14722 	}
14723 
14724 	for (i = 0; i < insn_cnt; i++) {
14725 		if (insn_state[i] != EXPLORED) {
14726 			verbose(env, "unreachable insn %d\n", i);
14727 			ret = -EINVAL;
14728 			goto err_free;
14729 		}
14730 	}
14731 	ret = 0; /* cfg looks good */
14732 
14733 err_free:
14734 	kvfree(insn_state);
14735 	kvfree(insn_stack);
14736 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
14737 	return ret;
14738 }
14739 
14740 static int check_abnormal_return(struct bpf_verifier_env *env)
14741 {
14742 	int i;
14743 
14744 	for (i = 1; i < env->subprog_cnt; i++) {
14745 		if (env->subprog_info[i].has_ld_abs) {
14746 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14747 			return -EINVAL;
14748 		}
14749 		if (env->subprog_info[i].has_tail_call) {
14750 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14751 			return -EINVAL;
14752 		}
14753 	}
14754 	return 0;
14755 }
14756 
14757 /* The minimum supported BTF func info size */
14758 #define MIN_BPF_FUNCINFO_SIZE	8
14759 #define MAX_FUNCINFO_REC_SIZE	252
14760 
14761 static int check_btf_func(struct bpf_verifier_env *env,
14762 			  const union bpf_attr *attr,
14763 			  bpfptr_t uattr)
14764 {
14765 	const struct btf_type *type, *func_proto, *ret_type;
14766 	u32 i, nfuncs, urec_size, min_size;
14767 	u32 krec_size = sizeof(struct bpf_func_info);
14768 	struct bpf_func_info *krecord;
14769 	struct bpf_func_info_aux *info_aux = NULL;
14770 	struct bpf_prog *prog;
14771 	const struct btf *btf;
14772 	bpfptr_t urecord;
14773 	u32 prev_offset = 0;
14774 	bool scalar_return;
14775 	int ret = -ENOMEM;
14776 
14777 	nfuncs = attr->func_info_cnt;
14778 	if (!nfuncs) {
14779 		if (check_abnormal_return(env))
14780 			return -EINVAL;
14781 		return 0;
14782 	}
14783 
14784 	if (nfuncs != env->subprog_cnt) {
14785 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14786 		return -EINVAL;
14787 	}
14788 
14789 	urec_size = attr->func_info_rec_size;
14790 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14791 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
14792 	    urec_size % sizeof(u32)) {
14793 		verbose(env, "invalid func info rec size %u\n", urec_size);
14794 		return -EINVAL;
14795 	}
14796 
14797 	prog = env->prog;
14798 	btf = prog->aux->btf;
14799 
14800 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
14801 	min_size = min_t(u32, krec_size, urec_size);
14802 
14803 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
14804 	if (!krecord)
14805 		return -ENOMEM;
14806 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
14807 	if (!info_aux)
14808 		goto err_free;
14809 
14810 	for (i = 0; i < nfuncs; i++) {
14811 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
14812 		if (ret) {
14813 			if (ret == -E2BIG) {
14814 				verbose(env, "nonzero tailing record in func info");
14815 				/* set the size kernel expects so loader can zero
14816 				 * out the rest of the record.
14817 				 */
14818 				if (copy_to_bpfptr_offset(uattr,
14819 							  offsetof(union bpf_attr, func_info_rec_size),
14820 							  &min_size, sizeof(min_size)))
14821 					ret = -EFAULT;
14822 			}
14823 			goto err_free;
14824 		}
14825 
14826 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
14827 			ret = -EFAULT;
14828 			goto err_free;
14829 		}
14830 
14831 		/* check insn_off */
14832 		ret = -EINVAL;
14833 		if (i == 0) {
14834 			if (krecord[i].insn_off) {
14835 				verbose(env,
14836 					"nonzero insn_off %u for the first func info record",
14837 					krecord[i].insn_off);
14838 				goto err_free;
14839 			}
14840 		} else if (krecord[i].insn_off <= prev_offset) {
14841 			verbose(env,
14842 				"same or smaller insn offset (%u) than previous func info record (%u)",
14843 				krecord[i].insn_off, prev_offset);
14844 			goto err_free;
14845 		}
14846 
14847 		if (env->subprog_info[i].start != krecord[i].insn_off) {
14848 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
14849 			goto err_free;
14850 		}
14851 
14852 		/* check type_id */
14853 		type = btf_type_by_id(btf, krecord[i].type_id);
14854 		if (!type || !btf_type_is_func(type)) {
14855 			verbose(env, "invalid type id %d in func info",
14856 				krecord[i].type_id);
14857 			goto err_free;
14858 		}
14859 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
14860 
14861 		func_proto = btf_type_by_id(btf, type->type);
14862 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
14863 			/* btf_func_check() already verified it during BTF load */
14864 			goto err_free;
14865 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
14866 		scalar_return =
14867 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
14868 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
14869 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
14870 			goto err_free;
14871 		}
14872 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
14873 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
14874 			goto err_free;
14875 		}
14876 
14877 		prev_offset = krecord[i].insn_off;
14878 		bpfptr_add(&urecord, urec_size);
14879 	}
14880 
14881 	prog->aux->func_info = krecord;
14882 	prog->aux->func_info_cnt = nfuncs;
14883 	prog->aux->func_info_aux = info_aux;
14884 	return 0;
14885 
14886 err_free:
14887 	kvfree(krecord);
14888 	kfree(info_aux);
14889 	return ret;
14890 }
14891 
14892 static void adjust_btf_func(struct bpf_verifier_env *env)
14893 {
14894 	struct bpf_prog_aux *aux = env->prog->aux;
14895 	int i;
14896 
14897 	if (!aux->func_info)
14898 		return;
14899 
14900 	for (i = 0; i < env->subprog_cnt; i++)
14901 		aux->func_info[i].insn_off = env->subprog_info[i].start;
14902 }
14903 
14904 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
14905 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
14906 
14907 static int check_btf_line(struct bpf_verifier_env *env,
14908 			  const union bpf_attr *attr,
14909 			  bpfptr_t uattr)
14910 {
14911 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
14912 	struct bpf_subprog_info *sub;
14913 	struct bpf_line_info *linfo;
14914 	struct bpf_prog *prog;
14915 	const struct btf *btf;
14916 	bpfptr_t ulinfo;
14917 	int err;
14918 
14919 	nr_linfo = attr->line_info_cnt;
14920 	if (!nr_linfo)
14921 		return 0;
14922 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
14923 		return -EINVAL;
14924 
14925 	rec_size = attr->line_info_rec_size;
14926 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
14927 	    rec_size > MAX_LINEINFO_REC_SIZE ||
14928 	    rec_size & (sizeof(u32) - 1))
14929 		return -EINVAL;
14930 
14931 	/* Need to zero it in case the userspace may
14932 	 * pass in a smaller bpf_line_info object.
14933 	 */
14934 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
14935 			 GFP_KERNEL | __GFP_NOWARN);
14936 	if (!linfo)
14937 		return -ENOMEM;
14938 
14939 	prog = env->prog;
14940 	btf = prog->aux->btf;
14941 
14942 	s = 0;
14943 	sub = env->subprog_info;
14944 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
14945 	expected_size = sizeof(struct bpf_line_info);
14946 	ncopy = min_t(u32, expected_size, rec_size);
14947 	for (i = 0; i < nr_linfo; i++) {
14948 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
14949 		if (err) {
14950 			if (err == -E2BIG) {
14951 				verbose(env, "nonzero tailing record in line_info");
14952 				if (copy_to_bpfptr_offset(uattr,
14953 							  offsetof(union bpf_attr, line_info_rec_size),
14954 							  &expected_size, sizeof(expected_size)))
14955 					err = -EFAULT;
14956 			}
14957 			goto err_free;
14958 		}
14959 
14960 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
14961 			err = -EFAULT;
14962 			goto err_free;
14963 		}
14964 
14965 		/*
14966 		 * Check insn_off to ensure
14967 		 * 1) strictly increasing AND
14968 		 * 2) bounded by prog->len
14969 		 *
14970 		 * The linfo[0].insn_off == 0 check logically falls into
14971 		 * the later "missing bpf_line_info for func..." case
14972 		 * because the first linfo[0].insn_off must be the
14973 		 * first sub also and the first sub must have
14974 		 * subprog_info[0].start == 0.
14975 		 */
14976 		if ((i && linfo[i].insn_off <= prev_offset) ||
14977 		    linfo[i].insn_off >= prog->len) {
14978 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
14979 				i, linfo[i].insn_off, prev_offset,
14980 				prog->len);
14981 			err = -EINVAL;
14982 			goto err_free;
14983 		}
14984 
14985 		if (!prog->insnsi[linfo[i].insn_off].code) {
14986 			verbose(env,
14987 				"Invalid insn code at line_info[%u].insn_off\n",
14988 				i);
14989 			err = -EINVAL;
14990 			goto err_free;
14991 		}
14992 
14993 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
14994 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
14995 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
14996 			err = -EINVAL;
14997 			goto err_free;
14998 		}
14999 
15000 		if (s != env->subprog_cnt) {
15001 			if (linfo[i].insn_off == sub[s].start) {
15002 				sub[s].linfo_idx = i;
15003 				s++;
15004 			} else if (sub[s].start < linfo[i].insn_off) {
15005 				verbose(env, "missing bpf_line_info for func#%u\n", s);
15006 				err = -EINVAL;
15007 				goto err_free;
15008 			}
15009 		}
15010 
15011 		prev_offset = linfo[i].insn_off;
15012 		bpfptr_add(&ulinfo, rec_size);
15013 	}
15014 
15015 	if (s != env->subprog_cnt) {
15016 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15017 			env->subprog_cnt - s, s);
15018 		err = -EINVAL;
15019 		goto err_free;
15020 	}
15021 
15022 	prog->aux->linfo = linfo;
15023 	prog->aux->nr_linfo = nr_linfo;
15024 
15025 	return 0;
15026 
15027 err_free:
15028 	kvfree(linfo);
15029 	return err;
15030 }
15031 
15032 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
15033 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
15034 
15035 static int check_core_relo(struct bpf_verifier_env *env,
15036 			   const union bpf_attr *attr,
15037 			   bpfptr_t uattr)
15038 {
15039 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15040 	struct bpf_core_relo core_relo = {};
15041 	struct bpf_prog *prog = env->prog;
15042 	const struct btf *btf = prog->aux->btf;
15043 	struct bpf_core_ctx ctx = {
15044 		.log = &env->log,
15045 		.btf = btf,
15046 	};
15047 	bpfptr_t u_core_relo;
15048 	int err;
15049 
15050 	nr_core_relo = attr->core_relo_cnt;
15051 	if (!nr_core_relo)
15052 		return 0;
15053 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15054 		return -EINVAL;
15055 
15056 	rec_size = attr->core_relo_rec_size;
15057 	if (rec_size < MIN_CORE_RELO_SIZE ||
15058 	    rec_size > MAX_CORE_RELO_SIZE ||
15059 	    rec_size % sizeof(u32))
15060 		return -EINVAL;
15061 
15062 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15063 	expected_size = sizeof(struct bpf_core_relo);
15064 	ncopy = min_t(u32, expected_size, rec_size);
15065 
15066 	/* Unlike func_info and line_info, copy and apply each CO-RE
15067 	 * relocation record one at a time.
15068 	 */
15069 	for (i = 0; i < nr_core_relo; i++) {
15070 		/* future proofing when sizeof(bpf_core_relo) changes */
15071 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15072 		if (err) {
15073 			if (err == -E2BIG) {
15074 				verbose(env, "nonzero tailing record in core_relo");
15075 				if (copy_to_bpfptr_offset(uattr,
15076 							  offsetof(union bpf_attr, core_relo_rec_size),
15077 							  &expected_size, sizeof(expected_size)))
15078 					err = -EFAULT;
15079 			}
15080 			break;
15081 		}
15082 
15083 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15084 			err = -EFAULT;
15085 			break;
15086 		}
15087 
15088 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15089 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15090 				i, core_relo.insn_off, prog->len);
15091 			err = -EINVAL;
15092 			break;
15093 		}
15094 
15095 		err = bpf_core_apply(&ctx, &core_relo, i,
15096 				     &prog->insnsi[core_relo.insn_off / 8]);
15097 		if (err)
15098 			break;
15099 		bpfptr_add(&u_core_relo, rec_size);
15100 	}
15101 	return err;
15102 }
15103 
15104 static int check_btf_info(struct bpf_verifier_env *env,
15105 			  const union bpf_attr *attr,
15106 			  bpfptr_t uattr)
15107 {
15108 	struct btf *btf;
15109 	int err;
15110 
15111 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
15112 		if (check_abnormal_return(env))
15113 			return -EINVAL;
15114 		return 0;
15115 	}
15116 
15117 	btf = btf_get_by_fd(attr->prog_btf_fd);
15118 	if (IS_ERR(btf))
15119 		return PTR_ERR(btf);
15120 	if (btf_is_kernel(btf)) {
15121 		btf_put(btf);
15122 		return -EACCES;
15123 	}
15124 	env->prog->aux->btf = btf;
15125 
15126 	err = check_btf_func(env, attr, uattr);
15127 	if (err)
15128 		return err;
15129 
15130 	err = check_btf_line(env, attr, uattr);
15131 	if (err)
15132 		return err;
15133 
15134 	err = check_core_relo(env, attr, uattr);
15135 	if (err)
15136 		return err;
15137 
15138 	return 0;
15139 }
15140 
15141 /* check %cur's range satisfies %old's */
15142 static bool range_within(struct bpf_reg_state *old,
15143 			 struct bpf_reg_state *cur)
15144 {
15145 	return old->umin_value <= cur->umin_value &&
15146 	       old->umax_value >= cur->umax_value &&
15147 	       old->smin_value <= cur->smin_value &&
15148 	       old->smax_value >= cur->smax_value &&
15149 	       old->u32_min_value <= cur->u32_min_value &&
15150 	       old->u32_max_value >= cur->u32_max_value &&
15151 	       old->s32_min_value <= cur->s32_min_value &&
15152 	       old->s32_max_value >= cur->s32_max_value;
15153 }
15154 
15155 /* If in the old state two registers had the same id, then they need to have
15156  * the same id in the new state as well.  But that id could be different from
15157  * the old state, so we need to track the mapping from old to new ids.
15158  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15159  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15160  * regs with a different old id could still have new id 9, we don't care about
15161  * that.
15162  * So we look through our idmap to see if this old id has been seen before.  If
15163  * so, we require the new id to match; otherwise, we add the id pair to the map.
15164  */
15165 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15166 {
15167 	struct bpf_id_pair *map = idmap->map;
15168 	unsigned int i;
15169 
15170 	/* either both IDs should be set or both should be zero */
15171 	if (!!old_id != !!cur_id)
15172 		return false;
15173 
15174 	if (old_id == 0) /* cur_id == 0 as well */
15175 		return true;
15176 
15177 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15178 		if (!map[i].old) {
15179 			/* Reached an empty slot; haven't seen this id before */
15180 			map[i].old = old_id;
15181 			map[i].cur = cur_id;
15182 			return true;
15183 		}
15184 		if (map[i].old == old_id)
15185 			return map[i].cur == cur_id;
15186 		if (map[i].cur == cur_id)
15187 			return false;
15188 	}
15189 	/* We ran out of idmap slots, which should be impossible */
15190 	WARN_ON_ONCE(1);
15191 	return false;
15192 }
15193 
15194 /* Similar to check_ids(), but allocate a unique temporary ID
15195  * for 'old_id' or 'cur_id' of zero.
15196  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15197  */
15198 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15199 {
15200 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15201 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15202 
15203 	return check_ids(old_id, cur_id, idmap);
15204 }
15205 
15206 static void clean_func_state(struct bpf_verifier_env *env,
15207 			     struct bpf_func_state *st)
15208 {
15209 	enum bpf_reg_liveness live;
15210 	int i, j;
15211 
15212 	for (i = 0; i < BPF_REG_FP; i++) {
15213 		live = st->regs[i].live;
15214 		/* liveness must not touch this register anymore */
15215 		st->regs[i].live |= REG_LIVE_DONE;
15216 		if (!(live & REG_LIVE_READ))
15217 			/* since the register is unused, clear its state
15218 			 * to make further comparison simpler
15219 			 */
15220 			__mark_reg_not_init(env, &st->regs[i]);
15221 	}
15222 
15223 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15224 		live = st->stack[i].spilled_ptr.live;
15225 		/* liveness must not touch this stack slot anymore */
15226 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15227 		if (!(live & REG_LIVE_READ)) {
15228 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15229 			for (j = 0; j < BPF_REG_SIZE; j++)
15230 				st->stack[i].slot_type[j] = STACK_INVALID;
15231 		}
15232 	}
15233 }
15234 
15235 static void clean_verifier_state(struct bpf_verifier_env *env,
15236 				 struct bpf_verifier_state *st)
15237 {
15238 	int i;
15239 
15240 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15241 		/* all regs in this state in all frames were already marked */
15242 		return;
15243 
15244 	for (i = 0; i <= st->curframe; i++)
15245 		clean_func_state(env, st->frame[i]);
15246 }
15247 
15248 /* the parentage chains form a tree.
15249  * the verifier states are added to state lists at given insn and
15250  * pushed into state stack for future exploration.
15251  * when the verifier reaches bpf_exit insn some of the verifer states
15252  * stored in the state lists have their final liveness state already,
15253  * but a lot of states will get revised from liveness point of view when
15254  * the verifier explores other branches.
15255  * Example:
15256  * 1: r0 = 1
15257  * 2: if r1 == 100 goto pc+1
15258  * 3: r0 = 2
15259  * 4: exit
15260  * when the verifier reaches exit insn the register r0 in the state list of
15261  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15262  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15263  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15264  *
15265  * Since the verifier pushes the branch states as it sees them while exploring
15266  * the program the condition of walking the branch instruction for the second
15267  * time means that all states below this branch were already explored and
15268  * their final liveness marks are already propagated.
15269  * Hence when the verifier completes the search of state list in is_state_visited()
15270  * we can call this clean_live_states() function to mark all liveness states
15271  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15272  * will not be used.
15273  * This function also clears the registers and stack for states that !READ
15274  * to simplify state merging.
15275  *
15276  * Important note here that walking the same branch instruction in the callee
15277  * doesn't meant that the states are DONE. The verifier has to compare
15278  * the callsites
15279  */
15280 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15281 			      struct bpf_verifier_state *cur)
15282 {
15283 	struct bpf_verifier_state_list *sl;
15284 	int i;
15285 
15286 	sl = *explored_state(env, insn);
15287 	while (sl) {
15288 		if (sl->state.branches)
15289 			goto next;
15290 		if (sl->state.insn_idx != insn ||
15291 		    sl->state.curframe != cur->curframe)
15292 			goto next;
15293 		for (i = 0; i <= cur->curframe; i++)
15294 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15295 				goto next;
15296 		clean_verifier_state(env, &sl->state);
15297 next:
15298 		sl = sl->next;
15299 	}
15300 }
15301 
15302 static bool regs_exact(const struct bpf_reg_state *rold,
15303 		       const struct bpf_reg_state *rcur,
15304 		       struct bpf_idmap *idmap)
15305 {
15306 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15307 	       check_ids(rold->id, rcur->id, idmap) &&
15308 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15309 }
15310 
15311 /* Returns true if (rold safe implies rcur safe) */
15312 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15313 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap)
15314 {
15315 	if (!(rold->live & REG_LIVE_READ))
15316 		/* explored state didn't use this */
15317 		return true;
15318 	if (rold->type == NOT_INIT)
15319 		/* explored state can't have used this */
15320 		return true;
15321 	if (rcur->type == NOT_INIT)
15322 		return false;
15323 
15324 	/* Enforce that register types have to match exactly, including their
15325 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15326 	 * rule.
15327 	 *
15328 	 * One can make a point that using a pointer register as unbounded
15329 	 * SCALAR would be technically acceptable, but this could lead to
15330 	 * pointer leaks because scalars are allowed to leak while pointers
15331 	 * are not. We could make this safe in special cases if root is
15332 	 * calling us, but it's probably not worth the hassle.
15333 	 *
15334 	 * Also, register types that are *not* MAYBE_NULL could technically be
15335 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15336 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15337 	 * to the same map).
15338 	 * However, if the old MAYBE_NULL register then got NULL checked,
15339 	 * doing so could have affected others with the same id, and we can't
15340 	 * check for that because we lost the id when we converted to
15341 	 * a non-MAYBE_NULL variant.
15342 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
15343 	 * non-MAYBE_NULL registers as well.
15344 	 */
15345 	if (rold->type != rcur->type)
15346 		return false;
15347 
15348 	switch (base_type(rold->type)) {
15349 	case SCALAR_VALUE:
15350 		if (env->explore_alu_limits) {
15351 			/* explore_alu_limits disables tnum_in() and range_within()
15352 			 * logic and requires everything to be strict
15353 			 */
15354 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15355 			       check_scalar_ids(rold->id, rcur->id, idmap);
15356 		}
15357 		if (!rold->precise)
15358 			return true;
15359 		/* Why check_ids() for scalar registers?
15360 		 *
15361 		 * Consider the following BPF code:
15362 		 *   1: r6 = ... unbound scalar, ID=a ...
15363 		 *   2: r7 = ... unbound scalar, ID=b ...
15364 		 *   3: if (r6 > r7) goto +1
15365 		 *   4: r6 = r7
15366 		 *   5: if (r6 > X) goto ...
15367 		 *   6: ... memory operation using r7 ...
15368 		 *
15369 		 * First verification path is [1-6]:
15370 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
15371 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
15372 		 *   r7 <= X, because r6 and r7 share same id.
15373 		 * Next verification path is [1-4, 6].
15374 		 *
15375 		 * Instruction (6) would be reached in two states:
15376 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
15377 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
15378 		 *
15379 		 * Use check_ids() to distinguish these states.
15380 		 * ---
15381 		 * Also verify that new value satisfies old value range knowledge.
15382 		 */
15383 		return range_within(rold, rcur) &&
15384 		       tnum_in(rold->var_off, rcur->var_off) &&
15385 		       check_scalar_ids(rold->id, rcur->id, idmap);
15386 	case PTR_TO_MAP_KEY:
15387 	case PTR_TO_MAP_VALUE:
15388 	case PTR_TO_MEM:
15389 	case PTR_TO_BUF:
15390 	case PTR_TO_TP_BUFFER:
15391 		/* If the new min/max/var_off satisfy the old ones and
15392 		 * everything else matches, we are OK.
15393 		 */
15394 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15395 		       range_within(rold, rcur) &&
15396 		       tnum_in(rold->var_off, rcur->var_off) &&
15397 		       check_ids(rold->id, rcur->id, idmap) &&
15398 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15399 	case PTR_TO_PACKET_META:
15400 	case PTR_TO_PACKET:
15401 		/* We must have at least as much range as the old ptr
15402 		 * did, so that any accesses which were safe before are
15403 		 * still safe.  This is true even if old range < old off,
15404 		 * since someone could have accessed through (ptr - k), or
15405 		 * even done ptr -= k in a register, to get a safe access.
15406 		 */
15407 		if (rold->range > rcur->range)
15408 			return false;
15409 		/* If the offsets don't match, we can't trust our alignment;
15410 		 * nor can we be sure that we won't fall out of range.
15411 		 */
15412 		if (rold->off != rcur->off)
15413 			return false;
15414 		/* id relations must be preserved */
15415 		if (!check_ids(rold->id, rcur->id, idmap))
15416 			return false;
15417 		/* new val must satisfy old val knowledge */
15418 		return range_within(rold, rcur) &&
15419 		       tnum_in(rold->var_off, rcur->var_off);
15420 	case PTR_TO_STACK:
15421 		/* two stack pointers are equal only if they're pointing to
15422 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
15423 		 */
15424 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15425 	default:
15426 		return regs_exact(rold, rcur, idmap);
15427 	}
15428 }
15429 
15430 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15431 		      struct bpf_func_state *cur, struct bpf_idmap *idmap)
15432 {
15433 	int i, spi;
15434 
15435 	/* walk slots of the explored stack and ignore any additional
15436 	 * slots in the current stack, since explored(safe) state
15437 	 * didn't use them
15438 	 */
15439 	for (i = 0; i < old->allocated_stack; i++) {
15440 		struct bpf_reg_state *old_reg, *cur_reg;
15441 
15442 		spi = i / BPF_REG_SIZE;
15443 
15444 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15445 			i += BPF_REG_SIZE - 1;
15446 			/* explored state didn't use this */
15447 			continue;
15448 		}
15449 
15450 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15451 			continue;
15452 
15453 		if (env->allow_uninit_stack &&
15454 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15455 			continue;
15456 
15457 		/* explored stack has more populated slots than current stack
15458 		 * and these slots were used
15459 		 */
15460 		if (i >= cur->allocated_stack)
15461 			return false;
15462 
15463 		/* if old state was safe with misc data in the stack
15464 		 * it will be safe with zero-initialized stack.
15465 		 * The opposite is not true
15466 		 */
15467 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15468 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15469 			continue;
15470 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15471 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15472 			/* Ex: old explored (safe) state has STACK_SPILL in
15473 			 * this stack slot, but current has STACK_MISC ->
15474 			 * this verifier states are not equivalent,
15475 			 * return false to continue verification of this path
15476 			 */
15477 			return false;
15478 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15479 			continue;
15480 		/* Both old and cur are having same slot_type */
15481 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15482 		case STACK_SPILL:
15483 			/* when explored and current stack slot are both storing
15484 			 * spilled registers, check that stored pointers types
15485 			 * are the same as well.
15486 			 * Ex: explored safe path could have stored
15487 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15488 			 * but current path has stored:
15489 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15490 			 * such verifier states are not equivalent.
15491 			 * return false to continue verification of this path
15492 			 */
15493 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
15494 				     &cur->stack[spi].spilled_ptr, idmap))
15495 				return false;
15496 			break;
15497 		case STACK_DYNPTR:
15498 			old_reg = &old->stack[spi].spilled_ptr;
15499 			cur_reg = &cur->stack[spi].spilled_ptr;
15500 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15501 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15502 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15503 				return false;
15504 			break;
15505 		case STACK_ITER:
15506 			old_reg = &old->stack[spi].spilled_ptr;
15507 			cur_reg = &cur->stack[spi].spilled_ptr;
15508 			/* iter.depth is not compared between states as it
15509 			 * doesn't matter for correctness and would otherwise
15510 			 * prevent convergence; we maintain it only to prevent
15511 			 * infinite loop check triggering, see
15512 			 * iter_active_depths_differ()
15513 			 */
15514 			if (old_reg->iter.btf != cur_reg->iter.btf ||
15515 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15516 			    old_reg->iter.state != cur_reg->iter.state ||
15517 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
15518 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15519 				return false;
15520 			break;
15521 		case STACK_MISC:
15522 		case STACK_ZERO:
15523 		case STACK_INVALID:
15524 			continue;
15525 		/* Ensure that new unhandled slot types return false by default */
15526 		default:
15527 			return false;
15528 		}
15529 	}
15530 	return true;
15531 }
15532 
15533 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15534 		    struct bpf_idmap *idmap)
15535 {
15536 	int i;
15537 
15538 	if (old->acquired_refs != cur->acquired_refs)
15539 		return false;
15540 
15541 	for (i = 0; i < old->acquired_refs; i++) {
15542 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15543 			return false;
15544 	}
15545 
15546 	return true;
15547 }
15548 
15549 /* compare two verifier states
15550  *
15551  * all states stored in state_list are known to be valid, since
15552  * verifier reached 'bpf_exit' instruction through them
15553  *
15554  * this function is called when verifier exploring different branches of
15555  * execution popped from the state stack. If it sees an old state that has
15556  * more strict register state and more strict stack state then this execution
15557  * branch doesn't need to be explored further, since verifier already
15558  * concluded that more strict state leads to valid finish.
15559  *
15560  * Therefore two states are equivalent if register state is more conservative
15561  * and explored stack state is more conservative than the current one.
15562  * Example:
15563  *       explored                   current
15564  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15565  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15566  *
15567  * In other words if current stack state (one being explored) has more
15568  * valid slots than old one that already passed validation, it means
15569  * the verifier can stop exploring and conclude that current state is valid too
15570  *
15571  * Similarly with registers. If explored state has register type as invalid
15572  * whereas register type in current state is meaningful, it means that
15573  * the current state will reach 'bpf_exit' instruction safely
15574  */
15575 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15576 			      struct bpf_func_state *cur)
15577 {
15578 	int i;
15579 
15580 	for (i = 0; i < MAX_BPF_REG; i++)
15581 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
15582 			     &env->idmap_scratch))
15583 			return false;
15584 
15585 	if (!stacksafe(env, old, cur, &env->idmap_scratch))
15586 		return false;
15587 
15588 	if (!refsafe(old, cur, &env->idmap_scratch))
15589 		return false;
15590 
15591 	return true;
15592 }
15593 
15594 static bool states_equal(struct bpf_verifier_env *env,
15595 			 struct bpf_verifier_state *old,
15596 			 struct bpf_verifier_state *cur)
15597 {
15598 	int i;
15599 
15600 	if (old->curframe != cur->curframe)
15601 		return false;
15602 
15603 	env->idmap_scratch.tmp_id_gen = env->id_gen;
15604 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
15605 
15606 	/* Verification state from speculative execution simulation
15607 	 * must never prune a non-speculative execution one.
15608 	 */
15609 	if (old->speculative && !cur->speculative)
15610 		return false;
15611 
15612 	if (old->active_lock.ptr != cur->active_lock.ptr)
15613 		return false;
15614 
15615 	/* Old and cur active_lock's have to be either both present
15616 	 * or both absent.
15617 	 */
15618 	if (!!old->active_lock.id != !!cur->active_lock.id)
15619 		return false;
15620 
15621 	if (old->active_lock.id &&
15622 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
15623 		return false;
15624 
15625 	if (old->active_rcu_lock != cur->active_rcu_lock)
15626 		return false;
15627 
15628 	/* for states to be equal callsites have to be the same
15629 	 * and all frame states need to be equivalent
15630 	 */
15631 	for (i = 0; i <= old->curframe; i++) {
15632 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
15633 			return false;
15634 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15635 			return false;
15636 	}
15637 	return true;
15638 }
15639 
15640 /* Return 0 if no propagation happened. Return negative error code if error
15641  * happened. Otherwise, return the propagated bit.
15642  */
15643 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15644 				  struct bpf_reg_state *reg,
15645 				  struct bpf_reg_state *parent_reg)
15646 {
15647 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15648 	u8 flag = reg->live & REG_LIVE_READ;
15649 	int err;
15650 
15651 	/* When comes here, read flags of PARENT_REG or REG could be any of
15652 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15653 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15654 	 */
15655 	if (parent_flag == REG_LIVE_READ64 ||
15656 	    /* Or if there is no read flag from REG. */
15657 	    !flag ||
15658 	    /* Or if the read flag from REG is the same as PARENT_REG. */
15659 	    parent_flag == flag)
15660 		return 0;
15661 
15662 	err = mark_reg_read(env, reg, parent_reg, flag);
15663 	if (err)
15664 		return err;
15665 
15666 	return flag;
15667 }
15668 
15669 /* A write screens off any subsequent reads; but write marks come from the
15670  * straight-line code between a state and its parent.  When we arrive at an
15671  * equivalent state (jump target or such) we didn't arrive by the straight-line
15672  * code, so read marks in the state must propagate to the parent regardless
15673  * of the state's write marks. That's what 'parent == state->parent' comparison
15674  * in mark_reg_read() is for.
15675  */
15676 static int propagate_liveness(struct bpf_verifier_env *env,
15677 			      const struct bpf_verifier_state *vstate,
15678 			      struct bpf_verifier_state *vparent)
15679 {
15680 	struct bpf_reg_state *state_reg, *parent_reg;
15681 	struct bpf_func_state *state, *parent;
15682 	int i, frame, err = 0;
15683 
15684 	if (vparent->curframe != vstate->curframe) {
15685 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
15686 		     vparent->curframe, vstate->curframe);
15687 		return -EFAULT;
15688 	}
15689 	/* Propagate read liveness of registers... */
15690 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15691 	for (frame = 0; frame <= vstate->curframe; frame++) {
15692 		parent = vparent->frame[frame];
15693 		state = vstate->frame[frame];
15694 		parent_reg = parent->regs;
15695 		state_reg = state->regs;
15696 		/* We don't need to worry about FP liveness, it's read-only */
15697 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15698 			err = propagate_liveness_reg(env, &state_reg[i],
15699 						     &parent_reg[i]);
15700 			if (err < 0)
15701 				return err;
15702 			if (err == REG_LIVE_READ64)
15703 				mark_insn_zext(env, &parent_reg[i]);
15704 		}
15705 
15706 		/* Propagate stack slots. */
15707 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15708 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15709 			parent_reg = &parent->stack[i].spilled_ptr;
15710 			state_reg = &state->stack[i].spilled_ptr;
15711 			err = propagate_liveness_reg(env, state_reg,
15712 						     parent_reg);
15713 			if (err < 0)
15714 				return err;
15715 		}
15716 	}
15717 	return 0;
15718 }
15719 
15720 /* find precise scalars in the previous equivalent state and
15721  * propagate them into the current state
15722  */
15723 static int propagate_precision(struct bpf_verifier_env *env,
15724 			       const struct bpf_verifier_state *old)
15725 {
15726 	struct bpf_reg_state *state_reg;
15727 	struct bpf_func_state *state;
15728 	int i, err = 0, fr;
15729 	bool first;
15730 
15731 	for (fr = old->curframe; fr >= 0; fr--) {
15732 		state = old->frame[fr];
15733 		state_reg = state->regs;
15734 		first = true;
15735 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15736 			if (state_reg->type != SCALAR_VALUE ||
15737 			    !state_reg->precise ||
15738 			    !(state_reg->live & REG_LIVE_READ))
15739 				continue;
15740 			if (env->log.level & BPF_LOG_LEVEL2) {
15741 				if (first)
15742 					verbose(env, "frame %d: propagating r%d", fr, i);
15743 				else
15744 					verbose(env, ",r%d", i);
15745 			}
15746 			bt_set_frame_reg(&env->bt, fr, i);
15747 			first = false;
15748 		}
15749 
15750 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15751 			if (!is_spilled_reg(&state->stack[i]))
15752 				continue;
15753 			state_reg = &state->stack[i].spilled_ptr;
15754 			if (state_reg->type != SCALAR_VALUE ||
15755 			    !state_reg->precise ||
15756 			    !(state_reg->live & REG_LIVE_READ))
15757 				continue;
15758 			if (env->log.level & BPF_LOG_LEVEL2) {
15759 				if (first)
15760 					verbose(env, "frame %d: propagating fp%d",
15761 						fr, (-i - 1) * BPF_REG_SIZE);
15762 				else
15763 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
15764 			}
15765 			bt_set_frame_slot(&env->bt, fr, i);
15766 			first = false;
15767 		}
15768 		if (!first)
15769 			verbose(env, "\n");
15770 	}
15771 
15772 	err = mark_chain_precision_batch(env);
15773 	if (err < 0)
15774 		return err;
15775 
15776 	return 0;
15777 }
15778 
15779 static bool states_maybe_looping(struct bpf_verifier_state *old,
15780 				 struct bpf_verifier_state *cur)
15781 {
15782 	struct bpf_func_state *fold, *fcur;
15783 	int i, fr = cur->curframe;
15784 
15785 	if (old->curframe != fr)
15786 		return false;
15787 
15788 	fold = old->frame[fr];
15789 	fcur = cur->frame[fr];
15790 	for (i = 0; i < MAX_BPF_REG; i++)
15791 		if (memcmp(&fold->regs[i], &fcur->regs[i],
15792 			   offsetof(struct bpf_reg_state, parent)))
15793 			return false;
15794 	return true;
15795 }
15796 
15797 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
15798 {
15799 	return env->insn_aux_data[insn_idx].is_iter_next;
15800 }
15801 
15802 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
15803  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
15804  * states to match, which otherwise would look like an infinite loop. So while
15805  * iter_next() calls are taken care of, we still need to be careful and
15806  * prevent erroneous and too eager declaration of "ininite loop", when
15807  * iterators are involved.
15808  *
15809  * Here's a situation in pseudo-BPF assembly form:
15810  *
15811  *   0: again:                          ; set up iter_next() call args
15812  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
15813  *   2:   call bpf_iter_num_next        ; this is iter_next() call
15814  *   3:   if r0 == 0 goto done
15815  *   4:   ... something useful here ...
15816  *   5:   goto again                    ; another iteration
15817  *   6: done:
15818  *   7:   r1 = &it
15819  *   8:   call bpf_iter_num_destroy     ; clean up iter state
15820  *   9:   exit
15821  *
15822  * This is a typical loop. Let's assume that we have a prune point at 1:,
15823  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
15824  * again`, assuming other heuristics don't get in a way).
15825  *
15826  * When we first time come to 1:, let's say we have some state X. We proceed
15827  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
15828  * Now we come back to validate that forked ACTIVE state. We proceed through
15829  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
15830  * are converging. But the problem is that we don't know that yet, as this
15831  * convergence has to happen at iter_next() call site only. So if nothing is
15832  * done, at 1: verifier will use bounded loop logic and declare infinite
15833  * looping (and would be *technically* correct, if not for iterator's
15834  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
15835  * don't want that. So what we do in process_iter_next_call() when we go on
15836  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
15837  * a different iteration. So when we suspect an infinite loop, we additionally
15838  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
15839  * pretend we are not looping and wait for next iter_next() call.
15840  *
15841  * This only applies to ACTIVE state. In DRAINED state we don't expect to
15842  * loop, because that would actually mean infinite loop, as DRAINED state is
15843  * "sticky", and so we'll keep returning into the same instruction with the
15844  * same state (at least in one of possible code paths).
15845  *
15846  * This approach allows to keep infinite loop heuristic even in the face of
15847  * active iterator. E.g., C snippet below is and will be detected as
15848  * inifintely looping:
15849  *
15850  *   struct bpf_iter_num it;
15851  *   int *p, x;
15852  *
15853  *   bpf_iter_num_new(&it, 0, 10);
15854  *   while ((p = bpf_iter_num_next(&t))) {
15855  *       x = p;
15856  *       while (x--) {} // <<-- infinite loop here
15857  *   }
15858  *
15859  */
15860 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
15861 {
15862 	struct bpf_reg_state *slot, *cur_slot;
15863 	struct bpf_func_state *state;
15864 	int i, fr;
15865 
15866 	for (fr = old->curframe; fr >= 0; fr--) {
15867 		state = old->frame[fr];
15868 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15869 			if (state->stack[i].slot_type[0] != STACK_ITER)
15870 				continue;
15871 
15872 			slot = &state->stack[i].spilled_ptr;
15873 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
15874 				continue;
15875 
15876 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
15877 			if (cur_slot->iter.depth != slot->iter.depth)
15878 				return true;
15879 		}
15880 	}
15881 	return false;
15882 }
15883 
15884 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
15885 {
15886 	struct bpf_verifier_state_list *new_sl;
15887 	struct bpf_verifier_state_list *sl, **pprev;
15888 	struct bpf_verifier_state *cur = env->cur_state, *new;
15889 	int i, j, err, states_cnt = 0;
15890 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
15891 	bool add_new_state = force_new_state;
15892 
15893 	/* bpf progs typically have pruning point every 4 instructions
15894 	 * http://vger.kernel.org/bpfconf2019.html#session-1
15895 	 * Do not add new state for future pruning if the verifier hasn't seen
15896 	 * at least 2 jumps and at least 8 instructions.
15897 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
15898 	 * In tests that amounts to up to 50% reduction into total verifier
15899 	 * memory consumption and 20% verifier time speedup.
15900 	 */
15901 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
15902 	    env->insn_processed - env->prev_insn_processed >= 8)
15903 		add_new_state = true;
15904 
15905 	pprev = explored_state(env, insn_idx);
15906 	sl = *pprev;
15907 
15908 	clean_live_states(env, insn_idx, cur);
15909 
15910 	while (sl) {
15911 		states_cnt++;
15912 		if (sl->state.insn_idx != insn_idx)
15913 			goto next;
15914 
15915 		if (sl->state.branches) {
15916 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
15917 
15918 			if (frame->in_async_callback_fn &&
15919 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
15920 				/* Different async_entry_cnt means that the verifier is
15921 				 * processing another entry into async callback.
15922 				 * Seeing the same state is not an indication of infinite
15923 				 * loop or infinite recursion.
15924 				 * But finding the same state doesn't mean that it's safe
15925 				 * to stop processing the current state. The previous state
15926 				 * hasn't yet reached bpf_exit, since state.branches > 0.
15927 				 * Checking in_async_callback_fn alone is not enough either.
15928 				 * Since the verifier still needs to catch infinite loops
15929 				 * inside async callbacks.
15930 				 */
15931 				goto skip_inf_loop_check;
15932 			}
15933 			/* BPF open-coded iterators loop detection is special.
15934 			 * states_maybe_looping() logic is too simplistic in detecting
15935 			 * states that *might* be equivalent, because it doesn't know
15936 			 * about ID remapping, so don't even perform it.
15937 			 * See process_iter_next_call() and iter_active_depths_differ()
15938 			 * for overview of the logic. When current and one of parent
15939 			 * states are detected as equivalent, it's a good thing: we prove
15940 			 * convergence and can stop simulating further iterations.
15941 			 * It's safe to assume that iterator loop will finish, taking into
15942 			 * account iter_next() contract of eventually returning
15943 			 * sticky NULL result.
15944 			 */
15945 			if (is_iter_next_insn(env, insn_idx)) {
15946 				if (states_equal(env, &sl->state, cur)) {
15947 					struct bpf_func_state *cur_frame;
15948 					struct bpf_reg_state *iter_state, *iter_reg;
15949 					int spi;
15950 
15951 					cur_frame = cur->frame[cur->curframe];
15952 					/* btf_check_iter_kfuncs() enforces that
15953 					 * iter state pointer is always the first arg
15954 					 */
15955 					iter_reg = &cur_frame->regs[BPF_REG_1];
15956 					/* current state is valid due to states_equal(),
15957 					 * so we can assume valid iter and reg state,
15958 					 * no need for extra (re-)validations
15959 					 */
15960 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
15961 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
15962 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
15963 						goto hit;
15964 				}
15965 				goto skip_inf_loop_check;
15966 			}
15967 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
15968 			if (states_maybe_looping(&sl->state, cur) &&
15969 			    states_equal(env, &sl->state, cur) &&
15970 			    !iter_active_depths_differ(&sl->state, cur)) {
15971 				verbose_linfo(env, insn_idx, "; ");
15972 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
15973 				return -EINVAL;
15974 			}
15975 			/* if the verifier is processing a loop, avoid adding new state
15976 			 * too often, since different loop iterations have distinct
15977 			 * states and may not help future pruning.
15978 			 * This threshold shouldn't be too low to make sure that
15979 			 * a loop with large bound will be rejected quickly.
15980 			 * The most abusive loop will be:
15981 			 * r1 += 1
15982 			 * if r1 < 1000000 goto pc-2
15983 			 * 1M insn_procssed limit / 100 == 10k peak states.
15984 			 * This threshold shouldn't be too high either, since states
15985 			 * at the end of the loop are likely to be useful in pruning.
15986 			 */
15987 skip_inf_loop_check:
15988 			if (!force_new_state &&
15989 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
15990 			    env->insn_processed - env->prev_insn_processed < 100)
15991 				add_new_state = false;
15992 			goto miss;
15993 		}
15994 		if (states_equal(env, &sl->state, cur)) {
15995 hit:
15996 			sl->hit_cnt++;
15997 			/* reached equivalent register/stack state,
15998 			 * prune the search.
15999 			 * Registers read by the continuation are read by us.
16000 			 * If we have any write marks in env->cur_state, they
16001 			 * will prevent corresponding reads in the continuation
16002 			 * from reaching our parent (an explored_state).  Our
16003 			 * own state will get the read marks recorded, but
16004 			 * they'll be immediately forgotten as we're pruning
16005 			 * this state and will pop a new one.
16006 			 */
16007 			err = propagate_liveness(env, &sl->state, cur);
16008 
16009 			/* if previous state reached the exit with precision and
16010 			 * current state is equivalent to it (except precsion marks)
16011 			 * the precision needs to be propagated back in
16012 			 * the current state.
16013 			 */
16014 			err = err ? : push_jmp_history(env, cur);
16015 			err = err ? : propagate_precision(env, &sl->state);
16016 			if (err)
16017 				return err;
16018 			return 1;
16019 		}
16020 miss:
16021 		/* when new state is not going to be added do not increase miss count.
16022 		 * Otherwise several loop iterations will remove the state
16023 		 * recorded earlier. The goal of these heuristics is to have
16024 		 * states from some iterations of the loop (some in the beginning
16025 		 * and some at the end) to help pruning.
16026 		 */
16027 		if (add_new_state)
16028 			sl->miss_cnt++;
16029 		/* heuristic to determine whether this state is beneficial
16030 		 * to keep checking from state equivalence point of view.
16031 		 * Higher numbers increase max_states_per_insn and verification time,
16032 		 * but do not meaningfully decrease insn_processed.
16033 		 */
16034 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
16035 			/* the state is unlikely to be useful. Remove it to
16036 			 * speed up verification
16037 			 */
16038 			*pprev = sl->next;
16039 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
16040 				u32 br = sl->state.branches;
16041 
16042 				WARN_ONCE(br,
16043 					  "BUG live_done but branches_to_explore %d\n",
16044 					  br);
16045 				free_verifier_state(&sl->state, false);
16046 				kfree(sl);
16047 				env->peak_states--;
16048 			} else {
16049 				/* cannot free this state, since parentage chain may
16050 				 * walk it later. Add it for free_list instead to
16051 				 * be freed at the end of verification
16052 				 */
16053 				sl->next = env->free_list;
16054 				env->free_list = sl;
16055 			}
16056 			sl = *pprev;
16057 			continue;
16058 		}
16059 next:
16060 		pprev = &sl->next;
16061 		sl = *pprev;
16062 	}
16063 
16064 	if (env->max_states_per_insn < states_cnt)
16065 		env->max_states_per_insn = states_cnt;
16066 
16067 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16068 		return 0;
16069 
16070 	if (!add_new_state)
16071 		return 0;
16072 
16073 	/* There were no equivalent states, remember the current one.
16074 	 * Technically the current state is not proven to be safe yet,
16075 	 * but it will either reach outer most bpf_exit (which means it's safe)
16076 	 * or it will be rejected. When there are no loops the verifier won't be
16077 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16078 	 * again on the way to bpf_exit.
16079 	 * When looping the sl->state.branches will be > 0 and this state
16080 	 * will not be considered for equivalence until branches == 0.
16081 	 */
16082 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16083 	if (!new_sl)
16084 		return -ENOMEM;
16085 	env->total_states++;
16086 	env->peak_states++;
16087 	env->prev_jmps_processed = env->jmps_processed;
16088 	env->prev_insn_processed = env->insn_processed;
16089 
16090 	/* forget precise markings we inherited, see __mark_chain_precision */
16091 	if (env->bpf_capable)
16092 		mark_all_scalars_imprecise(env, cur);
16093 
16094 	/* add new state to the head of linked list */
16095 	new = &new_sl->state;
16096 	err = copy_verifier_state(new, cur);
16097 	if (err) {
16098 		free_verifier_state(new, false);
16099 		kfree(new_sl);
16100 		return err;
16101 	}
16102 	new->insn_idx = insn_idx;
16103 	WARN_ONCE(new->branches != 1,
16104 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16105 
16106 	cur->parent = new;
16107 	cur->first_insn_idx = insn_idx;
16108 	clear_jmp_history(cur);
16109 	new_sl->next = *explored_state(env, insn_idx);
16110 	*explored_state(env, insn_idx) = new_sl;
16111 	/* connect new state to parentage chain. Current frame needs all
16112 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
16113 	 * to the stack implicitly by JITs) so in callers' frames connect just
16114 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16115 	 * the state of the call instruction (with WRITTEN set), and r0 comes
16116 	 * from callee with its full parentage chain, anyway.
16117 	 */
16118 	/* clear write marks in current state: the writes we did are not writes
16119 	 * our child did, so they don't screen off its reads from us.
16120 	 * (There are no read marks in current state, because reads always mark
16121 	 * their parent and current state never has children yet.  Only
16122 	 * explored_states can get read marks.)
16123 	 */
16124 	for (j = 0; j <= cur->curframe; j++) {
16125 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16126 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16127 		for (i = 0; i < BPF_REG_FP; i++)
16128 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16129 	}
16130 
16131 	/* all stack frames are accessible from callee, clear them all */
16132 	for (j = 0; j <= cur->curframe; j++) {
16133 		struct bpf_func_state *frame = cur->frame[j];
16134 		struct bpf_func_state *newframe = new->frame[j];
16135 
16136 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16137 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16138 			frame->stack[i].spilled_ptr.parent =
16139 						&newframe->stack[i].spilled_ptr;
16140 		}
16141 	}
16142 	return 0;
16143 }
16144 
16145 /* Return true if it's OK to have the same insn return a different type. */
16146 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16147 {
16148 	switch (base_type(type)) {
16149 	case PTR_TO_CTX:
16150 	case PTR_TO_SOCKET:
16151 	case PTR_TO_SOCK_COMMON:
16152 	case PTR_TO_TCP_SOCK:
16153 	case PTR_TO_XDP_SOCK:
16154 	case PTR_TO_BTF_ID:
16155 		return false;
16156 	default:
16157 		return true;
16158 	}
16159 }
16160 
16161 /* If an instruction was previously used with particular pointer types, then we
16162  * need to be careful to avoid cases such as the below, where it may be ok
16163  * for one branch accessing the pointer, but not ok for the other branch:
16164  *
16165  * R1 = sock_ptr
16166  * goto X;
16167  * ...
16168  * R1 = some_other_valid_ptr;
16169  * goto X;
16170  * ...
16171  * R2 = *(u32 *)(R1 + 0);
16172  */
16173 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16174 {
16175 	return src != prev && (!reg_type_mismatch_ok(src) ||
16176 			       !reg_type_mismatch_ok(prev));
16177 }
16178 
16179 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16180 			     bool allow_trust_missmatch)
16181 {
16182 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16183 
16184 	if (*prev_type == NOT_INIT) {
16185 		/* Saw a valid insn
16186 		 * dst_reg = *(u32 *)(src_reg + off)
16187 		 * save type to validate intersecting paths
16188 		 */
16189 		*prev_type = type;
16190 	} else if (reg_type_mismatch(type, *prev_type)) {
16191 		/* Abuser program is trying to use the same insn
16192 		 * dst_reg = *(u32*) (src_reg + off)
16193 		 * with different pointer types:
16194 		 * src_reg == ctx in one branch and
16195 		 * src_reg == stack|map in some other branch.
16196 		 * Reject it.
16197 		 */
16198 		if (allow_trust_missmatch &&
16199 		    base_type(type) == PTR_TO_BTF_ID &&
16200 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
16201 			/*
16202 			 * Have to support a use case when one path through
16203 			 * the program yields TRUSTED pointer while another
16204 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16205 			 * BPF_PROBE_MEM.
16206 			 */
16207 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16208 		} else {
16209 			verbose(env, "same insn cannot be used with different pointers\n");
16210 			return -EINVAL;
16211 		}
16212 	}
16213 
16214 	return 0;
16215 }
16216 
16217 static int do_check(struct bpf_verifier_env *env)
16218 {
16219 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16220 	struct bpf_verifier_state *state = env->cur_state;
16221 	struct bpf_insn *insns = env->prog->insnsi;
16222 	struct bpf_reg_state *regs;
16223 	int insn_cnt = env->prog->len;
16224 	bool do_print_state = false;
16225 	int prev_insn_idx = -1;
16226 
16227 	for (;;) {
16228 		struct bpf_insn *insn;
16229 		u8 class;
16230 		int err;
16231 
16232 		env->prev_insn_idx = prev_insn_idx;
16233 		if (env->insn_idx >= insn_cnt) {
16234 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
16235 				env->insn_idx, insn_cnt);
16236 			return -EFAULT;
16237 		}
16238 
16239 		insn = &insns[env->insn_idx];
16240 		class = BPF_CLASS(insn->code);
16241 
16242 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16243 			verbose(env,
16244 				"BPF program is too large. Processed %d insn\n",
16245 				env->insn_processed);
16246 			return -E2BIG;
16247 		}
16248 
16249 		state->last_insn_idx = env->prev_insn_idx;
16250 
16251 		if (is_prune_point(env, env->insn_idx)) {
16252 			err = is_state_visited(env, env->insn_idx);
16253 			if (err < 0)
16254 				return err;
16255 			if (err == 1) {
16256 				/* found equivalent state, can prune the search */
16257 				if (env->log.level & BPF_LOG_LEVEL) {
16258 					if (do_print_state)
16259 						verbose(env, "\nfrom %d to %d%s: safe\n",
16260 							env->prev_insn_idx, env->insn_idx,
16261 							env->cur_state->speculative ?
16262 							" (speculative execution)" : "");
16263 					else
16264 						verbose(env, "%d: safe\n", env->insn_idx);
16265 				}
16266 				goto process_bpf_exit;
16267 			}
16268 		}
16269 
16270 		if (is_jmp_point(env, env->insn_idx)) {
16271 			err = push_jmp_history(env, state);
16272 			if (err)
16273 				return err;
16274 		}
16275 
16276 		if (signal_pending(current))
16277 			return -EAGAIN;
16278 
16279 		if (need_resched())
16280 			cond_resched();
16281 
16282 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16283 			verbose(env, "\nfrom %d to %d%s:",
16284 				env->prev_insn_idx, env->insn_idx,
16285 				env->cur_state->speculative ?
16286 				" (speculative execution)" : "");
16287 			print_verifier_state(env, state->frame[state->curframe], true);
16288 			do_print_state = false;
16289 		}
16290 
16291 		if (env->log.level & BPF_LOG_LEVEL) {
16292 			const struct bpf_insn_cbs cbs = {
16293 				.cb_call	= disasm_kfunc_name,
16294 				.cb_print	= verbose,
16295 				.private_data	= env,
16296 			};
16297 
16298 			if (verifier_state_scratched(env))
16299 				print_insn_state(env, state->frame[state->curframe]);
16300 
16301 			verbose_linfo(env, env->insn_idx, "; ");
16302 			env->prev_log_pos = env->log.end_pos;
16303 			verbose(env, "%d: ", env->insn_idx);
16304 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16305 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16306 			env->prev_log_pos = env->log.end_pos;
16307 		}
16308 
16309 		if (bpf_prog_is_offloaded(env->prog->aux)) {
16310 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16311 							   env->prev_insn_idx);
16312 			if (err)
16313 				return err;
16314 		}
16315 
16316 		regs = cur_regs(env);
16317 		sanitize_mark_insn_seen(env);
16318 		prev_insn_idx = env->insn_idx;
16319 
16320 		if (class == BPF_ALU || class == BPF_ALU64) {
16321 			err = check_alu_op(env, insn);
16322 			if (err)
16323 				return err;
16324 
16325 		} else if (class == BPF_LDX) {
16326 			enum bpf_reg_type src_reg_type;
16327 
16328 			/* check for reserved fields is already done */
16329 
16330 			/* check src operand */
16331 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
16332 			if (err)
16333 				return err;
16334 
16335 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16336 			if (err)
16337 				return err;
16338 
16339 			src_reg_type = regs[insn->src_reg].type;
16340 
16341 			/* check that memory (src_reg + off) is readable,
16342 			 * the state of dst_reg will be updated by this func
16343 			 */
16344 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
16345 					       insn->off, BPF_SIZE(insn->code),
16346 					       BPF_READ, insn->dst_reg, false);
16347 			if (err)
16348 				return err;
16349 
16350 			err = save_aux_ptr_type(env, src_reg_type, true);
16351 			if (err)
16352 				return err;
16353 		} else if (class == BPF_STX) {
16354 			enum bpf_reg_type dst_reg_type;
16355 
16356 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16357 				err = check_atomic(env, env->insn_idx, insn);
16358 				if (err)
16359 					return err;
16360 				env->insn_idx++;
16361 				continue;
16362 			}
16363 
16364 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16365 				verbose(env, "BPF_STX uses reserved fields\n");
16366 				return -EINVAL;
16367 			}
16368 
16369 			/* check src1 operand */
16370 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
16371 			if (err)
16372 				return err;
16373 			/* check src2 operand */
16374 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16375 			if (err)
16376 				return err;
16377 
16378 			dst_reg_type = regs[insn->dst_reg].type;
16379 
16380 			/* check that memory (dst_reg + off) is writeable */
16381 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16382 					       insn->off, BPF_SIZE(insn->code),
16383 					       BPF_WRITE, insn->src_reg, false);
16384 			if (err)
16385 				return err;
16386 
16387 			err = save_aux_ptr_type(env, dst_reg_type, false);
16388 			if (err)
16389 				return err;
16390 		} else if (class == BPF_ST) {
16391 			enum bpf_reg_type dst_reg_type;
16392 
16393 			if (BPF_MODE(insn->code) != BPF_MEM ||
16394 			    insn->src_reg != BPF_REG_0) {
16395 				verbose(env, "BPF_ST uses reserved fields\n");
16396 				return -EINVAL;
16397 			}
16398 			/* check src operand */
16399 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16400 			if (err)
16401 				return err;
16402 
16403 			dst_reg_type = regs[insn->dst_reg].type;
16404 
16405 			/* check that memory (dst_reg + off) is writeable */
16406 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16407 					       insn->off, BPF_SIZE(insn->code),
16408 					       BPF_WRITE, -1, false);
16409 			if (err)
16410 				return err;
16411 
16412 			err = save_aux_ptr_type(env, dst_reg_type, false);
16413 			if (err)
16414 				return err;
16415 		} else if (class == BPF_JMP || class == BPF_JMP32) {
16416 			u8 opcode = BPF_OP(insn->code);
16417 
16418 			env->jmps_processed++;
16419 			if (opcode == BPF_CALL) {
16420 				if (BPF_SRC(insn->code) != BPF_K ||
16421 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16422 				     && insn->off != 0) ||
16423 				    (insn->src_reg != BPF_REG_0 &&
16424 				     insn->src_reg != BPF_PSEUDO_CALL &&
16425 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16426 				    insn->dst_reg != BPF_REG_0 ||
16427 				    class == BPF_JMP32) {
16428 					verbose(env, "BPF_CALL uses reserved fields\n");
16429 					return -EINVAL;
16430 				}
16431 
16432 				if (env->cur_state->active_lock.ptr) {
16433 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16434 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
16435 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16436 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16437 						verbose(env, "function calls are not allowed while holding a lock\n");
16438 						return -EINVAL;
16439 					}
16440 				}
16441 				if (insn->src_reg == BPF_PSEUDO_CALL)
16442 					err = check_func_call(env, insn, &env->insn_idx);
16443 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16444 					err = check_kfunc_call(env, insn, &env->insn_idx);
16445 				else
16446 					err = check_helper_call(env, insn, &env->insn_idx);
16447 				if (err)
16448 					return err;
16449 
16450 				mark_reg_scratched(env, BPF_REG_0);
16451 			} else if (opcode == BPF_JA) {
16452 				if (BPF_SRC(insn->code) != BPF_K ||
16453 				    insn->imm != 0 ||
16454 				    insn->src_reg != BPF_REG_0 ||
16455 				    insn->dst_reg != BPF_REG_0 ||
16456 				    class == BPF_JMP32) {
16457 					verbose(env, "BPF_JA uses reserved fields\n");
16458 					return -EINVAL;
16459 				}
16460 
16461 				env->insn_idx += insn->off + 1;
16462 				continue;
16463 
16464 			} else if (opcode == BPF_EXIT) {
16465 				if (BPF_SRC(insn->code) != BPF_K ||
16466 				    insn->imm != 0 ||
16467 				    insn->src_reg != BPF_REG_0 ||
16468 				    insn->dst_reg != BPF_REG_0 ||
16469 				    class == BPF_JMP32) {
16470 					verbose(env, "BPF_EXIT uses reserved fields\n");
16471 					return -EINVAL;
16472 				}
16473 
16474 				if (env->cur_state->active_lock.ptr &&
16475 				    !in_rbtree_lock_required_cb(env)) {
16476 					verbose(env, "bpf_spin_unlock is missing\n");
16477 					return -EINVAL;
16478 				}
16479 
16480 				if (env->cur_state->active_rcu_lock) {
16481 					verbose(env, "bpf_rcu_read_unlock is missing\n");
16482 					return -EINVAL;
16483 				}
16484 
16485 				/* We must do check_reference_leak here before
16486 				 * prepare_func_exit to handle the case when
16487 				 * state->curframe > 0, it may be a callback
16488 				 * function, for which reference_state must
16489 				 * match caller reference state when it exits.
16490 				 */
16491 				err = check_reference_leak(env);
16492 				if (err)
16493 					return err;
16494 
16495 				if (state->curframe) {
16496 					/* exit from nested function */
16497 					err = prepare_func_exit(env, &env->insn_idx);
16498 					if (err)
16499 						return err;
16500 					do_print_state = true;
16501 					continue;
16502 				}
16503 
16504 				err = check_return_code(env);
16505 				if (err)
16506 					return err;
16507 process_bpf_exit:
16508 				mark_verifier_state_scratched(env);
16509 				update_branch_counts(env, env->cur_state);
16510 				err = pop_stack(env, &prev_insn_idx,
16511 						&env->insn_idx, pop_log);
16512 				if (err < 0) {
16513 					if (err != -ENOENT)
16514 						return err;
16515 					break;
16516 				} else {
16517 					do_print_state = true;
16518 					continue;
16519 				}
16520 			} else {
16521 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
16522 				if (err)
16523 					return err;
16524 			}
16525 		} else if (class == BPF_LD) {
16526 			u8 mode = BPF_MODE(insn->code);
16527 
16528 			if (mode == BPF_ABS || mode == BPF_IND) {
16529 				err = check_ld_abs(env, insn);
16530 				if (err)
16531 					return err;
16532 
16533 			} else if (mode == BPF_IMM) {
16534 				err = check_ld_imm(env, insn);
16535 				if (err)
16536 					return err;
16537 
16538 				env->insn_idx++;
16539 				sanitize_mark_insn_seen(env);
16540 			} else {
16541 				verbose(env, "invalid BPF_LD mode\n");
16542 				return -EINVAL;
16543 			}
16544 		} else {
16545 			verbose(env, "unknown insn class %d\n", class);
16546 			return -EINVAL;
16547 		}
16548 
16549 		env->insn_idx++;
16550 	}
16551 
16552 	return 0;
16553 }
16554 
16555 static int find_btf_percpu_datasec(struct btf *btf)
16556 {
16557 	const struct btf_type *t;
16558 	const char *tname;
16559 	int i, n;
16560 
16561 	/*
16562 	 * Both vmlinux and module each have their own ".data..percpu"
16563 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16564 	 * types to look at only module's own BTF types.
16565 	 */
16566 	n = btf_nr_types(btf);
16567 	if (btf_is_module(btf))
16568 		i = btf_nr_types(btf_vmlinux);
16569 	else
16570 		i = 1;
16571 
16572 	for(; i < n; i++) {
16573 		t = btf_type_by_id(btf, i);
16574 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16575 			continue;
16576 
16577 		tname = btf_name_by_offset(btf, t->name_off);
16578 		if (!strcmp(tname, ".data..percpu"))
16579 			return i;
16580 	}
16581 
16582 	return -ENOENT;
16583 }
16584 
16585 /* replace pseudo btf_id with kernel symbol address */
16586 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16587 			       struct bpf_insn *insn,
16588 			       struct bpf_insn_aux_data *aux)
16589 {
16590 	const struct btf_var_secinfo *vsi;
16591 	const struct btf_type *datasec;
16592 	struct btf_mod_pair *btf_mod;
16593 	const struct btf_type *t;
16594 	const char *sym_name;
16595 	bool percpu = false;
16596 	u32 type, id = insn->imm;
16597 	struct btf *btf;
16598 	s32 datasec_id;
16599 	u64 addr;
16600 	int i, btf_fd, err;
16601 
16602 	btf_fd = insn[1].imm;
16603 	if (btf_fd) {
16604 		btf = btf_get_by_fd(btf_fd);
16605 		if (IS_ERR(btf)) {
16606 			verbose(env, "invalid module BTF object FD specified.\n");
16607 			return -EINVAL;
16608 		}
16609 	} else {
16610 		if (!btf_vmlinux) {
16611 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16612 			return -EINVAL;
16613 		}
16614 		btf = btf_vmlinux;
16615 		btf_get(btf);
16616 	}
16617 
16618 	t = btf_type_by_id(btf, id);
16619 	if (!t) {
16620 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16621 		err = -ENOENT;
16622 		goto err_put;
16623 	}
16624 
16625 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16626 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16627 		err = -EINVAL;
16628 		goto err_put;
16629 	}
16630 
16631 	sym_name = btf_name_by_offset(btf, t->name_off);
16632 	addr = kallsyms_lookup_name(sym_name);
16633 	if (!addr) {
16634 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16635 			sym_name);
16636 		err = -ENOENT;
16637 		goto err_put;
16638 	}
16639 	insn[0].imm = (u32)addr;
16640 	insn[1].imm = addr >> 32;
16641 
16642 	if (btf_type_is_func(t)) {
16643 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16644 		aux->btf_var.mem_size = 0;
16645 		goto check_btf;
16646 	}
16647 
16648 	datasec_id = find_btf_percpu_datasec(btf);
16649 	if (datasec_id > 0) {
16650 		datasec = btf_type_by_id(btf, datasec_id);
16651 		for_each_vsi(i, datasec, vsi) {
16652 			if (vsi->type == id) {
16653 				percpu = true;
16654 				break;
16655 			}
16656 		}
16657 	}
16658 
16659 	type = t->type;
16660 	t = btf_type_skip_modifiers(btf, type, NULL);
16661 	if (percpu) {
16662 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16663 		aux->btf_var.btf = btf;
16664 		aux->btf_var.btf_id = type;
16665 	} else if (!btf_type_is_struct(t)) {
16666 		const struct btf_type *ret;
16667 		const char *tname;
16668 		u32 tsize;
16669 
16670 		/* resolve the type size of ksym. */
16671 		ret = btf_resolve_size(btf, t, &tsize);
16672 		if (IS_ERR(ret)) {
16673 			tname = btf_name_by_offset(btf, t->name_off);
16674 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16675 				tname, PTR_ERR(ret));
16676 			err = -EINVAL;
16677 			goto err_put;
16678 		}
16679 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16680 		aux->btf_var.mem_size = tsize;
16681 	} else {
16682 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
16683 		aux->btf_var.btf = btf;
16684 		aux->btf_var.btf_id = type;
16685 	}
16686 check_btf:
16687 	/* check whether we recorded this BTF (and maybe module) already */
16688 	for (i = 0; i < env->used_btf_cnt; i++) {
16689 		if (env->used_btfs[i].btf == btf) {
16690 			btf_put(btf);
16691 			return 0;
16692 		}
16693 	}
16694 
16695 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
16696 		err = -E2BIG;
16697 		goto err_put;
16698 	}
16699 
16700 	btf_mod = &env->used_btfs[env->used_btf_cnt];
16701 	btf_mod->btf = btf;
16702 	btf_mod->module = NULL;
16703 
16704 	/* if we reference variables from kernel module, bump its refcount */
16705 	if (btf_is_module(btf)) {
16706 		btf_mod->module = btf_try_get_module(btf);
16707 		if (!btf_mod->module) {
16708 			err = -ENXIO;
16709 			goto err_put;
16710 		}
16711 	}
16712 
16713 	env->used_btf_cnt++;
16714 
16715 	return 0;
16716 err_put:
16717 	btf_put(btf);
16718 	return err;
16719 }
16720 
16721 static bool is_tracing_prog_type(enum bpf_prog_type type)
16722 {
16723 	switch (type) {
16724 	case BPF_PROG_TYPE_KPROBE:
16725 	case BPF_PROG_TYPE_TRACEPOINT:
16726 	case BPF_PROG_TYPE_PERF_EVENT:
16727 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
16728 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16729 		return true;
16730 	default:
16731 		return false;
16732 	}
16733 }
16734 
16735 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16736 					struct bpf_map *map,
16737 					struct bpf_prog *prog)
16738 
16739 {
16740 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
16741 
16742 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16743 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
16744 		if (is_tracing_prog_type(prog_type)) {
16745 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16746 			return -EINVAL;
16747 		}
16748 	}
16749 
16750 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16751 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16752 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16753 			return -EINVAL;
16754 		}
16755 
16756 		if (is_tracing_prog_type(prog_type)) {
16757 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16758 			return -EINVAL;
16759 		}
16760 
16761 		if (prog->aux->sleepable) {
16762 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16763 			return -EINVAL;
16764 		}
16765 	}
16766 
16767 	if (btf_record_has_field(map->record, BPF_TIMER)) {
16768 		if (is_tracing_prog_type(prog_type)) {
16769 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
16770 			return -EINVAL;
16771 		}
16772 	}
16773 
16774 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16775 	    !bpf_offload_prog_map_match(prog, map)) {
16776 		verbose(env, "offload device mismatch between prog and map\n");
16777 		return -EINVAL;
16778 	}
16779 
16780 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16781 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16782 		return -EINVAL;
16783 	}
16784 
16785 	if (prog->aux->sleepable)
16786 		switch (map->map_type) {
16787 		case BPF_MAP_TYPE_HASH:
16788 		case BPF_MAP_TYPE_LRU_HASH:
16789 		case BPF_MAP_TYPE_ARRAY:
16790 		case BPF_MAP_TYPE_PERCPU_HASH:
16791 		case BPF_MAP_TYPE_PERCPU_ARRAY:
16792 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16793 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16794 		case BPF_MAP_TYPE_HASH_OF_MAPS:
16795 		case BPF_MAP_TYPE_RINGBUF:
16796 		case BPF_MAP_TYPE_USER_RINGBUF:
16797 		case BPF_MAP_TYPE_INODE_STORAGE:
16798 		case BPF_MAP_TYPE_SK_STORAGE:
16799 		case BPF_MAP_TYPE_TASK_STORAGE:
16800 		case BPF_MAP_TYPE_CGRP_STORAGE:
16801 			break;
16802 		default:
16803 			verbose(env,
16804 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
16805 			return -EINVAL;
16806 		}
16807 
16808 	return 0;
16809 }
16810 
16811 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
16812 {
16813 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
16814 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
16815 }
16816 
16817 /* find and rewrite pseudo imm in ld_imm64 instructions:
16818  *
16819  * 1. if it accesses map FD, replace it with actual map pointer.
16820  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
16821  *
16822  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
16823  */
16824 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
16825 {
16826 	struct bpf_insn *insn = env->prog->insnsi;
16827 	int insn_cnt = env->prog->len;
16828 	int i, j, err;
16829 
16830 	err = bpf_prog_calc_tag(env->prog);
16831 	if (err)
16832 		return err;
16833 
16834 	for (i = 0; i < insn_cnt; i++, insn++) {
16835 		if (BPF_CLASS(insn->code) == BPF_LDX &&
16836 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
16837 			verbose(env, "BPF_LDX uses reserved fields\n");
16838 			return -EINVAL;
16839 		}
16840 
16841 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
16842 			struct bpf_insn_aux_data *aux;
16843 			struct bpf_map *map;
16844 			struct fd f;
16845 			u64 addr;
16846 			u32 fd;
16847 
16848 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
16849 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
16850 			    insn[1].off != 0) {
16851 				verbose(env, "invalid bpf_ld_imm64 insn\n");
16852 				return -EINVAL;
16853 			}
16854 
16855 			if (insn[0].src_reg == 0)
16856 				/* valid generic load 64-bit imm */
16857 				goto next_insn;
16858 
16859 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
16860 				aux = &env->insn_aux_data[i];
16861 				err = check_pseudo_btf_id(env, insn, aux);
16862 				if (err)
16863 					return err;
16864 				goto next_insn;
16865 			}
16866 
16867 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
16868 				aux = &env->insn_aux_data[i];
16869 				aux->ptr_type = PTR_TO_FUNC;
16870 				goto next_insn;
16871 			}
16872 
16873 			/* In final convert_pseudo_ld_imm64() step, this is
16874 			 * converted into regular 64-bit imm load insn.
16875 			 */
16876 			switch (insn[0].src_reg) {
16877 			case BPF_PSEUDO_MAP_VALUE:
16878 			case BPF_PSEUDO_MAP_IDX_VALUE:
16879 				break;
16880 			case BPF_PSEUDO_MAP_FD:
16881 			case BPF_PSEUDO_MAP_IDX:
16882 				if (insn[1].imm == 0)
16883 					break;
16884 				fallthrough;
16885 			default:
16886 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
16887 				return -EINVAL;
16888 			}
16889 
16890 			switch (insn[0].src_reg) {
16891 			case BPF_PSEUDO_MAP_IDX_VALUE:
16892 			case BPF_PSEUDO_MAP_IDX:
16893 				if (bpfptr_is_null(env->fd_array)) {
16894 					verbose(env, "fd_idx without fd_array is invalid\n");
16895 					return -EPROTO;
16896 				}
16897 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
16898 							    insn[0].imm * sizeof(fd),
16899 							    sizeof(fd)))
16900 					return -EFAULT;
16901 				break;
16902 			default:
16903 				fd = insn[0].imm;
16904 				break;
16905 			}
16906 
16907 			f = fdget(fd);
16908 			map = __bpf_map_get(f);
16909 			if (IS_ERR(map)) {
16910 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
16911 					insn[0].imm);
16912 				return PTR_ERR(map);
16913 			}
16914 
16915 			err = check_map_prog_compatibility(env, map, env->prog);
16916 			if (err) {
16917 				fdput(f);
16918 				return err;
16919 			}
16920 
16921 			aux = &env->insn_aux_data[i];
16922 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
16923 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
16924 				addr = (unsigned long)map;
16925 			} else {
16926 				u32 off = insn[1].imm;
16927 
16928 				if (off >= BPF_MAX_VAR_OFF) {
16929 					verbose(env, "direct value offset of %u is not allowed\n", off);
16930 					fdput(f);
16931 					return -EINVAL;
16932 				}
16933 
16934 				if (!map->ops->map_direct_value_addr) {
16935 					verbose(env, "no direct value access support for this map type\n");
16936 					fdput(f);
16937 					return -EINVAL;
16938 				}
16939 
16940 				err = map->ops->map_direct_value_addr(map, &addr, off);
16941 				if (err) {
16942 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
16943 						map->value_size, off);
16944 					fdput(f);
16945 					return err;
16946 				}
16947 
16948 				aux->map_off = off;
16949 				addr += off;
16950 			}
16951 
16952 			insn[0].imm = (u32)addr;
16953 			insn[1].imm = addr >> 32;
16954 
16955 			/* check whether we recorded this map already */
16956 			for (j = 0; j < env->used_map_cnt; j++) {
16957 				if (env->used_maps[j] == map) {
16958 					aux->map_index = j;
16959 					fdput(f);
16960 					goto next_insn;
16961 				}
16962 			}
16963 
16964 			if (env->used_map_cnt >= MAX_USED_MAPS) {
16965 				fdput(f);
16966 				return -E2BIG;
16967 			}
16968 
16969 			/* hold the map. If the program is rejected by verifier,
16970 			 * the map will be released by release_maps() or it
16971 			 * will be used by the valid program until it's unloaded
16972 			 * and all maps are released in free_used_maps()
16973 			 */
16974 			bpf_map_inc(map);
16975 
16976 			aux->map_index = env->used_map_cnt;
16977 			env->used_maps[env->used_map_cnt++] = map;
16978 
16979 			if (bpf_map_is_cgroup_storage(map) &&
16980 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
16981 				verbose(env, "only one cgroup storage of each type is allowed\n");
16982 				fdput(f);
16983 				return -EBUSY;
16984 			}
16985 
16986 			fdput(f);
16987 next_insn:
16988 			insn++;
16989 			i++;
16990 			continue;
16991 		}
16992 
16993 		/* Basic sanity check before we invest more work here. */
16994 		if (!bpf_opcode_in_insntable(insn->code)) {
16995 			verbose(env, "unknown opcode %02x\n", insn->code);
16996 			return -EINVAL;
16997 		}
16998 	}
16999 
17000 	/* now all pseudo BPF_LD_IMM64 instructions load valid
17001 	 * 'struct bpf_map *' into a register instead of user map_fd.
17002 	 * These pointers will be used later by verifier to validate map access.
17003 	 */
17004 	return 0;
17005 }
17006 
17007 /* drop refcnt of maps used by the rejected program */
17008 static void release_maps(struct bpf_verifier_env *env)
17009 {
17010 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
17011 			     env->used_map_cnt);
17012 }
17013 
17014 /* drop refcnt of maps used by the rejected program */
17015 static void release_btfs(struct bpf_verifier_env *env)
17016 {
17017 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17018 			     env->used_btf_cnt);
17019 }
17020 
17021 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17022 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17023 {
17024 	struct bpf_insn *insn = env->prog->insnsi;
17025 	int insn_cnt = env->prog->len;
17026 	int i;
17027 
17028 	for (i = 0; i < insn_cnt; i++, insn++) {
17029 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17030 			continue;
17031 		if (insn->src_reg == BPF_PSEUDO_FUNC)
17032 			continue;
17033 		insn->src_reg = 0;
17034 	}
17035 }
17036 
17037 /* single env->prog->insni[off] instruction was replaced with the range
17038  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17039  * [0, off) and [off, end) to new locations, so the patched range stays zero
17040  */
17041 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17042 				 struct bpf_insn_aux_data *new_data,
17043 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
17044 {
17045 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17046 	struct bpf_insn *insn = new_prog->insnsi;
17047 	u32 old_seen = old_data[off].seen;
17048 	u32 prog_len;
17049 	int i;
17050 
17051 	/* aux info at OFF always needs adjustment, no matter fast path
17052 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17053 	 * original insn at old prog.
17054 	 */
17055 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17056 
17057 	if (cnt == 1)
17058 		return;
17059 	prog_len = new_prog->len;
17060 
17061 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17062 	memcpy(new_data + off + cnt - 1, old_data + off,
17063 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17064 	for (i = off; i < off + cnt - 1; i++) {
17065 		/* Expand insni[off]'s seen count to the patched range. */
17066 		new_data[i].seen = old_seen;
17067 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
17068 	}
17069 	env->insn_aux_data = new_data;
17070 	vfree(old_data);
17071 }
17072 
17073 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17074 {
17075 	int i;
17076 
17077 	if (len == 1)
17078 		return;
17079 	/* NOTE: fake 'exit' subprog should be updated as well. */
17080 	for (i = 0; i <= env->subprog_cnt; i++) {
17081 		if (env->subprog_info[i].start <= off)
17082 			continue;
17083 		env->subprog_info[i].start += len - 1;
17084 	}
17085 }
17086 
17087 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17088 {
17089 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17090 	int i, sz = prog->aux->size_poke_tab;
17091 	struct bpf_jit_poke_descriptor *desc;
17092 
17093 	for (i = 0; i < sz; i++) {
17094 		desc = &tab[i];
17095 		if (desc->insn_idx <= off)
17096 			continue;
17097 		desc->insn_idx += len - 1;
17098 	}
17099 }
17100 
17101 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17102 					    const struct bpf_insn *patch, u32 len)
17103 {
17104 	struct bpf_prog *new_prog;
17105 	struct bpf_insn_aux_data *new_data = NULL;
17106 
17107 	if (len > 1) {
17108 		new_data = vzalloc(array_size(env->prog->len + len - 1,
17109 					      sizeof(struct bpf_insn_aux_data)));
17110 		if (!new_data)
17111 			return NULL;
17112 	}
17113 
17114 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17115 	if (IS_ERR(new_prog)) {
17116 		if (PTR_ERR(new_prog) == -ERANGE)
17117 			verbose(env,
17118 				"insn %d cannot be patched due to 16-bit range\n",
17119 				env->insn_aux_data[off].orig_idx);
17120 		vfree(new_data);
17121 		return NULL;
17122 	}
17123 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
17124 	adjust_subprog_starts(env, off, len);
17125 	adjust_poke_descs(new_prog, off, len);
17126 	return new_prog;
17127 }
17128 
17129 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17130 					      u32 off, u32 cnt)
17131 {
17132 	int i, j;
17133 
17134 	/* find first prog starting at or after off (first to remove) */
17135 	for (i = 0; i < env->subprog_cnt; i++)
17136 		if (env->subprog_info[i].start >= off)
17137 			break;
17138 	/* find first prog starting at or after off + cnt (first to stay) */
17139 	for (j = i; j < env->subprog_cnt; j++)
17140 		if (env->subprog_info[j].start >= off + cnt)
17141 			break;
17142 	/* if j doesn't start exactly at off + cnt, we are just removing
17143 	 * the front of previous prog
17144 	 */
17145 	if (env->subprog_info[j].start != off + cnt)
17146 		j--;
17147 
17148 	if (j > i) {
17149 		struct bpf_prog_aux *aux = env->prog->aux;
17150 		int move;
17151 
17152 		/* move fake 'exit' subprog as well */
17153 		move = env->subprog_cnt + 1 - j;
17154 
17155 		memmove(env->subprog_info + i,
17156 			env->subprog_info + j,
17157 			sizeof(*env->subprog_info) * move);
17158 		env->subprog_cnt -= j - i;
17159 
17160 		/* remove func_info */
17161 		if (aux->func_info) {
17162 			move = aux->func_info_cnt - j;
17163 
17164 			memmove(aux->func_info + i,
17165 				aux->func_info + j,
17166 				sizeof(*aux->func_info) * move);
17167 			aux->func_info_cnt -= j - i;
17168 			/* func_info->insn_off is set after all code rewrites,
17169 			 * in adjust_btf_func() - no need to adjust
17170 			 */
17171 		}
17172 	} else {
17173 		/* convert i from "first prog to remove" to "first to adjust" */
17174 		if (env->subprog_info[i].start == off)
17175 			i++;
17176 	}
17177 
17178 	/* update fake 'exit' subprog as well */
17179 	for (; i <= env->subprog_cnt; i++)
17180 		env->subprog_info[i].start -= cnt;
17181 
17182 	return 0;
17183 }
17184 
17185 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17186 				      u32 cnt)
17187 {
17188 	struct bpf_prog *prog = env->prog;
17189 	u32 i, l_off, l_cnt, nr_linfo;
17190 	struct bpf_line_info *linfo;
17191 
17192 	nr_linfo = prog->aux->nr_linfo;
17193 	if (!nr_linfo)
17194 		return 0;
17195 
17196 	linfo = prog->aux->linfo;
17197 
17198 	/* find first line info to remove, count lines to be removed */
17199 	for (i = 0; i < nr_linfo; i++)
17200 		if (linfo[i].insn_off >= off)
17201 			break;
17202 
17203 	l_off = i;
17204 	l_cnt = 0;
17205 	for (; i < nr_linfo; i++)
17206 		if (linfo[i].insn_off < off + cnt)
17207 			l_cnt++;
17208 		else
17209 			break;
17210 
17211 	/* First live insn doesn't match first live linfo, it needs to "inherit"
17212 	 * last removed linfo.  prog is already modified, so prog->len == off
17213 	 * means no live instructions after (tail of the program was removed).
17214 	 */
17215 	if (prog->len != off && l_cnt &&
17216 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17217 		l_cnt--;
17218 		linfo[--i].insn_off = off + cnt;
17219 	}
17220 
17221 	/* remove the line info which refer to the removed instructions */
17222 	if (l_cnt) {
17223 		memmove(linfo + l_off, linfo + i,
17224 			sizeof(*linfo) * (nr_linfo - i));
17225 
17226 		prog->aux->nr_linfo -= l_cnt;
17227 		nr_linfo = prog->aux->nr_linfo;
17228 	}
17229 
17230 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
17231 	for (i = l_off; i < nr_linfo; i++)
17232 		linfo[i].insn_off -= cnt;
17233 
17234 	/* fix up all subprogs (incl. 'exit') which start >= off */
17235 	for (i = 0; i <= env->subprog_cnt; i++)
17236 		if (env->subprog_info[i].linfo_idx > l_off) {
17237 			/* program may have started in the removed region but
17238 			 * may not be fully removed
17239 			 */
17240 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17241 				env->subprog_info[i].linfo_idx -= l_cnt;
17242 			else
17243 				env->subprog_info[i].linfo_idx = l_off;
17244 		}
17245 
17246 	return 0;
17247 }
17248 
17249 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17250 {
17251 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17252 	unsigned int orig_prog_len = env->prog->len;
17253 	int err;
17254 
17255 	if (bpf_prog_is_offloaded(env->prog->aux))
17256 		bpf_prog_offload_remove_insns(env, off, cnt);
17257 
17258 	err = bpf_remove_insns(env->prog, off, cnt);
17259 	if (err)
17260 		return err;
17261 
17262 	err = adjust_subprog_starts_after_remove(env, off, cnt);
17263 	if (err)
17264 		return err;
17265 
17266 	err = bpf_adj_linfo_after_remove(env, off, cnt);
17267 	if (err)
17268 		return err;
17269 
17270 	memmove(aux_data + off,	aux_data + off + cnt,
17271 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
17272 
17273 	return 0;
17274 }
17275 
17276 /* The verifier does more data flow analysis than llvm and will not
17277  * explore branches that are dead at run time. Malicious programs can
17278  * have dead code too. Therefore replace all dead at-run-time code
17279  * with 'ja -1'.
17280  *
17281  * Just nops are not optimal, e.g. if they would sit at the end of the
17282  * program and through another bug we would manage to jump there, then
17283  * we'd execute beyond program memory otherwise. Returning exception
17284  * code also wouldn't work since we can have subprogs where the dead
17285  * code could be located.
17286  */
17287 static void sanitize_dead_code(struct bpf_verifier_env *env)
17288 {
17289 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17290 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17291 	struct bpf_insn *insn = env->prog->insnsi;
17292 	const int insn_cnt = env->prog->len;
17293 	int i;
17294 
17295 	for (i = 0; i < insn_cnt; i++) {
17296 		if (aux_data[i].seen)
17297 			continue;
17298 		memcpy(insn + i, &trap, sizeof(trap));
17299 		aux_data[i].zext_dst = false;
17300 	}
17301 }
17302 
17303 static bool insn_is_cond_jump(u8 code)
17304 {
17305 	u8 op;
17306 
17307 	if (BPF_CLASS(code) == BPF_JMP32)
17308 		return true;
17309 
17310 	if (BPF_CLASS(code) != BPF_JMP)
17311 		return false;
17312 
17313 	op = BPF_OP(code);
17314 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17315 }
17316 
17317 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17318 {
17319 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17320 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17321 	struct bpf_insn *insn = env->prog->insnsi;
17322 	const int insn_cnt = env->prog->len;
17323 	int i;
17324 
17325 	for (i = 0; i < insn_cnt; i++, insn++) {
17326 		if (!insn_is_cond_jump(insn->code))
17327 			continue;
17328 
17329 		if (!aux_data[i + 1].seen)
17330 			ja.off = insn->off;
17331 		else if (!aux_data[i + 1 + insn->off].seen)
17332 			ja.off = 0;
17333 		else
17334 			continue;
17335 
17336 		if (bpf_prog_is_offloaded(env->prog->aux))
17337 			bpf_prog_offload_replace_insn(env, i, &ja);
17338 
17339 		memcpy(insn, &ja, sizeof(ja));
17340 	}
17341 }
17342 
17343 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17344 {
17345 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17346 	int insn_cnt = env->prog->len;
17347 	int i, err;
17348 
17349 	for (i = 0; i < insn_cnt; i++) {
17350 		int j;
17351 
17352 		j = 0;
17353 		while (i + j < insn_cnt && !aux_data[i + j].seen)
17354 			j++;
17355 		if (!j)
17356 			continue;
17357 
17358 		err = verifier_remove_insns(env, i, j);
17359 		if (err)
17360 			return err;
17361 		insn_cnt = env->prog->len;
17362 	}
17363 
17364 	return 0;
17365 }
17366 
17367 static int opt_remove_nops(struct bpf_verifier_env *env)
17368 {
17369 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17370 	struct bpf_insn *insn = env->prog->insnsi;
17371 	int insn_cnt = env->prog->len;
17372 	int i, err;
17373 
17374 	for (i = 0; i < insn_cnt; i++) {
17375 		if (memcmp(&insn[i], &ja, sizeof(ja)))
17376 			continue;
17377 
17378 		err = verifier_remove_insns(env, i, 1);
17379 		if (err)
17380 			return err;
17381 		insn_cnt--;
17382 		i--;
17383 	}
17384 
17385 	return 0;
17386 }
17387 
17388 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17389 					 const union bpf_attr *attr)
17390 {
17391 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17392 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
17393 	int i, patch_len, delta = 0, len = env->prog->len;
17394 	struct bpf_insn *insns = env->prog->insnsi;
17395 	struct bpf_prog *new_prog;
17396 	bool rnd_hi32;
17397 
17398 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17399 	zext_patch[1] = BPF_ZEXT_REG(0);
17400 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17401 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17402 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17403 	for (i = 0; i < len; i++) {
17404 		int adj_idx = i + delta;
17405 		struct bpf_insn insn;
17406 		int load_reg;
17407 
17408 		insn = insns[adj_idx];
17409 		load_reg = insn_def_regno(&insn);
17410 		if (!aux[adj_idx].zext_dst) {
17411 			u8 code, class;
17412 			u32 imm_rnd;
17413 
17414 			if (!rnd_hi32)
17415 				continue;
17416 
17417 			code = insn.code;
17418 			class = BPF_CLASS(code);
17419 			if (load_reg == -1)
17420 				continue;
17421 
17422 			/* NOTE: arg "reg" (the fourth one) is only used for
17423 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
17424 			 *       here.
17425 			 */
17426 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17427 				if (class == BPF_LD &&
17428 				    BPF_MODE(code) == BPF_IMM)
17429 					i++;
17430 				continue;
17431 			}
17432 
17433 			/* ctx load could be transformed into wider load. */
17434 			if (class == BPF_LDX &&
17435 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
17436 				continue;
17437 
17438 			imm_rnd = get_random_u32();
17439 			rnd_hi32_patch[0] = insn;
17440 			rnd_hi32_patch[1].imm = imm_rnd;
17441 			rnd_hi32_patch[3].dst_reg = load_reg;
17442 			patch = rnd_hi32_patch;
17443 			patch_len = 4;
17444 			goto apply_patch_buffer;
17445 		}
17446 
17447 		/* Add in an zero-extend instruction if a) the JIT has requested
17448 		 * it or b) it's a CMPXCHG.
17449 		 *
17450 		 * The latter is because: BPF_CMPXCHG always loads a value into
17451 		 * R0, therefore always zero-extends. However some archs'
17452 		 * equivalent instruction only does this load when the
17453 		 * comparison is successful. This detail of CMPXCHG is
17454 		 * orthogonal to the general zero-extension behaviour of the
17455 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
17456 		 */
17457 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17458 			continue;
17459 
17460 		/* Zero-extension is done by the caller. */
17461 		if (bpf_pseudo_kfunc_call(&insn))
17462 			continue;
17463 
17464 		if (WARN_ON(load_reg == -1)) {
17465 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17466 			return -EFAULT;
17467 		}
17468 
17469 		zext_patch[0] = insn;
17470 		zext_patch[1].dst_reg = load_reg;
17471 		zext_patch[1].src_reg = load_reg;
17472 		patch = zext_patch;
17473 		patch_len = 2;
17474 apply_patch_buffer:
17475 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17476 		if (!new_prog)
17477 			return -ENOMEM;
17478 		env->prog = new_prog;
17479 		insns = new_prog->insnsi;
17480 		aux = env->insn_aux_data;
17481 		delta += patch_len - 1;
17482 	}
17483 
17484 	return 0;
17485 }
17486 
17487 /* convert load instructions that access fields of a context type into a
17488  * sequence of instructions that access fields of the underlying structure:
17489  *     struct __sk_buff    -> struct sk_buff
17490  *     struct bpf_sock_ops -> struct sock
17491  */
17492 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17493 {
17494 	const struct bpf_verifier_ops *ops = env->ops;
17495 	int i, cnt, size, ctx_field_size, delta = 0;
17496 	const int insn_cnt = env->prog->len;
17497 	struct bpf_insn insn_buf[16], *insn;
17498 	u32 target_size, size_default, off;
17499 	struct bpf_prog *new_prog;
17500 	enum bpf_access_type type;
17501 	bool is_narrower_load;
17502 
17503 	if (ops->gen_prologue || env->seen_direct_write) {
17504 		if (!ops->gen_prologue) {
17505 			verbose(env, "bpf verifier is misconfigured\n");
17506 			return -EINVAL;
17507 		}
17508 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17509 					env->prog);
17510 		if (cnt >= ARRAY_SIZE(insn_buf)) {
17511 			verbose(env, "bpf verifier is misconfigured\n");
17512 			return -EINVAL;
17513 		} else if (cnt) {
17514 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17515 			if (!new_prog)
17516 				return -ENOMEM;
17517 
17518 			env->prog = new_prog;
17519 			delta += cnt - 1;
17520 		}
17521 	}
17522 
17523 	if (bpf_prog_is_offloaded(env->prog->aux))
17524 		return 0;
17525 
17526 	insn = env->prog->insnsi + delta;
17527 
17528 	for (i = 0; i < insn_cnt; i++, insn++) {
17529 		bpf_convert_ctx_access_t convert_ctx_access;
17530 
17531 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17532 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17533 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17534 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
17535 			type = BPF_READ;
17536 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17537 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17538 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17539 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17540 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17541 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17542 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17543 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17544 			type = BPF_WRITE;
17545 		} else {
17546 			continue;
17547 		}
17548 
17549 		if (type == BPF_WRITE &&
17550 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
17551 			struct bpf_insn patch[] = {
17552 				*insn,
17553 				BPF_ST_NOSPEC(),
17554 			};
17555 
17556 			cnt = ARRAY_SIZE(patch);
17557 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17558 			if (!new_prog)
17559 				return -ENOMEM;
17560 
17561 			delta    += cnt - 1;
17562 			env->prog = new_prog;
17563 			insn      = new_prog->insnsi + i + delta;
17564 			continue;
17565 		}
17566 
17567 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17568 		case PTR_TO_CTX:
17569 			if (!ops->convert_ctx_access)
17570 				continue;
17571 			convert_ctx_access = ops->convert_ctx_access;
17572 			break;
17573 		case PTR_TO_SOCKET:
17574 		case PTR_TO_SOCK_COMMON:
17575 			convert_ctx_access = bpf_sock_convert_ctx_access;
17576 			break;
17577 		case PTR_TO_TCP_SOCK:
17578 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17579 			break;
17580 		case PTR_TO_XDP_SOCK:
17581 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17582 			break;
17583 		case PTR_TO_BTF_ID:
17584 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17585 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17586 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17587 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
17588 		 * any faults for loads into such types. BPF_WRITE is disallowed
17589 		 * for this case.
17590 		 */
17591 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17592 			if (type == BPF_READ) {
17593 				insn->code = BPF_LDX | BPF_PROBE_MEM |
17594 					BPF_SIZE((insn)->code);
17595 				env->prog->aux->num_exentries++;
17596 			}
17597 			continue;
17598 		default:
17599 			continue;
17600 		}
17601 
17602 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17603 		size = BPF_LDST_BYTES(insn);
17604 
17605 		/* If the read access is a narrower load of the field,
17606 		 * convert to a 4/8-byte load, to minimum program type specific
17607 		 * convert_ctx_access changes. If conversion is successful,
17608 		 * we will apply proper mask to the result.
17609 		 */
17610 		is_narrower_load = size < ctx_field_size;
17611 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17612 		off = insn->off;
17613 		if (is_narrower_load) {
17614 			u8 size_code;
17615 
17616 			if (type == BPF_WRITE) {
17617 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17618 				return -EINVAL;
17619 			}
17620 
17621 			size_code = BPF_H;
17622 			if (ctx_field_size == 4)
17623 				size_code = BPF_W;
17624 			else if (ctx_field_size == 8)
17625 				size_code = BPF_DW;
17626 
17627 			insn->off = off & ~(size_default - 1);
17628 			insn->code = BPF_LDX | BPF_MEM | size_code;
17629 		}
17630 
17631 		target_size = 0;
17632 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17633 					 &target_size);
17634 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17635 		    (ctx_field_size && !target_size)) {
17636 			verbose(env, "bpf verifier is misconfigured\n");
17637 			return -EINVAL;
17638 		}
17639 
17640 		if (is_narrower_load && size < target_size) {
17641 			u8 shift = bpf_ctx_narrow_access_offset(
17642 				off, size, size_default) * 8;
17643 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17644 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17645 				return -EINVAL;
17646 			}
17647 			if (ctx_field_size <= 4) {
17648 				if (shift)
17649 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17650 									insn->dst_reg,
17651 									shift);
17652 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17653 								(1 << size * 8) - 1);
17654 			} else {
17655 				if (shift)
17656 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17657 									insn->dst_reg,
17658 									shift);
17659 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17660 								(1ULL << size * 8) - 1);
17661 			}
17662 		}
17663 
17664 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17665 		if (!new_prog)
17666 			return -ENOMEM;
17667 
17668 		delta += cnt - 1;
17669 
17670 		/* keep walking new program and skip insns we just inserted */
17671 		env->prog = new_prog;
17672 		insn      = new_prog->insnsi + i + delta;
17673 	}
17674 
17675 	return 0;
17676 }
17677 
17678 static int jit_subprogs(struct bpf_verifier_env *env)
17679 {
17680 	struct bpf_prog *prog = env->prog, **func, *tmp;
17681 	int i, j, subprog_start, subprog_end = 0, len, subprog;
17682 	struct bpf_map *map_ptr;
17683 	struct bpf_insn *insn;
17684 	void *old_bpf_func;
17685 	int err, num_exentries;
17686 
17687 	if (env->subprog_cnt <= 1)
17688 		return 0;
17689 
17690 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17691 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17692 			continue;
17693 
17694 		/* Upon error here we cannot fall back to interpreter but
17695 		 * need a hard reject of the program. Thus -EFAULT is
17696 		 * propagated in any case.
17697 		 */
17698 		subprog = find_subprog(env, i + insn->imm + 1);
17699 		if (subprog < 0) {
17700 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17701 				  i + insn->imm + 1);
17702 			return -EFAULT;
17703 		}
17704 		/* temporarily remember subprog id inside insn instead of
17705 		 * aux_data, since next loop will split up all insns into funcs
17706 		 */
17707 		insn->off = subprog;
17708 		/* remember original imm in case JIT fails and fallback
17709 		 * to interpreter will be needed
17710 		 */
17711 		env->insn_aux_data[i].call_imm = insn->imm;
17712 		/* point imm to __bpf_call_base+1 from JITs point of view */
17713 		insn->imm = 1;
17714 		if (bpf_pseudo_func(insn))
17715 			/* jit (e.g. x86_64) may emit fewer instructions
17716 			 * if it learns a u32 imm is the same as a u64 imm.
17717 			 * Force a non zero here.
17718 			 */
17719 			insn[1].imm = 1;
17720 	}
17721 
17722 	err = bpf_prog_alloc_jited_linfo(prog);
17723 	if (err)
17724 		goto out_undo_insn;
17725 
17726 	err = -ENOMEM;
17727 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17728 	if (!func)
17729 		goto out_undo_insn;
17730 
17731 	for (i = 0; i < env->subprog_cnt; i++) {
17732 		subprog_start = subprog_end;
17733 		subprog_end = env->subprog_info[i + 1].start;
17734 
17735 		len = subprog_end - subprog_start;
17736 		/* bpf_prog_run() doesn't call subprogs directly,
17737 		 * hence main prog stats include the runtime of subprogs.
17738 		 * subprogs don't have IDs and not reachable via prog_get_next_id
17739 		 * func[i]->stats will never be accessed and stays NULL
17740 		 */
17741 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17742 		if (!func[i])
17743 			goto out_free;
17744 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17745 		       len * sizeof(struct bpf_insn));
17746 		func[i]->type = prog->type;
17747 		func[i]->len = len;
17748 		if (bpf_prog_calc_tag(func[i]))
17749 			goto out_free;
17750 		func[i]->is_func = 1;
17751 		func[i]->aux->func_idx = i;
17752 		/* Below members will be freed only at prog->aux */
17753 		func[i]->aux->btf = prog->aux->btf;
17754 		func[i]->aux->func_info = prog->aux->func_info;
17755 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17756 		func[i]->aux->poke_tab = prog->aux->poke_tab;
17757 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17758 
17759 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
17760 			struct bpf_jit_poke_descriptor *poke;
17761 
17762 			poke = &prog->aux->poke_tab[j];
17763 			if (poke->insn_idx < subprog_end &&
17764 			    poke->insn_idx >= subprog_start)
17765 				poke->aux = func[i]->aux;
17766 		}
17767 
17768 		func[i]->aux->name[0] = 'F';
17769 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17770 		func[i]->jit_requested = 1;
17771 		func[i]->blinding_requested = prog->blinding_requested;
17772 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
17773 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
17774 		func[i]->aux->linfo = prog->aux->linfo;
17775 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17776 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17777 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
17778 		num_exentries = 0;
17779 		insn = func[i]->insnsi;
17780 		for (j = 0; j < func[i]->len; j++, insn++) {
17781 			if (BPF_CLASS(insn->code) == BPF_LDX &&
17782 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
17783 				num_exentries++;
17784 		}
17785 		func[i]->aux->num_exentries = num_exentries;
17786 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
17787 		func[i] = bpf_int_jit_compile(func[i]);
17788 		if (!func[i]->jited) {
17789 			err = -ENOTSUPP;
17790 			goto out_free;
17791 		}
17792 		cond_resched();
17793 	}
17794 
17795 	/* at this point all bpf functions were successfully JITed
17796 	 * now populate all bpf_calls with correct addresses and
17797 	 * run last pass of JIT
17798 	 */
17799 	for (i = 0; i < env->subprog_cnt; i++) {
17800 		insn = func[i]->insnsi;
17801 		for (j = 0; j < func[i]->len; j++, insn++) {
17802 			if (bpf_pseudo_func(insn)) {
17803 				subprog = insn->off;
17804 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
17805 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
17806 				continue;
17807 			}
17808 			if (!bpf_pseudo_call(insn))
17809 				continue;
17810 			subprog = insn->off;
17811 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
17812 		}
17813 
17814 		/* we use the aux data to keep a list of the start addresses
17815 		 * of the JITed images for each function in the program
17816 		 *
17817 		 * for some architectures, such as powerpc64, the imm field
17818 		 * might not be large enough to hold the offset of the start
17819 		 * address of the callee's JITed image from __bpf_call_base
17820 		 *
17821 		 * in such cases, we can lookup the start address of a callee
17822 		 * by using its subprog id, available from the off field of
17823 		 * the call instruction, as an index for this list
17824 		 */
17825 		func[i]->aux->func = func;
17826 		func[i]->aux->func_cnt = env->subprog_cnt;
17827 	}
17828 	for (i = 0; i < env->subprog_cnt; i++) {
17829 		old_bpf_func = func[i]->bpf_func;
17830 		tmp = bpf_int_jit_compile(func[i]);
17831 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
17832 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
17833 			err = -ENOTSUPP;
17834 			goto out_free;
17835 		}
17836 		cond_resched();
17837 	}
17838 
17839 	/* finally lock prog and jit images for all functions and
17840 	 * populate kallsysm. Begin at the first subprogram, since
17841 	 * bpf_prog_load will add the kallsyms for the main program.
17842 	 */
17843 	for (i = 1; i < env->subprog_cnt; i++) {
17844 		bpf_prog_lock_ro(func[i]);
17845 		bpf_prog_kallsyms_add(func[i]);
17846 	}
17847 
17848 	/* Last step: make now unused interpreter insns from main
17849 	 * prog consistent for later dump requests, so they can
17850 	 * later look the same as if they were interpreted only.
17851 	 */
17852 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17853 		if (bpf_pseudo_func(insn)) {
17854 			insn[0].imm = env->insn_aux_data[i].call_imm;
17855 			insn[1].imm = insn->off;
17856 			insn->off = 0;
17857 			continue;
17858 		}
17859 		if (!bpf_pseudo_call(insn))
17860 			continue;
17861 		insn->off = env->insn_aux_data[i].call_imm;
17862 		subprog = find_subprog(env, i + insn->off + 1);
17863 		insn->imm = subprog;
17864 	}
17865 
17866 	prog->jited = 1;
17867 	prog->bpf_func = func[0]->bpf_func;
17868 	prog->jited_len = func[0]->jited_len;
17869 	prog->aux->extable = func[0]->aux->extable;
17870 	prog->aux->num_exentries = func[0]->aux->num_exentries;
17871 	prog->aux->func = func;
17872 	prog->aux->func_cnt = env->subprog_cnt;
17873 	bpf_prog_jit_attempt_done(prog);
17874 	return 0;
17875 out_free:
17876 	/* We failed JIT'ing, so at this point we need to unregister poke
17877 	 * descriptors from subprogs, so that kernel is not attempting to
17878 	 * patch it anymore as we're freeing the subprog JIT memory.
17879 	 */
17880 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
17881 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
17882 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
17883 	}
17884 	/* At this point we're guaranteed that poke descriptors are not
17885 	 * live anymore. We can just unlink its descriptor table as it's
17886 	 * released with the main prog.
17887 	 */
17888 	for (i = 0; i < env->subprog_cnt; i++) {
17889 		if (!func[i])
17890 			continue;
17891 		func[i]->aux->poke_tab = NULL;
17892 		bpf_jit_free(func[i]);
17893 	}
17894 	kfree(func);
17895 out_undo_insn:
17896 	/* cleanup main prog to be interpreted */
17897 	prog->jit_requested = 0;
17898 	prog->blinding_requested = 0;
17899 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17900 		if (!bpf_pseudo_call(insn))
17901 			continue;
17902 		insn->off = 0;
17903 		insn->imm = env->insn_aux_data[i].call_imm;
17904 	}
17905 	bpf_prog_jit_attempt_done(prog);
17906 	return err;
17907 }
17908 
17909 static int fixup_call_args(struct bpf_verifier_env *env)
17910 {
17911 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17912 	struct bpf_prog *prog = env->prog;
17913 	struct bpf_insn *insn = prog->insnsi;
17914 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
17915 	int i, depth;
17916 #endif
17917 	int err = 0;
17918 
17919 	if (env->prog->jit_requested &&
17920 	    !bpf_prog_is_offloaded(env->prog->aux)) {
17921 		err = jit_subprogs(env);
17922 		if (err == 0)
17923 			return 0;
17924 		if (err == -EFAULT)
17925 			return err;
17926 	}
17927 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17928 	if (has_kfunc_call) {
17929 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
17930 		return -EINVAL;
17931 	}
17932 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
17933 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
17934 		 * have to be rejected, since interpreter doesn't support them yet.
17935 		 */
17936 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
17937 		return -EINVAL;
17938 	}
17939 	for (i = 0; i < prog->len; i++, insn++) {
17940 		if (bpf_pseudo_func(insn)) {
17941 			/* When JIT fails the progs with callback calls
17942 			 * have to be rejected, since interpreter doesn't support them yet.
17943 			 */
17944 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
17945 			return -EINVAL;
17946 		}
17947 
17948 		if (!bpf_pseudo_call(insn))
17949 			continue;
17950 		depth = get_callee_stack_depth(env, insn, i);
17951 		if (depth < 0)
17952 			return depth;
17953 		bpf_patch_call_args(insn, depth);
17954 	}
17955 	err = 0;
17956 #endif
17957 	return err;
17958 }
17959 
17960 /* replace a generic kfunc with a specialized version if necessary */
17961 static void specialize_kfunc(struct bpf_verifier_env *env,
17962 			     u32 func_id, u16 offset, unsigned long *addr)
17963 {
17964 	struct bpf_prog *prog = env->prog;
17965 	bool seen_direct_write;
17966 	void *xdp_kfunc;
17967 	bool is_rdonly;
17968 
17969 	if (bpf_dev_bound_kfunc_id(func_id)) {
17970 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
17971 		if (xdp_kfunc) {
17972 			*addr = (unsigned long)xdp_kfunc;
17973 			return;
17974 		}
17975 		/* fallback to default kfunc when not supported by netdev */
17976 	}
17977 
17978 	if (offset)
17979 		return;
17980 
17981 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
17982 		seen_direct_write = env->seen_direct_write;
17983 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
17984 
17985 		if (is_rdonly)
17986 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
17987 
17988 		/* restore env->seen_direct_write to its original value, since
17989 		 * may_access_direct_pkt_data mutates it
17990 		 */
17991 		env->seen_direct_write = seen_direct_write;
17992 	}
17993 }
17994 
17995 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
17996 					    u16 struct_meta_reg,
17997 					    u16 node_offset_reg,
17998 					    struct bpf_insn *insn,
17999 					    struct bpf_insn *insn_buf,
18000 					    int *cnt)
18001 {
18002 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18003 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18004 
18005 	insn_buf[0] = addr[0];
18006 	insn_buf[1] = addr[1];
18007 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18008 	insn_buf[3] = *insn;
18009 	*cnt = 4;
18010 }
18011 
18012 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18013 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18014 {
18015 	const struct bpf_kfunc_desc *desc;
18016 
18017 	if (!insn->imm) {
18018 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18019 		return -EINVAL;
18020 	}
18021 
18022 	*cnt = 0;
18023 
18024 	/* insn->imm has the btf func_id. Replace it with an offset relative to
18025 	 * __bpf_call_base, unless the JIT needs to call functions that are
18026 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18027 	 */
18028 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18029 	if (!desc) {
18030 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18031 			insn->imm);
18032 		return -EFAULT;
18033 	}
18034 
18035 	if (!bpf_jit_supports_far_kfunc_call())
18036 		insn->imm = BPF_CALL_IMM(desc->addr);
18037 	if (insn->off)
18038 		return 0;
18039 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18040 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18041 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18042 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18043 
18044 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18045 		insn_buf[1] = addr[0];
18046 		insn_buf[2] = addr[1];
18047 		insn_buf[3] = *insn;
18048 		*cnt = 4;
18049 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18050 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18051 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18052 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18053 
18054 		insn_buf[0] = addr[0];
18055 		insn_buf[1] = addr[1];
18056 		insn_buf[2] = *insn;
18057 		*cnt = 3;
18058 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18059 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18060 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18061 		int struct_meta_reg = BPF_REG_3;
18062 		int node_offset_reg = BPF_REG_4;
18063 
18064 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18065 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18066 			struct_meta_reg = BPF_REG_4;
18067 			node_offset_reg = BPF_REG_5;
18068 		}
18069 
18070 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18071 						node_offset_reg, insn, insn_buf, cnt);
18072 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18073 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18074 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18075 		*cnt = 1;
18076 	}
18077 	return 0;
18078 }
18079 
18080 /* Do various post-verification rewrites in a single program pass.
18081  * These rewrites simplify JIT and interpreter implementations.
18082  */
18083 static int do_misc_fixups(struct bpf_verifier_env *env)
18084 {
18085 	struct bpf_prog *prog = env->prog;
18086 	enum bpf_attach_type eatype = prog->expected_attach_type;
18087 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18088 	struct bpf_insn *insn = prog->insnsi;
18089 	const struct bpf_func_proto *fn;
18090 	const int insn_cnt = prog->len;
18091 	const struct bpf_map_ops *ops;
18092 	struct bpf_insn_aux_data *aux;
18093 	struct bpf_insn insn_buf[16];
18094 	struct bpf_prog *new_prog;
18095 	struct bpf_map *map_ptr;
18096 	int i, ret, cnt, delta = 0;
18097 
18098 	for (i = 0; i < insn_cnt; i++, insn++) {
18099 		/* Make divide-by-zero exceptions impossible. */
18100 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18101 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18102 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18103 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18104 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18105 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18106 			struct bpf_insn *patchlet;
18107 			struct bpf_insn chk_and_div[] = {
18108 				/* [R,W]x div 0 -> 0 */
18109 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18110 					     BPF_JNE | BPF_K, insn->src_reg,
18111 					     0, 2, 0),
18112 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18113 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18114 				*insn,
18115 			};
18116 			struct bpf_insn chk_and_mod[] = {
18117 				/* [R,W]x mod 0 -> [R,W]x */
18118 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18119 					     BPF_JEQ | BPF_K, insn->src_reg,
18120 					     0, 1 + (is64 ? 0 : 1), 0),
18121 				*insn,
18122 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18123 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18124 			};
18125 
18126 			patchlet = isdiv ? chk_and_div : chk_and_mod;
18127 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18128 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18129 
18130 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18131 			if (!new_prog)
18132 				return -ENOMEM;
18133 
18134 			delta    += cnt - 1;
18135 			env->prog = prog = new_prog;
18136 			insn      = new_prog->insnsi + i + delta;
18137 			continue;
18138 		}
18139 
18140 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18141 		if (BPF_CLASS(insn->code) == BPF_LD &&
18142 		    (BPF_MODE(insn->code) == BPF_ABS ||
18143 		     BPF_MODE(insn->code) == BPF_IND)) {
18144 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
18145 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18146 				verbose(env, "bpf verifier is misconfigured\n");
18147 				return -EINVAL;
18148 			}
18149 
18150 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18151 			if (!new_prog)
18152 				return -ENOMEM;
18153 
18154 			delta    += cnt - 1;
18155 			env->prog = prog = new_prog;
18156 			insn      = new_prog->insnsi + i + delta;
18157 			continue;
18158 		}
18159 
18160 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
18161 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18162 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18163 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18164 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18165 			struct bpf_insn *patch = &insn_buf[0];
18166 			bool issrc, isneg, isimm;
18167 			u32 off_reg;
18168 
18169 			aux = &env->insn_aux_data[i + delta];
18170 			if (!aux->alu_state ||
18171 			    aux->alu_state == BPF_ALU_NON_POINTER)
18172 				continue;
18173 
18174 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18175 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18176 				BPF_ALU_SANITIZE_SRC;
18177 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18178 
18179 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
18180 			if (isimm) {
18181 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18182 			} else {
18183 				if (isneg)
18184 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18185 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18186 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18187 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18188 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18189 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18190 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18191 			}
18192 			if (!issrc)
18193 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18194 			insn->src_reg = BPF_REG_AX;
18195 			if (isneg)
18196 				insn->code = insn->code == code_add ?
18197 					     code_sub : code_add;
18198 			*patch++ = *insn;
18199 			if (issrc && isneg && !isimm)
18200 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18201 			cnt = patch - insn_buf;
18202 
18203 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18204 			if (!new_prog)
18205 				return -ENOMEM;
18206 
18207 			delta    += cnt - 1;
18208 			env->prog = prog = new_prog;
18209 			insn      = new_prog->insnsi + i + delta;
18210 			continue;
18211 		}
18212 
18213 		if (insn->code != (BPF_JMP | BPF_CALL))
18214 			continue;
18215 		if (insn->src_reg == BPF_PSEUDO_CALL)
18216 			continue;
18217 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18218 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18219 			if (ret)
18220 				return ret;
18221 			if (cnt == 0)
18222 				continue;
18223 
18224 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18225 			if (!new_prog)
18226 				return -ENOMEM;
18227 
18228 			delta	 += cnt - 1;
18229 			env->prog = prog = new_prog;
18230 			insn	  = new_prog->insnsi + i + delta;
18231 			continue;
18232 		}
18233 
18234 		if (insn->imm == BPF_FUNC_get_route_realm)
18235 			prog->dst_needed = 1;
18236 		if (insn->imm == BPF_FUNC_get_prandom_u32)
18237 			bpf_user_rnd_init_once();
18238 		if (insn->imm == BPF_FUNC_override_return)
18239 			prog->kprobe_override = 1;
18240 		if (insn->imm == BPF_FUNC_tail_call) {
18241 			/* If we tail call into other programs, we
18242 			 * cannot make any assumptions since they can
18243 			 * be replaced dynamically during runtime in
18244 			 * the program array.
18245 			 */
18246 			prog->cb_access = 1;
18247 			if (!allow_tail_call_in_subprogs(env))
18248 				prog->aux->stack_depth = MAX_BPF_STACK;
18249 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18250 
18251 			/* mark bpf_tail_call as different opcode to avoid
18252 			 * conditional branch in the interpreter for every normal
18253 			 * call and to prevent accidental JITing by JIT compiler
18254 			 * that doesn't support bpf_tail_call yet
18255 			 */
18256 			insn->imm = 0;
18257 			insn->code = BPF_JMP | BPF_TAIL_CALL;
18258 
18259 			aux = &env->insn_aux_data[i + delta];
18260 			if (env->bpf_capable && !prog->blinding_requested &&
18261 			    prog->jit_requested &&
18262 			    !bpf_map_key_poisoned(aux) &&
18263 			    !bpf_map_ptr_poisoned(aux) &&
18264 			    !bpf_map_ptr_unpriv(aux)) {
18265 				struct bpf_jit_poke_descriptor desc = {
18266 					.reason = BPF_POKE_REASON_TAIL_CALL,
18267 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18268 					.tail_call.key = bpf_map_key_immediate(aux),
18269 					.insn_idx = i + delta,
18270 				};
18271 
18272 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
18273 				if (ret < 0) {
18274 					verbose(env, "adding tail call poke descriptor failed\n");
18275 					return ret;
18276 				}
18277 
18278 				insn->imm = ret + 1;
18279 				continue;
18280 			}
18281 
18282 			if (!bpf_map_ptr_unpriv(aux))
18283 				continue;
18284 
18285 			/* instead of changing every JIT dealing with tail_call
18286 			 * emit two extra insns:
18287 			 * if (index >= max_entries) goto out;
18288 			 * index &= array->index_mask;
18289 			 * to avoid out-of-bounds cpu speculation
18290 			 */
18291 			if (bpf_map_ptr_poisoned(aux)) {
18292 				verbose(env, "tail_call abusing map_ptr\n");
18293 				return -EINVAL;
18294 			}
18295 
18296 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18297 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18298 						  map_ptr->max_entries, 2);
18299 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18300 						    container_of(map_ptr,
18301 								 struct bpf_array,
18302 								 map)->index_mask);
18303 			insn_buf[2] = *insn;
18304 			cnt = 3;
18305 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18306 			if (!new_prog)
18307 				return -ENOMEM;
18308 
18309 			delta    += cnt - 1;
18310 			env->prog = prog = new_prog;
18311 			insn      = new_prog->insnsi + i + delta;
18312 			continue;
18313 		}
18314 
18315 		if (insn->imm == BPF_FUNC_timer_set_callback) {
18316 			/* The verifier will process callback_fn as many times as necessary
18317 			 * with different maps and the register states prepared by
18318 			 * set_timer_callback_state will be accurate.
18319 			 *
18320 			 * The following use case is valid:
18321 			 *   map1 is shared by prog1, prog2, prog3.
18322 			 *   prog1 calls bpf_timer_init for some map1 elements
18323 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
18324 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
18325 			 *   prog3 calls bpf_timer_start for some map1 elements.
18326 			 *     Those that were not both bpf_timer_init-ed and
18327 			 *     bpf_timer_set_callback-ed will return -EINVAL.
18328 			 */
18329 			struct bpf_insn ld_addrs[2] = {
18330 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18331 			};
18332 
18333 			insn_buf[0] = ld_addrs[0];
18334 			insn_buf[1] = ld_addrs[1];
18335 			insn_buf[2] = *insn;
18336 			cnt = 3;
18337 
18338 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18339 			if (!new_prog)
18340 				return -ENOMEM;
18341 
18342 			delta    += cnt - 1;
18343 			env->prog = prog = new_prog;
18344 			insn      = new_prog->insnsi + i + delta;
18345 			goto patch_call_imm;
18346 		}
18347 
18348 		if (is_storage_get_function(insn->imm)) {
18349 			if (!env->prog->aux->sleepable ||
18350 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
18351 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18352 			else
18353 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18354 			insn_buf[1] = *insn;
18355 			cnt = 2;
18356 
18357 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18358 			if (!new_prog)
18359 				return -ENOMEM;
18360 
18361 			delta += cnt - 1;
18362 			env->prog = prog = new_prog;
18363 			insn = new_prog->insnsi + i + delta;
18364 			goto patch_call_imm;
18365 		}
18366 
18367 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
18368 		 * and other inlining handlers are currently limited to 64 bit
18369 		 * only.
18370 		 */
18371 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
18372 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
18373 		     insn->imm == BPF_FUNC_map_update_elem ||
18374 		     insn->imm == BPF_FUNC_map_delete_elem ||
18375 		     insn->imm == BPF_FUNC_map_push_elem   ||
18376 		     insn->imm == BPF_FUNC_map_pop_elem    ||
18377 		     insn->imm == BPF_FUNC_map_peek_elem   ||
18378 		     insn->imm == BPF_FUNC_redirect_map    ||
18379 		     insn->imm == BPF_FUNC_for_each_map_elem ||
18380 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18381 			aux = &env->insn_aux_data[i + delta];
18382 			if (bpf_map_ptr_poisoned(aux))
18383 				goto patch_call_imm;
18384 
18385 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18386 			ops = map_ptr->ops;
18387 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
18388 			    ops->map_gen_lookup) {
18389 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18390 				if (cnt == -EOPNOTSUPP)
18391 					goto patch_map_ops_generic;
18392 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18393 					verbose(env, "bpf verifier is misconfigured\n");
18394 					return -EINVAL;
18395 				}
18396 
18397 				new_prog = bpf_patch_insn_data(env, i + delta,
18398 							       insn_buf, cnt);
18399 				if (!new_prog)
18400 					return -ENOMEM;
18401 
18402 				delta    += cnt - 1;
18403 				env->prog = prog = new_prog;
18404 				insn      = new_prog->insnsi + i + delta;
18405 				continue;
18406 			}
18407 
18408 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18409 				     (void *(*)(struct bpf_map *map, void *key))NULL));
18410 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18411 				     (long (*)(struct bpf_map *map, void *key))NULL));
18412 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18413 				     (long (*)(struct bpf_map *map, void *key, void *value,
18414 					      u64 flags))NULL));
18415 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18416 				     (long (*)(struct bpf_map *map, void *value,
18417 					      u64 flags))NULL));
18418 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18419 				     (long (*)(struct bpf_map *map, void *value))NULL));
18420 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18421 				     (long (*)(struct bpf_map *map, void *value))NULL));
18422 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
18423 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18424 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18425 				     (long (*)(struct bpf_map *map,
18426 					      bpf_callback_t callback_fn,
18427 					      void *callback_ctx,
18428 					      u64 flags))NULL));
18429 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18430 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18431 
18432 patch_map_ops_generic:
18433 			switch (insn->imm) {
18434 			case BPF_FUNC_map_lookup_elem:
18435 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18436 				continue;
18437 			case BPF_FUNC_map_update_elem:
18438 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18439 				continue;
18440 			case BPF_FUNC_map_delete_elem:
18441 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18442 				continue;
18443 			case BPF_FUNC_map_push_elem:
18444 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18445 				continue;
18446 			case BPF_FUNC_map_pop_elem:
18447 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18448 				continue;
18449 			case BPF_FUNC_map_peek_elem:
18450 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18451 				continue;
18452 			case BPF_FUNC_redirect_map:
18453 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
18454 				continue;
18455 			case BPF_FUNC_for_each_map_elem:
18456 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18457 				continue;
18458 			case BPF_FUNC_map_lookup_percpu_elem:
18459 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18460 				continue;
18461 			}
18462 
18463 			goto patch_call_imm;
18464 		}
18465 
18466 		/* Implement bpf_jiffies64 inline. */
18467 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
18468 		    insn->imm == BPF_FUNC_jiffies64) {
18469 			struct bpf_insn ld_jiffies_addr[2] = {
18470 				BPF_LD_IMM64(BPF_REG_0,
18471 					     (unsigned long)&jiffies),
18472 			};
18473 
18474 			insn_buf[0] = ld_jiffies_addr[0];
18475 			insn_buf[1] = ld_jiffies_addr[1];
18476 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18477 						  BPF_REG_0, 0);
18478 			cnt = 3;
18479 
18480 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18481 						       cnt);
18482 			if (!new_prog)
18483 				return -ENOMEM;
18484 
18485 			delta    += cnt - 1;
18486 			env->prog = prog = new_prog;
18487 			insn      = new_prog->insnsi + i + delta;
18488 			continue;
18489 		}
18490 
18491 		/* Implement bpf_get_func_arg inline. */
18492 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18493 		    insn->imm == BPF_FUNC_get_func_arg) {
18494 			/* Load nr_args from ctx - 8 */
18495 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18496 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18497 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18498 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18499 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18500 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18501 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18502 			insn_buf[7] = BPF_JMP_A(1);
18503 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18504 			cnt = 9;
18505 
18506 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18507 			if (!new_prog)
18508 				return -ENOMEM;
18509 
18510 			delta    += cnt - 1;
18511 			env->prog = prog = new_prog;
18512 			insn      = new_prog->insnsi + i + delta;
18513 			continue;
18514 		}
18515 
18516 		/* Implement bpf_get_func_ret inline. */
18517 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18518 		    insn->imm == BPF_FUNC_get_func_ret) {
18519 			if (eatype == BPF_TRACE_FEXIT ||
18520 			    eatype == BPF_MODIFY_RETURN) {
18521 				/* Load nr_args from ctx - 8 */
18522 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18523 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18524 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18525 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18526 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18527 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18528 				cnt = 6;
18529 			} else {
18530 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18531 				cnt = 1;
18532 			}
18533 
18534 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18535 			if (!new_prog)
18536 				return -ENOMEM;
18537 
18538 			delta    += cnt - 1;
18539 			env->prog = prog = new_prog;
18540 			insn      = new_prog->insnsi + i + delta;
18541 			continue;
18542 		}
18543 
18544 		/* Implement get_func_arg_cnt inline. */
18545 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18546 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
18547 			/* Load nr_args from ctx - 8 */
18548 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18549 
18550 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18551 			if (!new_prog)
18552 				return -ENOMEM;
18553 
18554 			env->prog = prog = new_prog;
18555 			insn      = new_prog->insnsi + i + delta;
18556 			continue;
18557 		}
18558 
18559 		/* Implement bpf_get_func_ip inline. */
18560 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18561 		    insn->imm == BPF_FUNC_get_func_ip) {
18562 			/* Load IP address from ctx - 16 */
18563 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18564 
18565 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18566 			if (!new_prog)
18567 				return -ENOMEM;
18568 
18569 			env->prog = prog = new_prog;
18570 			insn      = new_prog->insnsi + i + delta;
18571 			continue;
18572 		}
18573 
18574 patch_call_imm:
18575 		fn = env->ops->get_func_proto(insn->imm, env->prog);
18576 		/* all functions that have prototype and verifier allowed
18577 		 * programs to call them, must be real in-kernel functions
18578 		 */
18579 		if (!fn->func) {
18580 			verbose(env,
18581 				"kernel subsystem misconfigured func %s#%d\n",
18582 				func_id_name(insn->imm), insn->imm);
18583 			return -EFAULT;
18584 		}
18585 		insn->imm = fn->func - __bpf_call_base;
18586 	}
18587 
18588 	/* Since poke tab is now finalized, publish aux to tracker. */
18589 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18590 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18591 		if (!map_ptr->ops->map_poke_track ||
18592 		    !map_ptr->ops->map_poke_untrack ||
18593 		    !map_ptr->ops->map_poke_run) {
18594 			verbose(env, "bpf verifier is misconfigured\n");
18595 			return -EINVAL;
18596 		}
18597 
18598 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18599 		if (ret < 0) {
18600 			verbose(env, "tracking tail call prog failed\n");
18601 			return ret;
18602 		}
18603 	}
18604 
18605 	sort_kfunc_descs_by_imm_off(env->prog);
18606 
18607 	return 0;
18608 }
18609 
18610 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18611 					int position,
18612 					s32 stack_base,
18613 					u32 callback_subprogno,
18614 					u32 *cnt)
18615 {
18616 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18617 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18618 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18619 	int reg_loop_max = BPF_REG_6;
18620 	int reg_loop_cnt = BPF_REG_7;
18621 	int reg_loop_ctx = BPF_REG_8;
18622 
18623 	struct bpf_prog *new_prog;
18624 	u32 callback_start;
18625 	u32 call_insn_offset;
18626 	s32 callback_offset;
18627 
18628 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
18629 	 * be careful to modify this code in sync.
18630 	 */
18631 	struct bpf_insn insn_buf[] = {
18632 		/* Return error and jump to the end of the patch if
18633 		 * expected number of iterations is too big.
18634 		 */
18635 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18636 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18637 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18638 		/* spill R6, R7, R8 to use these as loop vars */
18639 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18640 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18641 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18642 		/* initialize loop vars */
18643 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18644 		BPF_MOV32_IMM(reg_loop_cnt, 0),
18645 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18646 		/* loop header,
18647 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
18648 		 */
18649 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18650 		/* callback call,
18651 		 * correct callback offset would be set after patching
18652 		 */
18653 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18654 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18655 		BPF_CALL_REL(0),
18656 		/* increment loop counter */
18657 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18658 		/* jump to loop header if callback returned 0 */
18659 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18660 		/* return value of bpf_loop,
18661 		 * set R0 to the number of iterations
18662 		 */
18663 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18664 		/* restore original values of R6, R7, R8 */
18665 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18666 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18667 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18668 	};
18669 
18670 	*cnt = ARRAY_SIZE(insn_buf);
18671 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18672 	if (!new_prog)
18673 		return new_prog;
18674 
18675 	/* callback start is known only after patching */
18676 	callback_start = env->subprog_info[callback_subprogno].start;
18677 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18678 	call_insn_offset = position + 12;
18679 	callback_offset = callback_start - call_insn_offset - 1;
18680 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
18681 
18682 	return new_prog;
18683 }
18684 
18685 static bool is_bpf_loop_call(struct bpf_insn *insn)
18686 {
18687 	return insn->code == (BPF_JMP | BPF_CALL) &&
18688 		insn->src_reg == 0 &&
18689 		insn->imm == BPF_FUNC_loop;
18690 }
18691 
18692 /* For all sub-programs in the program (including main) check
18693  * insn_aux_data to see if there are bpf_loop calls that require
18694  * inlining. If such calls are found the calls are replaced with a
18695  * sequence of instructions produced by `inline_bpf_loop` function and
18696  * subprog stack_depth is increased by the size of 3 registers.
18697  * This stack space is used to spill values of the R6, R7, R8.  These
18698  * registers are used to store the loop bound, counter and context
18699  * variables.
18700  */
18701 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18702 {
18703 	struct bpf_subprog_info *subprogs = env->subprog_info;
18704 	int i, cur_subprog = 0, cnt, delta = 0;
18705 	struct bpf_insn *insn = env->prog->insnsi;
18706 	int insn_cnt = env->prog->len;
18707 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
18708 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18709 	u16 stack_depth_extra = 0;
18710 
18711 	for (i = 0; i < insn_cnt; i++, insn++) {
18712 		struct bpf_loop_inline_state *inline_state =
18713 			&env->insn_aux_data[i + delta].loop_inline_state;
18714 
18715 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18716 			struct bpf_prog *new_prog;
18717 
18718 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18719 			new_prog = inline_bpf_loop(env,
18720 						   i + delta,
18721 						   -(stack_depth + stack_depth_extra),
18722 						   inline_state->callback_subprogno,
18723 						   &cnt);
18724 			if (!new_prog)
18725 				return -ENOMEM;
18726 
18727 			delta     += cnt - 1;
18728 			env->prog  = new_prog;
18729 			insn       = new_prog->insnsi + i + delta;
18730 		}
18731 
18732 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18733 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
18734 			cur_subprog++;
18735 			stack_depth = subprogs[cur_subprog].stack_depth;
18736 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18737 			stack_depth_extra = 0;
18738 		}
18739 	}
18740 
18741 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18742 
18743 	return 0;
18744 }
18745 
18746 static void free_states(struct bpf_verifier_env *env)
18747 {
18748 	struct bpf_verifier_state_list *sl, *sln;
18749 	int i;
18750 
18751 	sl = env->free_list;
18752 	while (sl) {
18753 		sln = sl->next;
18754 		free_verifier_state(&sl->state, false);
18755 		kfree(sl);
18756 		sl = sln;
18757 	}
18758 	env->free_list = NULL;
18759 
18760 	if (!env->explored_states)
18761 		return;
18762 
18763 	for (i = 0; i < state_htab_size(env); i++) {
18764 		sl = env->explored_states[i];
18765 
18766 		while (sl) {
18767 			sln = sl->next;
18768 			free_verifier_state(&sl->state, false);
18769 			kfree(sl);
18770 			sl = sln;
18771 		}
18772 		env->explored_states[i] = NULL;
18773 	}
18774 }
18775 
18776 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18777 {
18778 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18779 	struct bpf_verifier_state *state;
18780 	struct bpf_reg_state *regs;
18781 	int ret, i;
18782 
18783 	env->prev_linfo = NULL;
18784 	env->pass_cnt++;
18785 
18786 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
18787 	if (!state)
18788 		return -ENOMEM;
18789 	state->curframe = 0;
18790 	state->speculative = false;
18791 	state->branches = 1;
18792 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
18793 	if (!state->frame[0]) {
18794 		kfree(state);
18795 		return -ENOMEM;
18796 	}
18797 	env->cur_state = state;
18798 	init_func_state(env, state->frame[0],
18799 			BPF_MAIN_FUNC /* callsite */,
18800 			0 /* frameno */,
18801 			subprog);
18802 	state->first_insn_idx = env->subprog_info[subprog].start;
18803 	state->last_insn_idx = -1;
18804 
18805 	regs = state->frame[state->curframe]->regs;
18806 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
18807 		ret = btf_prepare_func_args(env, subprog, regs);
18808 		if (ret)
18809 			goto out;
18810 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
18811 			if (regs[i].type == PTR_TO_CTX)
18812 				mark_reg_known_zero(env, regs, i);
18813 			else if (regs[i].type == SCALAR_VALUE)
18814 				mark_reg_unknown(env, regs, i);
18815 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
18816 				const u32 mem_size = regs[i].mem_size;
18817 
18818 				mark_reg_known_zero(env, regs, i);
18819 				regs[i].mem_size = mem_size;
18820 				regs[i].id = ++env->id_gen;
18821 			}
18822 		}
18823 	} else {
18824 		/* 1st arg to a function */
18825 		regs[BPF_REG_1].type = PTR_TO_CTX;
18826 		mark_reg_known_zero(env, regs, BPF_REG_1);
18827 		ret = btf_check_subprog_arg_match(env, subprog, regs);
18828 		if (ret == -EFAULT)
18829 			/* unlikely verifier bug. abort.
18830 			 * ret == 0 and ret < 0 are sadly acceptable for
18831 			 * main() function due to backward compatibility.
18832 			 * Like socket filter program may be written as:
18833 			 * int bpf_prog(struct pt_regs *ctx)
18834 			 * and never dereference that ctx in the program.
18835 			 * 'struct pt_regs' is a type mismatch for socket
18836 			 * filter that should be using 'struct __sk_buff'.
18837 			 */
18838 			goto out;
18839 	}
18840 
18841 	ret = do_check(env);
18842 out:
18843 	/* check for NULL is necessary, since cur_state can be freed inside
18844 	 * do_check() under memory pressure.
18845 	 */
18846 	if (env->cur_state) {
18847 		free_verifier_state(env->cur_state, true);
18848 		env->cur_state = NULL;
18849 	}
18850 	while (!pop_stack(env, NULL, NULL, false));
18851 	if (!ret && pop_log)
18852 		bpf_vlog_reset(&env->log, 0);
18853 	free_states(env);
18854 	return ret;
18855 }
18856 
18857 /* Verify all global functions in a BPF program one by one based on their BTF.
18858  * All global functions must pass verification. Otherwise the whole program is rejected.
18859  * Consider:
18860  * int bar(int);
18861  * int foo(int f)
18862  * {
18863  *    return bar(f);
18864  * }
18865  * int bar(int b)
18866  * {
18867  *    ...
18868  * }
18869  * foo() will be verified first for R1=any_scalar_value. During verification it
18870  * will be assumed that bar() already verified successfully and call to bar()
18871  * from foo() will be checked for type match only. Later bar() will be verified
18872  * independently to check that it's safe for R1=any_scalar_value.
18873  */
18874 static int do_check_subprogs(struct bpf_verifier_env *env)
18875 {
18876 	struct bpf_prog_aux *aux = env->prog->aux;
18877 	int i, ret;
18878 
18879 	if (!aux->func_info)
18880 		return 0;
18881 
18882 	for (i = 1; i < env->subprog_cnt; i++) {
18883 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
18884 			continue;
18885 		env->insn_idx = env->subprog_info[i].start;
18886 		WARN_ON_ONCE(env->insn_idx == 0);
18887 		ret = do_check_common(env, i);
18888 		if (ret) {
18889 			return ret;
18890 		} else if (env->log.level & BPF_LOG_LEVEL) {
18891 			verbose(env,
18892 				"Func#%d is safe for any args that match its prototype\n",
18893 				i);
18894 		}
18895 	}
18896 	return 0;
18897 }
18898 
18899 static int do_check_main(struct bpf_verifier_env *env)
18900 {
18901 	int ret;
18902 
18903 	env->insn_idx = 0;
18904 	ret = do_check_common(env, 0);
18905 	if (!ret)
18906 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18907 	return ret;
18908 }
18909 
18910 
18911 static void print_verification_stats(struct bpf_verifier_env *env)
18912 {
18913 	int i;
18914 
18915 	if (env->log.level & BPF_LOG_STATS) {
18916 		verbose(env, "verification time %lld usec\n",
18917 			div_u64(env->verification_time, 1000));
18918 		verbose(env, "stack depth ");
18919 		for (i = 0; i < env->subprog_cnt; i++) {
18920 			u32 depth = env->subprog_info[i].stack_depth;
18921 
18922 			verbose(env, "%d", depth);
18923 			if (i + 1 < env->subprog_cnt)
18924 				verbose(env, "+");
18925 		}
18926 		verbose(env, "\n");
18927 	}
18928 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
18929 		"total_states %d peak_states %d mark_read %d\n",
18930 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
18931 		env->max_states_per_insn, env->total_states,
18932 		env->peak_states, env->longest_mark_read_walk);
18933 }
18934 
18935 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
18936 {
18937 	const struct btf_type *t, *func_proto;
18938 	const struct bpf_struct_ops *st_ops;
18939 	const struct btf_member *member;
18940 	struct bpf_prog *prog = env->prog;
18941 	u32 btf_id, member_idx;
18942 	const char *mname;
18943 
18944 	if (!prog->gpl_compatible) {
18945 		verbose(env, "struct ops programs must have a GPL compatible license\n");
18946 		return -EINVAL;
18947 	}
18948 
18949 	btf_id = prog->aux->attach_btf_id;
18950 	st_ops = bpf_struct_ops_find(btf_id);
18951 	if (!st_ops) {
18952 		verbose(env, "attach_btf_id %u is not a supported struct\n",
18953 			btf_id);
18954 		return -ENOTSUPP;
18955 	}
18956 
18957 	t = st_ops->type;
18958 	member_idx = prog->expected_attach_type;
18959 	if (member_idx >= btf_type_vlen(t)) {
18960 		verbose(env, "attach to invalid member idx %u of struct %s\n",
18961 			member_idx, st_ops->name);
18962 		return -EINVAL;
18963 	}
18964 
18965 	member = &btf_type_member(t)[member_idx];
18966 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
18967 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
18968 					       NULL);
18969 	if (!func_proto) {
18970 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
18971 			mname, member_idx, st_ops->name);
18972 		return -EINVAL;
18973 	}
18974 
18975 	if (st_ops->check_member) {
18976 		int err = st_ops->check_member(t, member, prog);
18977 
18978 		if (err) {
18979 			verbose(env, "attach to unsupported member %s of struct %s\n",
18980 				mname, st_ops->name);
18981 			return err;
18982 		}
18983 	}
18984 
18985 	prog->aux->attach_func_proto = func_proto;
18986 	prog->aux->attach_func_name = mname;
18987 	env->ops = st_ops->verifier_ops;
18988 
18989 	return 0;
18990 }
18991 #define SECURITY_PREFIX "security_"
18992 
18993 static int check_attach_modify_return(unsigned long addr, const char *func_name)
18994 {
18995 	if (within_error_injection_list(addr) ||
18996 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
18997 		return 0;
18998 
18999 	return -EINVAL;
19000 }
19001 
19002 /* list of non-sleepable functions that are otherwise on
19003  * ALLOW_ERROR_INJECTION list
19004  */
19005 BTF_SET_START(btf_non_sleepable_error_inject)
19006 /* Three functions below can be called from sleepable and non-sleepable context.
19007  * Assume non-sleepable from bpf safety point of view.
19008  */
19009 BTF_ID(func, __filemap_add_folio)
19010 BTF_ID(func, should_fail_alloc_page)
19011 BTF_ID(func, should_failslab)
19012 BTF_SET_END(btf_non_sleepable_error_inject)
19013 
19014 static int check_non_sleepable_error_inject(u32 btf_id)
19015 {
19016 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19017 }
19018 
19019 int bpf_check_attach_target(struct bpf_verifier_log *log,
19020 			    const struct bpf_prog *prog,
19021 			    const struct bpf_prog *tgt_prog,
19022 			    u32 btf_id,
19023 			    struct bpf_attach_target_info *tgt_info)
19024 {
19025 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19026 	const char prefix[] = "btf_trace_";
19027 	int ret = 0, subprog = -1, i;
19028 	const struct btf_type *t;
19029 	bool conservative = true;
19030 	const char *tname;
19031 	struct btf *btf;
19032 	long addr = 0;
19033 	struct module *mod = NULL;
19034 
19035 	if (!btf_id) {
19036 		bpf_log(log, "Tracing programs must provide btf_id\n");
19037 		return -EINVAL;
19038 	}
19039 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19040 	if (!btf) {
19041 		bpf_log(log,
19042 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19043 		return -EINVAL;
19044 	}
19045 	t = btf_type_by_id(btf, btf_id);
19046 	if (!t) {
19047 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19048 		return -EINVAL;
19049 	}
19050 	tname = btf_name_by_offset(btf, t->name_off);
19051 	if (!tname) {
19052 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19053 		return -EINVAL;
19054 	}
19055 	if (tgt_prog) {
19056 		struct bpf_prog_aux *aux = tgt_prog->aux;
19057 
19058 		if (bpf_prog_is_dev_bound(prog->aux) &&
19059 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19060 			bpf_log(log, "Target program bound device mismatch");
19061 			return -EINVAL;
19062 		}
19063 
19064 		for (i = 0; i < aux->func_info_cnt; i++)
19065 			if (aux->func_info[i].type_id == btf_id) {
19066 				subprog = i;
19067 				break;
19068 			}
19069 		if (subprog == -1) {
19070 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
19071 			return -EINVAL;
19072 		}
19073 		conservative = aux->func_info_aux[subprog].unreliable;
19074 		if (prog_extension) {
19075 			if (conservative) {
19076 				bpf_log(log,
19077 					"Cannot replace static functions\n");
19078 				return -EINVAL;
19079 			}
19080 			if (!prog->jit_requested) {
19081 				bpf_log(log,
19082 					"Extension programs should be JITed\n");
19083 				return -EINVAL;
19084 			}
19085 		}
19086 		if (!tgt_prog->jited) {
19087 			bpf_log(log, "Can attach to only JITed progs\n");
19088 			return -EINVAL;
19089 		}
19090 		if (tgt_prog->type == prog->type) {
19091 			/* Cannot fentry/fexit another fentry/fexit program.
19092 			 * Cannot attach program extension to another extension.
19093 			 * It's ok to attach fentry/fexit to extension program.
19094 			 */
19095 			bpf_log(log, "Cannot recursively attach\n");
19096 			return -EINVAL;
19097 		}
19098 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19099 		    prog_extension &&
19100 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19101 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19102 			/* Program extensions can extend all program types
19103 			 * except fentry/fexit. The reason is the following.
19104 			 * The fentry/fexit programs are used for performance
19105 			 * analysis, stats and can be attached to any program
19106 			 * type except themselves. When extension program is
19107 			 * replacing XDP function it is necessary to allow
19108 			 * performance analysis of all functions. Both original
19109 			 * XDP program and its program extension. Hence
19110 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19111 			 * allowed. If extending of fentry/fexit was allowed it
19112 			 * would be possible to create long call chain
19113 			 * fentry->extension->fentry->extension beyond
19114 			 * reasonable stack size. Hence extending fentry is not
19115 			 * allowed.
19116 			 */
19117 			bpf_log(log, "Cannot extend fentry/fexit\n");
19118 			return -EINVAL;
19119 		}
19120 	} else {
19121 		if (prog_extension) {
19122 			bpf_log(log, "Cannot replace kernel functions\n");
19123 			return -EINVAL;
19124 		}
19125 	}
19126 
19127 	switch (prog->expected_attach_type) {
19128 	case BPF_TRACE_RAW_TP:
19129 		if (tgt_prog) {
19130 			bpf_log(log,
19131 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19132 			return -EINVAL;
19133 		}
19134 		if (!btf_type_is_typedef(t)) {
19135 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
19136 				btf_id);
19137 			return -EINVAL;
19138 		}
19139 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19140 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19141 				btf_id, tname);
19142 			return -EINVAL;
19143 		}
19144 		tname += sizeof(prefix) - 1;
19145 		t = btf_type_by_id(btf, t->type);
19146 		if (!btf_type_is_ptr(t))
19147 			/* should never happen in valid vmlinux build */
19148 			return -EINVAL;
19149 		t = btf_type_by_id(btf, t->type);
19150 		if (!btf_type_is_func_proto(t))
19151 			/* should never happen in valid vmlinux build */
19152 			return -EINVAL;
19153 
19154 		break;
19155 	case BPF_TRACE_ITER:
19156 		if (!btf_type_is_func(t)) {
19157 			bpf_log(log, "attach_btf_id %u is not a function\n",
19158 				btf_id);
19159 			return -EINVAL;
19160 		}
19161 		t = btf_type_by_id(btf, t->type);
19162 		if (!btf_type_is_func_proto(t))
19163 			return -EINVAL;
19164 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19165 		if (ret)
19166 			return ret;
19167 		break;
19168 	default:
19169 		if (!prog_extension)
19170 			return -EINVAL;
19171 		fallthrough;
19172 	case BPF_MODIFY_RETURN:
19173 	case BPF_LSM_MAC:
19174 	case BPF_LSM_CGROUP:
19175 	case BPF_TRACE_FENTRY:
19176 	case BPF_TRACE_FEXIT:
19177 		if (!btf_type_is_func(t)) {
19178 			bpf_log(log, "attach_btf_id %u is not a function\n",
19179 				btf_id);
19180 			return -EINVAL;
19181 		}
19182 		if (prog_extension &&
19183 		    btf_check_type_match(log, prog, btf, t))
19184 			return -EINVAL;
19185 		t = btf_type_by_id(btf, t->type);
19186 		if (!btf_type_is_func_proto(t))
19187 			return -EINVAL;
19188 
19189 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19190 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19191 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19192 			return -EINVAL;
19193 
19194 		if (tgt_prog && conservative)
19195 			t = NULL;
19196 
19197 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19198 		if (ret < 0)
19199 			return ret;
19200 
19201 		if (tgt_prog) {
19202 			if (subprog == 0)
19203 				addr = (long) tgt_prog->bpf_func;
19204 			else
19205 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19206 		} else {
19207 			if (btf_is_module(btf)) {
19208 				mod = btf_try_get_module(btf);
19209 				if (mod)
19210 					addr = find_kallsyms_symbol_value(mod, tname);
19211 				else
19212 					addr = 0;
19213 			} else {
19214 				addr = kallsyms_lookup_name(tname);
19215 			}
19216 			if (!addr) {
19217 				module_put(mod);
19218 				bpf_log(log,
19219 					"The address of function %s cannot be found\n",
19220 					tname);
19221 				return -ENOENT;
19222 			}
19223 		}
19224 
19225 		if (prog->aux->sleepable) {
19226 			ret = -EINVAL;
19227 			switch (prog->type) {
19228 			case BPF_PROG_TYPE_TRACING:
19229 
19230 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
19231 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19232 				 */
19233 				if (!check_non_sleepable_error_inject(btf_id) &&
19234 				    within_error_injection_list(addr))
19235 					ret = 0;
19236 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
19237 				 * in the fmodret id set with the KF_SLEEPABLE flag.
19238 				 */
19239 				else {
19240 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19241 										prog);
19242 
19243 					if (flags && (*flags & KF_SLEEPABLE))
19244 						ret = 0;
19245 				}
19246 				break;
19247 			case BPF_PROG_TYPE_LSM:
19248 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
19249 				 * Only some of them are sleepable.
19250 				 */
19251 				if (bpf_lsm_is_sleepable_hook(btf_id))
19252 					ret = 0;
19253 				break;
19254 			default:
19255 				break;
19256 			}
19257 			if (ret) {
19258 				module_put(mod);
19259 				bpf_log(log, "%s is not sleepable\n", tname);
19260 				return ret;
19261 			}
19262 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19263 			if (tgt_prog) {
19264 				module_put(mod);
19265 				bpf_log(log, "can't modify return codes of BPF programs\n");
19266 				return -EINVAL;
19267 			}
19268 			ret = -EINVAL;
19269 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19270 			    !check_attach_modify_return(addr, tname))
19271 				ret = 0;
19272 			if (ret) {
19273 				module_put(mod);
19274 				bpf_log(log, "%s() is not modifiable\n", tname);
19275 				return ret;
19276 			}
19277 		}
19278 
19279 		break;
19280 	}
19281 	tgt_info->tgt_addr = addr;
19282 	tgt_info->tgt_name = tname;
19283 	tgt_info->tgt_type = t;
19284 	tgt_info->tgt_mod = mod;
19285 	return 0;
19286 }
19287 
19288 BTF_SET_START(btf_id_deny)
19289 BTF_ID_UNUSED
19290 #ifdef CONFIG_SMP
19291 BTF_ID(func, migrate_disable)
19292 BTF_ID(func, migrate_enable)
19293 #endif
19294 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19295 BTF_ID(func, rcu_read_unlock_strict)
19296 #endif
19297 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19298 BTF_ID(func, preempt_count_add)
19299 BTF_ID(func, preempt_count_sub)
19300 #endif
19301 #ifdef CONFIG_PREEMPT_RCU
19302 BTF_ID(func, __rcu_read_lock)
19303 BTF_ID(func, __rcu_read_unlock)
19304 #endif
19305 BTF_SET_END(btf_id_deny)
19306 
19307 static bool can_be_sleepable(struct bpf_prog *prog)
19308 {
19309 	if (prog->type == BPF_PROG_TYPE_TRACING) {
19310 		switch (prog->expected_attach_type) {
19311 		case BPF_TRACE_FENTRY:
19312 		case BPF_TRACE_FEXIT:
19313 		case BPF_MODIFY_RETURN:
19314 		case BPF_TRACE_ITER:
19315 			return true;
19316 		default:
19317 			return false;
19318 		}
19319 	}
19320 	return prog->type == BPF_PROG_TYPE_LSM ||
19321 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19322 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19323 }
19324 
19325 static int check_attach_btf_id(struct bpf_verifier_env *env)
19326 {
19327 	struct bpf_prog *prog = env->prog;
19328 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19329 	struct bpf_attach_target_info tgt_info = {};
19330 	u32 btf_id = prog->aux->attach_btf_id;
19331 	struct bpf_trampoline *tr;
19332 	int ret;
19333 	u64 key;
19334 
19335 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19336 		if (prog->aux->sleepable)
19337 			/* attach_btf_id checked to be zero already */
19338 			return 0;
19339 		verbose(env, "Syscall programs can only be sleepable\n");
19340 		return -EINVAL;
19341 	}
19342 
19343 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19344 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19345 		return -EINVAL;
19346 	}
19347 
19348 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19349 		return check_struct_ops_btf_id(env);
19350 
19351 	if (prog->type != BPF_PROG_TYPE_TRACING &&
19352 	    prog->type != BPF_PROG_TYPE_LSM &&
19353 	    prog->type != BPF_PROG_TYPE_EXT)
19354 		return 0;
19355 
19356 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19357 	if (ret)
19358 		return ret;
19359 
19360 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19361 		/* to make freplace equivalent to their targets, they need to
19362 		 * inherit env->ops and expected_attach_type for the rest of the
19363 		 * verification
19364 		 */
19365 		env->ops = bpf_verifier_ops[tgt_prog->type];
19366 		prog->expected_attach_type = tgt_prog->expected_attach_type;
19367 	}
19368 
19369 	/* store info about the attachment target that will be used later */
19370 	prog->aux->attach_func_proto = tgt_info.tgt_type;
19371 	prog->aux->attach_func_name = tgt_info.tgt_name;
19372 	prog->aux->mod = tgt_info.tgt_mod;
19373 
19374 	if (tgt_prog) {
19375 		prog->aux->saved_dst_prog_type = tgt_prog->type;
19376 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19377 	}
19378 
19379 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19380 		prog->aux->attach_btf_trace = true;
19381 		return 0;
19382 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19383 		if (!bpf_iter_prog_supported(prog))
19384 			return -EINVAL;
19385 		return 0;
19386 	}
19387 
19388 	if (prog->type == BPF_PROG_TYPE_LSM) {
19389 		ret = bpf_lsm_verify_prog(&env->log, prog);
19390 		if (ret < 0)
19391 			return ret;
19392 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
19393 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
19394 		return -EINVAL;
19395 	}
19396 
19397 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19398 	tr = bpf_trampoline_get(key, &tgt_info);
19399 	if (!tr)
19400 		return -ENOMEM;
19401 
19402 	prog->aux->dst_trampoline = tr;
19403 	return 0;
19404 }
19405 
19406 struct btf *bpf_get_btf_vmlinux(void)
19407 {
19408 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19409 		mutex_lock(&bpf_verifier_lock);
19410 		if (!btf_vmlinux)
19411 			btf_vmlinux = btf_parse_vmlinux();
19412 		mutex_unlock(&bpf_verifier_lock);
19413 	}
19414 	return btf_vmlinux;
19415 }
19416 
19417 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19418 {
19419 	u64 start_time = ktime_get_ns();
19420 	struct bpf_verifier_env *env;
19421 	int i, len, ret = -EINVAL, err;
19422 	u32 log_true_size;
19423 	bool is_priv;
19424 
19425 	/* no program is valid */
19426 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19427 		return -EINVAL;
19428 
19429 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
19430 	 * allocate/free it every time bpf_check() is called
19431 	 */
19432 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19433 	if (!env)
19434 		return -ENOMEM;
19435 
19436 	env->bt.env = env;
19437 
19438 	len = (*prog)->len;
19439 	env->insn_aux_data =
19440 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19441 	ret = -ENOMEM;
19442 	if (!env->insn_aux_data)
19443 		goto err_free_env;
19444 	for (i = 0; i < len; i++)
19445 		env->insn_aux_data[i].orig_idx = i;
19446 	env->prog = *prog;
19447 	env->ops = bpf_verifier_ops[env->prog->type];
19448 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19449 	is_priv = bpf_capable();
19450 
19451 	bpf_get_btf_vmlinux();
19452 
19453 	/* grab the mutex to protect few globals used by verifier */
19454 	if (!is_priv)
19455 		mutex_lock(&bpf_verifier_lock);
19456 
19457 	/* user could have requested verbose verifier output
19458 	 * and supplied buffer to store the verification trace
19459 	 */
19460 	ret = bpf_vlog_init(&env->log, attr->log_level,
19461 			    (char __user *) (unsigned long) attr->log_buf,
19462 			    attr->log_size);
19463 	if (ret)
19464 		goto err_unlock;
19465 
19466 	mark_verifier_state_clean(env);
19467 
19468 	if (IS_ERR(btf_vmlinux)) {
19469 		/* Either gcc or pahole or kernel are broken. */
19470 		verbose(env, "in-kernel BTF is malformed\n");
19471 		ret = PTR_ERR(btf_vmlinux);
19472 		goto skip_full_check;
19473 	}
19474 
19475 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19476 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19477 		env->strict_alignment = true;
19478 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19479 		env->strict_alignment = false;
19480 
19481 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19482 	env->allow_uninit_stack = bpf_allow_uninit_stack();
19483 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
19484 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
19485 	env->bpf_capable = bpf_capable();
19486 
19487 	if (is_priv)
19488 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19489 
19490 	env->explored_states = kvcalloc(state_htab_size(env),
19491 				       sizeof(struct bpf_verifier_state_list *),
19492 				       GFP_USER);
19493 	ret = -ENOMEM;
19494 	if (!env->explored_states)
19495 		goto skip_full_check;
19496 
19497 	ret = add_subprog_and_kfunc(env);
19498 	if (ret < 0)
19499 		goto skip_full_check;
19500 
19501 	ret = check_subprogs(env);
19502 	if (ret < 0)
19503 		goto skip_full_check;
19504 
19505 	ret = check_btf_info(env, attr, uattr);
19506 	if (ret < 0)
19507 		goto skip_full_check;
19508 
19509 	ret = check_attach_btf_id(env);
19510 	if (ret)
19511 		goto skip_full_check;
19512 
19513 	ret = resolve_pseudo_ldimm64(env);
19514 	if (ret < 0)
19515 		goto skip_full_check;
19516 
19517 	if (bpf_prog_is_offloaded(env->prog->aux)) {
19518 		ret = bpf_prog_offload_verifier_prep(env->prog);
19519 		if (ret)
19520 			goto skip_full_check;
19521 	}
19522 
19523 	ret = check_cfg(env);
19524 	if (ret < 0)
19525 		goto skip_full_check;
19526 
19527 	ret = do_check_subprogs(env);
19528 	ret = ret ?: do_check_main(env);
19529 
19530 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19531 		ret = bpf_prog_offload_finalize(env);
19532 
19533 skip_full_check:
19534 	kvfree(env->explored_states);
19535 
19536 	if (ret == 0)
19537 		ret = check_max_stack_depth(env);
19538 
19539 	/* instruction rewrites happen after this point */
19540 	if (ret == 0)
19541 		ret = optimize_bpf_loop(env);
19542 
19543 	if (is_priv) {
19544 		if (ret == 0)
19545 			opt_hard_wire_dead_code_branches(env);
19546 		if (ret == 0)
19547 			ret = opt_remove_dead_code(env);
19548 		if (ret == 0)
19549 			ret = opt_remove_nops(env);
19550 	} else {
19551 		if (ret == 0)
19552 			sanitize_dead_code(env);
19553 	}
19554 
19555 	if (ret == 0)
19556 		/* program is valid, convert *(u32*)(ctx + off) accesses */
19557 		ret = convert_ctx_accesses(env);
19558 
19559 	if (ret == 0)
19560 		ret = do_misc_fixups(env);
19561 
19562 	/* do 32-bit optimization after insn patching has done so those patched
19563 	 * insns could be handled correctly.
19564 	 */
19565 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19566 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19567 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19568 								     : false;
19569 	}
19570 
19571 	if (ret == 0)
19572 		ret = fixup_call_args(env);
19573 
19574 	env->verification_time = ktime_get_ns() - start_time;
19575 	print_verification_stats(env);
19576 	env->prog->aux->verified_insns = env->insn_processed;
19577 
19578 	/* preserve original error even if log finalization is successful */
19579 	err = bpf_vlog_finalize(&env->log, &log_true_size);
19580 	if (err)
19581 		ret = err;
19582 
19583 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19584 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19585 				  &log_true_size, sizeof(log_true_size))) {
19586 		ret = -EFAULT;
19587 		goto err_release_maps;
19588 	}
19589 
19590 	if (ret)
19591 		goto err_release_maps;
19592 
19593 	if (env->used_map_cnt) {
19594 		/* if program passed verifier, update used_maps in bpf_prog_info */
19595 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19596 							  sizeof(env->used_maps[0]),
19597 							  GFP_KERNEL);
19598 
19599 		if (!env->prog->aux->used_maps) {
19600 			ret = -ENOMEM;
19601 			goto err_release_maps;
19602 		}
19603 
19604 		memcpy(env->prog->aux->used_maps, env->used_maps,
19605 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
19606 		env->prog->aux->used_map_cnt = env->used_map_cnt;
19607 	}
19608 	if (env->used_btf_cnt) {
19609 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
19610 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19611 							  sizeof(env->used_btfs[0]),
19612 							  GFP_KERNEL);
19613 		if (!env->prog->aux->used_btfs) {
19614 			ret = -ENOMEM;
19615 			goto err_release_maps;
19616 		}
19617 
19618 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
19619 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19620 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19621 	}
19622 	if (env->used_map_cnt || env->used_btf_cnt) {
19623 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
19624 		 * bpf_ld_imm64 instructions
19625 		 */
19626 		convert_pseudo_ld_imm64(env);
19627 	}
19628 
19629 	adjust_btf_func(env);
19630 
19631 err_release_maps:
19632 	if (!env->prog->aux->used_maps)
19633 		/* if we didn't copy map pointers into bpf_prog_info, release
19634 		 * them now. Otherwise free_used_maps() will release them.
19635 		 */
19636 		release_maps(env);
19637 	if (!env->prog->aux->used_btfs)
19638 		release_btfs(env);
19639 
19640 	/* extension progs temporarily inherit the attach_type of their targets
19641 	   for verification purposes, so set it back to zero before returning
19642 	 */
19643 	if (env->prog->type == BPF_PROG_TYPE_EXT)
19644 		env->prog->expected_attach_type = 0;
19645 
19646 	*prog = env->prog;
19647 err_unlock:
19648 	if (!is_priv)
19649 		mutex_unlock(&bpf_verifier_lock);
19650 	vfree(env->insn_aux_data);
19651 err_free_env:
19652 	kfree(env);
19653 	return ret;
19654 }
19655