xref: /openbmc/linux/kernel/bpf/verifier.c (revision d1100acab464e054cbd056aac0e24b790926f18d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <net/xdp.h>
30 
31 #include "disasm.h"
32 
33 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
34 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
35 	[_id] = & _name ## _verifier_ops,
36 #define BPF_MAP_TYPE(_id, _ops)
37 #define BPF_LINK_TYPE(_id, _name)
38 #include <linux/bpf_types.h>
39 #undef BPF_PROG_TYPE
40 #undef BPF_MAP_TYPE
41 #undef BPF_LINK_TYPE
42 };
43 
44 /* bpf_check() is a static code analyzer that walks eBPF program
45  * instruction by instruction and updates register/stack state.
46  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
47  *
48  * The first pass is depth-first-search to check that the program is a DAG.
49  * It rejects the following programs:
50  * - larger than BPF_MAXINSNS insns
51  * - if loop is present (detected via back-edge)
52  * - unreachable insns exist (shouldn't be a forest. program = one function)
53  * - out of bounds or malformed jumps
54  * The second pass is all possible path descent from the 1st insn.
55  * Since it's analyzing all paths through the program, the length of the
56  * analysis is limited to 64k insn, which may be hit even if total number of
57  * insn is less then 4K, but there are too many branches that change stack/regs.
58  * Number of 'branches to be analyzed' is limited to 1k
59  *
60  * On entry to each instruction, each register has a type, and the instruction
61  * changes the types of the registers depending on instruction semantics.
62  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
63  * copied to R1.
64  *
65  * All registers are 64-bit.
66  * R0 - return register
67  * R1-R5 argument passing registers
68  * R6-R9 callee saved registers
69  * R10 - frame pointer read-only
70  *
71  * At the start of BPF program the register R1 contains a pointer to bpf_context
72  * and has type PTR_TO_CTX.
73  *
74  * Verifier tracks arithmetic operations on pointers in case:
75  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
76  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
77  * 1st insn copies R10 (which has FRAME_PTR) type into R1
78  * and 2nd arithmetic instruction is pattern matched to recognize
79  * that it wants to construct a pointer to some element within stack.
80  * So after 2nd insn, the register R1 has type PTR_TO_STACK
81  * (and -20 constant is saved for further stack bounds checking).
82  * Meaning that this reg is a pointer to stack plus known immediate constant.
83  *
84  * Most of the time the registers have SCALAR_VALUE type, which
85  * means the register has some value, but it's not a valid pointer.
86  * (like pointer plus pointer becomes SCALAR_VALUE type)
87  *
88  * When verifier sees load or store instructions the type of base register
89  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
90  * four pointer types recognized by check_mem_access() function.
91  *
92  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
93  * and the range of [ptr, ptr + map's value_size) is accessible.
94  *
95  * registers used to pass values to function calls are checked against
96  * function argument constraints.
97  *
98  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
99  * It means that the register type passed to this function must be
100  * PTR_TO_STACK and it will be used inside the function as
101  * 'pointer to map element key'
102  *
103  * For example the argument constraints for bpf_map_lookup_elem():
104  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
105  *   .arg1_type = ARG_CONST_MAP_PTR,
106  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
107  *
108  * ret_type says that this function returns 'pointer to map elem value or null'
109  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
110  * 2nd argument should be a pointer to stack, which will be used inside
111  * the helper function as a pointer to map element key.
112  *
113  * On the kernel side the helper function looks like:
114  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
115  * {
116  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
117  *    void *key = (void *) (unsigned long) r2;
118  *    void *value;
119  *
120  *    here kernel can access 'key' and 'map' pointers safely, knowing that
121  *    [key, key + map->key_size) bytes are valid and were initialized on
122  *    the stack of eBPF program.
123  * }
124  *
125  * Corresponding eBPF program may look like:
126  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
127  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
128  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
129  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
130  * here verifier looks at prototype of map_lookup_elem() and sees:
131  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
132  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
133  *
134  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
135  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
136  * and were initialized prior to this call.
137  * If it's ok, then verifier allows this BPF_CALL insn and looks at
138  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
139  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
140  * returns either pointer to map value or NULL.
141  *
142  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
143  * insn, the register holding that pointer in the true branch changes state to
144  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
145  * branch. See check_cond_jmp_op().
146  *
147  * After the call R0 is set to return type of the function and registers R1-R5
148  * are set to NOT_INIT to indicate that they are no longer readable.
149  *
150  * The following reference types represent a potential reference to a kernel
151  * resource which, after first being allocated, must be checked and freed by
152  * the BPF program:
153  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
154  *
155  * When the verifier sees a helper call return a reference type, it allocates a
156  * pointer id for the reference and stores it in the current function state.
157  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
158  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
159  * passes through a NULL-check conditional. For the branch wherein the state is
160  * changed to CONST_IMM, the verifier releases the reference.
161  *
162  * For each helper function that allocates a reference, such as
163  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
164  * bpf_sk_release(). When a reference type passes into the release function,
165  * the verifier also releases the reference. If any unchecked or unreleased
166  * reference remains at the end of the program, the verifier rejects it.
167  */
168 
169 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
170 struct bpf_verifier_stack_elem {
171 	/* verifer state is 'st'
172 	 * before processing instruction 'insn_idx'
173 	 * and after processing instruction 'prev_insn_idx'
174 	 */
175 	struct bpf_verifier_state st;
176 	int insn_idx;
177 	int prev_insn_idx;
178 	struct bpf_verifier_stack_elem *next;
179 	/* length of verifier log at the time this state was pushed on stack */
180 	u32 log_pos;
181 };
182 
183 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
184 #define BPF_COMPLEXITY_LIMIT_STATES	64
185 
186 #define BPF_MAP_KEY_POISON	(1ULL << 63)
187 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
188 
189 #define BPF_MAP_PTR_UNPRIV	1UL
190 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
191 					  POISON_POINTER_DELTA))
192 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
193 
194 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
195 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
196 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
197 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
198 static int ref_set_non_owning(struct bpf_verifier_env *env,
199 			      struct bpf_reg_state *reg);
200 static void specialize_kfunc(struct bpf_verifier_env *env,
201 			     u32 func_id, u16 offset, unsigned long *addr);
202 static bool is_trusted_reg(const struct bpf_reg_state *reg);
203 
204 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
205 {
206 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
207 }
208 
209 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
210 {
211 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
212 }
213 
214 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
215 			      const struct bpf_map *map, bool unpriv)
216 {
217 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
218 	unpriv |= bpf_map_ptr_unpriv(aux);
219 	aux->map_ptr_state = (unsigned long)map |
220 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
221 }
222 
223 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
224 {
225 	return aux->map_key_state & BPF_MAP_KEY_POISON;
226 }
227 
228 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
229 {
230 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
231 }
232 
233 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
234 {
235 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
236 }
237 
238 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
239 {
240 	bool poisoned = bpf_map_key_poisoned(aux);
241 
242 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
243 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
244 }
245 
246 static bool bpf_helper_call(const struct bpf_insn *insn)
247 {
248 	return insn->code == (BPF_JMP | BPF_CALL) &&
249 	       insn->src_reg == 0;
250 }
251 
252 static bool bpf_pseudo_call(const struct bpf_insn *insn)
253 {
254 	return insn->code == (BPF_JMP | BPF_CALL) &&
255 	       insn->src_reg == BPF_PSEUDO_CALL;
256 }
257 
258 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
259 {
260 	return insn->code == (BPF_JMP | BPF_CALL) &&
261 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
262 }
263 
264 struct bpf_call_arg_meta {
265 	struct bpf_map *map_ptr;
266 	bool raw_mode;
267 	bool pkt_access;
268 	u8 release_regno;
269 	int regno;
270 	int access_size;
271 	int mem_size;
272 	u64 msize_max_value;
273 	int ref_obj_id;
274 	int dynptr_id;
275 	int map_uid;
276 	int func_id;
277 	struct btf *btf;
278 	u32 btf_id;
279 	struct btf *ret_btf;
280 	u32 ret_btf_id;
281 	u32 subprogno;
282 	struct btf_field *kptr_field;
283 };
284 
285 struct bpf_kfunc_call_arg_meta {
286 	/* In parameters */
287 	struct btf *btf;
288 	u32 func_id;
289 	u32 kfunc_flags;
290 	const struct btf_type *func_proto;
291 	const char *func_name;
292 	/* Out parameters */
293 	u32 ref_obj_id;
294 	u8 release_regno;
295 	bool r0_rdonly;
296 	u32 ret_btf_id;
297 	u64 r0_size;
298 	u32 subprogno;
299 	struct {
300 		u64 value;
301 		bool found;
302 	} arg_constant;
303 
304 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
305 	 * generally to pass info about user-defined local kptr types to later
306 	 * verification logic
307 	 *   bpf_obj_drop
308 	 *     Record the local kptr type to be drop'd
309 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
310 	 *     Record the local kptr type to be refcount_incr'd and use
311 	 *     arg_owning_ref to determine whether refcount_acquire should be
312 	 *     fallible
313 	 */
314 	struct btf *arg_btf;
315 	u32 arg_btf_id;
316 	bool arg_owning_ref;
317 
318 	struct {
319 		struct btf_field *field;
320 	} arg_list_head;
321 	struct {
322 		struct btf_field *field;
323 	} arg_rbtree_root;
324 	struct {
325 		enum bpf_dynptr_type type;
326 		u32 id;
327 		u32 ref_obj_id;
328 	} initialized_dynptr;
329 	struct {
330 		u8 spi;
331 		u8 frameno;
332 	} iter;
333 	u64 mem_size;
334 };
335 
336 struct btf *btf_vmlinux;
337 
338 static DEFINE_MUTEX(bpf_verifier_lock);
339 
340 static const struct bpf_line_info *
341 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
342 {
343 	const struct bpf_line_info *linfo;
344 	const struct bpf_prog *prog;
345 	u32 i, nr_linfo;
346 
347 	prog = env->prog;
348 	nr_linfo = prog->aux->nr_linfo;
349 
350 	if (!nr_linfo || insn_off >= prog->len)
351 		return NULL;
352 
353 	linfo = prog->aux->linfo;
354 	for (i = 1; i < nr_linfo; i++)
355 		if (insn_off < linfo[i].insn_off)
356 			break;
357 
358 	return &linfo[i - 1];
359 }
360 
361 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
362 {
363 	struct bpf_verifier_env *env = private_data;
364 	va_list args;
365 
366 	if (!bpf_verifier_log_needed(&env->log))
367 		return;
368 
369 	va_start(args, fmt);
370 	bpf_verifier_vlog(&env->log, fmt, args);
371 	va_end(args);
372 }
373 
374 static const char *ltrim(const char *s)
375 {
376 	while (isspace(*s))
377 		s++;
378 
379 	return s;
380 }
381 
382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
383 					 u32 insn_off,
384 					 const char *prefix_fmt, ...)
385 {
386 	const struct bpf_line_info *linfo;
387 
388 	if (!bpf_verifier_log_needed(&env->log))
389 		return;
390 
391 	linfo = find_linfo(env, insn_off);
392 	if (!linfo || linfo == env->prev_linfo)
393 		return;
394 
395 	if (prefix_fmt) {
396 		va_list args;
397 
398 		va_start(args, prefix_fmt);
399 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
400 		va_end(args);
401 	}
402 
403 	verbose(env, "%s\n",
404 		ltrim(btf_name_by_offset(env->prog->aux->btf,
405 					 linfo->line_off)));
406 
407 	env->prev_linfo = linfo;
408 }
409 
410 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
411 				   struct bpf_reg_state *reg,
412 				   struct tnum *range, const char *ctx,
413 				   const char *reg_name)
414 {
415 	char tn_buf[48];
416 
417 	verbose(env, "At %s the register %s ", ctx, reg_name);
418 	if (!tnum_is_unknown(reg->var_off)) {
419 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
420 		verbose(env, "has value %s", tn_buf);
421 	} else {
422 		verbose(env, "has unknown scalar value");
423 	}
424 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
425 	verbose(env, " should have been in %s\n", tn_buf);
426 }
427 
428 static bool type_is_pkt_pointer(enum bpf_reg_type type)
429 {
430 	type = base_type(type);
431 	return type == PTR_TO_PACKET ||
432 	       type == PTR_TO_PACKET_META;
433 }
434 
435 static bool type_is_sk_pointer(enum bpf_reg_type type)
436 {
437 	return type == PTR_TO_SOCKET ||
438 		type == PTR_TO_SOCK_COMMON ||
439 		type == PTR_TO_TCP_SOCK ||
440 		type == PTR_TO_XDP_SOCK;
441 }
442 
443 static bool type_may_be_null(u32 type)
444 {
445 	return type & PTR_MAYBE_NULL;
446 }
447 
448 static bool reg_not_null(const struct bpf_reg_state *reg)
449 {
450 	enum bpf_reg_type type;
451 
452 	type = reg->type;
453 	if (type_may_be_null(type))
454 		return false;
455 
456 	type = base_type(type);
457 	return type == PTR_TO_SOCKET ||
458 		type == PTR_TO_TCP_SOCK ||
459 		type == PTR_TO_MAP_VALUE ||
460 		type == PTR_TO_MAP_KEY ||
461 		type == PTR_TO_SOCK_COMMON ||
462 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
463 		type == PTR_TO_MEM;
464 }
465 
466 static bool type_is_ptr_alloc_obj(u32 type)
467 {
468 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
469 }
470 
471 static bool type_is_non_owning_ref(u32 type)
472 {
473 	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
474 }
475 
476 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
477 {
478 	struct btf_record *rec = NULL;
479 	struct btf_struct_meta *meta;
480 
481 	if (reg->type == PTR_TO_MAP_VALUE) {
482 		rec = reg->map_ptr->record;
483 	} else if (type_is_ptr_alloc_obj(reg->type)) {
484 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
485 		if (meta)
486 			rec = meta->record;
487 	}
488 	return rec;
489 }
490 
491 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
492 {
493 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
494 
495 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
496 }
497 
498 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
499 {
500 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
501 }
502 
503 static bool type_is_rdonly_mem(u32 type)
504 {
505 	return type & MEM_RDONLY;
506 }
507 
508 static bool is_acquire_function(enum bpf_func_id func_id,
509 				const struct bpf_map *map)
510 {
511 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
512 
513 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
514 	    func_id == BPF_FUNC_sk_lookup_udp ||
515 	    func_id == BPF_FUNC_skc_lookup_tcp ||
516 	    func_id == BPF_FUNC_ringbuf_reserve ||
517 	    func_id == BPF_FUNC_kptr_xchg)
518 		return true;
519 
520 	if (func_id == BPF_FUNC_map_lookup_elem &&
521 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
522 	     map_type == BPF_MAP_TYPE_SOCKHASH))
523 		return true;
524 
525 	return false;
526 }
527 
528 static bool is_ptr_cast_function(enum bpf_func_id func_id)
529 {
530 	return func_id == BPF_FUNC_tcp_sock ||
531 		func_id == BPF_FUNC_sk_fullsock ||
532 		func_id == BPF_FUNC_skc_to_tcp_sock ||
533 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
534 		func_id == BPF_FUNC_skc_to_udp6_sock ||
535 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
536 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
537 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
538 }
539 
540 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
541 {
542 	return func_id == BPF_FUNC_dynptr_data;
543 }
544 
545 static bool is_sync_callback_calling_kfunc(u32 btf_id);
546 
547 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
548 {
549 	return func_id == BPF_FUNC_for_each_map_elem ||
550 	       func_id == BPF_FUNC_find_vma ||
551 	       func_id == BPF_FUNC_loop ||
552 	       func_id == BPF_FUNC_user_ringbuf_drain;
553 }
554 
555 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
556 {
557 	return func_id == BPF_FUNC_timer_set_callback;
558 }
559 
560 static bool is_callback_calling_function(enum bpf_func_id func_id)
561 {
562 	return is_sync_callback_calling_function(func_id) ||
563 	       is_async_callback_calling_function(func_id);
564 }
565 
566 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
567 {
568 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
569 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
570 }
571 
572 static bool is_storage_get_function(enum bpf_func_id func_id)
573 {
574 	return func_id == BPF_FUNC_sk_storage_get ||
575 	       func_id == BPF_FUNC_inode_storage_get ||
576 	       func_id == BPF_FUNC_task_storage_get ||
577 	       func_id == BPF_FUNC_cgrp_storage_get;
578 }
579 
580 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
581 					const struct bpf_map *map)
582 {
583 	int ref_obj_uses = 0;
584 
585 	if (is_ptr_cast_function(func_id))
586 		ref_obj_uses++;
587 	if (is_acquire_function(func_id, map))
588 		ref_obj_uses++;
589 	if (is_dynptr_ref_function(func_id))
590 		ref_obj_uses++;
591 
592 	return ref_obj_uses > 1;
593 }
594 
595 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
596 {
597 	return BPF_CLASS(insn->code) == BPF_STX &&
598 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
599 	       insn->imm == BPF_CMPXCHG;
600 }
601 
602 /* string representation of 'enum bpf_reg_type'
603  *
604  * Note that reg_type_str() can not appear more than once in a single verbose()
605  * statement.
606  */
607 static const char *reg_type_str(struct bpf_verifier_env *env,
608 				enum bpf_reg_type type)
609 {
610 	char postfix[16] = {0}, prefix[64] = {0};
611 	static const char * const str[] = {
612 		[NOT_INIT]		= "?",
613 		[SCALAR_VALUE]		= "scalar",
614 		[PTR_TO_CTX]		= "ctx",
615 		[CONST_PTR_TO_MAP]	= "map_ptr",
616 		[PTR_TO_MAP_VALUE]	= "map_value",
617 		[PTR_TO_STACK]		= "fp",
618 		[PTR_TO_PACKET]		= "pkt",
619 		[PTR_TO_PACKET_META]	= "pkt_meta",
620 		[PTR_TO_PACKET_END]	= "pkt_end",
621 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
622 		[PTR_TO_SOCKET]		= "sock",
623 		[PTR_TO_SOCK_COMMON]	= "sock_common",
624 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
625 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
626 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
627 		[PTR_TO_BTF_ID]		= "ptr_",
628 		[PTR_TO_MEM]		= "mem",
629 		[PTR_TO_BUF]		= "buf",
630 		[PTR_TO_FUNC]		= "func",
631 		[PTR_TO_MAP_KEY]	= "map_key",
632 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
633 	};
634 
635 	if (type & PTR_MAYBE_NULL) {
636 		if (base_type(type) == PTR_TO_BTF_ID)
637 			strncpy(postfix, "or_null_", 16);
638 		else
639 			strncpy(postfix, "_or_null", 16);
640 	}
641 
642 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
643 		 type & MEM_RDONLY ? "rdonly_" : "",
644 		 type & MEM_RINGBUF ? "ringbuf_" : "",
645 		 type & MEM_USER ? "user_" : "",
646 		 type & MEM_PERCPU ? "percpu_" : "",
647 		 type & MEM_RCU ? "rcu_" : "",
648 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
649 		 type & PTR_TRUSTED ? "trusted_" : ""
650 	);
651 
652 	snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
653 		 prefix, str[base_type(type)], postfix);
654 	return env->tmp_str_buf;
655 }
656 
657 static char slot_type_char[] = {
658 	[STACK_INVALID]	= '?',
659 	[STACK_SPILL]	= 'r',
660 	[STACK_MISC]	= 'm',
661 	[STACK_ZERO]	= '0',
662 	[STACK_DYNPTR]	= 'd',
663 	[STACK_ITER]	= 'i',
664 };
665 
666 static void print_liveness(struct bpf_verifier_env *env,
667 			   enum bpf_reg_liveness live)
668 {
669 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
670 	    verbose(env, "_");
671 	if (live & REG_LIVE_READ)
672 		verbose(env, "r");
673 	if (live & REG_LIVE_WRITTEN)
674 		verbose(env, "w");
675 	if (live & REG_LIVE_DONE)
676 		verbose(env, "D");
677 }
678 
679 static int __get_spi(s32 off)
680 {
681 	return (-off - 1) / BPF_REG_SIZE;
682 }
683 
684 static struct bpf_func_state *func(struct bpf_verifier_env *env,
685 				   const struct bpf_reg_state *reg)
686 {
687 	struct bpf_verifier_state *cur = env->cur_state;
688 
689 	return cur->frame[reg->frameno];
690 }
691 
692 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
693 {
694        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
695 
696        /* We need to check that slots between [spi - nr_slots + 1, spi] are
697 	* within [0, allocated_stack).
698 	*
699 	* Please note that the spi grows downwards. For example, a dynptr
700 	* takes the size of two stack slots; the first slot will be at
701 	* spi and the second slot will be at spi - 1.
702 	*/
703        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
704 }
705 
706 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
707 			          const char *obj_kind, int nr_slots)
708 {
709 	int off, spi;
710 
711 	if (!tnum_is_const(reg->var_off)) {
712 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
713 		return -EINVAL;
714 	}
715 
716 	off = reg->off + reg->var_off.value;
717 	if (off % BPF_REG_SIZE) {
718 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
719 		return -EINVAL;
720 	}
721 
722 	spi = __get_spi(off);
723 	if (spi + 1 < nr_slots) {
724 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
725 		return -EINVAL;
726 	}
727 
728 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
729 		return -ERANGE;
730 	return spi;
731 }
732 
733 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
734 {
735 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
736 }
737 
738 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
739 {
740 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
741 }
742 
743 static const char *btf_type_name(const struct btf *btf, u32 id)
744 {
745 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
746 }
747 
748 static const char *dynptr_type_str(enum bpf_dynptr_type type)
749 {
750 	switch (type) {
751 	case BPF_DYNPTR_TYPE_LOCAL:
752 		return "local";
753 	case BPF_DYNPTR_TYPE_RINGBUF:
754 		return "ringbuf";
755 	case BPF_DYNPTR_TYPE_SKB:
756 		return "skb";
757 	case BPF_DYNPTR_TYPE_XDP:
758 		return "xdp";
759 	case BPF_DYNPTR_TYPE_INVALID:
760 		return "<invalid>";
761 	default:
762 		WARN_ONCE(1, "unknown dynptr type %d\n", type);
763 		return "<unknown>";
764 	}
765 }
766 
767 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
768 {
769 	if (!btf || btf_id == 0)
770 		return "<invalid>";
771 
772 	/* we already validated that type is valid and has conforming name */
773 	return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
774 }
775 
776 static const char *iter_state_str(enum bpf_iter_state state)
777 {
778 	switch (state) {
779 	case BPF_ITER_STATE_ACTIVE:
780 		return "active";
781 	case BPF_ITER_STATE_DRAINED:
782 		return "drained";
783 	case BPF_ITER_STATE_INVALID:
784 		return "<invalid>";
785 	default:
786 		WARN_ONCE(1, "unknown iter state %d\n", state);
787 		return "<unknown>";
788 	}
789 }
790 
791 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
792 {
793 	env->scratched_regs |= 1U << regno;
794 }
795 
796 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
797 {
798 	env->scratched_stack_slots |= 1ULL << spi;
799 }
800 
801 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
802 {
803 	return (env->scratched_regs >> regno) & 1;
804 }
805 
806 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
807 {
808 	return (env->scratched_stack_slots >> regno) & 1;
809 }
810 
811 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
812 {
813 	return env->scratched_regs || env->scratched_stack_slots;
814 }
815 
816 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
817 {
818 	env->scratched_regs = 0U;
819 	env->scratched_stack_slots = 0ULL;
820 }
821 
822 /* Used for printing the entire verifier state. */
823 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
824 {
825 	env->scratched_regs = ~0U;
826 	env->scratched_stack_slots = ~0ULL;
827 }
828 
829 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
830 {
831 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
832 	case DYNPTR_TYPE_LOCAL:
833 		return BPF_DYNPTR_TYPE_LOCAL;
834 	case DYNPTR_TYPE_RINGBUF:
835 		return BPF_DYNPTR_TYPE_RINGBUF;
836 	case DYNPTR_TYPE_SKB:
837 		return BPF_DYNPTR_TYPE_SKB;
838 	case DYNPTR_TYPE_XDP:
839 		return BPF_DYNPTR_TYPE_XDP;
840 	default:
841 		return BPF_DYNPTR_TYPE_INVALID;
842 	}
843 }
844 
845 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
846 {
847 	switch (type) {
848 	case BPF_DYNPTR_TYPE_LOCAL:
849 		return DYNPTR_TYPE_LOCAL;
850 	case BPF_DYNPTR_TYPE_RINGBUF:
851 		return DYNPTR_TYPE_RINGBUF;
852 	case BPF_DYNPTR_TYPE_SKB:
853 		return DYNPTR_TYPE_SKB;
854 	case BPF_DYNPTR_TYPE_XDP:
855 		return DYNPTR_TYPE_XDP;
856 	default:
857 		return 0;
858 	}
859 }
860 
861 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
862 {
863 	return type == BPF_DYNPTR_TYPE_RINGBUF;
864 }
865 
866 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
867 			      enum bpf_dynptr_type type,
868 			      bool first_slot, int dynptr_id);
869 
870 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
871 				struct bpf_reg_state *reg);
872 
873 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
874 				   struct bpf_reg_state *sreg1,
875 				   struct bpf_reg_state *sreg2,
876 				   enum bpf_dynptr_type type)
877 {
878 	int id = ++env->id_gen;
879 
880 	__mark_dynptr_reg(sreg1, type, true, id);
881 	__mark_dynptr_reg(sreg2, type, false, id);
882 }
883 
884 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
885 			       struct bpf_reg_state *reg,
886 			       enum bpf_dynptr_type type)
887 {
888 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
889 }
890 
891 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
892 				        struct bpf_func_state *state, int spi);
893 
894 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
895 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
896 {
897 	struct bpf_func_state *state = func(env, reg);
898 	enum bpf_dynptr_type type;
899 	int spi, i, err;
900 
901 	spi = dynptr_get_spi(env, reg);
902 	if (spi < 0)
903 		return spi;
904 
905 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
906 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
907 	 * to ensure that for the following example:
908 	 *	[d1][d1][d2][d2]
909 	 * spi    3   2   1   0
910 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
911 	 * case they do belong to same dynptr, second call won't see slot_type
912 	 * as STACK_DYNPTR and will simply skip destruction.
913 	 */
914 	err = destroy_if_dynptr_stack_slot(env, state, spi);
915 	if (err)
916 		return err;
917 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
918 	if (err)
919 		return err;
920 
921 	for (i = 0; i < BPF_REG_SIZE; i++) {
922 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
923 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
924 	}
925 
926 	type = arg_to_dynptr_type(arg_type);
927 	if (type == BPF_DYNPTR_TYPE_INVALID)
928 		return -EINVAL;
929 
930 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
931 			       &state->stack[spi - 1].spilled_ptr, type);
932 
933 	if (dynptr_type_refcounted(type)) {
934 		/* The id is used to track proper releasing */
935 		int id;
936 
937 		if (clone_ref_obj_id)
938 			id = clone_ref_obj_id;
939 		else
940 			id = acquire_reference_state(env, insn_idx);
941 
942 		if (id < 0)
943 			return id;
944 
945 		state->stack[spi].spilled_ptr.ref_obj_id = id;
946 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
947 	}
948 
949 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
950 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
951 
952 	return 0;
953 }
954 
955 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
956 {
957 	int i;
958 
959 	for (i = 0; i < BPF_REG_SIZE; i++) {
960 		state->stack[spi].slot_type[i] = STACK_INVALID;
961 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
962 	}
963 
964 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
965 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
966 
967 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
968 	 *
969 	 * While we don't allow reading STACK_INVALID, it is still possible to
970 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
971 	 * helpers or insns can do partial read of that part without failing,
972 	 * but check_stack_range_initialized, check_stack_read_var_off, and
973 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
974 	 * the slot conservatively. Hence we need to prevent those liveness
975 	 * marking walks.
976 	 *
977 	 * This was not a problem before because STACK_INVALID is only set by
978 	 * default (where the default reg state has its reg->parent as NULL), or
979 	 * in clean_live_states after REG_LIVE_DONE (at which point
980 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
981 	 * verifier state exploration (like we did above). Hence, for our case
982 	 * parentage chain will still be live (i.e. reg->parent may be
983 	 * non-NULL), while earlier reg->parent was NULL, so we need
984 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
985 	 * done later on reads or by mark_dynptr_read as well to unnecessary
986 	 * mark registers in verifier state.
987 	 */
988 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
989 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
990 }
991 
992 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
993 {
994 	struct bpf_func_state *state = func(env, reg);
995 	int spi, ref_obj_id, i;
996 
997 	spi = dynptr_get_spi(env, reg);
998 	if (spi < 0)
999 		return spi;
1000 
1001 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1002 		invalidate_dynptr(env, state, spi);
1003 		return 0;
1004 	}
1005 
1006 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
1007 
1008 	/* If the dynptr has a ref_obj_id, then we need to invalidate
1009 	 * two things:
1010 	 *
1011 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
1012 	 * 2) Any slices derived from this dynptr.
1013 	 */
1014 
1015 	/* Invalidate any slices associated with this dynptr */
1016 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
1017 
1018 	/* Invalidate any dynptr clones */
1019 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1020 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1021 			continue;
1022 
1023 		/* it should always be the case that if the ref obj id
1024 		 * matches then the stack slot also belongs to a
1025 		 * dynptr
1026 		 */
1027 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1028 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1029 			return -EFAULT;
1030 		}
1031 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
1032 			invalidate_dynptr(env, state, i);
1033 	}
1034 
1035 	return 0;
1036 }
1037 
1038 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1039 			       struct bpf_reg_state *reg);
1040 
1041 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1042 {
1043 	if (!env->allow_ptr_leaks)
1044 		__mark_reg_not_init(env, reg);
1045 	else
1046 		__mark_reg_unknown(env, reg);
1047 }
1048 
1049 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1050 				        struct bpf_func_state *state, int spi)
1051 {
1052 	struct bpf_func_state *fstate;
1053 	struct bpf_reg_state *dreg;
1054 	int i, dynptr_id;
1055 
1056 	/* We always ensure that STACK_DYNPTR is never set partially,
1057 	 * hence just checking for slot_type[0] is enough. This is
1058 	 * different for STACK_SPILL, where it may be only set for
1059 	 * 1 byte, so code has to use is_spilled_reg.
1060 	 */
1061 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1062 		return 0;
1063 
1064 	/* Reposition spi to first slot */
1065 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1066 		spi = spi + 1;
1067 
1068 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1069 		verbose(env, "cannot overwrite referenced dynptr\n");
1070 		return -EINVAL;
1071 	}
1072 
1073 	mark_stack_slot_scratched(env, spi);
1074 	mark_stack_slot_scratched(env, spi - 1);
1075 
1076 	/* Writing partially to one dynptr stack slot destroys both. */
1077 	for (i = 0; i < BPF_REG_SIZE; i++) {
1078 		state->stack[spi].slot_type[i] = STACK_INVALID;
1079 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1080 	}
1081 
1082 	dynptr_id = state->stack[spi].spilled_ptr.id;
1083 	/* Invalidate any slices associated with this dynptr */
1084 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1085 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1086 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1087 			continue;
1088 		if (dreg->dynptr_id == dynptr_id)
1089 			mark_reg_invalid(env, dreg);
1090 	}));
1091 
1092 	/* Do not release reference state, we are destroying dynptr on stack,
1093 	 * not using some helper to release it. Just reset register.
1094 	 */
1095 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1096 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1097 
1098 	/* Same reason as unmark_stack_slots_dynptr above */
1099 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1100 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1101 
1102 	return 0;
1103 }
1104 
1105 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1106 {
1107 	int spi;
1108 
1109 	if (reg->type == CONST_PTR_TO_DYNPTR)
1110 		return false;
1111 
1112 	spi = dynptr_get_spi(env, reg);
1113 
1114 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1115 	 * error because this just means the stack state hasn't been updated yet.
1116 	 * We will do check_mem_access to check and update stack bounds later.
1117 	 */
1118 	if (spi < 0 && spi != -ERANGE)
1119 		return false;
1120 
1121 	/* We don't need to check if the stack slots are marked by previous
1122 	 * dynptr initializations because we allow overwriting existing unreferenced
1123 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1124 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1125 	 * touching are completely destructed before we reinitialize them for a new
1126 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1127 	 * instead of delaying it until the end where the user will get "Unreleased
1128 	 * reference" error.
1129 	 */
1130 	return true;
1131 }
1132 
1133 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1134 {
1135 	struct bpf_func_state *state = func(env, reg);
1136 	int i, spi;
1137 
1138 	/* This already represents first slot of initialized bpf_dynptr.
1139 	 *
1140 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1141 	 * check_func_arg_reg_off's logic, so we don't need to check its
1142 	 * offset and alignment.
1143 	 */
1144 	if (reg->type == CONST_PTR_TO_DYNPTR)
1145 		return true;
1146 
1147 	spi = dynptr_get_spi(env, reg);
1148 	if (spi < 0)
1149 		return false;
1150 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1151 		return false;
1152 
1153 	for (i = 0; i < BPF_REG_SIZE; i++) {
1154 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1155 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1156 			return false;
1157 	}
1158 
1159 	return true;
1160 }
1161 
1162 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1163 				    enum bpf_arg_type arg_type)
1164 {
1165 	struct bpf_func_state *state = func(env, reg);
1166 	enum bpf_dynptr_type dynptr_type;
1167 	int spi;
1168 
1169 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1170 	if (arg_type == ARG_PTR_TO_DYNPTR)
1171 		return true;
1172 
1173 	dynptr_type = arg_to_dynptr_type(arg_type);
1174 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1175 		return reg->dynptr.type == dynptr_type;
1176 	} else {
1177 		spi = dynptr_get_spi(env, reg);
1178 		if (spi < 0)
1179 			return false;
1180 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1181 	}
1182 }
1183 
1184 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1185 
1186 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1187 				 struct bpf_reg_state *reg, int insn_idx,
1188 				 struct btf *btf, u32 btf_id, int nr_slots)
1189 {
1190 	struct bpf_func_state *state = func(env, reg);
1191 	int spi, i, j, id;
1192 
1193 	spi = iter_get_spi(env, reg, nr_slots);
1194 	if (spi < 0)
1195 		return spi;
1196 
1197 	id = acquire_reference_state(env, insn_idx);
1198 	if (id < 0)
1199 		return id;
1200 
1201 	for (i = 0; i < nr_slots; i++) {
1202 		struct bpf_stack_state *slot = &state->stack[spi - i];
1203 		struct bpf_reg_state *st = &slot->spilled_ptr;
1204 
1205 		__mark_reg_known_zero(st);
1206 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1207 		st->live |= REG_LIVE_WRITTEN;
1208 		st->ref_obj_id = i == 0 ? id : 0;
1209 		st->iter.btf = btf;
1210 		st->iter.btf_id = btf_id;
1211 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1212 		st->iter.depth = 0;
1213 
1214 		for (j = 0; j < BPF_REG_SIZE; j++)
1215 			slot->slot_type[j] = STACK_ITER;
1216 
1217 		mark_stack_slot_scratched(env, spi - i);
1218 	}
1219 
1220 	return 0;
1221 }
1222 
1223 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1224 				   struct bpf_reg_state *reg, int nr_slots)
1225 {
1226 	struct bpf_func_state *state = func(env, reg);
1227 	int spi, i, j;
1228 
1229 	spi = iter_get_spi(env, reg, nr_slots);
1230 	if (spi < 0)
1231 		return spi;
1232 
1233 	for (i = 0; i < nr_slots; i++) {
1234 		struct bpf_stack_state *slot = &state->stack[spi - i];
1235 		struct bpf_reg_state *st = &slot->spilled_ptr;
1236 
1237 		if (i == 0)
1238 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1239 
1240 		__mark_reg_not_init(env, st);
1241 
1242 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1243 		st->live |= REG_LIVE_WRITTEN;
1244 
1245 		for (j = 0; j < BPF_REG_SIZE; j++)
1246 			slot->slot_type[j] = STACK_INVALID;
1247 
1248 		mark_stack_slot_scratched(env, spi - i);
1249 	}
1250 
1251 	return 0;
1252 }
1253 
1254 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1255 				     struct bpf_reg_state *reg, int nr_slots)
1256 {
1257 	struct bpf_func_state *state = func(env, reg);
1258 	int spi, i, j;
1259 
1260 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1261 	 * will do check_mem_access to check and update stack bounds later, so
1262 	 * return true for that case.
1263 	 */
1264 	spi = iter_get_spi(env, reg, nr_slots);
1265 	if (spi == -ERANGE)
1266 		return true;
1267 	if (spi < 0)
1268 		return false;
1269 
1270 	for (i = 0; i < nr_slots; i++) {
1271 		struct bpf_stack_state *slot = &state->stack[spi - i];
1272 
1273 		for (j = 0; j < BPF_REG_SIZE; j++)
1274 			if (slot->slot_type[j] == STACK_ITER)
1275 				return false;
1276 	}
1277 
1278 	return true;
1279 }
1280 
1281 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1282 				   struct btf *btf, u32 btf_id, int nr_slots)
1283 {
1284 	struct bpf_func_state *state = func(env, reg);
1285 	int spi, i, j;
1286 
1287 	spi = iter_get_spi(env, reg, nr_slots);
1288 	if (spi < 0)
1289 		return false;
1290 
1291 	for (i = 0; i < nr_slots; i++) {
1292 		struct bpf_stack_state *slot = &state->stack[spi - i];
1293 		struct bpf_reg_state *st = &slot->spilled_ptr;
1294 
1295 		/* only main (first) slot has ref_obj_id set */
1296 		if (i == 0 && !st->ref_obj_id)
1297 			return false;
1298 		if (i != 0 && st->ref_obj_id)
1299 			return false;
1300 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1301 			return false;
1302 
1303 		for (j = 0; j < BPF_REG_SIZE; j++)
1304 			if (slot->slot_type[j] != STACK_ITER)
1305 				return false;
1306 	}
1307 
1308 	return true;
1309 }
1310 
1311 /* Check if given stack slot is "special":
1312  *   - spilled register state (STACK_SPILL);
1313  *   - dynptr state (STACK_DYNPTR);
1314  *   - iter state (STACK_ITER).
1315  */
1316 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1317 {
1318 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1319 
1320 	switch (type) {
1321 	case STACK_SPILL:
1322 	case STACK_DYNPTR:
1323 	case STACK_ITER:
1324 		return true;
1325 	case STACK_INVALID:
1326 	case STACK_MISC:
1327 	case STACK_ZERO:
1328 		return false;
1329 	default:
1330 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1331 		return true;
1332 	}
1333 }
1334 
1335 /* The reg state of a pointer or a bounded scalar was saved when
1336  * it was spilled to the stack.
1337  */
1338 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1339 {
1340 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1341 }
1342 
1343 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1344 {
1345 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1346 	       stack->spilled_ptr.type == SCALAR_VALUE;
1347 }
1348 
1349 static void scrub_spilled_slot(u8 *stype)
1350 {
1351 	if (*stype != STACK_INVALID)
1352 		*stype = STACK_MISC;
1353 }
1354 
1355 static void print_verifier_state(struct bpf_verifier_env *env,
1356 				 const struct bpf_func_state *state,
1357 				 bool print_all)
1358 {
1359 	const struct bpf_reg_state *reg;
1360 	enum bpf_reg_type t;
1361 	int i;
1362 
1363 	if (state->frameno)
1364 		verbose(env, " frame%d:", state->frameno);
1365 	for (i = 0; i < MAX_BPF_REG; i++) {
1366 		reg = &state->regs[i];
1367 		t = reg->type;
1368 		if (t == NOT_INIT)
1369 			continue;
1370 		if (!print_all && !reg_scratched(env, i))
1371 			continue;
1372 		verbose(env, " R%d", i);
1373 		print_liveness(env, reg->live);
1374 		verbose(env, "=");
1375 		if (t == SCALAR_VALUE && reg->precise)
1376 			verbose(env, "P");
1377 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1378 		    tnum_is_const(reg->var_off)) {
1379 			/* reg->off should be 0 for SCALAR_VALUE */
1380 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1381 			verbose(env, "%lld", reg->var_off.value + reg->off);
1382 		} else {
1383 			const char *sep = "";
1384 
1385 			verbose(env, "%s", reg_type_str(env, t));
1386 			if (base_type(t) == PTR_TO_BTF_ID)
1387 				verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1388 			verbose(env, "(");
1389 /*
1390  * _a stands for append, was shortened to avoid multiline statements below.
1391  * This macro is used to output a comma separated list of attributes.
1392  */
1393 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1394 
1395 			if (reg->id)
1396 				verbose_a("id=%d", reg->id);
1397 			if (reg->ref_obj_id)
1398 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1399 			if (type_is_non_owning_ref(reg->type))
1400 				verbose_a("%s", "non_own_ref");
1401 			if (t != SCALAR_VALUE)
1402 				verbose_a("off=%d", reg->off);
1403 			if (type_is_pkt_pointer(t))
1404 				verbose_a("r=%d", reg->range);
1405 			else if (base_type(t) == CONST_PTR_TO_MAP ||
1406 				 base_type(t) == PTR_TO_MAP_KEY ||
1407 				 base_type(t) == PTR_TO_MAP_VALUE)
1408 				verbose_a("ks=%d,vs=%d",
1409 					  reg->map_ptr->key_size,
1410 					  reg->map_ptr->value_size);
1411 			if (tnum_is_const(reg->var_off)) {
1412 				/* Typically an immediate SCALAR_VALUE, but
1413 				 * could be a pointer whose offset is too big
1414 				 * for reg->off
1415 				 */
1416 				verbose_a("imm=%llx", reg->var_off.value);
1417 			} else {
1418 				if (reg->smin_value != reg->umin_value &&
1419 				    reg->smin_value != S64_MIN)
1420 					verbose_a("smin=%lld", (long long)reg->smin_value);
1421 				if (reg->smax_value != reg->umax_value &&
1422 				    reg->smax_value != S64_MAX)
1423 					verbose_a("smax=%lld", (long long)reg->smax_value);
1424 				if (reg->umin_value != 0)
1425 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1426 				if (reg->umax_value != U64_MAX)
1427 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1428 				if (!tnum_is_unknown(reg->var_off)) {
1429 					char tn_buf[48];
1430 
1431 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1432 					verbose_a("var_off=%s", tn_buf);
1433 				}
1434 				if (reg->s32_min_value != reg->smin_value &&
1435 				    reg->s32_min_value != S32_MIN)
1436 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1437 				if (reg->s32_max_value != reg->smax_value &&
1438 				    reg->s32_max_value != S32_MAX)
1439 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1440 				if (reg->u32_min_value != reg->umin_value &&
1441 				    reg->u32_min_value != U32_MIN)
1442 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1443 				if (reg->u32_max_value != reg->umax_value &&
1444 				    reg->u32_max_value != U32_MAX)
1445 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1446 			}
1447 #undef verbose_a
1448 
1449 			verbose(env, ")");
1450 		}
1451 	}
1452 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1453 		char types_buf[BPF_REG_SIZE + 1];
1454 		bool valid = false;
1455 		int j;
1456 
1457 		for (j = 0; j < BPF_REG_SIZE; j++) {
1458 			if (state->stack[i].slot_type[j] != STACK_INVALID)
1459 				valid = true;
1460 			types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1461 		}
1462 		types_buf[BPF_REG_SIZE] = 0;
1463 		if (!valid)
1464 			continue;
1465 		if (!print_all && !stack_slot_scratched(env, i))
1466 			continue;
1467 		switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1468 		case STACK_SPILL:
1469 			reg = &state->stack[i].spilled_ptr;
1470 			t = reg->type;
1471 
1472 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1473 			print_liveness(env, reg->live);
1474 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1475 			if (t == SCALAR_VALUE && reg->precise)
1476 				verbose(env, "P");
1477 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1478 				verbose(env, "%lld", reg->var_off.value + reg->off);
1479 			break;
1480 		case STACK_DYNPTR:
1481 			i += BPF_DYNPTR_NR_SLOTS - 1;
1482 			reg = &state->stack[i].spilled_ptr;
1483 
1484 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1485 			print_liveness(env, reg->live);
1486 			verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1487 			if (reg->ref_obj_id)
1488 				verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1489 			break;
1490 		case STACK_ITER:
1491 			/* only main slot has ref_obj_id set; skip others */
1492 			reg = &state->stack[i].spilled_ptr;
1493 			if (!reg->ref_obj_id)
1494 				continue;
1495 
1496 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1497 			print_liveness(env, reg->live);
1498 			verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1499 				iter_type_str(reg->iter.btf, reg->iter.btf_id),
1500 				reg->ref_obj_id, iter_state_str(reg->iter.state),
1501 				reg->iter.depth);
1502 			break;
1503 		case STACK_MISC:
1504 		case STACK_ZERO:
1505 		default:
1506 			reg = &state->stack[i].spilled_ptr;
1507 
1508 			for (j = 0; j < BPF_REG_SIZE; j++)
1509 				types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1510 			types_buf[BPF_REG_SIZE] = 0;
1511 
1512 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1513 			print_liveness(env, reg->live);
1514 			verbose(env, "=%s", types_buf);
1515 			break;
1516 		}
1517 	}
1518 	if (state->acquired_refs && state->refs[0].id) {
1519 		verbose(env, " refs=%d", state->refs[0].id);
1520 		for (i = 1; i < state->acquired_refs; i++)
1521 			if (state->refs[i].id)
1522 				verbose(env, ",%d", state->refs[i].id);
1523 	}
1524 	if (state->in_callback_fn)
1525 		verbose(env, " cb");
1526 	if (state->in_async_callback_fn)
1527 		verbose(env, " async_cb");
1528 	verbose(env, "\n");
1529 	if (!print_all)
1530 		mark_verifier_state_clean(env);
1531 }
1532 
1533 static inline u32 vlog_alignment(u32 pos)
1534 {
1535 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1536 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1537 }
1538 
1539 static void print_insn_state(struct bpf_verifier_env *env,
1540 			     const struct bpf_func_state *state)
1541 {
1542 	if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1543 		/* remove new line character */
1544 		bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1545 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1546 	} else {
1547 		verbose(env, "%d:", env->insn_idx);
1548 	}
1549 	print_verifier_state(env, state, false);
1550 }
1551 
1552 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1553  * small to hold src. This is different from krealloc since we don't want to preserve
1554  * the contents of dst.
1555  *
1556  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1557  * not be allocated.
1558  */
1559 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1560 {
1561 	size_t alloc_bytes;
1562 	void *orig = dst;
1563 	size_t bytes;
1564 
1565 	if (ZERO_OR_NULL_PTR(src))
1566 		goto out;
1567 
1568 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1569 		return NULL;
1570 
1571 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1572 	dst = krealloc(orig, alloc_bytes, flags);
1573 	if (!dst) {
1574 		kfree(orig);
1575 		return NULL;
1576 	}
1577 
1578 	memcpy(dst, src, bytes);
1579 out:
1580 	return dst ? dst : ZERO_SIZE_PTR;
1581 }
1582 
1583 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1584  * small to hold new_n items. new items are zeroed out if the array grows.
1585  *
1586  * Contrary to krealloc_array, does not free arr if new_n is zero.
1587  */
1588 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1589 {
1590 	size_t alloc_size;
1591 	void *new_arr;
1592 
1593 	if (!new_n || old_n == new_n)
1594 		goto out;
1595 
1596 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1597 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1598 	if (!new_arr) {
1599 		kfree(arr);
1600 		return NULL;
1601 	}
1602 	arr = new_arr;
1603 
1604 	if (new_n > old_n)
1605 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1606 
1607 out:
1608 	return arr ? arr : ZERO_SIZE_PTR;
1609 }
1610 
1611 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1612 {
1613 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1614 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1615 	if (!dst->refs)
1616 		return -ENOMEM;
1617 
1618 	dst->acquired_refs = src->acquired_refs;
1619 	return 0;
1620 }
1621 
1622 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1623 {
1624 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1625 
1626 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1627 				GFP_KERNEL);
1628 	if (!dst->stack)
1629 		return -ENOMEM;
1630 
1631 	dst->allocated_stack = src->allocated_stack;
1632 	return 0;
1633 }
1634 
1635 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1636 {
1637 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1638 				    sizeof(struct bpf_reference_state));
1639 	if (!state->refs)
1640 		return -ENOMEM;
1641 
1642 	state->acquired_refs = n;
1643 	return 0;
1644 }
1645 
1646 /* Possibly update state->allocated_stack to be at least size bytes. Also
1647  * possibly update the function's high-water mark in its bpf_subprog_info.
1648  */
1649 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1650 {
1651 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1652 
1653 	if (old_n >= n)
1654 		return 0;
1655 
1656 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1657 	if (!state->stack)
1658 		return -ENOMEM;
1659 
1660 	state->allocated_stack = size;
1661 
1662 	/* update known max for given subprogram */
1663 	if (env->subprog_info[state->subprogno].stack_depth < size)
1664 		env->subprog_info[state->subprogno].stack_depth = size;
1665 
1666 	return 0;
1667 }
1668 
1669 /* Acquire a pointer id from the env and update the state->refs to include
1670  * this new pointer reference.
1671  * On success, returns a valid pointer id to associate with the register
1672  * On failure, returns a negative errno.
1673  */
1674 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1675 {
1676 	struct bpf_func_state *state = cur_func(env);
1677 	int new_ofs = state->acquired_refs;
1678 	int id, err;
1679 
1680 	err = resize_reference_state(state, state->acquired_refs + 1);
1681 	if (err)
1682 		return err;
1683 	id = ++env->id_gen;
1684 	state->refs[new_ofs].id = id;
1685 	state->refs[new_ofs].insn_idx = insn_idx;
1686 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1687 
1688 	return id;
1689 }
1690 
1691 /* release function corresponding to acquire_reference_state(). Idempotent. */
1692 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1693 {
1694 	int i, last_idx;
1695 
1696 	last_idx = state->acquired_refs - 1;
1697 	for (i = 0; i < state->acquired_refs; i++) {
1698 		if (state->refs[i].id == ptr_id) {
1699 			/* Cannot release caller references in callbacks */
1700 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1701 				return -EINVAL;
1702 			if (last_idx && i != last_idx)
1703 				memcpy(&state->refs[i], &state->refs[last_idx],
1704 				       sizeof(*state->refs));
1705 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1706 			state->acquired_refs--;
1707 			return 0;
1708 		}
1709 	}
1710 	return -EINVAL;
1711 }
1712 
1713 static void free_func_state(struct bpf_func_state *state)
1714 {
1715 	if (!state)
1716 		return;
1717 	kfree(state->refs);
1718 	kfree(state->stack);
1719 	kfree(state);
1720 }
1721 
1722 static void clear_jmp_history(struct bpf_verifier_state *state)
1723 {
1724 	kfree(state->jmp_history);
1725 	state->jmp_history = NULL;
1726 	state->jmp_history_cnt = 0;
1727 }
1728 
1729 static void free_verifier_state(struct bpf_verifier_state *state,
1730 				bool free_self)
1731 {
1732 	int i;
1733 
1734 	for (i = 0; i <= state->curframe; i++) {
1735 		free_func_state(state->frame[i]);
1736 		state->frame[i] = NULL;
1737 	}
1738 	clear_jmp_history(state);
1739 	if (free_self)
1740 		kfree(state);
1741 }
1742 
1743 /* copy verifier state from src to dst growing dst stack space
1744  * when necessary to accommodate larger src stack
1745  */
1746 static int copy_func_state(struct bpf_func_state *dst,
1747 			   const struct bpf_func_state *src)
1748 {
1749 	int err;
1750 
1751 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1752 	err = copy_reference_state(dst, src);
1753 	if (err)
1754 		return err;
1755 	return copy_stack_state(dst, src);
1756 }
1757 
1758 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1759 			       const struct bpf_verifier_state *src)
1760 {
1761 	struct bpf_func_state *dst;
1762 	int i, err;
1763 
1764 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1765 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1766 					    GFP_USER);
1767 	if (!dst_state->jmp_history)
1768 		return -ENOMEM;
1769 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1770 
1771 	/* if dst has more stack frames then src frame, free them */
1772 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1773 		free_func_state(dst_state->frame[i]);
1774 		dst_state->frame[i] = NULL;
1775 	}
1776 	dst_state->speculative = src->speculative;
1777 	dst_state->active_rcu_lock = src->active_rcu_lock;
1778 	dst_state->curframe = src->curframe;
1779 	dst_state->active_lock.ptr = src->active_lock.ptr;
1780 	dst_state->active_lock.id = src->active_lock.id;
1781 	dst_state->branches = src->branches;
1782 	dst_state->parent = src->parent;
1783 	dst_state->first_insn_idx = src->first_insn_idx;
1784 	dst_state->last_insn_idx = src->last_insn_idx;
1785 	dst_state->dfs_depth = src->dfs_depth;
1786 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1787 	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1788 	for (i = 0; i <= src->curframe; i++) {
1789 		dst = dst_state->frame[i];
1790 		if (!dst) {
1791 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1792 			if (!dst)
1793 				return -ENOMEM;
1794 			dst_state->frame[i] = dst;
1795 		}
1796 		err = copy_func_state(dst, src->frame[i]);
1797 		if (err)
1798 			return err;
1799 	}
1800 	return 0;
1801 }
1802 
1803 static u32 state_htab_size(struct bpf_verifier_env *env)
1804 {
1805 	return env->prog->len;
1806 }
1807 
1808 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1809 {
1810 	struct bpf_verifier_state *cur = env->cur_state;
1811 	struct bpf_func_state *state = cur->frame[cur->curframe];
1812 
1813 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1814 }
1815 
1816 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1817 {
1818 	int fr;
1819 
1820 	if (a->curframe != b->curframe)
1821 		return false;
1822 
1823 	for (fr = a->curframe; fr >= 0; fr--)
1824 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1825 			return false;
1826 
1827 	return true;
1828 }
1829 
1830 /* Open coded iterators allow back-edges in the state graph in order to
1831  * check unbounded loops that iterators.
1832  *
1833  * In is_state_visited() it is necessary to know if explored states are
1834  * part of some loops in order to decide whether non-exact states
1835  * comparison could be used:
1836  * - non-exact states comparison establishes sub-state relation and uses
1837  *   read and precision marks to do so, these marks are propagated from
1838  *   children states and thus are not guaranteed to be final in a loop;
1839  * - exact states comparison just checks if current and explored states
1840  *   are identical (and thus form a back-edge).
1841  *
1842  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1843  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1844  * algorithm for loop structure detection and gives an overview of
1845  * relevant terminology. It also has helpful illustrations.
1846  *
1847  * [1] https://api.semanticscholar.org/CorpusID:15784067
1848  *
1849  * We use a similar algorithm but because loop nested structure is
1850  * irrelevant for verifier ours is significantly simpler and resembles
1851  * strongly connected components algorithm from Sedgewick's textbook.
1852  *
1853  * Define topmost loop entry as a first node of the loop traversed in a
1854  * depth first search starting from initial state. The goal of the loop
1855  * tracking algorithm is to associate topmost loop entries with states
1856  * derived from these entries.
1857  *
1858  * For each step in the DFS states traversal algorithm needs to identify
1859  * the following situations:
1860  *
1861  *          initial                     initial                   initial
1862  *            |                           |                         |
1863  *            V                           V                         V
1864  *           ...                         ...           .---------> hdr
1865  *            |                           |            |            |
1866  *            V                           V            |            V
1867  *           cur                     .-> succ          |    .------...
1868  *            |                      |    |            |    |       |
1869  *            V                      |    V            |    V       V
1870  *           succ                    '-- cur           |   ...     ...
1871  *                                                     |    |       |
1872  *                                                     |    V       V
1873  *                                                     |   succ <- cur
1874  *                                                     |    |
1875  *                                                     |    V
1876  *                                                     |   ...
1877  *                                                     |    |
1878  *                                                     '----'
1879  *
1880  *  (A) successor state of cur   (B) successor state of cur or it's entry
1881  *      not yet traversed            are in current DFS path, thus cur and succ
1882  *                                   are members of the same outermost loop
1883  *
1884  *                      initial                  initial
1885  *                        |                        |
1886  *                        V                        V
1887  *                       ...                      ...
1888  *                        |                        |
1889  *                        V                        V
1890  *                .------...               .------...
1891  *                |       |                |       |
1892  *                V       V                V       V
1893  *           .-> hdr     ...              ...     ...
1894  *           |    |       |                |       |
1895  *           |    V       V                V       V
1896  *           |   succ <- cur              succ <- cur
1897  *           |    |                        |
1898  *           |    V                        V
1899  *           |   ...                      ...
1900  *           |    |                        |
1901  *           '----'                       exit
1902  *
1903  * (C) successor state of cur is a part of some loop but this loop
1904  *     does not include cur or successor state is not in a loop at all.
1905  *
1906  * Algorithm could be described as the following python code:
1907  *
1908  *     traversed = set()   # Set of traversed nodes
1909  *     entries = {}        # Mapping from node to loop entry
1910  *     depths = {}         # Depth level assigned to graph node
1911  *     path = set()        # Current DFS path
1912  *
1913  *     # Find outermost loop entry known for n
1914  *     def get_loop_entry(n):
1915  *         h = entries.get(n, None)
1916  *         while h in entries and entries[h] != h:
1917  *             h = entries[h]
1918  *         return h
1919  *
1920  *     # Update n's loop entry if h's outermost entry comes
1921  *     # before n's outermost entry in current DFS path.
1922  *     def update_loop_entry(n, h):
1923  *         n1 = get_loop_entry(n) or n
1924  *         h1 = get_loop_entry(h) or h
1925  *         if h1 in path and depths[h1] <= depths[n1]:
1926  *             entries[n] = h1
1927  *
1928  *     def dfs(n, depth):
1929  *         traversed.add(n)
1930  *         path.add(n)
1931  *         depths[n] = depth
1932  *         for succ in G.successors(n):
1933  *             if succ not in traversed:
1934  *                 # Case A: explore succ and update cur's loop entry
1935  *                 #         only if succ's entry is in current DFS path.
1936  *                 dfs(succ, depth + 1)
1937  *                 h = get_loop_entry(succ)
1938  *                 update_loop_entry(n, h)
1939  *             else:
1940  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1941  *                 update_loop_entry(n, succ)
1942  *         path.remove(n)
1943  *
1944  * To adapt this algorithm for use with verifier:
1945  * - use st->branch == 0 as a signal that DFS of succ had been finished
1946  *   and cur's loop entry has to be updated (case A), handle this in
1947  *   update_branch_counts();
1948  * - use st->branch > 0 as a signal that st is in the current DFS path;
1949  * - handle cases B and C in is_state_visited();
1950  * - update topmost loop entry for intermediate states in get_loop_entry().
1951  */
1952 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1953 {
1954 	struct bpf_verifier_state *topmost = st->loop_entry, *old;
1955 
1956 	while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1957 		topmost = topmost->loop_entry;
1958 	/* Update loop entries for intermediate states to avoid this
1959 	 * traversal in future get_loop_entry() calls.
1960 	 */
1961 	while (st && st->loop_entry != topmost) {
1962 		old = st->loop_entry;
1963 		st->loop_entry = topmost;
1964 		st = old;
1965 	}
1966 	return topmost;
1967 }
1968 
1969 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1970 {
1971 	struct bpf_verifier_state *cur1, *hdr1;
1972 
1973 	cur1 = get_loop_entry(cur) ?: cur;
1974 	hdr1 = get_loop_entry(hdr) ?: hdr;
1975 	/* The head1->branches check decides between cases B and C in
1976 	 * comment for get_loop_entry(). If hdr1->branches == 0 then
1977 	 * head's topmost loop entry is not in current DFS path,
1978 	 * hence 'cur' and 'hdr' are not in the same loop and there is
1979 	 * no need to update cur->loop_entry.
1980 	 */
1981 	if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1982 		cur->loop_entry = hdr;
1983 		hdr->used_as_loop_entry = true;
1984 	}
1985 }
1986 
1987 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1988 {
1989 	while (st) {
1990 		u32 br = --st->branches;
1991 
1992 		/* br == 0 signals that DFS exploration for 'st' is finished,
1993 		 * thus it is necessary to update parent's loop entry if it
1994 		 * turned out that st is a part of some loop.
1995 		 * This is a part of 'case A' in get_loop_entry() comment.
1996 		 */
1997 		if (br == 0 && st->parent && st->loop_entry)
1998 			update_loop_entry(st->parent, st->loop_entry);
1999 
2000 		/* WARN_ON(br > 1) technically makes sense here,
2001 		 * but see comment in push_stack(), hence:
2002 		 */
2003 		WARN_ONCE((int)br < 0,
2004 			  "BUG update_branch_counts:branches_to_explore=%d\n",
2005 			  br);
2006 		if (br)
2007 			break;
2008 		st = st->parent;
2009 	}
2010 }
2011 
2012 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2013 		     int *insn_idx, bool pop_log)
2014 {
2015 	struct bpf_verifier_state *cur = env->cur_state;
2016 	struct bpf_verifier_stack_elem *elem, *head = env->head;
2017 	int err;
2018 
2019 	if (env->head == NULL)
2020 		return -ENOENT;
2021 
2022 	if (cur) {
2023 		err = copy_verifier_state(cur, &head->st);
2024 		if (err)
2025 			return err;
2026 	}
2027 	if (pop_log)
2028 		bpf_vlog_reset(&env->log, head->log_pos);
2029 	if (insn_idx)
2030 		*insn_idx = head->insn_idx;
2031 	if (prev_insn_idx)
2032 		*prev_insn_idx = head->prev_insn_idx;
2033 	elem = head->next;
2034 	free_verifier_state(&head->st, false);
2035 	kfree(head);
2036 	env->head = elem;
2037 	env->stack_size--;
2038 	return 0;
2039 }
2040 
2041 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2042 					     int insn_idx, int prev_insn_idx,
2043 					     bool speculative)
2044 {
2045 	struct bpf_verifier_state *cur = env->cur_state;
2046 	struct bpf_verifier_stack_elem *elem;
2047 	int err;
2048 
2049 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2050 	if (!elem)
2051 		goto err;
2052 
2053 	elem->insn_idx = insn_idx;
2054 	elem->prev_insn_idx = prev_insn_idx;
2055 	elem->next = env->head;
2056 	elem->log_pos = env->log.end_pos;
2057 	env->head = elem;
2058 	env->stack_size++;
2059 	err = copy_verifier_state(&elem->st, cur);
2060 	if (err)
2061 		goto err;
2062 	elem->st.speculative |= speculative;
2063 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2064 		verbose(env, "The sequence of %d jumps is too complex.\n",
2065 			env->stack_size);
2066 		goto err;
2067 	}
2068 	if (elem->st.parent) {
2069 		++elem->st.parent->branches;
2070 		/* WARN_ON(branches > 2) technically makes sense here,
2071 		 * but
2072 		 * 1. speculative states will bump 'branches' for non-branch
2073 		 * instructions
2074 		 * 2. is_state_visited() heuristics may decide not to create
2075 		 * a new state for a sequence of branches and all such current
2076 		 * and cloned states will be pointing to a single parent state
2077 		 * which might have large 'branches' count.
2078 		 */
2079 	}
2080 	return &elem->st;
2081 err:
2082 	free_verifier_state(env->cur_state, true);
2083 	env->cur_state = NULL;
2084 	/* pop all elements and return */
2085 	while (!pop_stack(env, NULL, NULL, false));
2086 	return NULL;
2087 }
2088 
2089 #define CALLER_SAVED_REGS 6
2090 static const int caller_saved[CALLER_SAVED_REGS] = {
2091 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2092 };
2093 
2094 /* This helper doesn't clear reg->id */
2095 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2096 {
2097 	reg->var_off = tnum_const(imm);
2098 	reg->smin_value = (s64)imm;
2099 	reg->smax_value = (s64)imm;
2100 	reg->umin_value = imm;
2101 	reg->umax_value = imm;
2102 
2103 	reg->s32_min_value = (s32)imm;
2104 	reg->s32_max_value = (s32)imm;
2105 	reg->u32_min_value = (u32)imm;
2106 	reg->u32_max_value = (u32)imm;
2107 }
2108 
2109 /* Mark the unknown part of a register (variable offset or scalar value) as
2110  * known to have the value @imm.
2111  */
2112 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2113 {
2114 	/* Clear off and union(map_ptr, range) */
2115 	memset(((u8 *)reg) + sizeof(reg->type), 0,
2116 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2117 	reg->id = 0;
2118 	reg->ref_obj_id = 0;
2119 	___mark_reg_known(reg, imm);
2120 }
2121 
2122 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2123 {
2124 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2125 	reg->s32_min_value = (s32)imm;
2126 	reg->s32_max_value = (s32)imm;
2127 	reg->u32_min_value = (u32)imm;
2128 	reg->u32_max_value = (u32)imm;
2129 }
2130 
2131 /* Mark the 'variable offset' part of a register as zero.  This should be
2132  * used only on registers holding a pointer type.
2133  */
2134 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2135 {
2136 	__mark_reg_known(reg, 0);
2137 }
2138 
2139 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
2140 {
2141 	__mark_reg_known(reg, 0);
2142 	reg->type = SCALAR_VALUE;
2143 }
2144 
2145 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2146 				struct bpf_reg_state *regs, u32 regno)
2147 {
2148 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2149 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2150 		/* Something bad happened, let's kill all regs */
2151 		for (regno = 0; regno < MAX_BPF_REG; regno++)
2152 			__mark_reg_not_init(env, regs + regno);
2153 		return;
2154 	}
2155 	__mark_reg_known_zero(regs + regno);
2156 }
2157 
2158 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2159 			      bool first_slot, int dynptr_id)
2160 {
2161 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2162 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2163 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2164 	 */
2165 	__mark_reg_known_zero(reg);
2166 	reg->type = CONST_PTR_TO_DYNPTR;
2167 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2168 	reg->id = dynptr_id;
2169 	reg->dynptr.type = type;
2170 	reg->dynptr.first_slot = first_slot;
2171 }
2172 
2173 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2174 {
2175 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2176 		const struct bpf_map *map = reg->map_ptr;
2177 
2178 		if (map->inner_map_meta) {
2179 			reg->type = CONST_PTR_TO_MAP;
2180 			reg->map_ptr = map->inner_map_meta;
2181 			/* transfer reg's id which is unique for every map_lookup_elem
2182 			 * as UID of the inner map.
2183 			 */
2184 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
2185 				reg->map_uid = reg->id;
2186 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2187 			reg->type = PTR_TO_XDP_SOCK;
2188 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2189 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2190 			reg->type = PTR_TO_SOCKET;
2191 		} else {
2192 			reg->type = PTR_TO_MAP_VALUE;
2193 		}
2194 		return;
2195 	}
2196 
2197 	reg->type &= ~PTR_MAYBE_NULL;
2198 }
2199 
2200 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2201 				struct btf_field_graph_root *ds_head)
2202 {
2203 	__mark_reg_known_zero(&regs[regno]);
2204 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2205 	regs[regno].btf = ds_head->btf;
2206 	regs[regno].btf_id = ds_head->value_btf_id;
2207 	regs[regno].off = ds_head->node_offset;
2208 }
2209 
2210 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2211 {
2212 	return type_is_pkt_pointer(reg->type);
2213 }
2214 
2215 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2216 {
2217 	return reg_is_pkt_pointer(reg) ||
2218 	       reg->type == PTR_TO_PACKET_END;
2219 }
2220 
2221 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2222 {
2223 	return base_type(reg->type) == PTR_TO_MEM &&
2224 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2225 }
2226 
2227 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2228 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2229 				    enum bpf_reg_type which)
2230 {
2231 	/* The register can already have a range from prior markings.
2232 	 * This is fine as long as it hasn't been advanced from its
2233 	 * origin.
2234 	 */
2235 	return reg->type == which &&
2236 	       reg->id == 0 &&
2237 	       reg->off == 0 &&
2238 	       tnum_equals_const(reg->var_off, 0);
2239 }
2240 
2241 /* Reset the min/max bounds of a register */
2242 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2243 {
2244 	reg->smin_value = S64_MIN;
2245 	reg->smax_value = S64_MAX;
2246 	reg->umin_value = 0;
2247 	reg->umax_value = U64_MAX;
2248 
2249 	reg->s32_min_value = S32_MIN;
2250 	reg->s32_max_value = S32_MAX;
2251 	reg->u32_min_value = 0;
2252 	reg->u32_max_value = U32_MAX;
2253 }
2254 
2255 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2256 {
2257 	reg->smin_value = S64_MIN;
2258 	reg->smax_value = S64_MAX;
2259 	reg->umin_value = 0;
2260 	reg->umax_value = U64_MAX;
2261 }
2262 
2263 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2264 {
2265 	reg->s32_min_value = S32_MIN;
2266 	reg->s32_max_value = S32_MAX;
2267 	reg->u32_min_value = 0;
2268 	reg->u32_max_value = U32_MAX;
2269 }
2270 
2271 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2272 {
2273 	struct tnum var32_off = tnum_subreg(reg->var_off);
2274 
2275 	/* min signed is max(sign bit) | min(other bits) */
2276 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2277 			var32_off.value | (var32_off.mask & S32_MIN));
2278 	/* max signed is min(sign bit) | max(other bits) */
2279 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2280 			var32_off.value | (var32_off.mask & S32_MAX));
2281 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2282 	reg->u32_max_value = min(reg->u32_max_value,
2283 				 (u32)(var32_off.value | var32_off.mask));
2284 }
2285 
2286 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2287 {
2288 	/* min signed is max(sign bit) | min(other bits) */
2289 	reg->smin_value = max_t(s64, reg->smin_value,
2290 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2291 	/* max signed is min(sign bit) | max(other bits) */
2292 	reg->smax_value = min_t(s64, reg->smax_value,
2293 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2294 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2295 	reg->umax_value = min(reg->umax_value,
2296 			      reg->var_off.value | reg->var_off.mask);
2297 }
2298 
2299 static void __update_reg_bounds(struct bpf_reg_state *reg)
2300 {
2301 	__update_reg32_bounds(reg);
2302 	__update_reg64_bounds(reg);
2303 }
2304 
2305 /* Uses signed min/max values to inform unsigned, and vice-versa */
2306 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2307 {
2308 	/* Learn sign from signed bounds.
2309 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2310 	 * are the same, so combine.  This works even in the negative case, e.g.
2311 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2312 	 */
2313 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2314 		reg->s32_min_value = reg->u32_min_value =
2315 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2316 		reg->s32_max_value = reg->u32_max_value =
2317 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2318 		return;
2319 	}
2320 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2321 	 * boundary, so we must be careful.
2322 	 */
2323 	if ((s32)reg->u32_max_value >= 0) {
2324 		/* Positive.  We can't learn anything from the smin, but smax
2325 		 * is positive, hence safe.
2326 		 */
2327 		reg->s32_min_value = reg->u32_min_value;
2328 		reg->s32_max_value = reg->u32_max_value =
2329 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2330 	} else if ((s32)reg->u32_min_value < 0) {
2331 		/* Negative.  We can't learn anything from the smax, but smin
2332 		 * is negative, hence safe.
2333 		 */
2334 		reg->s32_min_value = reg->u32_min_value =
2335 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2336 		reg->s32_max_value = reg->u32_max_value;
2337 	}
2338 }
2339 
2340 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2341 {
2342 	/* Learn sign from signed bounds.
2343 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2344 	 * are the same, so combine.  This works even in the negative case, e.g.
2345 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2346 	 */
2347 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
2348 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2349 							  reg->umin_value);
2350 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2351 							  reg->umax_value);
2352 		return;
2353 	}
2354 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2355 	 * boundary, so we must be careful.
2356 	 */
2357 	if ((s64)reg->umax_value >= 0) {
2358 		/* Positive.  We can't learn anything from the smin, but smax
2359 		 * is positive, hence safe.
2360 		 */
2361 		reg->smin_value = reg->umin_value;
2362 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2363 							  reg->umax_value);
2364 	} else if ((s64)reg->umin_value < 0) {
2365 		/* Negative.  We can't learn anything from the smax, but smin
2366 		 * is negative, hence safe.
2367 		 */
2368 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2369 							  reg->umin_value);
2370 		reg->smax_value = reg->umax_value;
2371 	}
2372 }
2373 
2374 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2375 {
2376 	__reg32_deduce_bounds(reg);
2377 	__reg64_deduce_bounds(reg);
2378 }
2379 
2380 /* Attempts to improve var_off based on unsigned min/max information */
2381 static void __reg_bound_offset(struct bpf_reg_state *reg)
2382 {
2383 	struct tnum var64_off = tnum_intersect(reg->var_off,
2384 					       tnum_range(reg->umin_value,
2385 							  reg->umax_value));
2386 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2387 					       tnum_range(reg->u32_min_value,
2388 							  reg->u32_max_value));
2389 
2390 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2391 }
2392 
2393 static void reg_bounds_sync(struct bpf_reg_state *reg)
2394 {
2395 	/* We might have learned new bounds from the var_off. */
2396 	__update_reg_bounds(reg);
2397 	/* We might have learned something about the sign bit. */
2398 	__reg_deduce_bounds(reg);
2399 	/* We might have learned some bits from the bounds. */
2400 	__reg_bound_offset(reg);
2401 	/* Intersecting with the old var_off might have improved our bounds
2402 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2403 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2404 	 */
2405 	__update_reg_bounds(reg);
2406 }
2407 
2408 static bool __reg32_bound_s64(s32 a)
2409 {
2410 	return a >= 0 && a <= S32_MAX;
2411 }
2412 
2413 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2414 {
2415 	reg->umin_value = reg->u32_min_value;
2416 	reg->umax_value = reg->u32_max_value;
2417 
2418 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2419 	 * be positive otherwise set to worse case bounds and refine later
2420 	 * from tnum.
2421 	 */
2422 	if (__reg32_bound_s64(reg->s32_min_value) &&
2423 	    __reg32_bound_s64(reg->s32_max_value)) {
2424 		reg->smin_value = reg->s32_min_value;
2425 		reg->smax_value = reg->s32_max_value;
2426 	} else {
2427 		reg->smin_value = 0;
2428 		reg->smax_value = U32_MAX;
2429 	}
2430 }
2431 
2432 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2433 {
2434 	/* special case when 64-bit register has upper 32-bit register
2435 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
2436 	 * allowing us to use 32-bit bounds directly,
2437 	 */
2438 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2439 		__reg_assign_32_into_64(reg);
2440 	} else {
2441 		/* Otherwise the best we can do is push lower 32bit known and
2442 		 * unknown bits into register (var_off set from jmp logic)
2443 		 * then learn as much as possible from the 64-bit tnum
2444 		 * known and unknown bits. The previous smin/smax bounds are
2445 		 * invalid here because of jmp32 compare so mark them unknown
2446 		 * so they do not impact tnum bounds calculation.
2447 		 */
2448 		__mark_reg64_unbounded(reg);
2449 	}
2450 	reg_bounds_sync(reg);
2451 }
2452 
2453 static bool __reg64_bound_s32(s64 a)
2454 {
2455 	return a >= S32_MIN && a <= S32_MAX;
2456 }
2457 
2458 static bool __reg64_bound_u32(u64 a)
2459 {
2460 	return a >= U32_MIN && a <= U32_MAX;
2461 }
2462 
2463 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2464 {
2465 	__mark_reg32_unbounded(reg);
2466 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2467 		reg->s32_min_value = (s32)reg->smin_value;
2468 		reg->s32_max_value = (s32)reg->smax_value;
2469 	}
2470 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2471 		reg->u32_min_value = (u32)reg->umin_value;
2472 		reg->u32_max_value = (u32)reg->umax_value;
2473 	}
2474 	reg_bounds_sync(reg);
2475 }
2476 
2477 /* Mark a register as having a completely unknown (scalar) value. */
2478 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2479 			       struct bpf_reg_state *reg)
2480 {
2481 	/*
2482 	 * Clear type, off, and union(map_ptr, range) and
2483 	 * padding between 'type' and union
2484 	 */
2485 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2486 	reg->type = SCALAR_VALUE;
2487 	reg->id = 0;
2488 	reg->ref_obj_id = 0;
2489 	reg->var_off = tnum_unknown;
2490 	reg->frameno = 0;
2491 	reg->precise = !env->bpf_capable;
2492 	__mark_reg_unbounded(reg);
2493 }
2494 
2495 static void mark_reg_unknown(struct bpf_verifier_env *env,
2496 			     struct bpf_reg_state *regs, u32 regno)
2497 {
2498 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2499 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2500 		/* Something bad happened, let's kill all regs except FP */
2501 		for (regno = 0; regno < BPF_REG_FP; regno++)
2502 			__mark_reg_not_init(env, regs + regno);
2503 		return;
2504 	}
2505 	__mark_reg_unknown(env, regs + regno);
2506 }
2507 
2508 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2509 				struct bpf_reg_state *reg)
2510 {
2511 	__mark_reg_unknown(env, reg);
2512 	reg->type = NOT_INIT;
2513 }
2514 
2515 static void mark_reg_not_init(struct bpf_verifier_env *env,
2516 			      struct bpf_reg_state *regs, u32 regno)
2517 {
2518 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2519 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2520 		/* Something bad happened, let's kill all regs except FP */
2521 		for (regno = 0; regno < BPF_REG_FP; regno++)
2522 			__mark_reg_not_init(env, regs + regno);
2523 		return;
2524 	}
2525 	__mark_reg_not_init(env, regs + regno);
2526 }
2527 
2528 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2529 			    struct bpf_reg_state *regs, u32 regno,
2530 			    enum bpf_reg_type reg_type,
2531 			    struct btf *btf, u32 btf_id,
2532 			    enum bpf_type_flag flag)
2533 {
2534 	if (reg_type == SCALAR_VALUE) {
2535 		mark_reg_unknown(env, regs, regno);
2536 		return;
2537 	}
2538 	mark_reg_known_zero(env, regs, regno);
2539 	regs[regno].type = PTR_TO_BTF_ID | flag;
2540 	regs[regno].btf = btf;
2541 	regs[regno].btf_id = btf_id;
2542 	if (type_may_be_null(flag))
2543 		regs[regno].id = ++env->id_gen;
2544 }
2545 
2546 #define DEF_NOT_SUBREG	(0)
2547 static void init_reg_state(struct bpf_verifier_env *env,
2548 			   struct bpf_func_state *state)
2549 {
2550 	struct bpf_reg_state *regs = state->regs;
2551 	int i;
2552 
2553 	for (i = 0; i < MAX_BPF_REG; i++) {
2554 		mark_reg_not_init(env, regs, i);
2555 		regs[i].live = REG_LIVE_NONE;
2556 		regs[i].parent = NULL;
2557 		regs[i].subreg_def = DEF_NOT_SUBREG;
2558 	}
2559 
2560 	/* frame pointer */
2561 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2562 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2563 	regs[BPF_REG_FP].frameno = state->frameno;
2564 }
2565 
2566 #define BPF_MAIN_FUNC (-1)
2567 static void init_func_state(struct bpf_verifier_env *env,
2568 			    struct bpf_func_state *state,
2569 			    int callsite, int frameno, int subprogno)
2570 {
2571 	state->callsite = callsite;
2572 	state->frameno = frameno;
2573 	state->subprogno = subprogno;
2574 	state->callback_ret_range = tnum_range(0, 0);
2575 	init_reg_state(env, state);
2576 	mark_verifier_state_scratched(env);
2577 }
2578 
2579 /* Similar to push_stack(), but for async callbacks */
2580 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2581 						int insn_idx, int prev_insn_idx,
2582 						int subprog)
2583 {
2584 	struct bpf_verifier_stack_elem *elem;
2585 	struct bpf_func_state *frame;
2586 
2587 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2588 	if (!elem)
2589 		goto err;
2590 
2591 	elem->insn_idx = insn_idx;
2592 	elem->prev_insn_idx = prev_insn_idx;
2593 	elem->next = env->head;
2594 	elem->log_pos = env->log.end_pos;
2595 	env->head = elem;
2596 	env->stack_size++;
2597 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2598 		verbose(env,
2599 			"The sequence of %d jumps is too complex for async cb.\n",
2600 			env->stack_size);
2601 		goto err;
2602 	}
2603 	/* Unlike push_stack() do not copy_verifier_state().
2604 	 * The caller state doesn't matter.
2605 	 * This is async callback. It starts in a fresh stack.
2606 	 * Initialize it similar to do_check_common().
2607 	 */
2608 	elem->st.branches = 1;
2609 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2610 	if (!frame)
2611 		goto err;
2612 	init_func_state(env, frame,
2613 			BPF_MAIN_FUNC /* callsite */,
2614 			0 /* frameno within this callchain */,
2615 			subprog /* subprog number within this prog */);
2616 	elem->st.frame[0] = frame;
2617 	return &elem->st;
2618 err:
2619 	free_verifier_state(env->cur_state, true);
2620 	env->cur_state = NULL;
2621 	/* pop all elements and return */
2622 	while (!pop_stack(env, NULL, NULL, false));
2623 	return NULL;
2624 }
2625 
2626 
2627 enum reg_arg_type {
2628 	SRC_OP,		/* register is used as source operand */
2629 	DST_OP,		/* register is used as destination operand */
2630 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2631 };
2632 
2633 static int cmp_subprogs(const void *a, const void *b)
2634 {
2635 	return ((struct bpf_subprog_info *)a)->start -
2636 	       ((struct bpf_subprog_info *)b)->start;
2637 }
2638 
2639 static int find_subprog(struct bpf_verifier_env *env, int off)
2640 {
2641 	struct bpf_subprog_info *p;
2642 
2643 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2644 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2645 	if (!p)
2646 		return -ENOENT;
2647 	return p - env->subprog_info;
2648 
2649 }
2650 
2651 static int add_subprog(struct bpf_verifier_env *env, int off)
2652 {
2653 	int insn_cnt = env->prog->len;
2654 	int ret;
2655 
2656 	if (off >= insn_cnt || off < 0) {
2657 		verbose(env, "call to invalid destination\n");
2658 		return -EINVAL;
2659 	}
2660 	ret = find_subprog(env, off);
2661 	if (ret >= 0)
2662 		return ret;
2663 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2664 		verbose(env, "too many subprograms\n");
2665 		return -E2BIG;
2666 	}
2667 	/* determine subprog starts. The end is one before the next starts */
2668 	env->subprog_info[env->subprog_cnt++].start = off;
2669 	sort(env->subprog_info, env->subprog_cnt,
2670 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2671 	return env->subprog_cnt - 1;
2672 }
2673 
2674 #define MAX_KFUNC_DESCS 256
2675 #define MAX_KFUNC_BTFS	256
2676 
2677 struct bpf_kfunc_desc {
2678 	struct btf_func_model func_model;
2679 	u32 func_id;
2680 	s32 imm;
2681 	u16 offset;
2682 	unsigned long addr;
2683 };
2684 
2685 struct bpf_kfunc_btf {
2686 	struct btf *btf;
2687 	struct module *module;
2688 	u16 offset;
2689 };
2690 
2691 struct bpf_kfunc_desc_tab {
2692 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2693 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2694 	 * available, therefore at the end of verification do_misc_fixups()
2695 	 * sorts this by imm and offset.
2696 	 */
2697 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2698 	u32 nr_descs;
2699 };
2700 
2701 struct bpf_kfunc_btf_tab {
2702 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2703 	u32 nr_descs;
2704 };
2705 
2706 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2707 {
2708 	const struct bpf_kfunc_desc *d0 = a;
2709 	const struct bpf_kfunc_desc *d1 = b;
2710 
2711 	/* func_id is not greater than BTF_MAX_TYPE */
2712 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2713 }
2714 
2715 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2716 {
2717 	const struct bpf_kfunc_btf *d0 = a;
2718 	const struct bpf_kfunc_btf *d1 = b;
2719 
2720 	return d0->offset - d1->offset;
2721 }
2722 
2723 static const struct bpf_kfunc_desc *
2724 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2725 {
2726 	struct bpf_kfunc_desc desc = {
2727 		.func_id = func_id,
2728 		.offset = offset,
2729 	};
2730 	struct bpf_kfunc_desc_tab *tab;
2731 
2732 	tab = prog->aux->kfunc_tab;
2733 	return bsearch(&desc, tab->descs, tab->nr_descs,
2734 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2735 }
2736 
2737 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2738 		       u16 btf_fd_idx, u8 **func_addr)
2739 {
2740 	const struct bpf_kfunc_desc *desc;
2741 
2742 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2743 	if (!desc)
2744 		return -EFAULT;
2745 
2746 	*func_addr = (u8 *)desc->addr;
2747 	return 0;
2748 }
2749 
2750 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2751 					 s16 offset)
2752 {
2753 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2754 	struct bpf_kfunc_btf_tab *tab;
2755 	struct bpf_kfunc_btf *b;
2756 	struct module *mod;
2757 	struct btf *btf;
2758 	int btf_fd;
2759 
2760 	tab = env->prog->aux->kfunc_btf_tab;
2761 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2762 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2763 	if (!b) {
2764 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2765 			verbose(env, "too many different module BTFs\n");
2766 			return ERR_PTR(-E2BIG);
2767 		}
2768 
2769 		if (bpfptr_is_null(env->fd_array)) {
2770 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2771 			return ERR_PTR(-EPROTO);
2772 		}
2773 
2774 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2775 					    offset * sizeof(btf_fd),
2776 					    sizeof(btf_fd)))
2777 			return ERR_PTR(-EFAULT);
2778 
2779 		btf = btf_get_by_fd(btf_fd);
2780 		if (IS_ERR(btf)) {
2781 			verbose(env, "invalid module BTF fd specified\n");
2782 			return btf;
2783 		}
2784 
2785 		if (!btf_is_module(btf)) {
2786 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2787 			btf_put(btf);
2788 			return ERR_PTR(-EINVAL);
2789 		}
2790 
2791 		mod = btf_try_get_module(btf);
2792 		if (!mod) {
2793 			btf_put(btf);
2794 			return ERR_PTR(-ENXIO);
2795 		}
2796 
2797 		b = &tab->descs[tab->nr_descs++];
2798 		b->btf = btf;
2799 		b->module = mod;
2800 		b->offset = offset;
2801 
2802 		/* sort() reorders entries by value, so b may no longer point
2803 		 * to the right entry after this
2804 		 */
2805 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2806 		     kfunc_btf_cmp_by_off, NULL);
2807 	} else {
2808 		btf = b->btf;
2809 	}
2810 
2811 	return btf;
2812 }
2813 
2814 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2815 {
2816 	if (!tab)
2817 		return;
2818 
2819 	while (tab->nr_descs--) {
2820 		module_put(tab->descs[tab->nr_descs].module);
2821 		btf_put(tab->descs[tab->nr_descs].btf);
2822 	}
2823 	kfree(tab);
2824 }
2825 
2826 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2827 {
2828 	if (offset) {
2829 		if (offset < 0) {
2830 			/* In the future, this can be allowed to increase limit
2831 			 * of fd index into fd_array, interpreted as u16.
2832 			 */
2833 			verbose(env, "negative offset disallowed for kernel module function call\n");
2834 			return ERR_PTR(-EINVAL);
2835 		}
2836 
2837 		return __find_kfunc_desc_btf(env, offset);
2838 	}
2839 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2840 }
2841 
2842 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2843 {
2844 	const struct btf_type *func, *func_proto;
2845 	struct bpf_kfunc_btf_tab *btf_tab;
2846 	struct bpf_kfunc_desc_tab *tab;
2847 	struct bpf_prog_aux *prog_aux;
2848 	struct bpf_kfunc_desc *desc;
2849 	const char *func_name;
2850 	struct btf *desc_btf;
2851 	unsigned long call_imm;
2852 	unsigned long addr;
2853 	int err;
2854 
2855 	prog_aux = env->prog->aux;
2856 	tab = prog_aux->kfunc_tab;
2857 	btf_tab = prog_aux->kfunc_btf_tab;
2858 	if (!tab) {
2859 		if (!btf_vmlinux) {
2860 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2861 			return -ENOTSUPP;
2862 		}
2863 
2864 		if (!env->prog->jit_requested) {
2865 			verbose(env, "JIT is required for calling kernel function\n");
2866 			return -ENOTSUPP;
2867 		}
2868 
2869 		if (!bpf_jit_supports_kfunc_call()) {
2870 			verbose(env, "JIT does not support calling kernel function\n");
2871 			return -ENOTSUPP;
2872 		}
2873 
2874 		if (!env->prog->gpl_compatible) {
2875 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2876 			return -EINVAL;
2877 		}
2878 
2879 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2880 		if (!tab)
2881 			return -ENOMEM;
2882 		prog_aux->kfunc_tab = tab;
2883 	}
2884 
2885 	/* func_id == 0 is always invalid, but instead of returning an error, be
2886 	 * conservative and wait until the code elimination pass before returning
2887 	 * error, so that invalid calls that get pruned out can be in BPF programs
2888 	 * loaded from userspace.  It is also required that offset be untouched
2889 	 * for such calls.
2890 	 */
2891 	if (!func_id && !offset)
2892 		return 0;
2893 
2894 	if (!btf_tab && offset) {
2895 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2896 		if (!btf_tab)
2897 			return -ENOMEM;
2898 		prog_aux->kfunc_btf_tab = btf_tab;
2899 	}
2900 
2901 	desc_btf = find_kfunc_desc_btf(env, offset);
2902 	if (IS_ERR(desc_btf)) {
2903 		verbose(env, "failed to find BTF for kernel function\n");
2904 		return PTR_ERR(desc_btf);
2905 	}
2906 
2907 	if (find_kfunc_desc(env->prog, func_id, offset))
2908 		return 0;
2909 
2910 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2911 		verbose(env, "too many different kernel function calls\n");
2912 		return -E2BIG;
2913 	}
2914 
2915 	func = btf_type_by_id(desc_btf, func_id);
2916 	if (!func || !btf_type_is_func(func)) {
2917 		verbose(env, "kernel btf_id %u is not a function\n",
2918 			func_id);
2919 		return -EINVAL;
2920 	}
2921 	func_proto = btf_type_by_id(desc_btf, func->type);
2922 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2923 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2924 			func_id);
2925 		return -EINVAL;
2926 	}
2927 
2928 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2929 	addr = kallsyms_lookup_name(func_name);
2930 	if (!addr) {
2931 		verbose(env, "cannot find address for kernel function %s\n",
2932 			func_name);
2933 		return -EINVAL;
2934 	}
2935 	specialize_kfunc(env, func_id, offset, &addr);
2936 
2937 	if (bpf_jit_supports_far_kfunc_call()) {
2938 		call_imm = func_id;
2939 	} else {
2940 		call_imm = BPF_CALL_IMM(addr);
2941 		/* Check whether the relative offset overflows desc->imm */
2942 		if ((unsigned long)(s32)call_imm != call_imm) {
2943 			verbose(env, "address of kernel function %s is out of range\n",
2944 				func_name);
2945 			return -EINVAL;
2946 		}
2947 	}
2948 
2949 	if (bpf_dev_bound_kfunc_id(func_id)) {
2950 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2951 		if (err)
2952 			return err;
2953 	}
2954 
2955 	desc = &tab->descs[tab->nr_descs++];
2956 	desc->func_id = func_id;
2957 	desc->imm = call_imm;
2958 	desc->offset = offset;
2959 	desc->addr = addr;
2960 	err = btf_distill_func_proto(&env->log, desc_btf,
2961 				     func_proto, func_name,
2962 				     &desc->func_model);
2963 	if (!err)
2964 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2965 		     kfunc_desc_cmp_by_id_off, NULL);
2966 	return err;
2967 }
2968 
2969 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2970 {
2971 	const struct bpf_kfunc_desc *d0 = a;
2972 	const struct bpf_kfunc_desc *d1 = b;
2973 
2974 	if (d0->imm != d1->imm)
2975 		return d0->imm < d1->imm ? -1 : 1;
2976 	if (d0->offset != d1->offset)
2977 		return d0->offset < d1->offset ? -1 : 1;
2978 	return 0;
2979 }
2980 
2981 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2982 {
2983 	struct bpf_kfunc_desc_tab *tab;
2984 
2985 	tab = prog->aux->kfunc_tab;
2986 	if (!tab)
2987 		return;
2988 
2989 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2990 	     kfunc_desc_cmp_by_imm_off, NULL);
2991 }
2992 
2993 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2994 {
2995 	return !!prog->aux->kfunc_tab;
2996 }
2997 
2998 const struct btf_func_model *
2999 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3000 			 const struct bpf_insn *insn)
3001 {
3002 	const struct bpf_kfunc_desc desc = {
3003 		.imm = insn->imm,
3004 		.offset = insn->off,
3005 	};
3006 	const struct bpf_kfunc_desc *res;
3007 	struct bpf_kfunc_desc_tab *tab;
3008 
3009 	tab = prog->aux->kfunc_tab;
3010 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3011 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3012 
3013 	return res ? &res->func_model : NULL;
3014 }
3015 
3016 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3017 {
3018 	struct bpf_subprog_info *subprog = env->subprog_info;
3019 	struct bpf_insn *insn = env->prog->insnsi;
3020 	int i, ret, insn_cnt = env->prog->len;
3021 
3022 	/* Add entry function. */
3023 	ret = add_subprog(env, 0);
3024 	if (ret)
3025 		return ret;
3026 
3027 	for (i = 0; i < insn_cnt; i++, insn++) {
3028 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3029 		    !bpf_pseudo_kfunc_call(insn))
3030 			continue;
3031 
3032 		if (!env->bpf_capable) {
3033 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3034 			return -EPERM;
3035 		}
3036 
3037 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3038 			ret = add_subprog(env, i + insn->imm + 1);
3039 		else
3040 			ret = add_kfunc_call(env, insn->imm, insn->off);
3041 
3042 		if (ret < 0)
3043 			return ret;
3044 	}
3045 
3046 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3047 	 * logic. 'subprog_cnt' should not be increased.
3048 	 */
3049 	subprog[env->subprog_cnt].start = insn_cnt;
3050 
3051 	if (env->log.level & BPF_LOG_LEVEL2)
3052 		for (i = 0; i < env->subprog_cnt; i++)
3053 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3054 
3055 	return 0;
3056 }
3057 
3058 static int check_subprogs(struct bpf_verifier_env *env)
3059 {
3060 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3061 	struct bpf_subprog_info *subprog = env->subprog_info;
3062 	struct bpf_insn *insn = env->prog->insnsi;
3063 	int insn_cnt = env->prog->len;
3064 
3065 	/* now check that all jumps are within the same subprog */
3066 	subprog_start = subprog[cur_subprog].start;
3067 	subprog_end = subprog[cur_subprog + 1].start;
3068 	for (i = 0; i < insn_cnt; i++) {
3069 		u8 code = insn[i].code;
3070 
3071 		if (code == (BPF_JMP | BPF_CALL) &&
3072 		    insn[i].src_reg == 0 &&
3073 		    insn[i].imm == BPF_FUNC_tail_call) {
3074 			subprog[cur_subprog].has_tail_call = true;
3075 			subprog[cur_subprog].tail_call_reachable = true;
3076 		}
3077 		if (BPF_CLASS(code) == BPF_LD &&
3078 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3079 			subprog[cur_subprog].has_ld_abs = true;
3080 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3081 			goto next;
3082 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3083 			goto next;
3084 		if (code == (BPF_JMP32 | BPF_JA))
3085 			off = i + insn[i].imm + 1;
3086 		else
3087 			off = i + insn[i].off + 1;
3088 		if (off < subprog_start || off >= subprog_end) {
3089 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3090 			return -EINVAL;
3091 		}
3092 next:
3093 		if (i == subprog_end - 1) {
3094 			/* to avoid fall-through from one subprog into another
3095 			 * the last insn of the subprog should be either exit
3096 			 * or unconditional jump back
3097 			 */
3098 			if (code != (BPF_JMP | BPF_EXIT) &&
3099 			    code != (BPF_JMP32 | BPF_JA) &&
3100 			    code != (BPF_JMP | BPF_JA)) {
3101 				verbose(env, "last insn is not an exit or jmp\n");
3102 				return -EINVAL;
3103 			}
3104 			subprog_start = subprog_end;
3105 			cur_subprog++;
3106 			if (cur_subprog < env->subprog_cnt)
3107 				subprog_end = subprog[cur_subprog + 1].start;
3108 		}
3109 	}
3110 	return 0;
3111 }
3112 
3113 /* Parentage chain of this register (or stack slot) should take care of all
3114  * issues like callee-saved registers, stack slot allocation time, etc.
3115  */
3116 static int mark_reg_read(struct bpf_verifier_env *env,
3117 			 const struct bpf_reg_state *state,
3118 			 struct bpf_reg_state *parent, u8 flag)
3119 {
3120 	bool writes = parent == state->parent; /* Observe write marks */
3121 	int cnt = 0;
3122 
3123 	while (parent) {
3124 		/* if read wasn't screened by an earlier write ... */
3125 		if (writes && state->live & REG_LIVE_WRITTEN)
3126 			break;
3127 		if (parent->live & REG_LIVE_DONE) {
3128 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3129 				reg_type_str(env, parent->type),
3130 				parent->var_off.value, parent->off);
3131 			return -EFAULT;
3132 		}
3133 		/* The first condition is more likely to be true than the
3134 		 * second, checked it first.
3135 		 */
3136 		if ((parent->live & REG_LIVE_READ) == flag ||
3137 		    parent->live & REG_LIVE_READ64)
3138 			/* The parentage chain never changes and
3139 			 * this parent was already marked as LIVE_READ.
3140 			 * There is no need to keep walking the chain again and
3141 			 * keep re-marking all parents as LIVE_READ.
3142 			 * This case happens when the same register is read
3143 			 * multiple times without writes into it in-between.
3144 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3145 			 * then no need to set the weak REG_LIVE_READ32.
3146 			 */
3147 			break;
3148 		/* ... then we depend on parent's value */
3149 		parent->live |= flag;
3150 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3151 		if (flag == REG_LIVE_READ64)
3152 			parent->live &= ~REG_LIVE_READ32;
3153 		state = parent;
3154 		parent = state->parent;
3155 		writes = true;
3156 		cnt++;
3157 	}
3158 
3159 	if (env->longest_mark_read_walk < cnt)
3160 		env->longest_mark_read_walk = cnt;
3161 	return 0;
3162 }
3163 
3164 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3165 {
3166 	struct bpf_func_state *state = func(env, reg);
3167 	int spi, ret;
3168 
3169 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3170 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3171 	 * check_kfunc_call.
3172 	 */
3173 	if (reg->type == CONST_PTR_TO_DYNPTR)
3174 		return 0;
3175 	spi = dynptr_get_spi(env, reg);
3176 	if (spi < 0)
3177 		return spi;
3178 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3179 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3180 	 * read.
3181 	 */
3182 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3183 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3184 	if (ret)
3185 		return ret;
3186 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3187 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3188 }
3189 
3190 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3191 			  int spi, int nr_slots)
3192 {
3193 	struct bpf_func_state *state = func(env, reg);
3194 	int err, i;
3195 
3196 	for (i = 0; i < nr_slots; i++) {
3197 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3198 
3199 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3200 		if (err)
3201 			return err;
3202 
3203 		mark_stack_slot_scratched(env, spi - i);
3204 	}
3205 
3206 	return 0;
3207 }
3208 
3209 /* This function is supposed to be used by the following 32-bit optimization
3210  * code only. It returns TRUE if the source or destination register operates
3211  * on 64-bit, otherwise return FALSE.
3212  */
3213 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3214 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3215 {
3216 	u8 code, class, op;
3217 
3218 	code = insn->code;
3219 	class = BPF_CLASS(code);
3220 	op = BPF_OP(code);
3221 	if (class == BPF_JMP) {
3222 		/* BPF_EXIT for "main" will reach here. Return TRUE
3223 		 * conservatively.
3224 		 */
3225 		if (op == BPF_EXIT)
3226 			return true;
3227 		if (op == BPF_CALL) {
3228 			/* BPF to BPF call will reach here because of marking
3229 			 * caller saved clobber with DST_OP_NO_MARK for which we
3230 			 * don't care the register def because they are anyway
3231 			 * marked as NOT_INIT already.
3232 			 */
3233 			if (insn->src_reg == BPF_PSEUDO_CALL)
3234 				return false;
3235 			/* Helper call will reach here because of arg type
3236 			 * check, conservatively return TRUE.
3237 			 */
3238 			if (t == SRC_OP)
3239 				return true;
3240 
3241 			return false;
3242 		}
3243 	}
3244 
3245 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3246 		return false;
3247 
3248 	if (class == BPF_ALU64 || class == BPF_JMP ||
3249 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3250 		return true;
3251 
3252 	if (class == BPF_ALU || class == BPF_JMP32)
3253 		return false;
3254 
3255 	if (class == BPF_LDX) {
3256 		if (t != SRC_OP)
3257 			return BPF_SIZE(code) == BPF_DW;
3258 		/* LDX source must be ptr. */
3259 		return true;
3260 	}
3261 
3262 	if (class == BPF_STX) {
3263 		/* BPF_STX (including atomic variants) has multiple source
3264 		 * operands, one of which is a ptr. Check whether the caller is
3265 		 * asking about it.
3266 		 */
3267 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3268 			return true;
3269 		return BPF_SIZE(code) == BPF_DW;
3270 	}
3271 
3272 	if (class == BPF_LD) {
3273 		u8 mode = BPF_MODE(code);
3274 
3275 		/* LD_IMM64 */
3276 		if (mode == BPF_IMM)
3277 			return true;
3278 
3279 		/* Both LD_IND and LD_ABS return 32-bit data. */
3280 		if (t != SRC_OP)
3281 			return  false;
3282 
3283 		/* Implicit ctx ptr. */
3284 		if (regno == BPF_REG_6)
3285 			return true;
3286 
3287 		/* Explicit source could be any width. */
3288 		return true;
3289 	}
3290 
3291 	if (class == BPF_ST)
3292 		/* The only source register for BPF_ST is a ptr. */
3293 		return true;
3294 
3295 	/* Conservatively return true at default. */
3296 	return true;
3297 }
3298 
3299 /* Return the regno defined by the insn, or -1. */
3300 static int insn_def_regno(const struct bpf_insn *insn)
3301 {
3302 	switch (BPF_CLASS(insn->code)) {
3303 	case BPF_JMP:
3304 	case BPF_JMP32:
3305 	case BPF_ST:
3306 		return -1;
3307 	case BPF_STX:
3308 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3309 		    (insn->imm & BPF_FETCH)) {
3310 			if (insn->imm == BPF_CMPXCHG)
3311 				return BPF_REG_0;
3312 			else
3313 				return insn->src_reg;
3314 		} else {
3315 			return -1;
3316 		}
3317 	default:
3318 		return insn->dst_reg;
3319 	}
3320 }
3321 
3322 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3323 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3324 {
3325 	int dst_reg = insn_def_regno(insn);
3326 
3327 	if (dst_reg == -1)
3328 		return false;
3329 
3330 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3331 }
3332 
3333 static void mark_insn_zext(struct bpf_verifier_env *env,
3334 			   struct bpf_reg_state *reg)
3335 {
3336 	s32 def_idx = reg->subreg_def;
3337 
3338 	if (def_idx == DEF_NOT_SUBREG)
3339 		return;
3340 
3341 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3342 	/* The dst will be zero extended, so won't be sub-register anymore. */
3343 	reg->subreg_def = DEF_NOT_SUBREG;
3344 }
3345 
3346 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3347 			   enum reg_arg_type t)
3348 {
3349 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3350 	struct bpf_reg_state *reg;
3351 	bool rw64;
3352 
3353 	if (regno >= MAX_BPF_REG) {
3354 		verbose(env, "R%d is invalid\n", regno);
3355 		return -EINVAL;
3356 	}
3357 
3358 	mark_reg_scratched(env, regno);
3359 
3360 	reg = &regs[regno];
3361 	rw64 = is_reg64(env, insn, regno, reg, t);
3362 	if (t == SRC_OP) {
3363 		/* check whether register used as source operand can be read */
3364 		if (reg->type == NOT_INIT) {
3365 			verbose(env, "R%d !read_ok\n", regno);
3366 			return -EACCES;
3367 		}
3368 		/* We don't need to worry about FP liveness because it's read-only */
3369 		if (regno == BPF_REG_FP)
3370 			return 0;
3371 
3372 		if (rw64)
3373 			mark_insn_zext(env, reg);
3374 
3375 		return mark_reg_read(env, reg, reg->parent,
3376 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3377 	} else {
3378 		/* check whether register used as dest operand can be written to */
3379 		if (regno == BPF_REG_FP) {
3380 			verbose(env, "frame pointer is read only\n");
3381 			return -EACCES;
3382 		}
3383 		reg->live |= REG_LIVE_WRITTEN;
3384 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3385 		if (t == DST_OP)
3386 			mark_reg_unknown(env, regs, regno);
3387 	}
3388 	return 0;
3389 }
3390 
3391 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3392 			 enum reg_arg_type t)
3393 {
3394 	struct bpf_verifier_state *vstate = env->cur_state;
3395 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3396 
3397 	return __check_reg_arg(env, state->regs, regno, t);
3398 }
3399 
3400 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3401 {
3402 	env->insn_aux_data[idx].jmp_point = true;
3403 }
3404 
3405 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3406 {
3407 	return env->insn_aux_data[insn_idx].jmp_point;
3408 }
3409 
3410 /* for any branch, call, exit record the history of jmps in the given state */
3411 static int push_jmp_history(struct bpf_verifier_env *env,
3412 			    struct bpf_verifier_state *cur)
3413 {
3414 	u32 cnt = cur->jmp_history_cnt;
3415 	struct bpf_idx_pair *p;
3416 	size_t alloc_size;
3417 
3418 	if (!is_jmp_point(env, env->insn_idx))
3419 		return 0;
3420 
3421 	cnt++;
3422 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3423 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3424 	if (!p)
3425 		return -ENOMEM;
3426 	p[cnt - 1].idx = env->insn_idx;
3427 	p[cnt - 1].prev_idx = env->prev_insn_idx;
3428 	cur->jmp_history = p;
3429 	cur->jmp_history_cnt = cnt;
3430 	return 0;
3431 }
3432 
3433 /* Backtrack one insn at a time. If idx is not at the top of recorded
3434  * history then previous instruction came from straight line execution.
3435  * Return -ENOENT if we exhausted all instructions within given state.
3436  *
3437  * It's legal to have a bit of a looping with the same starting and ending
3438  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3439  * instruction index is the same as state's first_idx doesn't mean we are
3440  * done. If there is still some jump history left, we should keep going. We
3441  * need to take into account that we might have a jump history between given
3442  * state's parent and itself, due to checkpointing. In this case, we'll have
3443  * history entry recording a jump from last instruction of parent state and
3444  * first instruction of given state.
3445  */
3446 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3447 			     u32 *history)
3448 {
3449 	u32 cnt = *history;
3450 
3451 	if (i == st->first_insn_idx) {
3452 		if (cnt == 0)
3453 			return -ENOENT;
3454 		if (cnt == 1 && st->jmp_history[0].idx == i)
3455 			return -ENOENT;
3456 	}
3457 
3458 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3459 		i = st->jmp_history[cnt - 1].prev_idx;
3460 		(*history)--;
3461 	} else {
3462 		i--;
3463 	}
3464 	return i;
3465 }
3466 
3467 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3468 {
3469 	const struct btf_type *func;
3470 	struct btf *desc_btf;
3471 
3472 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3473 		return NULL;
3474 
3475 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3476 	if (IS_ERR(desc_btf))
3477 		return "<error>";
3478 
3479 	func = btf_type_by_id(desc_btf, insn->imm);
3480 	return btf_name_by_offset(desc_btf, func->name_off);
3481 }
3482 
3483 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3484 {
3485 	bt->frame = frame;
3486 }
3487 
3488 static inline void bt_reset(struct backtrack_state *bt)
3489 {
3490 	struct bpf_verifier_env *env = bt->env;
3491 
3492 	memset(bt, 0, sizeof(*bt));
3493 	bt->env = env;
3494 }
3495 
3496 static inline u32 bt_empty(struct backtrack_state *bt)
3497 {
3498 	u64 mask = 0;
3499 	int i;
3500 
3501 	for (i = 0; i <= bt->frame; i++)
3502 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3503 
3504 	return mask == 0;
3505 }
3506 
3507 static inline int bt_subprog_enter(struct backtrack_state *bt)
3508 {
3509 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3510 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3511 		WARN_ONCE(1, "verifier backtracking bug");
3512 		return -EFAULT;
3513 	}
3514 	bt->frame++;
3515 	return 0;
3516 }
3517 
3518 static inline int bt_subprog_exit(struct backtrack_state *bt)
3519 {
3520 	if (bt->frame == 0) {
3521 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3522 		WARN_ONCE(1, "verifier backtracking bug");
3523 		return -EFAULT;
3524 	}
3525 	bt->frame--;
3526 	return 0;
3527 }
3528 
3529 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3530 {
3531 	bt->reg_masks[frame] |= 1 << reg;
3532 }
3533 
3534 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3535 {
3536 	bt->reg_masks[frame] &= ~(1 << reg);
3537 }
3538 
3539 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3540 {
3541 	bt_set_frame_reg(bt, bt->frame, reg);
3542 }
3543 
3544 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3545 {
3546 	bt_clear_frame_reg(bt, bt->frame, reg);
3547 }
3548 
3549 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3550 {
3551 	bt->stack_masks[frame] |= 1ull << slot;
3552 }
3553 
3554 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3555 {
3556 	bt->stack_masks[frame] &= ~(1ull << slot);
3557 }
3558 
3559 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3560 {
3561 	bt_set_frame_slot(bt, bt->frame, slot);
3562 }
3563 
3564 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3565 {
3566 	bt_clear_frame_slot(bt, bt->frame, slot);
3567 }
3568 
3569 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3570 {
3571 	return bt->reg_masks[frame];
3572 }
3573 
3574 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3575 {
3576 	return bt->reg_masks[bt->frame];
3577 }
3578 
3579 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3580 {
3581 	return bt->stack_masks[frame];
3582 }
3583 
3584 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3585 {
3586 	return bt->stack_masks[bt->frame];
3587 }
3588 
3589 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3590 {
3591 	return bt->reg_masks[bt->frame] & (1 << reg);
3592 }
3593 
3594 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3595 {
3596 	return bt->stack_masks[bt->frame] & (1ull << slot);
3597 }
3598 
3599 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3600 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3601 {
3602 	DECLARE_BITMAP(mask, 64);
3603 	bool first = true;
3604 	int i, n;
3605 
3606 	buf[0] = '\0';
3607 
3608 	bitmap_from_u64(mask, reg_mask);
3609 	for_each_set_bit(i, mask, 32) {
3610 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3611 		first = false;
3612 		buf += n;
3613 		buf_sz -= n;
3614 		if (buf_sz < 0)
3615 			break;
3616 	}
3617 }
3618 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3619 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3620 {
3621 	DECLARE_BITMAP(mask, 64);
3622 	bool first = true;
3623 	int i, n;
3624 
3625 	buf[0] = '\0';
3626 
3627 	bitmap_from_u64(mask, stack_mask);
3628 	for_each_set_bit(i, mask, 64) {
3629 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3630 		first = false;
3631 		buf += n;
3632 		buf_sz -= n;
3633 		if (buf_sz < 0)
3634 			break;
3635 	}
3636 }
3637 
3638 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3639 
3640 /* For given verifier state backtrack_insn() is called from the last insn to
3641  * the first insn. Its purpose is to compute a bitmask of registers and
3642  * stack slots that needs precision in the parent verifier state.
3643  *
3644  * @idx is an index of the instruction we are currently processing;
3645  * @subseq_idx is an index of the subsequent instruction that:
3646  *   - *would be* executed next, if jump history is viewed in forward order;
3647  *   - *was* processed previously during backtracking.
3648  */
3649 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3650 			  struct backtrack_state *bt)
3651 {
3652 	const struct bpf_insn_cbs cbs = {
3653 		.cb_call	= disasm_kfunc_name,
3654 		.cb_print	= verbose,
3655 		.private_data	= env,
3656 	};
3657 	struct bpf_insn *insn = env->prog->insnsi + idx;
3658 	u8 class = BPF_CLASS(insn->code);
3659 	u8 opcode = BPF_OP(insn->code);
3660 	u8 mode = BPF_MODE(insn->code);
3661 	u32 dreg = insn->dst_reg;
3662 	u32 sreg = insn->src_reg;
3663 	u32 spi, i;
3664 
3665 	if (insn->code == 0)
3666 		return 0;
3667 	if (env->log.level & BPF_LOG_LEVEL2) {
3668 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3669 		verbose(env, "mark_precise: frame%d: regs=%s ",
3670 			bt->frame, env->tmp_str_buf);
3671 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3672 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3673 		verbose(env, "%d: ", idx);
3674 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3675 	}
3676 
3677 	if (class == BPF_ALU || class == BPF_ALU64) {
3678 		if (!bt_is_reg_set(bt, dreg))
3679 			return 0;
3680 		if (opcode == BPF_END || opcode == BPF_NEG) {
3681 			/* sreg is reserved and unused
3682 			 * dreg still need precision before this insn
3683 			 */
3684 			return 0;
3685 		} else if (opcode == BPF_MOV) {
3686 			if (BPF_SRC(insn->code) == BPF_X) {
3687 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3688 				 * dreg needs precision after this insn
3689 				 * sreg needs precision before this insn
3690 				 */
3691 				bt_clear_reg(bt, dreg);
3692 				if (sreg != BPF_REG_FP)
3693 					bt_set_reg(bt, sreg);
3694 			} else {
3695 				/* dreg = K
3696 				 * dreg needs precision after this insn.
3697 				 * Corresponding register is already marked
3698 				 * as precise=true in this verifier state.
3699 				 * No further markings in parent are necessary
3700 				 */
3701 				bt_clear_reg(bt, dreg);
3702 			}
3703 		} else {
3704 			if (BPF_SRC(insn->code) == BPF_X) {
3705 				/* dreg += sreg
3706 				 * both dreg and sreg need precision
3707 				 * before this insn
3708 				 */
3709 				if (sreg != BPF_REG_FP)
3710 					bt_set_reg(bt, sreg);
3711 			} /* else dreg += K
3712 			   * dreg still needs precision before this insn
3713 			   */
3714 		}
3715 	} else if (class == BPF_LDX) {
3716 		if (!bt_is_reg_set(bt, dreg))
3717 			return 0;
3718 		bt_clear_reg(bt, dreg);
3719 
3720 		/* scalars can only be spilled into stack w/o losing precision.
3721 		 * Load from any other memory can be zero extended.
3722 		 * The desire to keep that precision is already indicated
3723 		 * by 'precise' mark in corresponding register of this state.
3724 		 * No further tracking necessary.
3725 		 */
3726 		if (insn->src_reg != BPF_REG_FP)
3727 			return 0;
3728 
3729 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3730 		 * that [fp - off] slot contains scalar that needs to be
3731 		 * tracked with precision
3732 		 */
3733 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3734 		if (spi >= 64) {
3735 			verbose(env, "BUG spi %d\n", spi);
3736 			WARN_ONCE(1, "verifier backtracking bug");
3737 			return -EFAULT;
3738 		}
3739 		bt_set_slot(bt, spi);
3740 	} else if (class == BPF_STX || class == BPF_ST) {
3741 		if (bt_is_reg_set(bt, dreg))
3742 			/* stx & st shouldn't be using _scalar_ dst_reg
3743 			 * to access memory. It means backtracking
3744 			 * encountered a case of pointer subtraction.
3745 			 */
3746 			return -ENOTSUPP;
3747 		/* scalars can only be spilled into stack */
3748 		if (insn->dst_reg != BPF_REG_FP)
3749 			return 0;
3750 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3751 		if (spi >= 64) {
3752 			verbose(env, "BUG spi %d\n", spi);
3753 			WARN_ONCE(1, "verifier backtracking bug");
3754 			return -EFAULT;
3755 		}
3756 		if (!bt_is_slot_set(bt, spi))
3757 			return 0;
3758 		bt_clear_slot(bt, spi);
3759 		if (class == BPF_STX)
3760 			bt_set_reg(bt, sreg);
3761 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3762 		if (bpf_pseudo_call(insn)) {
3763 			int subprog_insn_idx, subprog;
3764 
3765 			subprog_insn_idx = idx + insn->imm + 1;
3766 			subprog = find_subprog(env, subprog_insn_idx);
3767 			if (subprog < 0)
3768 				return -EFAULT;
3769 
3770 			if (subprog_is_global(env, subprog)) {
3771 				/* check that jump history doesn't have any
3772 				 * extra instructions from subprog; the next
3773 				 * instruction after call to global subprog
3774 				 * should be literally next instruction in
3775 				 * caller program
3776 				 */
3777 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3778 				/* r1-r5 are invalidated after subprog call,
3779 				 * so for global func call it shouldn't be set
3780 				 * anymore
3781 				 */
3782 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3783 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3784 					WARN_ONCE(1, "verifier backtracking bug");
3785 					return -EFAULT;
3786 				}
3787 				/* global subprog always sets R0 */
3788 				bt_clear_reg(bt, BPF_REG_0);
3789 				return 0;
3790 			} else {
3791 				/* static subprog call instruction, which
3792 				 * means that we are exiting current subprog,
3793 				 * so only r1-r5 could be still requested as
3794 				 * precise, r0 and r6-r10 or any stack slot in
3795 				 * the current frame should be zero by now
3796 				 */
3797 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3798 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3799 					WARN_ONCE(1, "verifier backtracking bug");
3800 					return -EFAULT;
3801 				}
3802 				/* we don't track register spills perfectly,
3803 				 * so fallback to force-precise instead of failing */
3804 				if (bt_stack_mask(bt) != 0)
3805 					return -ENOTSUPP;
3806 				/* propagate r1-r5 to the caller */
3807 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3808 					if (bt_is_reg_set(bt, i)) {
3809 						bt_clear_reg(bt, i);
3810 						bt_set_frame_reg(bt, bt->frame - 1, i);
3811 					}
3812 				}
3813 				if (bt_subprog_exit(bt))
3814 					return -EFAULT;
3815 				return 0;
3816 			}
3817 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3818 			/* exit from callback subprog to callback-calling helper or
3819 			 * kfunc call. Use idx/subseq_idx check to discern it from
3820 			 * straight line code backtracking.
3821 			 * Unlike the subprog call handling above, we shouldn't
3822 			 * propagate precision of r1-r5 (if any requested), as they are
3823 			 * not actually arguments passed directly to callback subprogs
3824 			 */
3825 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3826 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3827 				WARN_ONCE(1, "verifier backtracking bug");
3828 				return -EFAULT;
3829 			}
3830 			if (bt_stack_mask(bt) != 0)
3831 				return -ENOTSUPP;
3832 			/* clear r1-r5 in callback subprog's mask */
3833 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3834 				bt_clear_reg(bt, i);
3835 			if (bt_subprog_exit(bt))
3836 				return -EFAULT;
3837 			return 0;
3838 		} else if (opcode == BPF_CALL) {
3839 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3840 			 * catch this error later. Make backtracking conservative
3841 			 * with ENOTSUPP.
3842 			 */
3843 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3844 				return -ENOTSUPP;
3845 			/* regular helper call sets R0 */
3846 			bt_clear_reg(bt, BPF_REG_0);
3847 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3848 				/* if backtracing was looking for registers R1-R5
3849 				 * they should have been found already.
3850 				 */
3851 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3852 				WARN_ONCE(1, "verifier backtracking bug");
3853 				return -EFAULT;
3854 			}
3855 		} else if (opcode == BPF_EXIT) {
3856 			bool r0_precise;
3857 
3858 			/* Backtracking to a nested function call, 'idx' is a part of
3859 			 * the inner frame 'subseq_idx' is a part of the outer frame.
3860 			 * In case of a regular function call, instructions giving
3861 			 * precision to registers R1-R5 should have been found already.
3862 			 * In case of a callback, it is ok to have R1-R5 marked for
3863 			 * backtracking, as these registers are set by the function
3864 			 * invoking callback.
3865 			 */
3866 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3867 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3868 					bt_clear_reg(bt, i);
3869 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3870 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3871 				WARN_ONCE(1, "verifier backtracking bug");
3872 				return -EFAULT;
3873 			}
3874 
3875 			/* BPF_EXIT in subprog or callback always returns
3876 			 * right after the call instruction, so by checking
3877 			 * whether the instruction at subseq_idx-1 is subprog
3878 			 * call or not we can distinguish actual exit from
3879 			 * *subprog* from exit from *callback*. In the former
3880 			 * case, we need to propagate r0 precision, if
3881 			 * necessary. In the former we never do that.
3882 			 */
3883 			r0_precise = subseq_idx - 1 >= 0 &&
3884 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3885 				     bt_is_reg_set(bt, BPF_REG_0);
3886 
3887 			bt_clear_reg(bt, BPF_REG_0);
3888 			if (bt_subprog_enter(bt))
3889 				return -EFAULT;
3890 
3891 			if (r0_precise)
3892 				bt_set_reg(bt, BPF_REG_0);
3893 			/* r6-r9 and stack slots will stay set in caller frame
3894 			 * bitmasks until we return back from callee(s)
3895 			 */
3896 			return 0;
3897 		} else if (BPF_SRC(insn->code) == BPF_X) {
3898 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3899 				return 0;
3900 			/* dreg <cond> sreg
3901 			 * Both dreg and sreg need precision before
3902 			 * this insn. If only sreg was marked precise
3903 			 * before it would be equally necessary to
3904 			 * propagate it to dreg.
3905 			 */
3906 			bt_set_reg(bt, dreg);
3907 			bt_set_reg(bt, sreg);
3908 			 /* else dreg <cond> K
3909 			  * Only dreg still needs precision before
3910 			  * this insn, so for the K-based conditional
3911 			  * there is nothing new to be marked.
3912 			  */
3913 		}
3914 	} else if (class == BPF_LD) {
3915 		if (!bt_is_reg_set(bt, dreg))
3916 			return 0;
3917 		bt_clear_reg(bt, dreg);
3918 		/* It's ld_imm64 or ld_abs or ld_ind.
3919 		 * For ld_imm64 no further tracking of precision
3920 		 * into parent is necessary
3921 		 */
3922 		if (mode == BPF_IND || mode == BPF_ABS)
3923 			/* to be analyzed */
3924 			return -ENOTSUPP;
3925 	}
3926 	return 0;
3927 }
3928 
3929 /* the scalar precision tracking algorithm:
3930  * . at the start all registers have precise=false.
3931  * . scalar ranges are tracked as normal through alu and jmp insns.
3932  * . once precise value of the scalar register is used in:
3933  *   .  ptr + scalar alu
3934  *   . if (scalar cond K|scalar)
3935  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3936  *   backtrack through the verifier states and mark all registers and
3937  *   stack slots with spilled constants that these scalar regisers
3938  *   should be precise.
3939  * . during state pruning two registers (or spilled stack slots)
3940  *   are equivalent if both are not precise.
3941  *
3942  * Note the verifier cannot simply walk register parentage chain,
3943  * since many different registers and stack slots could have been
3944  * used to compute single precise scalar.
3945  *
3946  * The approach of starting with precise=true for all registers and then
3947  * backtrack to mark a register as not precise when the verifier detects
3948  * that program doesn't care about specific value (e.g., when helper
3949  * takes register as ARG_ANYTHING parameter) is not safe.
3950  *
3951  * It's ok to walk single parentage chain of the verifier states.
3952  * It's possible that this backtracking will go all the way till 1st insn.
3953  * All other branches will be explored for needing precision later.
3954  *
3955  * The backtracking needs to deal with cases like:
3956  *   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)
3957  * r9 -= r8
3958  * r5 = r9
3959  * if r5 > 0x79f goto pc+7
3960  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3961  * r5 += 1
3962  * ...
3963  * call bpf_perf_event_output#25
3964  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3965  *
3966  * and this case:
3967  * r6 = 1
3968  * call foo // uses callee's r6 inside to compute r0
3969  * r0 += r6
3970  * if r0 == 0 goto
3971  *
3972  * to track above reg_mask/stack_mask needs to be independent for each frame.
3973  *
3974  * Also if parent's curframe > frame where backtracking started,
3975  * the verifier need to mark registers in both frames, otherwise callees
3976  * may incorrectly prune callers. This is similar to
3977  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3978  *
3979  * For now backtracking falls back into conservative marking.
3980  */
3981 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3982 				     struct bpf_verifier_state *st)
3983 {
3984 	struct bpf_func_state *func;
3985 	struct bpf_reg_state *reg;
3986 	int i, j;
3987 
3988 	if (env->log.level & BPF_LOG_LEVEL2) {
3989 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3990 			st->curframe);
3991 	}
3992 
3993 	/* big hammer: mark all scalars precise in this path.
3994 	 * pop_stack may still get !precise scalars.
3995 	 * We also skip current state and go straight to first parent state,
3996 	 * because precision markings in current non-checkpointed state are
3997 	 * not needed. See why in the comment in __mark_chain_precision below.
3998 	 */
3999 	for (st = st->parent; st; st = st->parent) {
4000 		for (i = 0; i <= st->curframe; i++) {
4001 			func = st->frame[i];
4002 			for (j = 0; j < BPF_REG_FP; j++) {
4003 				reg = &func->regs[j];
4004 				if (reg->type != SCALAR_VALUE || reg->precise)
4005 					continue;
4006 				reg->precise = true;
4007 				if (env->log.level & BPF_LOG_LEVEL2) {
4008 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4009 						i, j);
4010 				}
4011 			}
4012 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4013 				if (!is_spilled_reg(&func->stack[j]))
4014 					continue;
4015 				reg = &func->stack[j].spilled_ptr;
4016 				if (reg->type != SCALAR_VALUE || reg->precise)
4017 					continue;
4018 				reg->precise = true;
4019 				if (env->log.level & BPF_LOG_LEVEL2) {
4020 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4021 						i, -(j + 1) * 8);
4022 				}
4023 			}
4024 		}
4025 	}
4026 }
4027 
4028 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4029 {
4030 	struct bpf_func_state *func;
4031 	struct bpf_reg_state *reg;
4032 	int i, j;
4033 
4034 	for (i = 0; i <= st->curframe; i++) {
4035 		func = st->frame[i];
4036 		for (j = 0; j < BPF_REG_FP; j++) {
4037 			reg = &func->regs[j];
4038 			if (reg->type != SCALAR_VALUE)
4039 				continue;
4040 			reg->precise = false;
4041 		}
4042 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4043 			if (!is_spilled_reg(&func->stack[j]))
4044 				continue;
4045 			reg = &func->stack[j].spilled_ptr;
4046 			if (reg->type != SCALAR_VALUE)
4047 				continue;
4048 			reg->precise = false;
4049 		}
4050 	}
4051 }
4052 
4053 static bool idset_contains(struct bpf_idset *s, u32 id)
4054 {
4055 	u32 i;
4056 
4057 	for (i = 0; i < s->count; ++i)
4058 		if (s->ids[i] == id)
4059 			return true;
4060 
4061 	return false;
4062 }
4063 
4064 static int idset_push(struct bpf_idset *s, u32 id)
4065 {
4066 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
4067 		return -EFAULT;
4068 	s->ids[s->count++] = id;
4069 	return 0;
4070 }
4071 
4072 static void idset_reset(struct bpf_idset *s)
4073 {
4074 	s->count = 0;
4075 }
4076 
4077 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
4078  * Mark all registers with these IDs as precise.
4079  */
4080 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4081 {
4082 	struct bpf_idset *precise_ids = &env->idset_scratch;
4083 	struct backtrack_state *bt = &env->bt;
4084 	struct bpf_func_state *func;
4085 	struct bpf_reg_state *reg;
4086 	DECLARE_BITMAP(mask, 64);
4087 	int i, fr;
4088 
4089 	idset_reset(precise_ids);
4090 
4091 	for (fr = bt->frame; fr >= 0; fr--) {
4092 		func = st->frame[fr];
4093 
4094 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4095 		for_each_set_bit(i, mask, 32) {
4096 			reg = &func->regs[i];
4097 			if (!reg->id || reg->type != SCALAR_VALUE)
4098 				continue;
4099 			if (idset_push(precise_ids, reg->id))
4100 				return -EFAULT;
4101 		}
4102 
4103 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4104 		for_each_set_bit(i, mask, 64) {
4105 			if (i >= func->allocated_stack / BPF_REG_SIZE)
4106 				break;
4107 			if (!is_spilled_scalar_reg(&func->stack[i]))
4108 				continue;
4109 			reg = &func->stack[i].spilled_ptr;
4110 			if (!reg->id)
4111 				continue;
4112 			if (idset_push(precise_ids, reg->id))
4113 				return -EFAULT;
4114 		}
4115 	}
4116 
4117 	for (fr = 0; fr <= st->curframe; ++fr) {
4118 		func = st->frame[fr];
4119 
4120 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4121 			reg = &func->regs[i];
4122 			if (!reg->id)
4123 				continue;
4124 			if (!idset_contains(precise_ids, reg->id))
4125 				continue;
4126 			bt_set_frame_reg(bt, fr, i);
4127 		}
4128 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4129 			if (!is_spilled_scalar_reg(&func->stack[i]))
4130 				continue;
4131 			reg = &func->stack[i].spilled_ptr;
4132 			if (!reg->id)
4133 				continue;
4134 			if (!idset_contains(precise_ids, reg->id))
4135 				continue;
4136 			bt_set_frame_slot(bt, fr, i);
4137 		}
4138 	}
4139 
4140 	return 0;
4141 }
4142 
4143 /*
4144  * __mark_chain_precision() backtracks BPF program instruction sequence and
4145  * chain of verifier states making sure that register *regno* (if regno >= 0)
4146  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4147  * SCALARS, as well as any other registers and slots that contribute to
4148  * a tracked state of given registers/stack slots, depending on specific BPF
4149  * assembly instructions (see backtrack_insns() for exact instruction handling
4150  * logic). This backtracking relies on recorded jmp_history and is able to
4151  * traverse entire chain of parent states. This process ends only when all the
4152  * necessary registers/slots and their transitive dependencies are marked as
4153  * precise.
4154  *
4155  * One important and subtle aspect is that precise marks *do not matter* in
4156  * the currently verified state (current state). It is important to understand
4157  * why this is the case.
4158  *
4159  * First, note that current state is the state that is not yet "checkpointed",
4160  * i.e., it is not yet put into env->explored_states, and it has no children
4161  * states as well. It's ephemeral, and can end up either a) being discarded if
4162  * compatible explored state is found at some point or BPF_EXIT instruction is
4163  * reached or b) checkpointed and put into env->explored_states, branching out
4164  * into one or more children states.
4165  *
4166  * In the former case, precise markings in current state are completely
4167  * ignored by state comparison code (see regsafe() for details). Only
4168  * checkpointed ("old") state precise markings are important, and if old
4169  * state's register/slot is precise, regsafe() assumes current state's
4170  * register/slot as precise and checks value ranges exactly and precisely. If
4171  * states turn out to be compatible, current state's necessary precise
4172  * markings and any required parent states' precise markings are enforced
4173  * after the fact with propagate_precision() logic, after the fact. But it's
4174  * important to realize that in this case, even after marking current state
4175  * registers/slots as precise, we immediately discard current state. So what
4176  * actually matters is any of the precise markings propagated into current
4177  * state's parent states, which are always checkpointed (due to b) case above).
4178  * As such, for scenario a) it doesn't matter if current state has precise
4179  * markings set or not.
4180  *
4181  * Now, for the scenario b), checkpointing and forking into child(ren)
4182  * state(s). Note that before current state gets to checkpointing step, any
4183  * processed instruction always assumes precise SCALAR register/slot
4184  * knowledge: if precise value or range is useful to prune jump branch, BPF
4185  * verifier takes this opportunity enthusiastically. Similarly, when
4186  * register's value is used to calculate offset or memory address, exact
4187  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4188  * what we mentioned above about state comparison ignoring precise markings
4189  * during state comparison, BPF verifier ignores and also assumes precise
4190  * markings *at will* during instruction verification process. But as verifier
4191  * assumes precision, it also propagates any precision dependencies across
4192  * parent states, which are not yet finalized, so can be further restricted
4193  * based on new knowledge gained from restrictions enforced by their children
4194  * states. This is so that once those parent states are finalized, i.e., when
4195  * they have no more active children state, state comparison logic in
4196  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4197  * required for correctness.
4198  *
4199  * To build a bit more intuition, note also that once a state is checkpointed,
4200  * the path we took to get to that state is not important. This is crucial
4201  * property for state pruning. When state is checkpointed and finalized at
4202  * some instruction index, it can be correctly and safely used to "short
4203  * circuit" any *compatible* state that reaches exactly the same instruction
4204  * index. I.e., if we jumped to that instruction from a completely different
4205  * code path than original finalized state was derived from, it doesn't
4206  * matter, current state can be discarded because from that instruction
4207  * forward having a compatible state will ensure we will safely reach the
4208  * exit. States describe preconditions for further exploration, but completely
4209  * forget the history of how we got here.
4210  *
4211  * This also means that even if we needed precise SCALAR range to get to
4212  * finalized state, but from that point forward *that same* SCALAR register is
4213  * never used in a precise context (i.e., it's precise value is not needed for
4214  * correctness), it's correct and safe to mark such register as "imprecise"
4215  * (i.e., precise marking set to false). This is what we rely on when we do
4216  * not set precise marking in current state. If no child state requires
4217  * precision for any given SCALAR register, it's safe to dictate that it can
4218  * be imprecise. If any child state does require this register to be precise,
4219  * we'll mark it precise later retroactively during precise markings
4220  * propagation from child state to parent states.
4221  *
4222  * Skipping precise marking setting in current state is a mild version of
4223  * relying on the above observation. But we can utilize this property even
4224  * more aggressively by proactively forgetting any precise marking in the
4225  * current state (which we inherited from the parent state), right before we
4226  * checkpoint it and branch off into new child state. This is done by
4227  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4228  * finalized states which help in short circuiting more future states.
4229  */
4230 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4231 {
4232 	struct backtrack_state *bt = &env->bt;
4233 	struct bpf_verifier_state *st = env->cur_state;
4234 	int first_idx = st->first_insn_idx;
4235 	int last_idx = env->insn_idx;
4236 	int subseq_idx = -1;
4237 	struct bpf_func_state *func;
4238 	struct bpf_reg_state *reg;
4239 	bool skip_first = true;
4240 	int i, fr, err;
4241 
4242 	if (!env->bpf_capable)
4243 		return 0;
4244 
4245 	/* set frame number from which we are starting to backtrack */
4246 	bt_init(bt, env->cur_state->curframe);
4247 
4248 	/* Do sanity checks against current state of register and/or stack
4249 	 * slot, but don't set precise flag in current state, as precision
4250 	 * tracking in the current state is unnecessary.
4251 	 */
4252 	func = st->frame[bt->frame];
4253 	if (regno >= 0) {
4254 		reg = &func->regs[regno];
4255 		if (reg->type != SCALAR_VALUE) {
4256 			WARN_ONCE(1, "backtracing misuse");
4257 			return -EFAULT;
4258 		}
4259 		bt_set_reg(bt, regno);
4260 	}
4261 
4262 	if (bt_empty(bt))
4263 		return 0;
4264 
4265 	for (;;) {
4266 		DECLARE_BITMAP(mask, 64);
4267 		u32 history = st->jmp_history_cnt;
4268 
4269 		if (env->log.level & BPF_LOG_LEVEL2) {
4270 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4271 				bt->frame, last_idx, first_idx, subseq_idx);
4272 		}
4273 
4274 		/* If some register with scalar ID is marked as precise,
4275 		 * make sure that all registers sharing this ID are also precise.
4276 		 * This is needed to estimate effect of find_equal_scalars().
4277 		 * Do this at the last instruction of each state,
4278 		 * bpf_reg_state::id fields are valid for these instructions.
4279 		 *
4280 		 * Allows to track precision in situation like below:
4281 		 *
4282 		 *     r2 = unknown value
4283 		 *     ...
4284 		 *   --- state #0 ---
4285 		 *     ...
4286 		 *     r1 = r2                 // r1 and r2 now share the same ID
4287 		 *     ...
4288 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4289 		 *     ...
4290 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4291 		 *     ...
4292 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4293 		 *     r3 = r10
4294 		 *     r3 += r1                // need to mark both r1 and r2
4295 		 */
4296 		if (mark_precise_scalar_ids(env, st))
4297 			return -EFAULT;
4298 
4299 		if (last_idx < 0) {
4300 			/* we are at the entry into subprog, which
4301 			 * is expected for global funcs, but only if
4302 			 * requested precise registers are R1-R5
4303 			 * (which are global func's input arguments)
4304 			 */
4305 			if (st->curframe == 0 &&
4306 			    st->frame[0]->subprogno > 0 &&
4307 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4308 			    bt_stack_mask(bt) == 0 &&
4309 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4310 				bitmap_from_u64(mask, bt_reg_mask(bt));
4311 				for_each_set_bit(i, mask, 32) {
4312 					reg = &st->frame[0]->regs[i];
4313 					bt_clear_reg(bt, i);
4314 					if (reg->type == SCALAR_VALUE)
4315 						reg->precise = true;
4316 				}
4317 				return 0;
4318 			}
4319 
4320 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4321 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4322 			WARN_ONCE(1, "verifier backtracking bug");
4323 			return -EFAULT;
4324 		}
4325 
4326 		for (i = last_idx;;) {
4327 			if (skip_first) {
4328 				err = 0;
4329 				skip_first = false;
4330 			} else {
4331 				err = backtrack_insn(env, i, subseq_idx, bt);
4332 			}
4333 			if (err == -ENOTSUPP) {
4334 				mark_all_scalars_precise(env, env->cur_state);
4335 				bt_reset(bt);
4336 				return 0;
4337 			} else if (err) {
4338 				return err;
4339 			}
4340 			if (bt_empty(bt))
4341 				/* Found assignment(s) into tracked register in this state.
4342 				 * Since this state is already marked, just return.
4343 				 * Nothing to be tracked further in the parent state.
4344 				 */
4345 				return 0;
4346 			subseq_idx = i;
4347 			i = get_prev_insn_idx(st, i, &history);
4348 			if (i == -ENOENT)
4349 				break;
4350 			if (i >= env->prog->len) {
4351 				/* This can happen if backtracking reached insn 0
4352 				 * and there are still reg_mask or stack_mask
4353 				 * to backtrack.
4354 				 * It means the backtracking missed the spot where
4355 				 * particular register was initialized with a constant.
4356 				 */
4357 				verbose(env, "BUG backtracking idx %d\n", i);
4358 				WARN_ONCE(1, "verifier backtracking bug");
4359 				return -EFAULT;
4360 			}
4361 		}
4362 		st = st->parent;
4363 		if (!st)
4364 			break;
4365 
4366 		for (fr = bt->frame; fr >= 0; fr--) {
4367 			func = st->frame[fr];
4368 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4369 			for_each_set_bit(i, mask, 32) {
4370 				reg = &func->regs[i];
4371 				if (reg->type != SCALAR_VALUE) {
4372 					bt_clear_frame_reg(bt, fr, i);
4373 					continue;
4374 				}
4375 				if (reg->precise)
4376 					bt_clear_frame_reg(bt, fr, i);
4377 				else
4378 					reg->precise = true;
4379 			}
4380 
4381 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4382 			for_each_set_bit(i, mask, 64) {
4383 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4384 					/* the sequence of instructions:
4385 					 * 2: (bf) r3 = r10
4386 					 * 3: (7b) *(u64 *)(r3 -8) = r0
4387 					 * 4: (79) r4 = *(u64 *)(r10 -8)
4388 					 * doesn't contain jmps. It's backtracked
4389 					 * as a single block.
4390 					 * During backtracking insn 3 is not recognized as
4391 					 * stack access, so at the end of backtracking
4392 					 * stack slot fp-8 is still marked in stack_mask.
4393 					 * However the parent state may not have accessed
4394 					 * fp-8 and it's "unallocated" stack space.
4395 					 * In such case fallback to conservative.
4396 					 */
4397 					mark_all_scalars_precise(env, env->cur_state);
4398 					bt_reset(bt);
4399 					return 0;
4400 				}
4401 
4402 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4403 					bt_clear_frame_slot(bt, fr, i);
4404 					continue;
4405 				}
4406 				reg = &func->stack[i].spilled_ptr;
4407 				if (reg->precise)
4408 					bt_clear_frame_slot(bt, fr, i);
4409 				else
4410 					reg->precise = true;
4411 			}
4412 			if (env->log.level & BPF_LOG_LEVEL2) {
4413 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4414 					     bt_frame_reg_mask(bt, fr));
4415 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4416 					fr, env->tmp_str_buf);
4417 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4418 					       bt_frame_stack_mask(bt, fr));
4419 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4420 				print_verifier_state(env, func, true);
4421 			}
4422 		}
4423 
4424 		if (bt_empty(bt))
4425 			return 0;
4426 
4427 		subseq_idx = first_idx;
4428 		last_idx = st->last_insn_idx;
4429 		first_idx = st->first_insn_idx;
4430 	}
4431 
4432 	/* if we still have requested precise regs or slots, we missed
4433 	 * something (e.g., stack access through non-r10 register), so
4434 	 * fallback to marking all precise
4435 	 */
4436 	if (!bt_empty(bt)) {
4437 		mark_all_scalars_precise(env, env->cur_state);
4438 		bt_reset(bt);
4439 	}
4440 
4441 	return 0;
4442 }
4443 
4444 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4445 {
4446 	return __mark_chain_precision(env, regno);
4447 }
4448 
4449 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4450  * desired reg and stack masks across all relevant frames
4451  */
4452 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4453 {
4454 	return __mark_chain_precision(env, -1);
4455 }
4456 
4457 static bool is_spillable_regtype(enum bpf_reg_type type)
4458 {
4459 	switch (base_type(type)) {
4460 	case PTR_TO_MAP_VALUE:
4461 	case PTR_TO_STACK:
4462 	case PTR_TO_CTX:
4463 	case PTR_TO_PACKET:
4464 	case PTR_TO_PACKET_META:
4465 	case PTR_TO_PACKET_END:
4466 	case PTR_TO_FLOW_KEYS:
4467 	case CONST_PTR_TO_MAP:
4468 	case PTR_TO_SOCKET:
4469 	case PTR_TO_SOCK_COMMON:
4470 	case PTR_TO_TCP_SOCK:
4471 	case PTR_TO_XDP_SOCK:
4472 	case PTR_TO_BTF_ID:
4473 	case PTR_TO_BUF:
4474 	case PTR_TO_MEM:
4475 	case PTR_TO_FUNC:
4476 	case PTR_TO_MAP_KEY:
4477 		return true;
4478 	default:
4479 		return false;
4480 	}
4481 }
4482 
4483 /* Does this register contain a constant zero? */
4484 static bool register_is_null(struct bpf_reg_state *reg)
4485 {
4486 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4487 }
4488 
4489 static bool register_is_const(struct bpf_reg_state *reg)
4490 {
4491 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4492 }
4493 
4494 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4495 {
4496 	return tnum_is_unknown(reg->var_off) &&
4497 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4498 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4499 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4500 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4501 }
4502 
4503 static bool register_is_bounded(struct bpf_reg_state *reg)
4504 {
4505 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4506 }
4507 
4508 static bool __is_pointer_value(bool allow_ptr_leaks,
4509 			       const struct bpf_reg_state *reg)
4510 {
4511 	if (allow_ptr_leaks)
4512 		return false;
4513 
4514 	return reg->type != SCALAR_VALUE;
4515 }
4516 
4517 /* Copy src state preserving dst->parent and dst->live fields */
4518 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4519 {
4520 	struct bpf_reg_state *parent = dst->parent;
4521 	enum bpf_reg_liveness live = dst->live;
4522 
4523 	*dst = *src;
4524 	dst->parent = parent;
4525 	dst->live = live;
4526 }
4527 
4528 static void save_register_state(struct bpf_func_state *state,
4529 				int spi, struct bpf_reg_state *reg,
4530 				int size)
4531 {
4532 	int i;
4533 
4534 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4535 	if (size == BPF_REG_SIZE)
4536 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4537 
4538 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4539 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4540 
4541 	/* size < 8 bytes spill */
4542 	for (; i; i--)
4543 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4544 }
4545 
4546 static bool is_bpf_st_mem(struct bpf_insn *insn)
4547 {
4548 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4549 }
4550 
4551 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4552  * stack boundary and alignment are checked in check_mem_access()
4553  */
4554 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4555 				       /* stack frame we're writing to */
4556 				       struct bpf_func_state *state,
4557 				       int off, int size, int value_regno,
4558 				       int insn_idx)
4559 {
4560 	struct bpf_func_state *cur; /* state of the current function */
4561 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4562 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4563 	struct bpf_reg_state *reg = NULL;
4564 	u32 dst_reg = insn->dst_reg;
4565 
4566 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4567 	 * so it's aligned access and [off, off + size) are within stack limits
4568 	 */
4569 	if (!env->allow_ptr_leaks &&
4570 	    is_spilled_reg(&state->stack[spi]) &&
4571 	    size != BPF_REG_SIZE) {
4572 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4573 		return -EACCES;
4574 	}
4575 
4576 	cur = env->cur_state->frame[env->cur_state->curframe];
4577 	if (value_regno >= 0)
4578 		reg = &cur->regs[value_regno];
4579 	if (!env->bypass_spec_v4) {
4580 		bool sanitize = reg && is_spillable_regtype(reg->type);
4581 
4582 		for (i = 0; i < size; i++) {
4583 			u8 type = state->stack[spi].slot_type[i];
4584 
4585 			if (type != STACK_MISC && type != STACK_ZERO) {
4586 				sanitize = true;
4587 				break;
4588 			}
4589 		}
4590 
4591 		if (sanitize)
4592 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4593 	}
4594 
4595 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4596 	if (err)
4597 		return err;
4598 
4599 	mark_stack_slot_scratched(env, spi);
4600 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4601 	    !register_is_null(reg) && env->bpf_capable) {
4602 		if (dst_reg != BPF_REG_FP) {
4603 			/* The backtracking logic can only recognize explicit
4604 			 * stack slot address like [fp - 8]. Other spill of
4605 			 * scalar via different register has to be conservative.
4606 			 * Backtrack from here and mark all registers as precise
4607 			 * that contributed into 'reg' being a constant.
4608 			 */
4609 			err = mark_chain_precision(env, value_regno);
4610 			if (err)
4611 				return err;
4612 		}
4613 		save_register_state(state, spi, reg, size);
4614 		/* Break the relation on a narrowing spill. */
4615 		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4616 			state->stack[spi].spilled_ptr.id = 0;
4617 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4618 		   insn->imm != 0 && env->bpf_capable) {
4619 		struct bpf_reg_state fake_reg = {};
4620 
4621 		__mark_reg_known(&fake_reg, insn->imm);
4622 		fake_reg.type = SCALAR_VALUE;
4623 		save_register_state(state, spi, &fake_reg, size);
4624 	} else if (reg && is_spillable_regtype(reg->type)) {
4625 		/* register containing pointer is being spilled into stack */
4626 		if (size != BPF_REG_SIZE) {
4627 			verbose_linfo(env, insn_idx, "; ");
4628 			verbose(env, "invalid size of register spill\n");
4629 			return -EACCES;
4630 		}
4631 		if (state != cur && reg->type == PTR_TO_STACK) {
4632 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4633 			return -EINVAL;
4634 		}
4635 		save_register_state(state, spi, reg, size);
4636 	} else {
4637 		u8 type = STACK_MISC;
4638 
4639 		/* regular write of data into stack destroys any spilled ptr */
4640 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4641 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4642 		if (is_stack_slot_special(&state->stack[spi]))
4643 			for (i = 0; i < BPF_REG_SIZE; i++)
4644 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4645 
4646 		/* only mark the slot as written if all 8 bytes were written
4647 		 * otherwise read propagation may incorrectly stop too soon
4648 		 * when stack slots are partially written.
4649 		 * This heuristic means that read propagation will be
4650 		 * conservative, since it will add reg_live_read marks
4651 		 * to stack slots all the way to first state when programs
4652 		 * writes+reads less than 8 bytes
4653 		 */
4654 		if (size == BPF_REG_SIZE)
4655 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4656 
4657 		/* when we zero initialize stack slots mark them as such */
4658 		if ((reg && register_is_null(reg)) ||
4659 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4660 			/* backtracking doesn't work for STACK_ZERO yet. */
4661 			err = mark_chain_precision(env, value_regno);
4662 			if (err)
4663 				return err;
4664 			type = STACK_ZERO;
4665 		}
4666 
4667 		/* Mark slots affected by this stack write. */
4668 		for (i = 0; i < size; i++)
4669 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4670 				type;
4671 	}
4672 	return 0;
4673 }
4674 
4675 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4676  * known to contain a variable offset.
4677  * This function checks whether the write is permitted and conservatively
4678  * tracks the effects of the write, considering that each stack slot in the
4679  * dynamic range is potentially written to.
4680  *
4681  * 'off' includes 'regno->off'.
4682  * 'value_regno' can be -1, meaning that an unknown value is being written to
4683  * the stack.
4684  *
4685  * Spilled pointers in range are not marked as written because we don't know
4686  * what's going to be actually written. This means that read propagation for
4687  * future reads cannot be terminated by this write.
4688  *
4689  * For privileged programs, uninitialized stack slots are considered
4690  * initialized by this write (even though we don't know exactly what offsets
4691  * are going to be written to). The idea is that we don't want the verifier to
4692  * reject future reads that access slots written to through variable offsets.
4693  */
4694 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4695 				     /* func where register points to */
4696 				     struct bpf_func_state *state,
4697 				     int ptr_regno, int off, int size,
4698 				     int value_regno, int insn_idx)
4699 {
4700 	struct bpf_func_state *cur; /* state of the current function */
4701 	int min_off, max_off;
4702 	int i, err;
4703 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4704 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4705 	bool writing_zero = false;
4706 	/* set if the fact that we're writing a zero is used to let any
4707 	 * stack slots remain STACK_ZERO
4708 	 */
4709 	bool zero_used = false;
4710 
4711 	cur = env->cur_state->frame[env->cur_state->curframe];
4712 	ptr_reg = &cur->regs[ptr_regno];
4713 	min_off = ptr_reg->smin_value + off;
4714 	max_off = ptr_reg->smax_value + off + size;
4715 	if (value_regno >= 0)
4716 		value_reg = &cur->regs[value_regno];
4717 	if ((value_reg && register_is_null(value_reg)) ||
4718 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4719 		writing_zero = true;
4720 
4721 	for (i = min_off; i < max_off; i++) {
4722 		int spi;
4723 
4724 		spi = __get_spi(i);
4725 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4726 		if (err)
4727 			return err;
4728 	}
4729 
4730 	/* Variable offset writes destroy any spilled pointers in range. */
4731 	for (i = min_off; i < max_off; i++) {
4732 		u8 new_type, *stype;
4733 		int slot, spi;
4734 
4735 		slot = -i - 1;
4736 		spi = slot / BPF_REG_SIZE;
4737 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4738 		mark_stack_slot_scratched(env, spi);
4739 
4740 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4741 			/* Reject the write if range we may write to has not
4742 			 * been initialized beforehand. If we didn't reject
4743 			 * here, the ptr status would be erased below (even
4744 			 * though not all slots are actually overwritten),
4745 			 * possibly opening the door to leaks.
4746 			 *
4747 			 * We do however catch STACK_INVALID case below, and
4748 			 * only allow reading possibly uninitialized memory
4749 			 * later for CAP_PERFMON, as the write may not happen to
4750 			 * that slot.
4751 			 */
4752 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4753 				insn_idx, i);
4754 			return -EINVAL;
4755 		}
4756 
4757 		/* Erase all spilled pointers. */
4758 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4759 
4760 		/* Update the slot type. */
4761 		new_type = STACK_MISC;
4762 		if (writing_zero && *stype == STACK_ZERO) {
4763 			new_type = STACK_ZERO;
4764 			zero_used = true;
4765 		}
4766 		/* If the slot is STACK_INVALID, we check whether it's OK to
4767 		 * pretend that it will be initialized by this write. The slot
4768 		 * might not actually be written to, and so if we mark it as
4769 		 * initialized future reads might leak uninitialized memory.
4770 		 * For privileged programs, we will accept such reads to slots
4771 		 * that may or may not be written because, if we're reject
4772 		 * them, the error would be too confusing.
4773 		 */
4774 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4775 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4776 					insn_idx, i);
4777 			return -EINVAL;
4778 		}
4779 		*stype = new_type;
4780 	}
4781 	if (zero_used) {
4782 		/* backtracking doesn't work for STACK_ZERO yet. */
4783 		err = mark_chain_precision(env, value_regno);
4784 		if (err)
4785 			return err;
4786 	}
4787 	return 0;
4788 }
4789 
4790 /* When register 'dst_regno' is assigned some values from stack[min_off,
4791  * max_off), we set the register's type according to the types of the
4792  * respective stack slots. If all the stack values are known to be zeros, then
4793  * so is the destination reg. Otherwise, the register is considered to be
4794  * SCALAR. This function does not deal with register filling; the caller must
4795  * ensure that all spilled registers in the stack range have been marked as
4796  * read.
4797  */
4798 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4799 				/* func where src register points to */
4800 				struct bpf_func_state *ptr_state,
4801 				int min_off, int max_off, int dst_regno)
4802 {
4803 	struct bpf_verifier_state *vstate = env->cur_state;
4804 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4805 	int i, slot, spi;
4806 	u8 *stype;
4807 	int zeros = 0;
4808 
4809 	for (i = min_off; i < max_off; i++) {
4810 		slot = -i - 1;
4811 		spi = slot / BPF_REG_SIZE;
4812 		mark_stack_slot_scratched(env, spi);
4813 		stype = ptr_state->stack[spi].slot_type;
4814 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4815 			break;
4816 		zeros++;
4817 	}
4818 	if (zeros == max_off - min_off) {
4819 		/* any access_size read into register is zero extended,
4820 		 * so the whole register == const_zero
4821 		 */
4822 		__mark_reg_const_zero(&state->regs[dst_regno]);
4823 		/* backtracking doesn't support STACK_ZERO yet,
4824 		 * so mark it precise here, so that later
4825 		 * backtracking can stop here.
4826 		 * Backtracking may not need this if this register
4827 		 * doesn't participate in pointer adjustment.
4828 		 * Forward propagation of precise flag is not
4829 		 * necessary either. This mark is only to stop
4830 		 * backtracking. Any register that contributed
4831 		 * to const 0 was marked precise before spill.
4832 		 */
4833 		state->regs[dst_regno].precise = true;
4834 	} else {
4835 		/* have read misc data from the stack */
4836 		mark_reg_unknown(env, state->regs, dst_regno);
4837 	}
4838 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4839 }
4840 
4841 /* Read the stack at 'off' and put the results into the register indicated by
4842  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4843  * spilled reg.
4844  *
4845  * 'dst_regno' can be -1, meaning that the read value is not going to a
4846  * register.
4847  *
4848  * The access is assumed to be within the current stack bounds.
4849  */
4850 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4851 				      /* func where src register points to */
4852 				      struct bpf_func_state *reg_state,
4853 				      int off, int size, int dst_regno)
4854 {
4855 	struct bpf_verifier_state *vstate = env->cur_state;
4856 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4857 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4858 	struct bpf_reg_state *reg;
4859 	u8 *stype, type;
4860 
4861 	stype = reg_state->stack[spi].slot_type;
4862 	reg = &reg_state->stack[spi].spilled_ptr;
4863 
4864 	mark_stack_slot_scratched(env, spi);
4865 
4866 	if (is_spilled_reg(&reg_state->stack[spi])) {
4867 		u8 spill_size = 1;
4868 
4869 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4870 			spill_size++;
4871 
4872 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4873 			if (reg->type != SCALAR_VALUE) {
4874 				verbose_linfo(env, env->insn_idx, "; ");
4875 				verbose(env, "invalid size of register fill\n");
4876 				return -EACCES;
4877 			}
4878 
4879 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4880 			if (dst_regno < 0)
4881 				return 0;
4882 
4883 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4884 				/* The earlier check_reg_arg() has decided the
4885 				 * subreg_def for this insn.  Save it first.
4886 				 */
4887 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4888 
4889 				copy_register_state(&state->regs[dst_regno], reg);
4890 				state->regs[dst_regno].subreg_def = subreg_def;
4891 			} else {
4892 				for (i = 0; i < size; i++) {
4893 					type = stype[(slot - i) % BPF_REG_SIZE];
4894 					if (type == STACK_SPILL)
4895 						continue;
4896 					if (type == STACK_MISC)
4897 						continue;
4898 					if (type == STACK_INVALID && env->allow_uninit_stack)
4899 						continue;
4900 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4901 						off, i, size);
4902 					return -EACCES;
4903 				}
4904 				mark_reg_unknown(env, state->regs, dst_regno);
4905 			}
4906 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4907 			return 0;
4908 		}
4909 
4910 		if (dst_regno >= 0) {
4911 			/* restore register state from stack */
4912 			copy_register_state(&state->regs[dst_regno], reg);
4913 			/* mark reg as written since spilled pointer state likely
4914 			 * has its liveness marks cleared by is_state_visited()
4915 			 * which resets stack/reg liveness for state transitions
4916 			 */
4917 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4918 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4919 			/* If dst_regno==-1, the caller is asking us whether
4920 			 * it is acceptable to use this value as a SCALAR_VALUE
4921 			 * (e.g. for XADD).
4922 			 * We must not allow unprivileged callers to do that
4923 			 * with spilled pointers.
4924 			 */
4925 			verbose(env, "leaking pointer from stack off %d\n",
4926 				off);
4927 			return -EACCES;
4928 		}
4929 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4930 	} else {
4931 		for (i = 0; i < size; i++) {
4932 			type = stype[(slot - i) % BPF_REG_SIZE];
4933 			if (type == STACK_MISC)
4934 				continue;
4935 			if (type == STACK_ZERO)
4936 				continue;
4937 			if (type == STACK_INVALID && env->allow_uninit_stack)
4938 				continue;
4939 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4940 				off, i, size);
4941 			return -EACCES;
4942 		}
4943 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4944 		if (dst_regno >= 0)
4945 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4946 	}
4947 	return 0;
4948 }
4949 
4950 enum bpf_access_src {
4951 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4952 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4953 };
4954 
4955 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4956 					 int regno, int off, int access_size,
4957 					 bool zero_size_allowed,
4958 					 enum bpf_access_src type,
4959 					 struct bpf_call_arg_meta *meta);
4960 
4961 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4962 {
4963 	return cur_regs(env) + regno;
4964 }
4965 
4966 /* Read the stack at 'ptr_regno + off' and put the result into the register
4967  * 'dst_regno'.
4968  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4969  * but not its variable offset.
4970  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4971  *
4972  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4973  * filling registers (i.e. reads of spilled register cannot be detected when
4974  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4975  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4976  * offset; for a fixed offset check_stack_read_fixed_off should be used
4977  * instead.
4978  */
4979 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4980 				    int ptr_regno, int off, int size, int dst_regno)
4981 {
4982 	/* The state of the source register. */
4983 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4984 	struct bpf_func_state *ptr_state = func(env, reg);
4985 	int err;
4986 	int min_off, max_off;
4987 
4988 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4989 	 */
4990 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4991 					    false, ACCESS_DIRECT, NULL);
4992 	if (err)
4993 		return err;
4994 
4995 	min_off = reg->smin_value + off;
4996 	max_off = reg->smax_value + off;
4997 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4998 	return 0;
4999 }
5000 
5001 /* check_stack_read dispatches to check_stack_read_fixed_off or
5002  * check_stack_read_var_off.
5003  *
5004  * The caller must ensure that the offset falls within the allocated stack
5005  * bounds.
5006  *
5007  * 'dst_regno' is a register which will receive the value from the stack. It
5008  * can be -1, meaning that the read value is not going to a register.
5009  */
5010 static int check_stack_read(struct bpf_verifier_env *env,
5011 			    int ptr_regno, int off, int size,
5012 			    int dst_regno)
5013 {
5014 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5015 	struct bpf_func_state *state = func(env, reg);
5016 	int err;
5017 	/* Some accesses are only permitted with a static offset. */
5018 	bool var_off = !tnum_is_const(reg->var_off);
5019 
5020 	/* The offset is required to be static when reads don't go to a
5021 	 * register, in order to not leak pointers (see
5022 	 * check_stack_read_fixed_off).
5023 	 */
5024 	if (dst_regno < 0 && var_off) {
5025 		char tn_buf[48];
5026 
5027 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5028 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5029 			tn_buf, off, size);
5030 		return -EACCES;
5031 	}
5032 	/* Variable offset is prohibited for unprivileged mode for simplicity
5033 	 * since it requires corresponding support in Spectre masking for stack
5034 	 * ALU. See also retrieve_ptr_limit(). The check in
5035 	 * check_stack_access_for_ptr_arithmetic() called by
5036 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5037 	 * with variable offsets, therefore no check is required here. Further,
5038 	 * just checking it here would be insufficient as speculative stack
5039 	 * writes could still lead to unsafe speculative behaviour.
5040 	 */
5041 	if (!var_off) {
5042 		off += reg->var_off.value;
5043 		err = check_stack_read_fixed_off(env, state, off, size,
5044 						 dst_regno);
5045 	} else {
5046 		/* Variable offset stack reads need more conservative handling
5047 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5048 		 * branch.
5049 		 */
5050 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5051 					       dst_regno);
5052 	}
5053 	return err;
5054 }
5055 
5056 
5057 /* check_stack_write dispatches to check_stack_write_fixed_off or
5058  * check_stack_write_var_off.
5059  *
5060  * 'ptr_regno' is the register used as a pointer into the stack.
5061  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5062  * 'value_regno' is the register whose value we're writing to the stack. It can
5063  * be -1, meaning that we're not writing from a register.
5064  *
5065  * The caller must ensure that the offset falls within the maximum stack size.
5066  */
5067 static int check_stack_write(struct bpf_verifier_env *env,
5068 			     int ptr_regno, int off, int size,
5069 			     int value_regno, int insn_idx)
5070 {
5071 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5072 	struct bpf_func_state *state = func(env, reg);
5073 	int err;
5074 
5075 	if (tnum_is_const(reg->var_off)) {
5076 		off += reg->var_off.value;
5077 		err = check_stack_write_fixed_off(env, state, off, size,
5078 						  value_regno, insn_idx);
5079 	} else {
5080 		/* Variable offset stack reads need more conservative handling
5081 		 * than fixed offset ones.
5082 		 */
5083 		err = check_stack_write_var_off(env, state,
5084 						ptr_regno, off, size,
5085 						value_regno, insn_idx);
5086 	}
5087 	return err;
5088 }
5089 
5090 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5091 				 int off, int size, enum bpf_access_type type)
5092 {
5093 	struct bpf_reg_state *regs = cur_regs(env);
5094 	struct bpf_map *map = regs[regno].map_ptr;
5095 	u32 cap = bpf_map_flags_to_cap(map);
5096 
5097 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5098 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5099 			map->value_size, off, size);
5100 		return -EACCES;
5101 	}
5102 
5103 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5104 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5105 			map->value_size, off, size);
5106 		return -EACCES;
5107 	}
5108 
5109 	return 0;
5110 }
5111 
5112 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5113 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5114 			      int off, int size, u32 mem_size,
5115 			      bool zero_size_allowed)
5116 {
5117 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5118 	struct bpf_reg_state *reg;
5119 
5120 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5121 		return 0;
5122 
5123 	reg = &cur_regs(env)[regno];
5124 	switch (reg->type) {
5125 	case PTR_TO_MAP_KEY:
5126 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5127 			mem_size, off, size);
5128 		break;
5129 	case PTR_TO_MAP_VALUE:
5130 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5131 			mem_size, off, size);
5132 		break;
5133 	case PTR_TO_PACKET:
5134 	case PTR_TO_PACKET_META:
5135 	case PTR_TO_PACKET_END:
5136 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5137 			off, size, regno, reg->id, off, mem_size);
5138 		break;
5139 	case PTR_TO_MEM:
5140 	default:
5141 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5142 			mem_size, off, size);
5143 	}
5144 
5145 	return -EACCES;
5146 }
5147 
5148 /* check read/write into a memory region with possible variable offset */
5149 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5150 				   int off, int size, u32 mem_size,
5151 				   bool zero_size_allowed)
5152 {
5153 	struct bpf_verifier_state *vstate = env->cur_state;
5154 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5155 	struct bpf_reg_state *reg = &state->regs[regno];
5156 	int err;
5157 
5158 	/* We may have adjusted the register pointing to memory region, so we
5159 	 * need to try adding each of min_value and max_value to off
5160 	 * to make sure our theoretical access will be safe.
5161 	 *
5162 	 * The minimum value is only important with signed
5163 	 * comparisons where we can't assume the floor of a
5164 	 * value is 0.  If we are using signed variables for our
5165 	 * index'es we need to make sure that whatever we use
5166 	 * will have a set floor within our range.
5167 	 */
5168 	if (reg->smin_value < 0 &&
5169 	    (reg->smin_value == S64_MIN ||
5170 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5171 	      reg->smin_value + off < 0)) {
5172 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5173 			regno);
5174 		return -EACCES;
5175 	}
5176 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5177 				 mem_size, zero_size_allowed);
5178 	if (err) {
5179 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5180 			regno);
5181 		return err;
5182 	}
5183 
5184 	/* If we haven't set a max value then we need to bail since we can't be
5185 	 * sure we won't do bad things.
5186 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5187 	 */
5188 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5189 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5190 			regno);
5191 		return -EACCES;
5192 	}
5193 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5194 				 mem_size, zero_size_allowed);
5195 	if (err) {
5196 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5197 			regno);
5198 		return err;
5199 	}
5200 
5201 	return 0;
5202 }
5203 
5204 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5205 			       const struct bpf_reg_state *reg, int regno,
5206 			       bool fixed_off_ok)
5207 {
5208 	/* Access to this pointer-typed register or passing it to a helper
5209 	 * is only allowed in its original, unmodified form.
5210 	 */
5211 
5212 	if (reg->off < 0) {
5213 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5214 			reg_type_str(env, reg->type), regno, reg->off);
5215 		return -EACCES;
5216 	}
5217 
5218 	if (!fixed_off_ok && reg->off) {
5219 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5220 			reg_type_str(env, reg->type), regno, reg->off);
5221 		return -EACCES;
5222 	}
5223 
5224 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5225 		char tn_buf[48];
5226 
5227 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5228 		verbose(env, "variable %s access var_off=%s disallowed\n",
5229 			reg_type_str(env, reg->type), tn_buf);
5230 		return -EACCES;
5231 	}
5232 
5233 	return 0;
5234 }
5235 
5236 int check_ptr_off_reg(struct bpf_verifier_env *env,
5237 		      const struct bpf_reg_state *reg, int regno)
5238 {
5239 	return __check_ptr_off_reg(env, reg, regno, false);
5240 }
5241 
5242 static int map_kptr_match_type(struct bpf_verifier_env *env,
5243 			       struct btf_field *kptr_field,
5244 			       struct bpf_reg_state *reg, u32 regno)
5245 {
5246 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5247 	int perm_flags;
5248 	const char *reg_name = "";
5249 
5250 	if (btf_is_kernel(reg->btf)) {
5251 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5252 
5253 		/* Only unreferenced case accepts untrusted pointers */
5254 		if (kptr_field->type == BPF_KPTR_UNREF)
5255 			perm_flags |= PTR_UNTRUSTED;
5256 	} else {
5257 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5258 	}
5259 
5260 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5261 		goto bad_type;
5262 
5263 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5264 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5265 
5266 	/* For ref_ptr case, release function check should ensure we get one
5267 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5268 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5269 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5270 	 * reg->off and reg->ref_obj_id are not needed here.
5271 	 */
5272 	if (__check_ptr_off_reg(env, reg, regno, true))
5273 		return -EACCES;
5274 
5275 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5276 	 * we also need to take into account the reg->off.
5277 	 *
5278 	 * We want to support cases like:
5279 	 *
5280 	 * struct foo {
5281 	 *         struct bar br;
5282 	 *         struct baz bz;
5283 	 * };
5284 	 *
5285 	 * struct foo *v;
5286 	 * v = func();	      // PTR_TO_BTF_ID
5287 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5288 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5289 	 *                    // first member type of struct after comparison fails
5290 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5291 	 *                    // to match type
5292 	 *
5293 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5294 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5295 	 * the struct to match type against first member of struct, i.e. reject
5296 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5297 	 * strict mode to true for type match.
5298 	 */
5299 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5300 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5301 				  kptr_field->type == BPF_KPTR_REF))
5302 		goto bad_type;
5303 	return 0;
5304 bad_type:
5305 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5306 		reg_type_str(env, reg->type), reg_name);
5307 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5308 	if (kptr_field->type == BPF_KPTR_UNREF)
5309 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5310 			targ_name);
5311 	else
5312 		verbose(env, "\n");
5313 	return -EINVAL;
5314 }
5315 
5316 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5317  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5318  */
5319 static bool in_rcu_cs(struct bpf_verifier_env *env)
5320 {
5321 	return env->cur_state->active_rcu_lock ||
5322 	       env->cur_state->active_lock.ptr ||
5323 	       !env->prog->aux->sleepable;
5324 }
5325 
5326 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5327 BTF_SET_START(rcu_protected_types)
5328 BTF_ID(struct, prog_test_ref_kfunc)
5329 BTF_ID(struct, cgroup)
5330 BTF_ID(struct, bpf_cpumask)
5331 BTF_ID(struct, task_struct)
5332 BTF_SET_END(rcu_protected_types)
5333 
5334 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5335 {
5336 	if (!btf_is_kernel(btf))
5337 		return false;
5338 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5339 }
5340 
5341 static bool rcu_safe_kptr(const struct btf_field *field)
5342 {
5343 	const struct btf_field_kptr *kptr = &field->kptr;
5344 
5345 	return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5346 }
5347 
5348 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5349 				 int value_regno, int insn_idx,
5350 				 struct btf_field *kptr_field)
5351 {
5352 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5353 	int class = BPF_CLASS(insn->code);
5354 	struct bpf_reg_state *val_reg;
5355 
5356 	/* Things we already checked for in check_map_access and caller:
5357 	 *  - Reject cases where variable offset may touch kptr
5358 	 *  - size of access (must be BPF_DW)
5359 	 *  - tnum_is_const(reg->var_off)
5360 	 *  - kptr_field->offset == off + reg->var_off.value
5361 	 */
5362 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5363 	if (BPF_MODE(insn->code) != BPF_MEM) {
5364 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5365 		return -EACCES;
5366 	}
5367 
5368 	/* We only allow loading referenced kptr, since it will be marked as
5369 	 * untrusted, similar to unreferenced kptr.
5370 	 */
5371 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5372 		verbose(env, "store to referenced kptr disallowed\n");
5373 		return -EACCES;
5374 	}
5375 
5376 	if (class == BPF_LDX) {
5377 		val_reg = reg_state(env, value_regno);
5378 		/* We can simply mark the value_regno receiving the pointer
5379 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5380 		 */
5381 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5382 				kptr_field->kptr.btf_id,
5383 				rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5384 				PTR_MAYBE_NULL | MEM_RCU :
5385 				PTR_MAYBE_NULL | PTR_UNTRUSTED);
5386 	} else if (class == BPF_STX) {
5387 		val_reg = reg_state(env, value_regno);
5388 		if (!register_is_null(val_reg) &&
5389 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5390 			return -EACCES;
5391 	} else if (class == BPF_ST) {
5392 		if (insn->imm) {
5393 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5394 				kptr_field->offset);
5395 			return -EACCES;
5396 		}
5397 	} else {
5398 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5399 		return -EACCES;
5400 	}
5401 	return 0;
5402 }
5403 
5404 /* check read/write into a map element with possible variable offset */
5405 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5406 			    int off, int size, bool zero_size_allowed,
5407 			    enum bpf_access_src src)
5408 {
5409 	struct bpf_verifier_state *vstate = env->cur_state;
5410 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5411 	struct bpf_reg_state *reg = &state->regs[regno];
5412 	struct bpf_map *map = reg->map_ptr;
5413 	struct btf_record *rec;
5414 	int err, i;
5415 
5416 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5417 				      zero_size_allowed);
5418 	if (err)
5419 		return err;
5420 
5421 	if (IS_ERR_OR_NULL(map->record))
5422 		return 0;
5423 	rec = map->record;
5424 	for (i = 0; i < rec->cnt; i++) {
5425 		struct btf_field *field = &rec->fields[i];
5426 		u32 p = field->offset;
5427 
5428 		/* If any part of a field  can be touched by load/store, reject
5429 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5430 		 * it is sufficient to check x1 < y2 && y1 < x2.
5431 		 */
5432 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5433 		    p < reg->umax_value + off + size) {
5434 			switch (field->type) {
5435 			case BPF_KPTR_UNREF:
5436 			case BPF_KPTR_REF:
5437 				if (src != ACCESS_DIRECT) {
5438 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5439 					return -EACCES;
5440 				}
5441 				if (!tnum_is_const(reg->var_off)) {
5442 					verbose(env, "kptr access cannot have variable offset\n");
5443 					return -EACCES;
5444 				}
5445 				if (p != off + reg->var_off.value) {
5446 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5447 						p, off + reg->var_off.value);
5448 					return -EACCES;
5449 				}
5450 				if (size != bpf_size_to_bytes(BPF_DW)) {
5451 					verbose(env, "kptr access size must be BPF_DW\n");
5452 					return -EACCES;
5453 				}
5454 				break;
5455 			default:
5456 				verbose(env, "%s cannot be accessed directly by load/store\n",
5457 					btf_field_type_name(field->type));
5458 				return -EACCES;
5459 			}
5460 		}
5461 	}
5462 	return 0;
5463 }
5464 
5465 #define MAX_PACKET_OFF 0xffff
5466 
5467 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5468 				       const struct bpf_call_arg_meta *meta,
5469 				       enum bpf_access_type t)
5470 {
5471 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5472 
5473 	switch (prog_type) {
5474 	/* Program types only with direct read access go here! */
5475 	case BPF_PROG_TYPE_LWT_IN:
5476 	case BPF_PROG_TYPE_LWT_OUT:
5477 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5478 	case BPF_PROG_TYPE_SK_REUSEPORT:
5479 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5480 	case BPF_PROG_TYPE_CGROUP_SKB:
5481 		if (t == BPF_WRITE)
5482 			return false;
5483 		fallthrough;
5484 
5485 	/* Program types with direct read + write access go here! */
5486 	case BPF_PROG_TYPE_SCHED_CLS:
5487 	case BPF_PROG_TYPE_SCHED_ACT:
5488 	case BPF_PROG_TYPE_XDP:
5489 	case BPF_PROG_TYPE_LWT_XMIT:
5490 	case BPF_PROG_TYPE_SK_SKB:
5491 	case BPF_PROG_TYPE_SK_MSG:
5492 		if (meta)
5493 			return meta->pkt_access;
5494 
5495 		env->seen_direct_write = true;
5496 		return true;
5497 
5498 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5499 		if (t == BPF_WRITE)
5500 			env->seen_direct_write = true;
5501 
5502 		return true;
5503 
5504 	default:
5505 		return false;
5506 	}
5507 }
5508 
5509 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5510 			       int size, bool zero_size_allowed)
5511 {
5512 	struct bpf_reg_state *regs = cur_regs(env);
5513 	struct bpf_reg_state *reg = &regs[regno];
5514 	int err;
5515 
5516 	/* We may have added a variable offset to the packet pointer; but any
5517 	 * reg->range we have comes after that.  We are only checking the fixed
5518 	 * offset.
5519 	 */
5520 
5521 	/* We don't allow negative numbers, because we aren't tracking enough
5522 	 * detail to prove they're safe.
5523 	 */
5524 	if (reg->smin_value < 0) {
5525 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5526 			regno);
5527 		return -EACCES;
5528 	}
5529 
5530 	err = reg->range < 0 ? -EINVAL :
5531 	      __check_mem_access(env, regno, off, size, reg->range,
5532 				 zero_size_allowed);
5533 	if (err) {
5534 		verbose(env, "R%d offset is outside of the packet\n", regno);
5535 		return err;
5536 	}
5537 
5538 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5539 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5540 	 * otherwise find_good_pkt_pointers would have refused to set range info
5541 	 * that __check_mem_access would have rejected this pkt access.
5542 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5543 	 */
5544 	env->prog->aux->max_pkt_offset =
5545 		max_t(u32, env->prog->aux->max_pkt_offset,
5546 		      off + reg->umax_value + size - 1);
5547 
5548 	return err;
5549 }
5550 
5551 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5552 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5553 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5554 			    struct btf **btf, u32 *btf_id)
5555 {
5556 	struct bpf_insn_access_aux info = {
5557 		.reg_type = *reg_type,
5558 		.log = &env->log,
5559 	};
5560 
5561 	if (env->ops->is_valid_access &&
5562 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5563 		/* A non zero info.ctx_field_size indicates that this field is a
5564 		 * candidate for later verifier transformation to load the whole
5565 		 * field and then apply a mask when accessed with a narrower
5566 		 * access than actual ctx access size. A zero info.ctx_field_size
5567 		 * will only allow for whole field access and rejects any other
5568 		 * type of narrower access.
5569 		 */
5570 		*reg_type = info.reg_type;
5571 
5572 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5573 			*btf = info.btf;
5574 			*btf_id = info.btf_id;
5575 		} else {
5576 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5577 		}
5578 		/* remember the offset of last byte accessed in ctx */
5579 		if (env->prog->aux->max_ctx_offset < off + size)
5580 			env->prog->aux->max_ctx_offset = off + size;
5581 		return 0;
5582 	}
5583 
5584 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5585 	return -EACCES;
5586 }
5587 
5588 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5589 				  int size)
5590 {
5591 	if (size < 0 || off < 0 ||
5592 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5593 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5594 			off, size);
5595 		return -EACCES;
5596 	}
5597 	return 0;
5598 }
5599 
5600 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5601 			     u32 regno, int off, int size,
5602 			     enum bpf_access_type t)
5603 {
5604 	struct bpf_reg_state *regs = cur_regs(env);
5605 	struct bpf_reg_state *reg = &regs[regno];
5606 	struct bpf_insn_access_aux info = {};
5607 	bool valid;
5608 
5609 	if (reg->smin_value < 0) {
5610 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5611 			regno);
5612 		return -EACCES;
5613 	}
5614 
5615 	switch (reg->type) {
5616 	case PTR_TO_SOCK_COMMON:
5617 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5618 		break;
5619 	case PTR_TO_SOCKET:
5620 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5621 		break;
5622 	case PTR_TO_TCP_SOCK:
5623 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5624 		break;
5625 	case PTR_TO_XDP_SOCK:
5626 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5627 		break;
5628 	default:
5629 		valid = false;
5630 	}
5631 
5632 
5633 	if (valid) {
5634 		env->insn_aux_data[insn_idx].ctx_field_size =
5635 			info.ctx_field_size;
5636 		return 0;
5637 	}
5638 
5639 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5640 		regno, reg_type_str(env, reg->type), off, size);
5641 
5642 	return -EACCES;
5643 }
5644 
5645 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5646 {
5647 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5648 }
5649 
5650 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5651 {
5652 	const struct bpf_reg_state *reg = reg_state(env, regno);
5653 
5654 	return reg->type == PTR_TO_CTX;
5655 }
5656 
5657 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5658 {
5659 	const struct bpf_reg_state *reg = reg_state(env, regno);
5660 
5661 	return type_is_sk_pointer(reg->type);
5662 }
5663 
5664 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5665 {
5666 	const struct bpf_reg_state *reg = reg_state(env, regno);
5667 
5668 	return type_is_pkt_pointer(reg->type);
5669 }
5670 
5671 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5672 {
5673 	const struct bpf_reg_state *reg = reg_state(env, regno);
5674 
5675 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5676 	return reg->type == PTR_TO_FLOW_KEYS;
5677 }
5678 
5679 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5680 #ifdef CONFIG_NET
5681 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5682 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5683 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5684 #endif
5685 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5686 };
5687 
5688 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5689 {
5690 	/* A referenced register is always trusted. */
5691 	if (reg->ref_obj_id)
5692 		return true;
5693 
5694 	/* Types listed in the reg2btf_ids are always trusted */
5695 	if (reg2btf_ids[base_type(reg->type)] &&
5696 	    !bpf_type_has_unsafe_modifiers(reg->type))
5697 		return true;
5698 
5699 	/* If a register is not referenced, it is trusted if it has the
5700 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5701 	 * other type modifiers may be safe, but we elect to take an opt-in
5702 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5703 	 * not.
5704 	 *
5705 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5706 	 * for whether a register is trusted.
5707 	 */
5708 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5709 	       !bpf_type_has_unsafe_modifiers(reg->type);
5710 }
5711 
5712 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5713 {
5714 	return reg->type & MEM_RCU;
5715 }
5716 
5717 static void clear_trusted_flags(enum bpf_type_flag *flag)
5718 {
5719 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5720 }
5721 
5722 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5723 				   const struct bpf_reg_state *reg,
5724 				   int off, int size, bool strict)
5725 {
5726 	struct tnum reg_off;
5727 	int ip_align;
5728 
5729 	/* Byte size accesses are always allowed. */
5730 	if (!strict || size == 1)
5731 		return 0;
5732 
5733 	/* For platforms that do not have a Kconfig enabling
5734 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5735 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5736 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5737 	 * to this code only in strict mode where we want to emulate
5738 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5739 	 * unconditional IP align value of '2'.
5740 	 */
5741 	ip_align = 2;
5742 
5743 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5744 	if (!tnum_is_aligned(reg_off, size)) {
5745 		char tn_buf[48];
5746 
5747 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5748 		verbose(env,
5749 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5750 			ip_align, tn_buf, reg->off, off, size);
5751 		return -EACCES;
5752 	}
5753 
5754 	return 0;
5755 }
5756 
5757 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5758 				       const struct bpf_reg_state *reg,
5759 				       const char *pointer_desc,
5760 				       int off, int size, bool strict)
5761 {
5762 	struct tnum reg_off;
5763 
5764 	/* Byte size accesses are always allowed. */
5765 	if (!strict || size == 1)
5766 		return 0;
5767 
5768 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5769 	if (!tnum_is_aligned(reg_off, size)) {
5770 		char tn_buf[48];
5771 
5772 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5773 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5774 			pointer_desc, tn_buf, reg->off, off, size);
5775 		return -EACCES;
5776 	}
5777 
5778 	return 0;
5779 }
5780 
5781 static int check_ptr_alignment(struct bpf_verifier_env *env,
5782 			       const struct bpf_reg_state *reg, int off,
5783 			       int size, bool strict_alignment_once)
5784 {
5785 	bool strict = env->strict_alignment || strict_alignment_once;
5786 	const char *pointer_desc = "";
5787 
5788 	switch (reg->type) {
5789 	case PTR_TO_PACKET:
5790 	case PTR_TO_PACKET_META:
5791 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5792 		 * right in front, treat it the very same way.
5793 		 */
5794 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5795 	case PTR_TO_FLOW_KEYS:
5796 		pointer_desc = "flow keys ";
5797 		break;
5798 	case PTR_TO_MAP_KEY:
5799 		pointer_desc = "key ";
5800 		break;
5801 	case PTR_TO_MAP_VALUE:
5802 		pointer_desc = "value ";
5803 		break;
5804 	case PTR_TO_CTX:
5805 		pointer_desc = "context ";
5806 		break;
5807 	case PTR_TO_STACK:
5808 		pointer_desc = "stack ";
5809 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5810 		 * and check_stack_read_fixed_off() relies on stack accesses being
5811 		 * aligned.
5812 		 */
5813 		strict = true;
5814 		break;
5815 	case PTR_TO_SOCKET:
5816 		pointer_desc = "sock ";
5817 		break;
5818 	case PTR_TO_SOCK_COMMON:
5819 		pointer_desc = "sock_common ";
5820 		break;
5821 	case PTR_TO_TCP_SOCK:
5822 		pointer_desc = "tcp_sock ";
5823 		break;
5824 	case PTR_TO_XDP_SOCK:
5825 		pointer_desc = "xdp_sock ";
5826 		break;
5827 	default:
5828 		break;
5829 	}
5830 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5831 					   strict);
5832 }
5833 
5834 /* starting from main bpf function walk all instructions of the function
5835  * and recursively walk all callees that given function can call.
5836  * Ignore jump and exit insns.
5837  * Since recursion is prevented by check_cfg() this algorithm
5838  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5839  */
5840 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5841 {
5842 	struct bpf_subprog_info *subprog = env->subprog_info;
5843 	struct bpf_insn *insn = env->prog->insnsi;
5844 	int depth = 0, frame = 0, i, subprog_end;
5845 	bool tail_call_reachable = false;
5846 	int ret_insn[MAX_CALL_FRAMES];
5847 	int ret_prog[MAX_CALL_FRAMES];
5848 	int j;
5849 
5850 	i = subprog[idx].start;
5851 process_func:
5852 	/* protect against potential stack overflow that might happen when
5853 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5854 	 * depth for such case down to 256 so that the worst case scenario
5855 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5856 	 * 8k).
5857 	 *
5858 	 * To get the idea what might happen, see an example:
5859 	 * func1 -> sub rsp, 128
5860 	 *  subfunc1 -> sub rsp, 256
5861 	 *  tailcall1 -> add rsp, 256
5862 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5863 	 *   subfunc2 -> sub rsp, 64
5864 	 *   subfunc22 -> sub rsp, 128
5865 	 *   tailcall2 -> add rsp, 128
5866 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5867 	 *
5868 	 * tailcall will unwind the current stack frame but it will not get rid
5869 	 * of caller's stack as shown on the example above.
5870 	 */
5871 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5872 		verbose(env,
5873 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5874 			depth);
5875 		return -EACCES;
5876 	}
5877 	/* round up to 32-bytes, since this is granularity
5878 	 * of interpreter stack size
5879 	 */
5880 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5881 	if (depth > MAX_BPF_STACK) {
5882 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5883 			frame + 1, depth);
5884 		return -EACCES;
5885 	}
5886 continue_func:
5887 	subprog_end = subprog[idx + 1].start;
5888 	for (; i < subprog_end; i++) {
5889 		int next_insn, sidx;
5890 
5891 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5892 			continue;
5893 		/* remember insn and function to return to */
5894 		ret_insn[frame] = i + 1;
5895 		ret_prog[frame] = idx;
5896 
5897 		/* find the callee */
5898 		next_insn = i + insn[i].imm + 1;
5899 		sidx = find_subprog(env, next_insn);
5900 		if (sidx < 0) {
5901 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5902 				  next_insn);
5903 			return -EFAULT;
5904 		}
5905 		if (subprog[sidx].is_async_cb) {
5906 			if (subprog[sidx].has_tail_call) {
5907 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5908 				return -EFAULT;
5909 			}
5910 			/* async callbacks don't increase bpf prog stack size unless called directly */
5911 			if (!bpf_pseudo_call(insn + i))
5912 				continue;
5913 		}
5914 		i = next_insn;
5915 		idx = sidx;
5916 
5917 		if (subprog[idx].has_tail_call)
5918 			tail_call_reachable = true;
5919 
5920 		frame++;
5921 		if (frame >= MAX_CALL_FRAMES) {
5922 			verbose(env, "the call stack of %d frames is too deep !\n",
5923 				frame);
5924 			return -E2BIG;
5925 		}
5926 		goto process_func;
5927 	}
5928 	/* if tail call got detected across bpf2bpf calls then mark each of the
5929 	 * currently present subprog frames as tail call reachable subprogs;
5930 	 * this info will be utilized by JIT so that we will be preserving the
5931 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5932 	 */
5933 	if (tail_call_reachable)
5934 		for (j = 0; j < frame; j++)
5935 			subprog[ret_prog[j]].tail_call_reachable = true;
5936 	if (subprog[0].tail_call_reachable)
5937 		env->prog->aux->tail_call_reachable = true;
5938 
5939 	/* end of for() loop means the last insn of the 'subprog'
5940 	 * was reached. Doesn't matter whether it was JA or EXIT
5941 	 */
5942 	if (frame == 0)
5943 		return 0;
5944 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5945 	frame--;
5946 	i = ret_insn[frame];
5947 	idx = ret_prog[frame];
5948 	goto continue_func;
5949 }
5950 
5951 static int check_max_stack_depth(struct bpf_verifier_env *env)
5952 {
5953 	struct bpf_subprog_info *si = env->subprog_info;
5954 	int ret;
5955 
5956 	for (int i = 0; i < env->subprog_cnt; i++) {
5957 		if (!i || si[i].is_async_cb) {
5958 			ret = check_max_stack_depth_subprog(env, i);
5959 			if (ret < 0)
5960 				return ret;
5961 		}
5962 		continue;
5963 	}
5964 	return 0;
5965 }
5966 
5967 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5968 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5969 				  const struct bpf_insn *insn, int idx)
5970 {
5971 	int start = idx + insn->imm + 1, subprog;
5972 
5973 	subprog = find_subprog(env, start);
5974 	if (subprog < 0) {
5975 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5976 			  start);
5977 		return -EFAULT;
5978 	}
5979 	return env->subprog_info[subprog].stack_depth;
5980 }
5981 #endif
5982 
5983 static int __check_buffer_access(struct bpf_verifier_env *env,
5984 				 const char *buf_info,
5985 				 const struct bpf_reg_state *reg,
5986 				 int regno, int off, int size)
5987 {
5988 	if (off < 0) {
5989 		verbose(env,
5990 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5991 			regno, buf_info, off, size);
5992 		return -EACCES;
5993 	}
5994 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5995 		char tn_buf[48];
5996 
5997 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5998 		verbose(env,
5999 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6000 			regno, off, tn_buf);
6001 		return -EACCES;
6002 	}
6003 
6004 	return 0;
6005 }
6006 
6007 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6008 				  const struct bpf_reg_state *reg,
6009 				  int regno, int off, int size)
6010 {
6011 	int err;
6012 
6013 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6014 	if (err)
6015 		return err;
6016 
6017 	if (off + size > env->prog->aux->max_tp_access)
6018 		env->prog->aux->max_tp_access = off + size;
6019 
6020 	return 0;
6021 }
6022 
6023 static int check_buffer_access(struct bpf_verifier_env *env,
6024 			       const struct bpf_reg_state *reg,
6025 			       int regno, int off, int size,
6026 			       bool zero_size_allowed,
6027 			       u32 *max_access)
6028 {
6029 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6030 	int err;
6031 
6032 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6033 	if (err)
6034 		return err;
6035 
6036 	if (off + size > *max_access)
6037 		*max_access = off + size;
6038 
6039 	return 0;
6040 }
6041 
6042 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6043 static void zext_32_to_64(struct bpf_reg_state *reg)
6044 {
6045 	reg->var_off = tnum_subreg(reg->var_off);
6046 	__reg_assign_32_into_64(reg);
6047 }
6048 
6049 /* truncate register to smaller size (in bytes)
6050  * must be called with size < BPF_REG_SIZE
6051  */
6052 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6053 {
6054 	u64 mask;
6055 
6056 	/* clear high bits in bit representation */
6057 	reg->var_off = tnum_cast(reg->var_off, size);
6058 
6059 	/* fix arithmetic bounds */
6060 	mask = ((u64)1 << (size * 8)) - 1;
6061 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6062 		reg->umin_value &= mask;
6063 		reg->umax_value &= mask;
6064 	} else {
6065 		reg->umin_value = 0;
6066 		reg->umax_value = mask;
6067 	}
6068 	reg->smin_value = reg->umin_value;
6069 	reg->smax_value = reg->umax_value;
6070 
6071 	/* If size is smaller than 32bit register the 32bit register
6072 	 * values are also truncated so we push 64-bit bounds into
6073 	 * 32-bit bounds. Above were truncated < 32-bits already.
6074 	 */
6075 	if (size >= 4)
6076 		return;
6077 	__reg_combine_64_into_32(reg);
6078 }
6079 
6080 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6081 {
6082 	if (size == 1) {
6083 		reg->smin_value = reg->s32_min_value = S8_MIN;
6084 		reg->smax_value = reg->s32_max_value = S8_MAX;
6085 	} else if (size == 2) {
6086 		reg->smin_value = reg->s32_min_value = S16_MIN;
6087 		reg->smax_value = reg->s32_max_value = S16_MAX;
6088 	} else {
6089 		/* size == 4 */
6090 		reg->smin_value = reg->s32_min_value = S32_MIN;
6091 		reg->smax_value = reg->s32_max_value = S32_MAX;
6092 	}
6093 	reg->umin_value = reg->u32_min_value = 0;
6094 	reg->umax_value = U64_MAX;
6095 	reg->u32_max_value = U32_MAX;
6096 	reg->var_off = tnum_unknown;
6097 }
6098 
6099 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6100 {
6101 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6102 	u64 top_smax_value, top_smin_value;
6103 	u64 num_bits = size * 8;
6104 
6105 	if (tnum_is_const(reg->var_off)) {
6106 		u64_cval = reg->var_off.value;
6107 		if (size == 1)
6108 			reg->var_off = tnum_const((s8)u64_cval);
6109 		else if (size == 2)
6110 			reg->var_off = tnum_const((s16)u64_cval);
6111 		else
6112 			/* size == 4 */
6113 			reg->var_off = tnum_const((s32)u64_cval);
6114 
6115 		u64_cval = reg->var_off.value;
6116 		reg->smax_value = reg->smin_value = u64_cval;
6117 		reg->umax_value = reg->umin_value = u64_cval;
6118 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6119 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6120 		return;
6121 	}
6122 
6123 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6124 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6125 
6126 	if (top_smax_value != top_smin_value)
6127 		goto out;
6128 
6129 	/* find the s64_min and s64_min after sign extension */
6130 	if (size == 1) {
6131 		init_s64_max = (s8)reg->smax_value;
6132 		init_s64_min = (s8)reg->smin_value;
6133 	} else if (size == 2) {
6134 		init_s64_max = (s16)reg->smax_value;
6135 		init_s64_min = (s16)reg->smin_value;
6136 	} else {
6137 		init_s64_max = (s32)reg->smax_value;
6138 		init_s64_min = (s32)reg->smin_value;
6139 	}
6140 
6141 	s64_max = max(init_s64_max, init_s64_min);
6142 	s64_min = min(init_s64_max, init_s64_min);
6143 
6144 	/* both of s64_max/s64_min positive or negative */
6145 	if ((s64_max >= 0) == (s64_min >= 0)) {
6146 		reg->s32_min_value = reg->smin_value = s64_min;
6147 		reg->s32_max_value = reg->smax_value = s64_max;
6148 		reg->u32_min_value = reg->umin_value = s64_min;
6149 		reg->u32_max_value = reg->umax_value = s64_max;
6150 		reg->var_off = tnum_range(s64_min, s64_max);
6151 		return;
6152 	}
6153 
6154 out:
6155 	set_sext64_default_val(reg, size);
6156 }
6157 
6158 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6159 {
6160 	if (size == 1) {
6161 		reg->s32_min_value = S8_MIN;
6162 		reg->s32_max_value = S8_MAX;
6163 	} else {
6164 		/* size == 2 */
6165 		reg->s32_min_value = S16_MIN;
6166 		reg->s32_max_value = S16_MAX;
6167 	}
6168 	reg->u32_min_value = 0;
6169 	reg->u32_max_value = U32_MAX;
6170 	reg->var_off = tnum_subreg(tnum_unknown);
6171 }
6172 
6173 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6174 {
6175 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6176 	u32 top_smax_value, top_smin_value;
6177 	u32 num_bits = size * 8;
6178 
6179 	if (tnum_is_const(reg->var_off)) {
6180 		u32_val = reg->var_off.value;
6181 		if (size == 1)
6182 			reg->var_off = tnum_const((s8)u32_val);
6183 		else
6184 			reg->var_off = tnum_const((s16)u32_val);
6185 
6186 		u32_val = reg->var_off.value;
6187 		reg->s32_min_value = reg->s32_max_value = u32_val;
6188 		reg->u32_min_value = reg->u32_max_value = u32_val;
6189 		return;
6190 	}
6191 
6192 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6193 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6194 
6195 	if (top_smax_value != top_smin_value)
6196 		goto out;
6197 
6198 	/* find the s32_min and s32_min after sign extension */
6199 	if (size == 1) {
6200 		init_s32_max = (s8)reg->s32_max_value;
6201 		init_s32_min = (s8)reg->s32_min_value;
6202 	} else {
6203 		/* size == 2 */
6204 		init_s32_max = (s16)reg->s32_max_value;
6205 		init_s32_min = (s16)reg->s32_min_value;
6206 	}
6207 	s32_max = max(init_s32_max, init_s32_min);
6208 	s32_min = min(init_s32_max, init_s32_min);
6209 
6210 	if ((s32_min >= 0) == (s32_max >= 0)) {
6211 		reg->s32_min_value = s32_min;
6212 		reg->s32_max_value = s32_max;
6213 		reg->u32_min_value = (u32)s32_min;
6214 		reg->u32_max_value = (u32)s32_max;
6215 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6216 		return;
6217 	}
6218 
6219 out:
6220 	set_sext32_default_val(reg, size);
6221 }
6222 
6223 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6224 {
6225 	/* A map is considered read-only if the following condition are true:
6226 	 *
6227 	 * 1) BPF program side cannot change any of the map content. The
6228 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6229 	 *    and was set at map creation time.
6230 	 * 2) The map value(s) have been initialized from user space by a
6231 	 *    loader and then "frozen", such that no new map update/delete
6232 	 *    operations from syscall side are possible for the rest of
6233 	 *    the map's lifetime from that point onwards.
6234 	 * 3) Any parallel/pending map update/delete operations from syscall
6235 	 *    side have been completed. Only after that point, it's safe to
6236 	 *    assume that map value(s) are immutable.
6237 	 */
6238 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6239 	       READ_ONCE(map->frozen) &&
6240 	       !bpf_map_write_active(map);
6241 }
6242 
6243 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6244 			       bool is_ldsx)
6245 {
6246 	void *ptr;
6247 	u64 addr;
6248 	int err;
6249 
6250 	err = map->ops->map_direct_value_addr(map, &addr, off);
6251 	if (err)
6252 		return err;
6253 	ptr = (void *)(long)addr + off;
6254 
6255 	switch (size) {
6256 	case sizeof(u8):
6257 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6258 		break;
6259 	case sizeof(u16):
6260 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6261 		break;
6262 	case sizeof(u32):
6263 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6264 		break;
6265 	case sizeof(u64):
6266 		*val = *(u64 *)ptr;
6267 		break;
6268 	default:
6269 		return -EINVAL;
6270 	}
6271 	return 0;
6272 }
6273 
6274 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6275 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6276 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6277 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
6278 
6279 /*
6280  * Allow list few fields as RCU trusted or full trusted.
6281  * This logic doesn't allow mix tagging and will be removed once GCC supports
6282  * btf_type_tag.
6283  */
6284 
6285 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6286 BTF_TYPE_SAFE_RCU(struct task_struct) {
6287 	const cpumask_t *cpus_ptr;
6288 	struct css_set __rcu *cgroups;
6289 	struct task_struct __rcu *real_parent;
6290 	struct task_struct *group_leader;
6291 };
6292 
6293 BTF_TYPE_SAFE_RCU(struct cgroup) {
6294 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6295 	struct kernfs_node *kn;
6296 };
6297 
6298 BTF_TYPE_SAFE_RCU(struct css_set) {
6299 	struct cgroup *dfl_cgrp;
6300 };
6301 
6302 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6303 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6304 	struct file __rcu *exe_file;
6305 };
6306 
6307 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6308  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6309  */
6310 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6311 	struct sock *sk;
6312 };
6313 
6314 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6315 	struct sock *sk;
6316 };
6317 
6318 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6319 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6320 	struct seq_file *seq;
6321 };
6322 
6323 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6324 	struct bpf_iter_meta *meta;
6325 	struct task_struct *task;
6326 };
6327 
6328 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6329 	struct file *file;
6330 };
6331 
6332 BTF_TYPE_SAFE_TRUSTED(struct file) {
6333 	struct inode *f_inode;
6334 };
6335 
6336 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6337 	/* no negative dentry-s in places where bpf can see it */
6338 	struct inode *d_inode;
6339 };
6340 
6341 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
6342 	struct sock *sk;
6343 };
6344 
6345 static bool type_is_rcu(struct bpf_verifier_env *env,
6346 			struct bpf_reg_state *reg,
6347 			const char *field_name, u32 btf_id)
6348 {
6349 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6350 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6351 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6352 
6353 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6354 }
6355 
6356 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6357 				struct bpf_reg_state *reg,
6358 				const char *field_name, u32 btf_id)
6359 {
6360 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6361 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6362 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6363 
6364 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6365 }
6366 
6367 static bool type_is_trusted(struct bpf_verifier_env *env,
6368 			    struct bpf_reg_state *reg,
6369 			    const char *field_name, u32 btf_id)
6370 {
6371 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6372 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6373 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6374 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6375 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6376 
6377 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6378 }
6379 
6380 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
6381 				    struct bpf_reg_state *reg,
6382 				    const char *field_name, u32 btf_id)
6383 {
6384 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
6385 
6386 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
6387 					  "__safe_trusted_or_null");
6388 }
6389 
6390 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6391 				   struct bpf_reg_state *regs,
6392 				   int regno, int off, int size,
6393 				   enum bpf_access_type atype,
6394 				   int value_regno)
6395 {
6396 	struct bpf_reg_state *reg = regs + regno;
6397 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6398 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6399 	const char *field_name = NULL;
6400 	enum bpf_type_flag flag = 0;
6401 	u32 btf_id = 0;
6402 	int ret;
6403 
6404 	if (!env->allow_ptr_leaks) {
6405 		verbose(env,
6406 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6407 			tname);
6408 		return -EPERM;
6409 	}
6410 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6411 		verbose(env,
6412 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6413 			tname);
6414 		return -EINVAL;
6415 	}
6416 	if (off < 0) {
6417 		verbose(env,
6418 			"R%d is ptr_%s invalid negative access: off=%d\n",
6419 			regno, tname, off);
6420 		return -EACCES;
6421 	}
6422 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6423 		char tn_buf[48];
6424 
6425 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6426 		verbose(env,
6427 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6428 			regno, tname, off, tn_buf);
6429 		return -EACCES;
6430 	}
6431 
6432 	if (reg->type & MEM_USER) {
6433 		verbose(env,
6434 			"R%d is ptr_%s access user memory: off=%d\n",
6435 			regno, tname, off);
6436 		return -EACCES;
6437 	}
6438 
6439 	if (reg->type & MEM_PERCPU) {
6440 		verbose(env,
6441 			"R%d is ptr_%s access percpu memory: off=%d\n",
6442 			regno, tname, off);
6443 		return -EACCES;
6444 	}
6445 
6446 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6447 		if (!btf_is_kernel(reg->btf)) {
6448 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6449 			return -EFAULT;
6450 		}
6451 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6452 	} else {
6453 		/* Writes are permitted with default btf_struct_access for
6454 		 * program allocated objects (which always have ref_obj_id > 0),
6455 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6456 		 */
6457 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6458 			verbose(env, "only read is supported\n");
6459 			return -EACCES;
6460 		}
6461 
6462 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6463 		    !reg->ref_obj_id) {
6464 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6465 			return -EFAULT;
6466 		}
6467 
6468 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6469 	}
6470 
6471 	if (ret < 0)
6472 		return ret;
6473 
6474 	if (ret != PTR_TO_BTF_ID) {
6475 		/* just mark; */
6476 
6477 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6478 		/* If this is an untrusted pointer, all pointers formed by walking it
6479 		 * also inherit the untrusted flag.
6480 		 */
6481 		flag = PTR_UNTRUSTED;
6482 
6483 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6484 		/* By default any pointer obtained from walking a trusted pointer is no
6485 		 * longer trusted, unless the field being accessed has explicitly been
6486 		 * marked as inheriting its parent's state of trust (either full or RCU).
6487 		 * For example:
6488 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6489 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6490 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6491 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6492 		 *
6493 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6494 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6495 		 */
6496 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6497 			flag |= PTR_TRUSTED;
6498 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
6499 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
6500 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6501 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6502 				/* ignore __rcu tag and mark it MEM_RCU */
6503 				flag |= MEM_RCU;
6504 			} else if (flag & MEM_RCU ||
6505 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6506 				/* __rcu tagged pointers can be NULL */
6507 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6508 
6509 				/* We always trust them */
6510 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6511 				    flag & PTR_UNTRUSTED)
6512 					flag &= ~PTR_UNTRUSTED;
6513 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6514 				/* keep as-is */
6515 			} else {
6516 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6517 				clear_trusted_flags(&flag);
6518 			}
6519 		} else {
6520 			/*
6521 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6522 			 * aggressively mark as untrusted otherwise such
6523 			 * pointers will be plain PTR_TO_BTF_ID without flags
6524 			 * and will be allowed to be passed into helpers for
6525 			 * compat reasons.
6526 			 */
6527 			flag = PTR_UNTRUSTED;
6528 		}
6529 	} else {
6530 		/* Old compat. Deprecated */
6531 		clear_trusted_flags(&flag);
6532 	}
6533 
6534 	if (atype == BPF_READ && value_regno >= 0)
6535 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6536 
6537 	return 0;
6538 }
6539 
6540 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6541 				   struct bpf_reg_state *regs,
6542 				   int regno, int off, int size,
6543 				   enum bpf_access_type atype,
6544 				   int value_regno)
6545 {
6546 	struct bpf_reg_state *reg = regs + regno;
6547 	struct bpf_map *map = reg->map_ptr;
6548 	struct bpf_reg_state map_reg;
6549 	enum bpf_type_flag flag = 0;
6550 	const struct btf_type *t;
6551 	const char *tname;
6552 	u32 btf_id;
6553 	int ret;
6554 
6555 	if (!btf_vmlinux) {
6556 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6557 		return -ENOTSUPP;
6558 	}
6559 
6560 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6561 		verbose(env, "map_ptr access not supported for map type %d\n",
6562 			map->map_type);
6563 		return -ENOTSUPP;
6564 	}
6565 
6566 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6567 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6568 
6569 	if (!env->allow_ptr_leaks) {
6570 		verbose(env,
6571 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6572 			tname);
6573 		return -EPERM;
6574 	}
6575 
6576 	if (off < 0) {
6577 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6578 			regno, tname, off);
6579 		return -EACCES;
6580 	}
6581 
6582 	if (atype != BPF_READ) {
6583 		verbose(env, "only read from %s is supported\n", tname);
6584 		return -EACCES;
6585 	}
6586 
6587 	/* Simulate access to a PTR_TO_BTF_ID */
6588 	memset(&map_reg, 0, sizeof(map_reg));
6589 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6590 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6591 	if (ret < 0)
6592 		return ret;
6593 
6594 	if (value_regno >= 0)
6595 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6596 
6597 	return 0;
6598 }
6599 
6600 /* Check that the stack access at the given offset is within bounds. The
6601  * maximum valid offset is -1.
6602  *
6603  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6604  * -state->allocated_stack for reads.
6605  */
6606 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6607                                           s64 off,
6608                                           struct bpf_func_state *state,
6609                                           enum bpf_access_type t)
6610 {
6611 	int min_valid_off;
6612 
6613 	if (t == BPF_WRITE || env->allow_uninit_stack)
6614 		min_valid_off = -MAX_BPF_STACK;
6615 	else
6616 		min_valid_off = -state->allocated_stack;
6617 
6618 	if (off < min_valid_off || off > -1)
6619 		return -EACCES;
6620 	return 0;
6621 }
6622 
6623 /* Check that the stack access at 'regno + off' falls within the maximum stack
6624  * bounds.
6625  *
6626  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6627  */
6628 static int check_stack_access_within_bounds(
6629 		struct bpf_verifier_env *env,
6630 		int regno, int off, int access_size,
6631 		enum bpf_access_src src, enum bpf_access_type type)
6632 {
6633 	struct bpf_reg_state *regs = cur_regs(env);
6634 	struct bpf_reg_state *reg = regs + regno;
6635 	struct bpf_func_state *state = func(env, reg);
6636 	s64 min_off, max_off;
6637 	int err;
6638 	char *err_extra;
6639 
6640 	if (src == ACCESS_HELPER)
6641 		/* We don't know if helpers are reading or writing (or both). */
6642 		err_extra = " indirect access to";
6643 	else if (type == BPF_READ)
6644 		err_extra = " read from";
6645 	else
6646 		err_extra = " write to";
6647 
6648 	if (tnum_is_const(reg->var_off)) {
6649 		min_off = (s64)reg->var_off.value + off;
6650 		max_off = min_off + access_size;
6651 	} else {
6652 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6653 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6654 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6655 				err_extra, regno);
6656 			return -EACCES;
6657 		}
6658 		min_off = reg->smin_value + off;
6659 		max_off = reg->smax_value + off + access_size;
6660 	}
6661 
6662 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6663 	if (!err && max_off > 0)
6664 		err = -EINVAL; /* out of stack access into non-negative offsets */
6665 	if (!err && access_size < 0)
6666 		/* access_size should not be negative (or overflow an int); others checks
6667 		 * along the way should have prevented such an access.
6668 		 */
6669 		err = -EFAULT; /* invalid negative access size; integer overflow? */
6670 
6671 	if (err) {
6672 		if (tnum_is_const(reg->var_off)) {
6673 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6674 				err_extra, regno, off, access_size);
6675 		} else {
6676 			char tn_buf[48];
6677 
6678 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6679 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6680 				err_extra, regno, tn_buf, access_size);
6681 		}
6682 		return err;
6683 	}
6684 
6685 	return grow_stack_state(env, state, round_up(-min_off, BPF_REG_SIZE));
6686 }
6687 
6688 /* check whether memory at (regno + off) is accessible for t = (read | write)
6689  * if t==write, value_regno is a register which value is stored into memory
6690  * if t==read, value_regno is a register which will receive the value from memory
6691  * if t==write && value_regno==-1, some unknown value is stored into memory
6692  * if t==read && value_regno==-1, don't care what we read from memory
6693  */
6694 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6695 			    int off, int bpf_size, enum bpf_access_type t,
6696 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6697 {
6698 	struct bpf_reg_state *regs = cur_regs(env);
6699 	struct bpf_reg_state *reg = regs + regno;
6700 	int size, err = 0;
6701 
6702 	size = bpf_size_to_bytes(bpf_size);
6703 	if (size < 0)
6704 		return size;
6705 
6706 	/* alignment checks will add in reg->off themselves */
6707 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6708 	if (err)
6709 		return err;
6710 
6711 	/* for access checks, reg->off is just part of off */
6712 	off += reg->off;
6713 
6714 	if (reg->type == PTR_TO_MAP_KEY) {
6715 		if (t == BPF_WRITE) {
6716 			verbose(env, "write to change key R%d not allowed\n", regno);
6717 			return -EACCES;
6718 		}
6719 
6720 		err = check_mem_region_access(env, regno, off, size,
6721 					      reg->map_ptr->key_size, false);
6722 		if (err)
6723 			return err;
6724 		if (value_regno >= 0)
6725 			mark_reg_unknown(env, regs, value_regno);
6726 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6727 		struct btf_field *kptr_field = NULL;
6728 
6729 		if (t == BPF_WRITE && value_regno >= 0 &&
6730 		    is_pointer_value(env, value_regno)) {
6731 			verbose(env, "R%d leaks addr into map\n", value_regno);
6732 			return -EACCES;
6733 		}
6734 		err = check_map_access_type(env, regno, off, size, t);
6735 		if (err)
6736 			return err;
6737 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6738 		if (err)
6739 			return err;
6740 		if (tnum_is_const(reg->var_off))
6741 			kptr_field = btf_record_find(reg->map_ptr->record,
6742 						     off + reg->var_off.value, BPF_KPTR);
6743 		if (kptr_field) {
6744 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6745 		} else if (t == BPF_READ && value_regno >= 0) {
6746 			struct bpf_map *map = reg->map_ptr;
6747 
6748 			/* if map is read-only, track its contents as scalars */
6749 			if (tnum_is_const(reg->var_off) &&
6750 			    bpf_map_is_rdonly(map) &&
6751 			    map->ops->map_direct_value_addr) {
6752 				int map_off = off + reg->var_off.value;
6753 				u64 val = 0;
6754 
6755 				err = bpf_map_direct_read(map, map_off, size,
6756 							  &val, is_ldsx);
6757 				if (err)
6758 					return err;
6759 
6760 				regs[value_regno].type = SCALAR_VALUE;
6761 				__mark_reg_known(&regs[value_regno], val);
6762 			} else {
6763 				mark_reg_unknown(env, regs, value_regno);
6764 			}
6765 		}
6766 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6767 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6768 
6769 		if (type_may_be_null(reg->type)) {
6770 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6771 				reg_type_str(env, reg->type));
6772 			return -EACCES;
6773 		}
6774 
6775 		if (t == BPF_WRITE && rdonly_mem) {
6776 			verbose(env, "R%d cannot write into %s\n",
6777 				regno, reg_type_str(env, reg->type));
6778 			return -EACCES;
6779 		}
6780 
6781 		if (t == BPF_WRITE && value_regno >= 0 &&
6782 		    is_pointer_value(env, value_regno)) {
6783 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6784 			return -EACCES;
6785 		}
6786 
6787 		err = check_mem_region_access(env, regno, off, size,
6788 					      reg->mem_size, false);
6789 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6790 			mark_reg_unknown(env, regs, value_regno);
6791 	} else if (reg->type == PTR_TO_CTX) {
6792 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6793 		struct btf *btf = NULL;
6794 		u32 btf_id = 0;
6795 
6796 		if (t == BPF_WRITE && value_regno >= 0 &&
6797 		    is_pointer_value(env, value_regno)) {
6798 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6799 			return -EACCES;
6800 		}
6801 
6802 		err = check_ptr_off_reg(env, reg, regno);
6803 		if (err < 0)
6804 			return err;
6805 
6806 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6807 				       &btf_id);
6808 		if (err)
6809 			verbose_linfo(env, insn_idx, "; ");
6810 		if (!err && t == BPF_READ && value_regno >= 0) {
6811 			/* ctx access returns either a scalar, or a
6812 			 * PTR_TO_PACKET[_META,_END]. In the latter
6813 			 * case, we know the offset is zero.
6814 			 */
6815 			if (reg_type == SCALAR_VALUE) {
6816 				mark_reg_unknown(env, regs, value_regno);
6817 			} else {
6818 				mark_reg_known_zero(env, regs,
6819 						    value_regno);
6820 				if (type_may_be_null(reg_type))
6821 					regs[value_regno].id = ++env->id_gen;
6822 				/* A load of ctx field could have different
6823 				 * actual load size with the one encoded in the
6824 				 * insn. When the dst is PTR, it is for sure not
6825 				 * a sub-register.
6826 				 */
6827 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6828 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6829 					regs[value_regno].btf = btf;
6830 					regs[value_regno].btf_id = btf_id;
6831 				}
6832 			}
6833 			regs[value_regno].type = reg_type;
6834 		}
6835 
6836 	} else if (reg->type == PTR_TO_STACK) {
6837 		/* Basic bounds checks. */
6838 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6839 		if (err)
6840 			return err;
6841 
6842 		if (t == BPF_READ)
6843 			err = check_stack_read(env, regno, off, size,
6844 					       value_regno);
6845 		else
6846 			err = check_stack_write(env, regno, off, size,
6847 						value_regno, insn_idx);
6848 	} else if (reg_is_pkt_pointer(reg)) {
6849 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6850 			verbose(env, "cannot write into packet\n");
6851 			return -EACCES;
6852 		}
6853 		if (t == BPF_WRITE && value_regno >= 0 &&
6854 		    is_pointer_value(env, value_regno)) {
6855 			verbose(env, "R%d leaks addr into packet\n",
6856 				value_regno);
6857 			return -EACCES;
6858 		}
6859 		err = check_packet_access(env, regno, off, size, false);
6860 		if (!err && t == BPF_READ && value_regno >= 0)
6861 			mark_reg_unknown(env, regs, value_regno);
6862 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6863 		if (t == BPF_WRITE && value_regno >= 0 &&
6864 		    is_pointer_value(env, value_regno)) {
6865 			verbose(env, "R%d leaks addr into flow keys\n",
6866 				value_regno);
6867 			return -EACCES;
6868 		}
6869 
6870 		err = check_flow_keys_access(env, off, size);
6871 		if (!err && t == BPF_READ && value_regno >= 0)
6872 			mark_reg_unknown(env, regs, value_regno);
6873 	} else if (type_is_sk_pointer(reg->type)) {
6874 		if (t == BPF_WRITE) {
6875 			verbose(env, "R%d cannot write into %s\n",
6876 				regno, reg_type_str(env, reg->type));
6877 			return -EACCES;
6878 		}
6879 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6880 		if (!err && value_regno >= 0)
6881 			mark_reg_unknown(env, regs, value_regno);
6882 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6883 		err = check_tp_buffer_access(env, reg, regno, off, size);
6884 		if (!err && t == BPF_READ && value_regno >= 0)
6885 			mark_reg_unknown(env, regs, value_regno);
6886 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6887 		   !type_may_be_null(reg->type)) {
6888 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6889 					      value_regno);
6890 	} else if (reg->type == CONST_PTR_TO_MAP) {
6891 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6892 					      value_regno);
6893 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6894 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6895 		u32 *max_access;
6896 
6897 		if (rdonly_mem) {
6898 			if (t == BPF_WRITE) {
6899 				verbose(env, "R%d cannot write into %s\n",
6900 					regno, reg_type_str(env, reg->type));
6901 				return -EACCES;
6902 			}
6903 			max_access = &env->prog->aux->max_rdonly_access;
6904 		} else {
6905 			max_access = &env->prog->aux->max_rdwr_access;
6906 		}
6907 
6908 		err = check_buffer_access(env, reg, regno, off, size, false,
6909 					  max_access);
6910 
6911 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6912 			mark_reg_unknown(env, regs, value_regno);
6913 	} else {
6914 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6915 			reg_type_str(env, reg->type));
6916 		return -EACCES;
6917 	}
6918 
6919 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6920 	    regs[value_regno].type == SCALAR_VALUE) {
6921 		if (!is_ldsx)
6922 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6923 			coerce_reg_to_size(&regs[value_regno], size);
6924 		else
6925 			coerce_reg_to_size_sx(&regs[value_regno], size);
6926 	}
6927 	return err;
6928 }
6929 
6930 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6931 {
6932 	int load_reg;
6933 	int err;
6934 
6935 	switch (insn->imm) {
6936 	case BPF_ADD:
6937 	case BPF_ADD | BPF_FETCH:
6938 	case BPF_AND:
6939 	case BPF_AND | BPF_FETCH:
6940 	case BPF_OR:
6941 	case BPF_OR | BPF_FETCH:
6942 	case BPF_XOR:
6943 	case BPF_XOR | BPF_FETCH:
6944 	case BPF_XCHG:
6945 	case BPF_CMPXCHG:
6946 		break;
6947 	default:
6948 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6949 		return -EINVAL;
6950 	}
6951 
6952 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6953 		verbose(env, "invalid atomic operand size\n");
6954 		return -EINVAL;
6955 	}
6956 
6957 	/* check src1 operand */
6958 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6959 	if (err)
6960 		return err;
6961 
6962 	/* check src2 operand */
6963 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6964 	if (err)
6965 		return err;
6966 
6967 	if (insn->imm == BPF_CMPXCHG) {
6968 		/* Check comparison of R0 with memory location */
6969 		const u32 aux_reg = BPF_REG_0;
6970 
6971 		err = check_reg_arg(env, aux_reg, SRC_OP);
6972 		if (err)
6973 			return err;
6974 
6975 		if (is_pointer_value(env, aux_reg)) {
6976 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6977 			return -EACCES;
6978 		}
6979 	}
6980 
6981 	if (is_pointer_value(env, insn->src_reg)) {
6982 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6983 		return -EACCES;
6984 	}
6985 
6986 	if (is_ctx_reg(env, insn->dst_reg) ||
6987 	    is_pkt_reg(env, insn->dst_reg) ||
6988 	    is_flow_key_reg(env, insn->dst_reg) ||
6989 	    is_sk_reg(env, insn->dst_reg)) {
6990 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6991 			insn->dst_reg,
6992 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6993 		return -EACCES;
6994 	}
6995 
6996 	if (insn->imm & BPF_FETCH) {
6997 		if (insn->imm == BPF_CMPXCHG)
6998 			load_reg = BPF_REG_0;
6999 		else
7000 			load_reg = insn->src_reg;
7001 
7002 		/* check and record load of old value */
7003 		err = check_reg_arg(env, load_reg, DST_OP);
7004 		if (err)
7005 			return err;
7006 	} else {
7007 		/* This instruction accesses a memory location but doesn't
7008 		 * actually load it into a register.
7009 		 */
7010 		load_reg = -1;
7011 	}
7012 
7013 	/* Check whether we can read the memory, with second call for fetch
7014 	 * case to simulate the register fill.
7015 	 */
7016 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7017 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7018 	if (!err && load_reg >= 0)
7019 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7020 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
7021 				       true, false);
7022 	if (err)
7023 		return err;
7024 
7025 	/* Check whether we can write into the same memory. */
7026 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7027 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7028 	if (err)
7029 		return err;
7030 
7031 	return 0;
7032 }
7033 
7034 /* When register 'regno' is used to read the stack (either directly or through
7035  * a helper function) make sure that it's within stack boundary and, depending
7036  * on the access type and privileges, that all elements of the stack are
7037  * initialized.
7038  *
7039  * 'off' includes 'regno->off', but not its dynamic part (if any).
7040  *
7041  * All registers that have been spilled on the stack in the slots within the
7042  * read offsets are marked as read.
7043  */
7044 static int check_stack_range_initialized(
7045 		struct bpf_verifier_env *env, int regno, int off,
7046 		int access_size, bool zero_size_allowed,
7047 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7048 {
7049 	struct bpf_reg_state *reg = reg_state(env, regno);
7050 	struct bpf_func_state *state = func(env, reg);
7051 	int err, min_off, max_off, i, j, slot, spi;
7052 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7053 	enum bpf_access_type bounds_check_type;
7054 	/* Some accesses can write anything into the stack, others are
7055 	 * read-only.
7056 	 */
7057 	bool clobber = false;
7058 
7059 	if (access_size == 0 && !zero_size_allowed) {
7060 		verbose(env, "invalid zero-sized read\n");
7061 		return -EACCES;
7062 	}
7063 
7064 	if (type == ACCESS_HELPER) {
7065 		/* The bounds checks for writes are more permissive than for
7066 		 * reads. However, if raw_mode is not set, we'll do extra
7067 		 * checks below.
7068 		 */
7069 		bounds_check_type = BPF_WRITE;
7070 		clobber = true;
7071 	} else {
7072 		bounds_check_type = BPF_READ;
7073 	}
7074 	err = check_stack_access_within_bounds(env, regno, off, access_size,
7075 					       type, bounds_check_type);
7076 	if (err)
7077 		return err;
7078 
7079 
7080 	if (tnum_is_const(reg->var_off)) {
7081 		min_off = max_off = reg->var_off.value + off;
7082 	} else {
7083 		/* Variable offset is prohibited for unprivileged mode for
7084 		 * simplicity since it requires corresponding support in
7085 		 * Spectre masking for stack ALU.
7086 		 * See also retrieve_ptr_limit().
7087 		 */
7088 		if (!env->bypass_spec_v1) {
7089 			char tn_buf[48];
7090 
7091 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7092 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7093 				regno, err_extra, tn_buf);
7094 			return -EACCES;
7095 		}
7096 		/* Only initialized buffer on stack is allowed to be accessed
7097 		 * with variable offset. With uninitialized buffer it's hard to
7098 		 * guarantee that whole memory is marked as initialized on
7099 		 * helper return since specific bounds are unknown what may
7100 		 * cause uninitialized stack leaking.
7101 		 */
7102 		if (meta && meta->raw_mode)
7103 			meta = NULL;
7104 
7105 		min_off = reg->smin_value + off;
7106 		max_off = reg->smax_value + off;
7107 	}
7108 
7109 	if (meta && meta->raw_mode) {
7110 		/* Ensure we won't be overwriting dynptrs when simulating byte
7111 		 * by byte access in check_helper_call using meta.access_size.
7112 		 * This would be a problem if we have a helper in the future
7113 		 * which takes:
7114 		 *
7115 		 *	helper(uninit_mem, len, dynptr)
7116 		 *
7117 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7118 		 * may end up writing to dynptr itself when touching memory from
7119 		 * arg 1. This can be relaxed on a case by case basis for known
7120 		 * safe cases, but reject due to the possibilitiy of aliasing by
7121 		 * default.
7122 		 */
7123 		for (i = min_off; i < max_off + access_size; i++) {
7124 			int stack_off = -i - 1;
7125 
7126 			spi = __get_spi(i);
7127 			/* raw_mode may write past allocated_stack */
7128 			if (state->allocated_stack <= stack_off)
7129 				continue;
7130 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7131 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7132 				return -EACCES;
7133 			}
7134 		}
7135 		meta->access_size = access_size;
7136 		meta->regno = regno;
7137 		return 0;
7138 	}
7139 
7140 	for (i = min_off; i < max_off + access_size; i++) {
7141 		u8 *stype;
7142 
7143 		slot = -i - 1;
7144 		spi = slot / BPF_REG_SIZE;
7145 		if (state->allocated_stack <= slot) {
7146 			verbose(env, "verifier bug: allocated_stack too small");
7147 			return -EFAULT;
7148 		}
7149 
7150 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7151 		if (*stype == STACK_MISC)
7152 			goto mark;
7153 		if ((*stype == STACK_ZERO) ||
7154 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7155 			if (clobber) {
7156 				/* helper can write anything into the stack */
7157 				*stype = STACK_MISC;
7158 			}
7159 			goto mark;
7160 		}
7161 
7162 		if (is_spilled_reg(&state->stack[spi]) &&
7163 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7164 		     env->allow_ptr_leaks)) {
7165 			if (clobber) {
7166 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7167 				for (j = 0; j < BPF_REG_SIZE; j++)
7168 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7169 			}
7170 			goto mark;
7171 		}
7172 
7173 		if (tnum_is_const(reg->var_off)) {
7174 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7175 				err_extra, regno, min_off, i - min_off, access_size);
7176 		} else {
7177 			char tn_buf[48];
7178 
7179 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7180 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7181 				err_extra, regno, tn_buf, i - min_off, access_size);
7182 		}
7183 		return -EACCES;
7184 mark:
7185 		/* reading any byte out of 8-byte 'spill_slot' will cause
7186 		 * the whole slot to be marked as 'read'
7187 		 */
7188 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7189 			      state->stack[spi].spilled_ptr.parent,
7190 			      REG_LIVE_READ64);
7191 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7192 		 * be sure that whether stack slot is written to or not. Hence,
7193 		 * we must still conservatively propagate reads upwards even if
7194 		 * helper may write to the entire memory range.
7195 		 */
7196 	}
7197 	return 0;
7198 }
7199 
7200 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7201 				   int access_size, bool zero_size_allowed,
7202 				   struct bpf_call_arg_meta *meta)
7203 {
7204 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7205 	u32 *max_access;
7206 
7207 	switch (base_type(reg->type)) {
7208 	case PTR_TO_PACKET:
7209 	case PTR_TO_PACKET_META:
7210 		return check_packet_access(env, regno, reg->off, access_size,
7211 					   zero_size_allowed);
7212 	case PTR_TO_MAP_KEY:
7213 		if (meta && meta->raw_mode) {
7214 			verbose(env, "R%d cannot write into %s\n", regno,
7215 				reg_type_str(env, reg->type));
7216 			return -EACCES;
7217 		}
7218 		return check_mem_region_access(env, regno, reg->off, access_size,
7219 					       reg->map_ptr->key_size, false);
7220 	case PTR_TO_MAP_VALUE:
7221 		if (check_map_access_type(env, regno, reg->off, access_size,
7222 					  meta && meta->raw_mode ? BPF_WRITE :
7223 					  BPF_READ))
7224 			return -EACCES;
7225 		return check_map_access(env, regno, reg->off, access_size,
7226 					zero_size_allowed, ACCESS_HELPER);
7227 	case PTR_TO_MEM:
7228 		if (type_is_rdonly_mem(reg->type)) {
7229 			if (meta && meta->raw_mode) {
7230 				verbose(env, "R%d cannot write into %s\n", regno,
7231 					reg_type_str(env, reg->type));
7232 				return -EACCES;
7233 			}
7234 		}
7235 		return check_mem_region_access(env, regno, reg->off,
7236 					       access_size, reg->mem_size,
7237 					       zero_size_allowed);
7238 	case PTR_TO_BUF:
7239 		if (type_is_rdonly_mem(reg->type)) {
7240 			if (meta && meta->raw_mode) {
7241 				verbose(env, "R%d cannot write into %s\n", regno,
7242 					reg_type_str(env, reg->type));
7243 				return -EACCES;
7244 			}
7245 
7246 			max_access = &env->prog->aux->max_rdonly_access;
7247 		} else {
7248 			max_access = &env->prog->aux->max_rdwr_access;
7249 		}
7250 		return check_buffer_access(env, reg, regno, reg->off,
7251 					   access_size, zero_size_allowed,
7252 					   max_access);
7253 	case PTR_TO_STACK:
7254 		return check_stack_range_initialized(
7255 				env,
7256 				regno, reg->off, access_size,
7257 				zero_size_allowed, ACCESS_HELPER, meta);
7258 	case PTR_TO_BTF_ID:
7259 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7260 					       access_size, BPF_READ, -1);
7261 	case PTR_TO_CTX:
7262 		/* in case the function doesn't know how to access the context,
7263 		 * (because we are in a program of type SYSCALL for example), we
7264 		 * can not statically check its size.
7265 		 * Dynamically check it now.
7266 		 */
7267 		if (!env->ops->convert_ctx_access) {
7268 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7269 			int offset = access_size - 1;
7270 
7271 			/* Allow zero-byte read from PTR_TO_CTX */
7272 			if (access_size == 0)
7273 				return zero_size_allowed ? 0 : -EACCES;
7274 
7275 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7276 						atype, -1, false, false);
7277 		}
7278 
7279 		fallthrough;
7280 	default: /* scalar_value or invalid ptr */
7281 		/* Allow zero-byte read from NULL, regardless of pointer type */
7282 		if (zero_size_allowed && access_size == 0 &&
7283 		    register_is_null(reg))
7284 			return 0;
7285 
7286 		verbose(env, "R%d type=%s ", regno,
7287 			reg_type_str(env, reg->type));
7288 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7289 		return -EACCES;
7290 	}
7291 }
7292 
7293 static int check_mem_size_reg(struct bpf_verifier_env *env,
7294 			      struct bpf_reg_state *reg, u32 regno,
7295 			      bool zero_size_allowed,
7296 			      struct bpf_call_arg_meta *meta)
7297 {
7298 	int err;
7299 
7300 	/* This is used to refine r0 return value bounds for helpers
7301 	 * that enforce this value as an upper bound on return values.
7302 	 * See do_refine_retval_range() for helpers that can refine
7303 	 * the return value. C type of helper is u32 so we pull register
7304 	 * bound from umax_value however, if negative verifier errors
7305 	 * out. Only upper bounds can be learned because retval is an
7306 	 * int type and negative retvals are allowed.
7307 	 */
7308 	meta->msize_max_value = reg->umax_value;
7309 
7310 	/* The register is SCALAR_VALUE; the access check
7311 	 * happens using its boundaries.
7312 	 */
7313 	if (!tnum_is_const(reg->var_off))
7314 		/* For unprivileged variable accesses, disable raw
7315 		 * mode so that the program is required to
7316 		 * initialize all the memory that the helper could
7317 		 * just partially fill up.
7318 		 */
7319 		meta = NULL;
7320 
7321 	if (reg->smin_value < 0) {
7322 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7323 			regno);
7324 		return -EACCES;
7325 	}
7326 
7327 	if (reg->umin_value == 0 && !zero_size_allowed) {
7328 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7329 			regno, reg->umin_value, reg->umax_value);
7330 		return -EACCES;
7331 	}
7332 
7333 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7334 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7335 			regno);
7336 		return -EACCES;
7337 	}
7338 	err = check_helper_mem_access(env, regno - 1,
7339 				      reg->umax_value,
7340 				      zero_size_allowed, meta);
7341 	if (!err)
7342 		err = mark_chain_precision(env, regno);
7343 	return err;
7344 }
7345 
7346 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7347 		   u32 regno, u32 mem_size)
7348 {
7349 	bool may_be_null = type_may_be_null(reg->type);
7350 	struct bpf_reg_state saved_reg;
7351 	struct bpf_call_arg_meta meta;
7352 	int err;
7353 
7354 	if (register_is_null(reg))
7355 		return 0;
7356 
7357 	memset(&meta, 0, sizeof(meta));
7358 	/* Assuming that the register contains a value check if the memory
7359 	 * access is safe. Temporarily save and restore the register's state as
7360 	 * the conversion shouldn't be visible to a caller.
7361 	 */
7362 	if (may_be_null) {
7363 		saved_reg = *reg;
7364 		mark_ptr_not_null_reg(reg);
7365 	}
7366 
7367 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7368 	/* Check access for BPF_WRITE */
7369 	meta.raw_mode = true;
7370 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7371 
7372 	if (may_be_null)
7373 		*reg = saved_reg;
7374 
7375 	return err;
7376 }
7377 
7378 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7379 				    u32 regno)
7380 {
7381 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7382 	bool may_be_null = type_may_be_null(mem_reg->type);
7383 	struct bpf_reg_state saved_reg;
7384 	struct bpf_call_arg_meta meta;
7385 	int err;
7386 
7387 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7388 
7389 	memset(&meta, 0, sizeof(meta));
7390 
7391 	if (may_be_null) {
7392 		saved_reg = *mem_reg;
7393 		mark_ptr_not_null_reg(mem_reg);
7394 	}
7395 
7396 	err = check_mem_size_reg(env, reg, regno, true, &meta);
7397 	/* Check access for BPF_WRITE */
7398 	meta.raw_mode = true;
7399 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7400 
7401 	if (may_be_null)
7402 		*mem_reg = saved_reg;
7403 	return err;
7404 }
7405 
7406 /* Implementation details:
7407  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7408  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7409  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7410  * Two separate bpf_obj_new will also have different reg->id.
7411  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7412  * clears reg->id after value_or_null->value transition, since the verifier only
7413  * cares about the range of access to valid map value pointer and doesn't care
7414  * about actual address of the map element.
7415  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7416  * reg->id > 0 after value_or_null->value transition. By doing so
7417  * two bpf_map_lookups will be considered two different pointers that
7418  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7419  * returned from bpf_obj_new.
7420  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7421  * dead-locks.
7422  * Since only one bpf_spin_lock is allowed the checks are simpler than
7423  * reg_is_refcounted() logic. The verifier needs to remember only
7424  * one spin_lock instead of array of acquired_refs.
7425  * cur_state->active_lock remembers which map value element or allocated
7426  * object got locked and clears it after bpf_spin_unlock.
7427  */
7428 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7429 			     bool is_lock)
7430 {
7431 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7432 	struct bpf_verifier_state *cur = env->cur_state;
7433 	bool is_const = tnum_is_const(reg->var_off);
7434 	u64 val = reg->var_off.value;
7435 	struct bpf_map *map = NULL;
7436 	struct btf *btf = NULL;
7437 	struct btf_record *rec;
7438 
7439 	if (!is_const) {
7440 		verbose(env,
7441 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7442 			regno);
7443 		return -EINVAL;
7444 	}
7445 	if (reg->type == PTR_TO_MAP_VALUE) {
7446 		map = reg->map_ptr;
7447 		if (!map->btf) {
7448 			verbose(env,
7449 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7450 				map->name);
7451 			return -EINVAL;
7452 		}
7453 	} else {
7454 		btf = reg->btf;
7455 	}
7456 
7457 	rec = reg_btf_record(reg);
7458 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7459 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7460 			map ? map->name : "kptr");
7461 		return -EINVAL;
7462 	}
7463 	if (rec->spin_lock_off != val + reg->off) {
7464 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7465 			val + reg->off, rec->spin_lock_off);
7466 		return -EINVAL;
7467 	}
7468 	if (is_lock) {
7469 		if (cur->active_lock.ptr) {
7470 			verbose(env,
7471 				"Locking two bpf_spin_locks are not allowed\n");
7472 			return -EINVAL;
7473 		}
7474 		if (map)
7475 			cur->active_lock.ptr = map;
7476 		else
7477 			cur->active_lock.ptr = btf;
7478 		cur->active_lock.id = reg->id;
7479 	} else {
7480 		void *ptr;
7481 
7482 		if (map)
7483 			ptr = map;
7484 		else
7485 			ptr = btf;
7486 
7487 		if (!cur->active_lock.ptr) {
7488 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7489 			return -EINVAL;
7490 		}
7491 		if (cur->active_lock.ptr != ptr ||
7492 		    cur->active_lock.id != reg->id) {
7493 			verbose(env, "bpf_spin_unlock of different lock\n");
7494 			return -EINVAL;
7495 		}
7496 
7497 		invalidate_non_owning_refs(env);
7498 
7499 		cur->active_lock.ptr = NULL;
7500 		cur->active_lock.id = 0;
7501 	}
7502 	return 0;
7503 }
7504 
7505 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7506 			      struct bpf_call_arg_meta *meta)
7507 {
7508 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7509 	bool is_const = tnum_is_const(reg->var_off);
7510 	struct bpf_map *map = reg->map_ptr;
7511 	u64 val = reg->var_off.value;
7512 
7513 	if (!is_const) {
7514 		verbose(env,
7515 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7516 			regno);
7517 		return -EINVAL;
7518 	}
7519 	if (!map->btf) {
7520 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7521 			map->name);
7522 		return -EINVAL;
7523 	}
7524 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7525 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7526 		return -EINVAL;
7527 	}
7528 	if (map->record->timer_off != val + reg->off) {
7529 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7530 			val + reg->off, map->record->timer_off);
7531 		return -EINVAL;
7532 	}
7533 	if (meta->map_ptr) {
7534 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7535 		return -EFAULT;
7536 	}
7537 	meta->map_uid = reg->map_uid;
7538 	meta->map_ptr = map;
7539 	return 0;
7540 }
7541 
7542 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7543 			     struct bpf_call_arg_meta *meta)
7544 {
7545 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7546 	struct bpf_map *map_ptr = reg->map_ptr;
7547 	struct btf_field *kptr_field;
7548 	u32 kptr_off;
7549 
7550 	if (!tnum_is_const(reg->var_off)) {
7551 		verbose(env,
7552 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7553 			regno);
7554 		return -EINVAL;
7555 	}
7556 	if (!map_ptr->btf) {
7557 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7558 			map_ptr->name);
7559 		return -EINVAL;
7560 	}
7561 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7562 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7563 		return -EINVAL;
7564 	}
7565 
7566 	meta->map_ptr = map_ptr;
7567 	kptr_off = reg->off + reg->var_off.value;
7568 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7569 	if (!kptr_field) {
7570 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7571 		return -EACCES;
7572 	}
7573 	if (kptr_field->type != BPF_KPTR_REF) {
7574 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7575 		return -EACCES;
7576 	}
7577 	meta->kptr_field = kptr_field;
7578 	return 0;
7579 }
7580 
7581 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7582  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7583  *
7584  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7585  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7586  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7587  *
7588  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7589  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7590  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7591  * mutate the view of the dynptr and also possibly destroy it. In the latter
7592  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7593  * memory that dynptr points to.
7594  *
7595  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7596  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7597  * readonly dynptr view yet, hence only the first case is tracked and checked.
7598  *
7599  * This is consistent with how C applies the const modifier to a struct object,
7600  * where the pointer itself inside bpf_dynptr becomes const but not what it
7601  * points to.
7602  *
7603  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7604  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7605  */
7606 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7607 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7608 {
7609 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7610 	int err;
7611 
7612 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7613 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7614 	 */
7615 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7616 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7617 		return -EFAULT;
7618 	}
7619 
7620 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7621 	 *		 constructing a mutable bpf_dynptr object.
7622 	 *
7623 	 *		 Currently, this is only possible with PTR_TO_STACK
7624 	 *		 pointing to a region of at least 16 bytes which doesn't
7625 	 *		 contain an existing bpf_dynptr.
7626 	 *
7627 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7628 	 *		 mutated or destroyed. However, the memory it points to
7629 	 *		 may be mutated.
7630 	 *
7631 	 *  None       - Points to a initialized dynptr that can be mutated and
7632 	 *		 destroyed, including mutation of the memory it points
7633 	 *		 to.
7634 	 */
7635 	if (arg_type & MEM_UNINIT) {
7636 		int i;
7637 
7638 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7639 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7640 			return -EINVAL;
7641 		}
7642 
7643 		/* we write BPF_DW bits (8 bytes) at a time */
7644 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7645 			err = check_mem_access(env, insn_idx, regno,
7646 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7647 			if (err)
7648 				return err;
7649 		}
7650 
7651 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7652 	} else /* MEM_RDONLY and None case from above */ {
7653 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7654 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7655 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7656 			return -EINVAL;
7657 		}
7658 
7659 		if (!is_dynptr_reg_valid_init(env, reg)) {
7660 			verbose(env,
7661 				"Expected an initialized dynptr as arg #%d\n",
7662 				regno);
7663 			return -EINVAL;
7664 		}
7665 
7666 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7667 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7668 			verbose(env,
7669 				"Expected a dynptr of type %s as arg #%d\n",
7670 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7671 			return -EINVAL;
7672 		}
7673 
7674 		err = mark_dynptr_read(env, reg);
7675 	}
7676 	return err;
7677 }
7678 
7679 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7680 {
7681 	struct bpf_func_state *state = func(env, reg);
7682 
7683 	return state->stack[spi].spilled_ptr.ref_obj_id;
7684 }
7685 
7686 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7687 {
7688 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7689 }
7690 
7691 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7692 {
7693 	return meta->kfunc_flags & KF_ITER_NEW;
7694 }
7695 
7696 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7697 {
7698 	return meta->kfunc_flags & KF_ITER_NEXT;
7699 }
7700 
7701 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7702 {
7703 	return meta->kfunc_flags & KF_ITER_DESTROY;
7704 }
7705 
7706 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7707 {
7708 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7709 	 * kfunc is iter state pointer
7710 	 */
7711 	return arg == 0 && is_iter_kfunc(meta);
7712 }
7713 
7714 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7715 			    struct bpf_kfunc_call_arg_meta *meta)
7716 {
7717 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7718 	const struct btf_type *t;
7719 	const struct btf_param *arg;
7720 	int spi, err, i, nr_slots;
7721 	u32 btf_id;
7722 
7723 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7724 	arg = &btf_params(meta->func_proto)[0];
7725 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7726 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7727 	nr_slots = t->size / BPF_REG_SIZE;
7728 
7729 	if (is_iter_new_kfunc(meta)) {
7730 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7731 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7732 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7733 				iter_type_str(meta->btf, btf_id), regno);
7734 			return -EINVAL;
7735 		}
7736 
7737 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7738 			err = check_mem_access(env, insn_idx, regno,
7739 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7740 			if (err)
7741 				return err;
7742 		}
7743 
7744 		err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7745 		if (err)
7746 			return err;
7747 	} else {
7748 		/* iter_next() or iter_destroy() expect initialized iter state*/
7749 		if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7750 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7751 				iter_type_str(meta->btf, btf_id), regno);
7752 			return -EINVAL;
7753 		}
7754 
7755 		spi = iter_get_spi(env, reg, nr_slots);
7756 		if (spi < 0)
7757 			return spi;
7758 
7759 		err = mark_iter_read(env, reg, spi, nr_slots);
7760 		if (err)
7761 			return err;
7762 
7763 		/* remember meta->iter info for process_iter_next_call() */
7764 		meta->iter.spi = spi;
7765 		meta->iter.frameno = reg->frameno;
7766 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7767 
7768 		if (is_iter_destroy_kfunc(meta)) {
7769 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7770 			if (err)
7771 				return err;
7772 		}
7773 	}
7774 
7775 	return 0;
7776 }
7777 
7778 /* Look for a previous loop entry at insn_idx: nearest parent state
7779  * stopped at insn_idx with callsites matching those in cur->frame.
7780  */
7781 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7782 						  struct bpf_verifier_state *cur,
7783 						  int insn_idx)
7784 {
7785 	struct bpf_verifier_state_list *sl;
7786 	struct bpf_verifier_state *st;
7787 
7788 	/* Explored states are pushed in stack order, most recent states come first */
7789 	sl = *explored_state(env, insn_idx);
7790 	for (; sl; sl = sl->next) {
7791 		/* If st->branches != 0 state is a part of current DFS verification path,
7792 		 * hence cur & st for a loop.
7793 		 */
7794 		st = &sl->state;
7795 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7796 		    st->dfs_depth < cur->dfs_depth)
7797 			return st;
7798 	}
7799 
7800 	return NULL;
7801 }
7802 
7803 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7804 static bool regs_exact(const struct bpf_reg_state *rold,
7805 		       const struct bpf_reg_state *rcur,
7806 		       struct bpf_idmap *idmap);
7807 
7808 static void maybe_widen_reg(struct bpf_verifier_env *env,
7809 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7810 			    struct bpf_idmap *idmap)
7811 {
7812 	if (rold->type != SCALAR_VALUE)
7813 		return;
7814 	if (rold->type != rcur->type)
7815 		return;
7816 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7817 		return;
7818 	__mark_reg_unknown(env, rcur);
7819 }
7820 
7821 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7822 				   struct bpf_verifier_state *old,
7823 				   struct bpf_verifier_state *cur)
7824 {
7825 	struct bpf_func_state *fold, *fcur;
7826 	int i, fr;
7827 
7828 	reset_idmap_scratch(env);
7829 	for (fr = old->curframe; fr >= 0; fr--) {
7830 		fold = old->frame[fr];
7831 		fcur = cur->frame[fr];
7832 
7833 		for (i = 0; i < MAX_BPF_REG; i++)
7834 			maybe_widen_reg(env,
7835 					&fold->regs[i],
7836 					&fcur->regs[i],
7837 					&env->idmap_scratch);
7838 
7839 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7840 			if (!is_spilled_reg(&fold->stack[i]) ||
7841 			    !is_spilled_reg(&fcur->stack[i]))
7842 				continue;
7843 
7844 			maybe_widen_reg(env,
7845 					&fold->stack[i].spilled_ptr,
7846 					&fcur->stack[i].spilled_ptr,
7847 					&env->idmap_scratch);
7848 		}
7849 	}
7850 	return 0;
7851 }
7852 
7853 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
7854 						 struct bpf_kfunc_call_arg_meta *meta)
7855 {
7856 	int iter_frameno = meta->iter.frameno;
7857 	int iter_spi = meta->iter.spi;
7858 
7859 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7860 }
7861 
7862 /* process_iter_next_call() is called when verifier gets to iterator's next
7863  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7864  * to it as just "iter_next()" in comments below.
7865  *
7866  * BPF verifier relies on a crucial contract for any iter_next()
7867  * implementation: it should *eventually* return NULL, and once that happens
7868  * it should keep returning NULL. That is, once iterator exhausts elements to
7869  * iterate, it should never reset or spuriously return new elements.
7870  *
7871  * With the assumption of such contract, process_iter_next_call() simulates
7872  * a fork in the verifier state to validate loop logic correctness and safety
7873  * without having to simulate infinite amount of iterations.
7874  *
7875  * In current state, we first assume that iter_next() returned NULL and
7876  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7877  * conditions we should not form an infinite loop and should eventually reach
7878  * exit.
7879  *
7880  * Besides that, we also fork current state and enqueue it for later
7881  * verification. In a forked state we keep iterator state as ACTIVE
7882  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7883  * also bump iteration depth to prevent erroneous infinite loop detection
7884  * later on (see iter_active_depths_differ() comment for details). In this
7885  * state we assume that we'll eventually loop back to another iter_next()
7886  * calls (it could be in exactly same location or in some other instruction,
7887  * it doesn't matter, we don't make any unnecessary assumptions about this,
7888  * everything revolves around iterator state in a stack slot, not which
7889  * instruction is calling iter_next()). When that happens, we either will come
7890  * to iter_next() with equivalent state and can conclude that next iteration
7891  * will proceed in exactly the same way as we just verified, so it's safe to
7892  * assume that loop converges. If not, we'll go on another iteration
7893  * simulation with a different input state, until all possible starting states
7894  * are validated or we reach maximum number of instructions limit.
7895  *
7896  * This way, we will either exhaustively discover all possible input states
7897  * that iterator loop can start with and eventually will converge, or we'll
7898  * effectively regress into bounded loop simulation logic and either reach
7899  * maximum number of instructions if loop is not provably convergent, or there
7900  * is some statically known limit on number of iterations (e.g., if there is
7901  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7902  *
7903  * Iteration convergence logic in is_state_visited() relies on exact
7904  * states comparison, which ignores read and precision marks.
7905  * This is necessary because read and precision marks are not finalized
7906  * while in the loop. Exact comparison might preclude convergence for
7907  * simple programs like below:
7908  *
7909  *     i = 0;
7910  *     while(iter_next(&it))
7911  *       i++;
7912  *
7913  * At each iteration step i++ would produce a new distinct state and
7914  * eventually instruction processing limit would be reached.
7915  *
7916  * To avoid such behavior speculatively forget (widen) range for
7917  * imprecise scalar registers, if those registers were not precise at the
7918  * end of the previous iteration and do not match exactly.
7919  *
7920  * This is a conservative heuristic that allows to verify wide range of programs,
7921  * however it precludes verification of programs that conjure an
7922  * imprecise value on the first loop iteration and use it as precise on a second.
7923  * For example, the following safe program would fail to verify:
7924  *
7925  *     struct bpf_num_iter it;
7926  *     int arr[10];
7927  *     int i = 0, a = 0;
7928  *     bpf_iter_num_new(&it, 0, 10);
7929  *     while (bpf_iter_num_next(&it)) {
7930  *       if (a == 0) {
7931  *         a = 1;
7932  *         i = 7; // Because i changed verifier would forget
7933  *                // it's range on second loop entry.
7934  *       } else {
7935  *         arr[i] = 42; // This would fail to verify.
7936  *       }
7937  *     }
7938  *     bpf_iter_num_destroy(&it);
7939  */
7940 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7941 				  struct bpf_kfunc_call_arg_meta *meta)
7942 {
7943 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7944 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7945 	struct bpf_reg_state *cur_iter, *queued_iter;
7946 
7947 	BTF_TYPE_EMIT(struct bpf_iter);
7948 
7949 	cur_iter = get_iter_from_state(cur_st, meta);
7950 
7951 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7952 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7953 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7954 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7955 		return -EFAULT;
7956 	}
7957 
7958 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7959 		/* Because iter_next() call is a checkpoint is_state_visitied()
7960 		 * should guarantee parent state with same call sites and insn_idx.
7961 		 */
7962 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7963 		    !same_callsites(cur_st->parent, cur_st)) {
7964 			verbose(env, "bug: bad parent state for iter next call");
7965 			return -EFAULT;
7966 		}
7967 		/* Note cur_st->parent in the call below, it is necessary to skip
7968 		 * checkpoint created for cur_st by is_state_visited()
7969 		 * right at this instruction.
7970 		 */
7971 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7972 		/* branch out active iter state */
7973 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7974 		if (!queued_st)
7975 			return -ENOMEM;
7976 
7977 		queued_iter = get_iter_from_state(queued_st, meta);
7978 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7979 		queued_iter->iter.depth++;
7980 		if (prev_st)
7981 			widen_imprecise_scalars(env, prev_st, queued_st);
7982 
7983 		queued_fr = queued_st->frame[queued_st->curframe];
7984 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7985 	}
7986 
7987 	/* switch to DRAINED state, but keep the depth unchanged */
7988 	/* mark current iter state as drained and assume returned NULL */
7989 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7990 	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7991 
7992 	return 0;
7993 }
7994 
7995 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7996 {
7997 	return type == ARG_CONST_SIZE ||
7998 	       type == ARG_CONST_SIZE_OR_ZERO;
7999 }
8000 
8001 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
8002 {
8003 	return base_type(type) == ARG_PTR_TO_MEM &&
8004 	       type & MEM_UNINIT;
8005 }
8006 
8007 static bool arg_type_is_release(enum bpf_arg_type type)
8008 {
8009 	return type & OBJ_RELEASE;
8010 }
8011 
8012 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8013 {
8014 	return base_type(type) == ARG_PTR_TO_DYNPTR;
8015 }
8016 
8017 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8018 				 const struct bpf_call_arg_meta *meta,
8019 				 enum bpf_arg_type *arg_type)
8020 {
8021 	if (!meta->map_ptr) {
8022 		/* kernel subsystem misconfigured verifier */
8023 		verbose(env, "invalid map_ptr to access map->type\n");
8024 		return -EACCES;
8025 	}
8026 
8027 	switch (meta->map_ptr->map_type) {
8028 	case BPF_MAP_TYPE_SOCKMAP:
8029 	case BPF_MAP_TYPE_SOCKHASH:
8030 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8031 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8032 		} else {
8033 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8034 			return -EINVAL;
8035 		}
8036 		break;
8037 	case BPF_MAP_TYPE_BLOOM_FILTER:
8038 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8039 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8040 		break;
8041 	default:
8042 		break;
8043 	}
8044 	return 0;
8045 }
8046 
8047 struct bpf_reg_types {
8048 	const enum bpf_reg_type types[10];
8049 	u32 *btf_id;
8050 };
8051 
8052 static const struct bpf_reg_types sock_types = {
8053 	.types = {
8054 		PTR_TO_SOCK_COMMON,
8055 		PTR_TO_SOCKET,
8056 		PTR_TO_TCP_SOCK,
8057 		PTR_TO_XDP_SOCK,
8058 	},
8059 };
8060 
8061 #ifdef CONFIG_NET
8062 static const struct bpf_reg_types btf_id_sock_common_types = {
8063 	.types = {
8064 		PTR_TO_SOCK_COMMON,
8065 		PTR_TO_SOCKET,
8066 		PTR_TO_TCP_SOCK,
8067 		PTR_TO_XDP_SOCK,
8068 		PTR_TO_BTF_ID,
8069 		PTR_TO_BTF_ID | PTR_TRUSTED,
8070 	},
8071 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8072 };
8073 #endif
8074 
8075 static const struct bpf_reg_types mem_types = {
8076 	.types = {
8077 		PTR_TO_STACK,
8078 		PTR_TO_PACKET,
8079 		PTR_TO_PACKET_META,
8080 		PTR_TO_MAP_KEY,
8081 		PTR_TO_MAP_VALUE,
8082 		PTR_TO_MEM,
8083 		PTR_TO_MEM | MEM_RINGBUF,
8084 		PTR_TO_BUF,
8085 		PTR_TO_BTF_ID | PTR_TRUSTED,
8086 	},
8087 };
8088 
8089 static const struct bpf_reg_types spin_lock_types = {
8090 	.types = {
8091 		PTR_TO_MAP_VALUE,
8092 		PTR_TO_BTF_ID | MEM_ALLOC,
8093 	}
8094 };
8095 
8096 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8097 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8098 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8099 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8100 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8101 static const struct bpf_reg_types btf_ptr_types = {
8102 	.types = {
8103 		PTR_TO_BTF_ID,
8104 		PTR_TO_BTF_ID | PTR_TRUSTED,
8105 		PTR_TO_BTF_ID | MEM_RCU,
8106 	},
8107 };
8108 static const struct bpf_reg_types percpu_btf_ptr_types = {
8109 	.types = {
8110 		PTR_TO_BTF_ID | MEM_PERCPU,
8111 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8112 	}
8113 };
8114 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8115 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8116 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8117 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8118 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8119 static const struct bpf_reg_types dynptr_types = {
8120 	.types = {
8121 		PTR_TO_STACK,
8122 		CONST_PTR_TO_DYNPTR,
8123 	}
8124 };
8125 
8126 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8127 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8128 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8129 	[ARG_CONST_SIZE]		= &scalar_types,
8130 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8131 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8132 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8133 	[ARG_PTR_TO_CTX]		= &context_types,
8134 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8135 #ifdef CONFIG_NET
8136 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8137 #endif
8138 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8139 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8140 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8141 	[ARG_PTR_TO_MEM]		= &mem_types,
8142 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8143 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8144 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8145 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8146 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8147 	[ARG_PTR_TO_TIMER]		= &timer_types,
8148 	[ARG_PTR_TO_KPTR]		= &kptr_types,
8149 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8150 };
8151 
8152 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8153 			  enum bpf_arg_type arg_type,
8154 			  const u32 *arg_btf_id,
8155 			  struct bpf_call_arg_meta *meta)
8156 {
8157 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8158 	enum bpf_reg_type expected, type = reg->type;
8159 	const struct bpf_reg_types *compatible;
8160 	int i, j;
8161 
8162 	compatible = compatible_reg_types[base_type(arg_type)];
8163 	if (!compatible) {
8164 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8165 		return -EFAULT;
8166 	}
8167 
8168 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8169 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8170 	 *
8171 	 * Same for MAYBE_NULL:
8172 	 *
8173 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8174 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8175 	 *
8176 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8177 	 *
8178 	 * Therefore we fold these flags depending on the arg_type before comparison.
8179 	 */
8180 	if (arg_type & MEM_RDONLY)
8181 		type &= ~MEM_RDONLY;
8182 	if (arg_type & PTR_MAYBE_NULL)
8183 		type &= ~PTR_MAYBE_NULL;
8184 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8185 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8186 
8187 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
8188 		type &= ~MEM_ALLOC;
8189 
8190 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8191 		expected = compatible->types[i];
8192 		if (expected == NOT_INIT)
8193 			break;
8194 
8195 		if (type == expected)
8196 			goto found;
8197 	}
8198 
8199 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8200 	for (j = 0; j + 1 < i; j++)
8201 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8202 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8203 	return -EACCES;
8204 
8205 found:
8206 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8207 		return 0;
8208 
8209 	if (compatible == &mem_types) {
8210 		if (!(arg_type & MEM_RDONLY)) {
8211 			verbose(env,
8212 				"%s() may write into memory pointed by R%d type=%s\n",
8213 				func_id_name(meta->func_id),
8214 				regno, reg_type_str(env, reg->type));
8215 			return -EACCES;
8216 		}
8217 		return 0;
8218 	}
8219 
8220 	switch ((int)reg->type) {
8221 	case PTR_TO_BTF_ID:
8222 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8223 	case PTR_TO_BTF_ID | MEM_RCU:
8224 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8225 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8226 	{
8227 		/* For bpf_sk_release, it needs to match against first member
8228 		 * 'struct sock_common', hence make an exception for it. This
8229 		 * allows bpf_sk_release to work for multiple socket types.
8230 		 */
8231 		bool strict_type_match = arg_type_is_release(arg_type) &&
8232 					 meta->func_id != BPF_FUNC_sk_release;
8233 
8234 		if (type_may_be_null(reg->type) &&
8235 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8236 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8237 			return -EACCES;
8238 		}
8239 
8240 		if (!arg_btf_id) {
8241 			if (!compatible->btf_id) {
8242 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8243 				return -EFAULT;
8244 			}
8245 			arg_btf_id = compatible->btf_id;
8246 		}
8247 
8248 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8249 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8250 				return -EACCES;
8251 		} else {
8252 			if (arg_btf_id == BPF_PTR_POISON) {
8253 				verbose(env, "verifier internal error:");
8254 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8255 					regno);
8256 				return -EACCES;
8257 			}
8258 
8259 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8260 						  btf_vmlinux, *arg_btf_id,
8261 						  strict_type_match)) {
8262 				verbose(env, "R%d is of type %s but %s is expected\n",
8263 					regno, btf_type_name(reg->btf, reg->btf_id),
8264 					btf_type_name(btf_vmlinux, *arg_btf_id));
8265 				return -EACCES;
8266 			}
8267 		}
8268 		break;
8269 	}
8270 	case PTR_TO_BTF_ID | MEM_ALLOC:
8271 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8272 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8273 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8274 			return -EFAULT;
8275 		}
8276 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8277 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8278 				return -EACCES;
8279 		}
8280 		break;
8281 	case PTR_TO_BTF_ID | MEM_PERCPU:
8282 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8283 		/* Handled by helper specific checks */
8284 		break;
8285 	default:
8286 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8287 		return -EFAULT;
8288 	}
8289 	return 0;
8290 }
8291 
8292 static struct btf_field *
8293 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8294 {
8295 	struct btf_field *field;
8296 	struct btf_record *rec;
8297 
8298 	rec = reg_btf_record(reg);
8299 	if (!rec)
8300 		return NULL;
8301 
8302 	field = btf_record_find(rec, off, fields);
8303 	if (!field)
8304 		return NULL;
8305 
8306 	return field;
8307 }
8308 
8309 int check_func_arg_reg_off(struct bpf_verifier_env *env,
8310 			   const struct bpf_reg_state *reg, int regno,
8311 			   enum bpf_arg_type arg_type)
8312 {
8313 	u32 type = reg->type;
8314 
8315 	/* When referenced register is passed to release function, its fixed
8316 	 * offset must be 0.
8317 	 *
8318 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8319 	 * meta->release_regno.
8320 	 */
8321 	if (arg_type_is_release(arg_type)) {
8322 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8323 		 * may not directly point to the object being released, but to
8324 		 * dynptr pointing to such object, which might be at some offset
8325 		 * on the stack. In that case, we simply to fallback to the
8326 		 * default handling.
8327 		 */
8328 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8329 			return 0;
8330 
8331 		/* Doing check_ptr_off_reg check for the offset will catch this
8332 		 * because fixed_off_ok is false, but checking here allows us
8333 		 * to give the user a better error message.
8334 		 */
8335 		if (reg->off) {
8336 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8337 				regno);
8338 			return -EINVAL;
8339 		}
8340 		return __check_ptr_off_reg(env, reg, regno, false);
8341 	}
8342 
8343 	switch (type) {
8344 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8345 	case PTR_TO_STACK:
8346 	case PTR_TO_PACKET:
8347 	case PTR_TO_PACKET_META:
8348 	case PTR_TO_MAP_KEY:
8349 	case PTR_TO_MAP_VALUE:
8350 	case PTR_TO_MEM:
8351 	case PTR_TO_MEM | MEM_RDONLY:
8352 	case PTR_TO_MEM | MEM_RINGBUF:
8353 	case PTR_TO_BUF:
8354 	case PTR_TO_BUF | MEM_RDONLY:
8355 	case SCALAR_VALUE:
8356 		return 0;
8357 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8358 	 * fixed offset.
8359 	 */
8360 	case PTR_TO_BTF_ID:
8361 	case PTR_TO_BTF_ID | MEM_ALLOC:
8362 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8363 	case PTR_TO_BTF_ID | MEM_RCU:
8364 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8365 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8366 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8367 		 * its fixed offset must be 0. In the other cases, fixed offset
8368 		 * can be non-zero. This was already checked above. So pass
8369 		 * fixed_off_ok as true to allow fixed offset for all other
8370 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8371 		 * still need to do checks instead of returning.
8372 		 */
8373 		return __check_ptr_off_reg(env, reg, regno, true);
8374 	default:
8375 		return __check_ptr_off_reg(env, reg, regno, false);
8376 	}
8377 }
8378 
8379 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8380 						const struct bpf_func_proto *fn,
8381 						struct bpf_reg_state *regs)
8382 {
8383 	struct bpf_reg_state *state = NULL;
8384 	int i;
8385 
8386 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8387 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8388 			if (state) {
8389 				verbose(env, "verifier internal error: multiple dynptr args\n");
8390 				return NULL;
8391 			}
8392 			state = &regs[BPF_REG_1 + i];
8393 		}
8394 
8395 	if (!state)
8396 		verbose(env, "verifier internal error: no dynptr arg found\n");
8397 
8398 	return state;
8399 }
8400 
8401 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8402 {
8403 	struct bpf_func_state *state = func(env, reg);
8404 	int spi;
8405 
8406 	if (reg->type == CONST_PTR_TO_DYNPTR)
8407 		return reg->id;
8408 	spi = dynptr_get_spi(env, reg);
8409 	if (spi < 0)
8410 		return spi;
8411 	return state->stack[spi].spilled_ptr.id;
8412 }
8413 
8414 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8415 {
8416 	struct bpf_func_state *state = func(env, reg);
8417 	int spi;
8418 
8419 	if (reg->type == CONST_PTR_TO_DYNPTR)
8420 		return reg->ref_obj_id;
8421 	spi = dynptr_get_spi(env, reg);
8422 	if (spi < 0)
8423 		return spi;
8424 	return state->stack[spi].spilled_ptr.ref_obj_id;
8425 }
8426 
8427 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8428 					    struct bpf_reg_state *reg)
8429 {
8430 	struct bpf_func_state *state = func(env, reg);
8431 	int spi;
8432 
8433 	if (reg->type == CONST_PTR_TO_DYNPTR)
8434 		return reg->dynptr.type;
8435 
8436 	spi = __get_spi(reg->off);
8437 	if (spi < 0) {
8438 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8439 		return BPF_DYNPTR_TYPE_INVALID;
8440 	}
8441 
8442 	return state->stack[spi].spilled_ptr.dynptr.type;
8443 }
8444 
8445 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8446 			  struct bpf_call_arg_meta *meta,
8447 			  const struct bpf_func_proto *fn,
8448 			  int insn_idx)
8449 {
8450 	u32 regno = BPF_REG_1 + arg;
8451 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8452 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8453 	enum bpf_reg_type type = reg->type;
8454 	u32 *arg_btf_id = NULL;
8455 	int err = 0;
8456 
8457 	if (arg_type == ARG_DONTCARE)
8458 		return 0;
8459 
8460 	err = check_reg_arg(env, regno, SRC_OP);
8461 	if (err)
8462 		return err;
8463 
8464 	if (arg_type == ARG_ANYTHING) {
8465 		if (is_pointer_value(env, regno)) {
8466 			verbose(env, "R%d leaks addr into helper function\n",
8467 				regno);
8468 			return -EACCES;
8469 		}
8470 		return 0;
8471 	}
8472 
8473 	if (type_is_pkt_pointer(type) &&
8474 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8475 		verbose(env, "helper access to the packet is not allowed\n");
8476 		return -EACCES;
8477 	}
8478 
8479 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8480 		err = resolve_map_arg_type(env, meta, &arg_type);
8481 		if (err)
8482 			return err;
8483 	}
8484 
8485 	if (register_is_null(reg) && type_may_be_null(arg_type))
8486 		/* A NULL register has a SCALAR_VALUE type, so skip
8487 		 * type checking.
8488 		 */
8489 		goto skip_type_check;
8490 
8491 	/* arg_btf_id and arg_size are in a union. */
8492 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8493 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8494 		arg_btf_id = fn->arg_btf_id[arg];
8495 
8496 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8497 	if (err)
8498 		return err;
8499 
8500 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8501 	if (err)
8502 		return err;
8503 
8504 skip_type_check:
8505 	if (arg_type_is_release(arg_type)) {
8506 		if (arg_type_is_dynptr(arg_type)) {
8507 			struct bpf_func_state *state = func(env, reg);
8508 			int spi;
8509 
8510 			/* Only dynptr created on stack can be released, thus
8511 			 * the get_spi and stack state checks for spilled_ptr
8512 			 * should only be done before process_dynptr_func for
8513 			 * PTR_TO_STACK.
8514 			 */
8515 			if (reg->type == PTR_TO_STACK) {
8516 				spi = dynptr_get_spi(env, reg);
8517 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8518 					verbose(env, "arg %d is an unacquired reference\n", regno);
8519 					return -EINVAL;
8520 				}
8521 			} else {
8522 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8523 				return -EINVAL;
8524 			}
8525 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8526 			verbose(env, "R%d must be referenced when passed to release function\n",
8527 				regno);
8528 			return -EINVAL;
8529 		}
8530 		if (meta->release_regno) {
8531 			verbose(env, "verifier internal error: more than one release argument\n");
8532 			return -EFAULT;
8533 		}
8534 		meta->release_regno = regno;
8535 	}
8536 
8537 	if (reg->ref_obj_id) {
8538 		if (meta->ref_obj_id) {
8539 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8540 				regno, reg->ref_obj_id,
8541 				meta->ref_obj_id);
8542 			return -EFAULT;
8543 		}
8544 		meta->ref_obj_id = reg->ref_obj_id;
8545 	}
8546 
8547 	switch (base_type(arg_type)) {
8548 	case ARG_CONST_MAP_PTR:
8549 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8550 		if (meta->map_ptr) {
8551 			/* Use map_uid (which is unique id of inner map) to reject:
8552 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8553 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8554 			 * if (inner_map1 && inner_map2) {
8555 			 *     timer = bpf_map_lookup_elem(inner_map1);
8556 			 *     if (timer)
8557 			 *         // mismatch would have been allowed
8558 			 *         bpf_timer_init(timer, inner_map2);
8559 			 * }
8560 			 *
8561 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8562 			 */
8563 			if (meta->map_ptr != reg->map_ptr ||
8564 			    meta->map_uid != reg->map_uid) {
8565 				verbose(env,
8566 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8567 					meta->map_uid, reg->map_uid);
8568 				return -EINVAL;
8569 			}
8570 		}
8571 		meta->map_ptr = reg->map_ptr;
8572 		meta->map_uid = reg->map_uid;
8573 		break;
8574 	case ARG_PTR_TO_MAP_KEY:
8575 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8576 		 * check that [key, key + map->key_size) are within
8577 		 * stack limits and initialized
8578 		 */
8579 		if (!meta->map_ptr) {
8580 			/* in function declaration map_ptr must come before
8581 			 * map_key, so that it's verified and known before
8582 			 * we have to check map_key here. Otherwise it means
8583 			 * that kernel subsystem misconfigured verifier
8584 			 */
8585 			verbose(env, "invalid map_ptr to access map->key\n");
8586 			return -EACCES;
8587 		}
8588 		err = check_helper_mem_access(env, regno,
8589 					      meta->map_ptr->key_size, false,
8590 					      NULL);
8591 		break;
8592 	case ARG_PTR_TO_MAP_VALUE:
8593 		if (type_may_be_null(arg_type) && register_is_null(reg))
8594 			return 0;
8595 
8596 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8597 		 * check [value, value + map->value_size) validity
8598 		 */
8599 		if (!meta->map_ptr) {
8600 			/* kernel subsystem misconfigured verifier */
8601 			verbose(env, "invalid map_ptr to access map->value\n");
8602 			return -EACCES;
8603 		}
8604 		meta->raw_mode = arg_type & MEM_UNINIT;
8605 		err = check_helper_mem_access(env, regno,
8606 					      meta->map_ptr->value_size, false,
8607 					      meta);
8608 		break;
8609 	case ARG_PTR_TO_PERCPU_BTF_ID:
8610 		if (!reg->btf_id) {
8611 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8612 			return -EACCES;
8613 		}
8614 		meta->ret_btf = reg->btf;
8615 		meta->ret_btf_id = reg->btf_id;
8616 		break;
8617 	case ARG_PTR_TO_SPIN_LOCK:
8618 		if (in_rbtree_lock_required_cb(env)) {
8619 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8620 			return -EACCES;
8621 		}
8622 		if (meta->func_id == BPF_FUNC_spin_lock) {
8623 			err = process_spin_lock(env, regno, true);
8624 			if (err)
8625 				return err;
8626 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8627 			err = process_spin_lock(env, regno, false);
8628 			if (err)
8629 				return err;
8630 		} else {
8631 			verbose(env, "verifier internal error\n");
8632 			return -EFAULT;
8633 		}
8634 		break;
8635 	case ARG_PTR_TO_TIMER:
8636 		err = process_timer_func(env, regno, meta);
8637 		if (err)
8638 			return err;
8639 		break;
8640 	case ARG_PTR_TO_FUNC:
8641 		meta->subprogno = reg->subprogno;
8642 		break;
8643 	case ARG_PTR_TO_MEM:
8644 		/* The access to this pointer is only checked when we hit the
8645 		 * next is_mem_size argument below.
8646 		 */
8647 		meta->raw_mode = arg_type & MEM_UNINIT;
8648 		if (arg_type & MEM_FIXED_SIZE) {
8649 			err = check_helper_mem_access(env, regno, fn->arg_size[arg], false, meta);
8650 			if (err)
8651 				return err;
8652 			if (arg_type & MEM_ALIGNED)
8653 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
8654 		}
8655 		break;
8656 	case ARG_CONST_SIZE:
8657 		err = check_mem_size_reg(env, reg, regno, false, meta);
8658 		break;
8659 	case ARG_CONST_SIZE_OR_ZERO:
8660 		err = check_mem_size_reg(env, reg, regno, true, meta);
8661 		break;
8662 	case ARG_PTR_TO_DYNPTR:
8663 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8664 		if (err)
8665 			return err;
8666 		break;
8667 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8668 		if (!tnum_is_const(reg->var_off)) {
8669 			verbose(env, "R%d is not a known constant'\n",
8670 				regno);
8671 			return -EACCES;
8672 		}
8673 		meta->mem_size = reg->var_off.value;
8674 		err = mark_chain_precision(env, regno);
8675 		if (err)
8676 			return err;
8677 		break;
8678 	case ARG_PTR_TO_CONST_STR:
8679 	{
8680 		struct bpf_map *map = reg->map_ptr;
8681 		int map_off;
8682 		u64 map_addr;
8683 		char *str_ptr;
8684 
8685 		if (!bpf_map_is_rdonly(map)) {
8686 			verbose(env, "R%d does not point to a readonly map'\n", regno);
8687 			return -EACCES;
8688 		}
8689 
8690 		if (!tnum_is_const(reg->var_off)) {
8691 			verbose(env, "R%d is not a constant address'\n", regno);
8692 			return -EACCES;
8693 		}
8694 
8695 		if (!map->ops->map_direct_value_addr) {
8696 			verbose(env, "no direct value access support for this map type\n");
8697 			return -EACCES;
8698 		}
8699 
8700 		err = check_map_access(env, regno, reg->off,
8701 				       map->value_size - reg->off, false,
8702 				       ACCESS_HELPER);
8703 		if (err)
8704 			return err;
8705 
8706 		map_off = reg->off + reg->var_off.value;
8707 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8708 		if (err) {
8709 			verbose(env, "direct value access on string failed\n");
8710 			return err;
8711 		}
8712 
8713 		str_ptr = (char *)(long)(map_addr);
8714 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8715 			verbose(env, "string is not zero-terminated\n");
8716 			return -EINVAL;
8717 		}
8718 		break;
8719 	}
8720 	case ARG_PTR_TO_KPTR:
8721 		err = process_kptr_func(env, regno, meta);
8722 		if (err)
8723 			return err;
8724 		break;
8725 	}
8726 
8727 	return err;
8728 }
8729 
8730 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8731 {
8732 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8733 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8734 
8735 	if (func_id != BPF_FUNC_map_update_elem &&
8736 	    func_id != BPF_FUNC_map_delete_elem)
8737 		return false;
8738 
8739 	/* It's not possible to get access to a locked struct sock in these
8740 	 * contexts, so updating is safe.
8741 	 */
8742 	switch (type) {
8743 	case BPF_PROG_TYPE_TRACING:
8744 		if (eatype == BPF_TRACE_ITER)
8745 			return true;
8746 		break;
8747 	case BPF_PROG_TYPE_SOCK_OPS:
8748 		/* map_update allowed only via dedicated helpers with event type checks */
8749 		if (func_id == BPF_FUNC_map_delete_elem)
8750 			return true;
8751 		break;
8752 	case BPF_PROG_TYPE_SOCKET_FILTER:
8753 	case BPF_PROG_TYPE_SCHED_CLS:
8754 	case BPF_PROG_TYPE_SCHED_ACT:
8755 	case BPF_PROG_TYPE_XDP:
8756 	case BPF_PROG_TYPE_SK_REUSEPORT:
8757 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8758 	case BPF_PROG_TYPE_SK_LOOKUP:
8759 		return true;
8760 	default:
8761 		break;
8762 	}
8763 
8764 	verbose(env, "cannot update sockmap in this context\n");
8765 	return false;
8766 }
8767 
8768 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8769 {
8770 	return env->prog->jit_requested &&
8771 	       bpf_jit_supports_subprog_tailcalls();
8772 }
8773 
8774 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8775 					struct bpf_map *map, int func_id)
8776 {
8777 	if (!map)
8778 		return 0;
8779 
8780 	/* We need a two way check, first is from map perspective ... */
8781 	switch (map->map_type) {
8782 	case BPF_MAP_TYPE_PROG_ARRAY:
8783 		if (func_id != BPF_FUNC_tail_call)
8784 			goto error;
8785 		break;
8786 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8787 		if (func_id != BPF_FUNC_perf_event_read &&
8788 		    func_id != BPF_FUNC_perf_event_output &&
8789 		    func_id != BPF_FUNC_skb_output &&
8790 		    func_id != BPF_FUNC_perf_event_read_value &&
8791 		    func_id != BPF_FUNC_xdp_output)
8792 			goto error;
8793 		break;
8794 	case BPF_MAP_TYPE_RINGBUF:
8795 		if (func_id != BPF_FUNC_ringbuf_output &&
8796 		    func_id != BPF_FUNC_ringbuf_reserve &&
8797 		    func_id != BPF_FUNC_ringbuf_query &&
8798 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8799 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8800 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8801 			goto error;
8802 		break;
8803 	case BPF_MAP_TYPE_USER_RINGBUF:
8804 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8805 			goto error;
8806 		break;
8807 	case BPF_MAP_TYPE_STACK_TRACE:
8808 		if (func_id != BPF_FUNC_get_stackid)
8809 			goto error;
8810 		break;
8811 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8812 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8813 		    func_id != BPF_FUNC_current_task_under_cgroup)
8814 			goto error;
8815 		break;
8816 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8817 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8818 		if (func_id != BPF_FUNC_get_local_storage)
8819 			goto error;
8820 		break;
8821 	case BPF_MAP_TYPE_DEVMAP:
8822 	case BPF_MAP_TYPE_DEVMAP_HASH:
8823 		if (func_id != BPF_FUNC_redirect_map &&
8824 		    func_id != BPF_FUNC_map_lookup_elem)
8825 			goto error;
8826 		break;
8827 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8828 	 * appear.
8829 	 */
8830 	case BPF_MAP_TYPE_CPUMAP:
8831 		if (func_id != BPF_FUNC_redirect_map)
8832 			goto error;
8833 		break;
8834 	case BPF_MAP_TYPE_XSKMAP:
8835 		if (func_id != BPF_FUNC_redirect_map &&
8836 		    func_id != BPF_FUNC_map_lookup_elem)
8837 			goto error;
8838 		break;
8839 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8840 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8841 		if (func_id != BPF_FUNC_map_lookup_elem)
8842 			goto error;
8843 		break;
8844 	case BPF_MAP_TYPE_SOCKMAP:
8845 		if (func_id != BPF_FUNC_sk_redirect_map &&
8846 		    func_id != BPF_FUNC_sock_map_update &&
8847 		    func_id != BPF_FUNC_msg_redirect_map &&
8848 		    func_id != BPF_FUNC_sk_select_reuseport &&
8849 		    func_id != BPF_FUNC_map_lookup_elem &&
8850 		    !may_update_sockmap(env, func_id))
8851 			goto error;
8852 		break;
8853 	case BPF_MAP_TYPE_SOCKHASH:
8854 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8855 		    func_id != BPF_FUNC_sock_hash_update &&
8856 		    func_id != BPF_FUNC_msg_redirect_hash &&
8857 		    func_id != BPF_FUNC_sk_select_reuseport &&
8858 		    func_id != BPF_FUNC_map_lookup_elem &&
8859 		    !may_update_sockmap(env, func_id))
8860 			goto error;
8861 		break;
8862 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8863 		if (func_id != BPF_FUNC_sk_select_reuseport)
8864 			goto error;
8865 		break;
8866 	case BPF_MAP_TYPE_QUEUE:
8867 	case BPF_MAP_TYPE_STACK:
8868 		if (func_id != BPF_FUNC_map_peek_elem &&
8869 		    func_id != BPF_FUNC_map_pop_elem &&
8870 		    func_id != BPF_FUNC_map_push_elem)
8871 			goto error;
8872 		break;
8873 	case BPF_MAP_TYPE_SK_STORAGE:
8874 		if (func_id != BPF_FUNC_sk_storage_get &&
8875 		    func_id != BPF_FUNC_sk_storage_delete &&
8876 		    func_id != BPF_FUNC_kptr_xchg)
8877 			goto error;
8878 		break;
8879 	case BPF_MAP_TYPE_INODE_STORAGE:
8880 		if (func_id != BPF_FUNC_inode_storage_get &&
8881 		    func_id != BPF_FUNC_inode_storage_delete &&
8882 		    func_id != BPF_FUNC_kptr_xchg)
8883 			goto error;
8884 		break;
8885 	case BPF_MAP_TYPE_TASK_STORAGE:
8886 		if (func_id != BPF_FUNC_task_storage_get &&
8887 		    func_id != BPF_FUNC_task_storage_delete &&
8888 		    func_id != BPF_FUNC_kptr_xchg)
8889 			goto error;
8890 		break;
8891 	case BPF_MAP_TYPE_CGRP_STORAGE:
8892 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8893 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8894 		    func_id != BPF_FUNC_kptr_xchg)
8895 			goto error;
8896 		break;
8897 	case BPF_MAP_TYPE_BLOOM_FILTER:
8898 		if (func_id != BPF_FUNC_map_peek_elem &&
8899 		    func_id != BPF_FUNC_map_push_elem)
8900 			goto error;
8901 		break;
8902 	default:
8903 		break;
8904 	}
8905 
8906 	/* ... and second from the function itself. */
8907 	switch (func_id) {
8908 	case BPF_FUNC_tail_call:
8909 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8910 			goto error;
8911 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8912 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8913 			return -EINVAL;
8914 		}
8915 		break;
8916 	case BPF_FUNC_perf_event_read:
8917 	case BPF_FUNC_perf_event_output:
8918 	case BPF_FUNC_perf_event_read_value:
8919 	case BPF_FUNC_skb_output:
8920 	case BPF_FUNC_xdp_output:
8921 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8922 			goto error;
8923 		break;
8924 	case BPF_FUNC_ringbuf_output:
8925 	case BPF_FUNC_ringbuf_reserve:
8926 	case BPF_FUNC_ringbuf_query:
8927 	case BPF_FUNC_ringbuf_reserve_dynptr:
8928 	case BPF_FUNC_ringbuf_submit_dynptr:
8929 	case BPF_FUNC_ringbuf_discard_dynptr:
8930 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8931 			goto error;
8932 		break;
8933 	case BPF_FUNC_user_ringbuf_drain:
8934 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8935 			goto error;
8936 		break;
8937 	case BPF_FUNC_get_stackid:
8938 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8939 			goto error;
8940 		break;
8941 	case BPF_FUNC_current_task_under_cgroup:
8942 	case BPF_FUNC_skb_under_cgroup:
8943 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8944 			goto error;
8945 		break;
8946 	case BPF_FUNC_redirect_map:
8947 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8948 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8949 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8950 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8951 			goto error;
8952 		break;
8953 	case BPF_FUNC_sk_redirect_map:
8954 	case BPF_FUNC_msg_redirect_map:
8955 	case BPF_FUNC_sock_map_update:
8956 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8957 			goto error;
8958 		break;
8959 	case BPF_FUNC_sk_redirect_hash:
8960 	case BPF_FUNC_msg_redirect_hash:
8961 	case BPF_FUNC_sock_hash_update:
8962 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8963 			goto error;
8964 		break;
8965 	case BPF_FUNC_get_local_storage:
8966 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8967 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8968 			goto error;
8969 		break;
8970 	case BPF_FUNC_sk_select_reuseport:
8971 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8972 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8973 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8974 			goto error;
8975 		break;
8976 	case BPF_FUNC_map_pop_elem:
8977 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8978 		    map->map_type != BPF_MAP_TYPE_STACK)
8979 			goto error;
8980 		break;
8981 	case BPF_FUNC_map_peek_elem:
8982 	case BPF_FUNC_map_push_elem:
8983 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8984 		    map->map_type != BPF_MAP_TYPE_STACK &&
8985 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8986 			goto error;
8987 		break;
8988 	case BPF_FUNC_map_lookup_percpu_elem:
8989 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8990 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8991 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8992 			goto error;
8993 		break;
8994 	case BPF_FUNC_sk_storage_get:
8995 	case BPF_FUNC_sk_storage_delete:
8996 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8997 			goto error;
8998 		break;
8999 	case BPF_FUNC_inode_storage_get:
9000 	case BPF_FUNC_inode_storage_delete:
9001 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9002 			goto error;
9003 		break;
9004 	case BPF_FUNC_task_storage_get:
9005 	case BPF_FUNC_task_storage_delete:
9006 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9007 			goto error;
9008 		break;
9009 	case BPF_FUNC_cgrp_storage_get:
9010 	case BPF_FUNC_cgrp_storage_delete:
9011 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9012 			goto error;
9013 		break;
9014 	default:
9015 		break;
9016 	}
9017 
9018 	return 0;
9019 error:
9020 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9021 		map->map_type, func_id_name(func_id), func_id);
9022 	return -EINVAL;
9023 }
9024 
9025 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9026 {
9027 	int count = 0;
9028 
9029 	if (arg_type_is_raw_mem(fn->arg1_type))
9030 		count++;
9031 	if (arg_type_is_raw_mem(fn->arg2_type))
9032 		count++;
9033 	if (arg_type_is_raw_mem(fn->arg3_type))
9034 		count++;
9035 	if (arg_type_is_raw_mem(fn->arg4_type))
9036 		count++;
9037 	if (arg_type_is_raw_mem(fn->arg5_type))
9038 		count++;
9039 
9040 	/* We only support one arg being in raw mode at the moment,
9041 	 * which is sufficient for the helper functions we have
9042 	 * right now.
9043 	 */
9044 	return count <= 1;
9045 }
9046 
9047 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9048 {
9049 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9050 	bool has_size = fn->arg_size[arg] != 0;
9051 	bool is_next_size = false;
9052 
9053 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9054 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9055 
9056 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9057 		return is_next_size;
9058 
9059 	return has_size == is_next_size || is_next_size == is_fixed;
9060 }
9061 
9062 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9063 {
9064 	/* bpf_xxx(..., buf, len) call will access 'len'
9065 	 * bytes from memory 'buf'. Both arg types need
9066 	 * to be paired, so make sure there's no buggy
9067 	 * helper function specification.
9068 	 */
9069 	if (arg_type_is_mem_size(fn->arg1_type) ||
9070 	    check_args_pair_invalid(fn, 0) ||
9071 	    check_args_pair_invalid(fn, 1) ||
9072 	    check_args_pair_invalid(fn, 2) ||
9073 	    check_args_pair_invalid(fn, 3) ||
9074 	    check_args_pair_invalid(fn, 4))
9075 		return false;
9076 
9077 	return true;
9078 }
9079 
9080 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9081 {
9082 	int i;
9083 
9084 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9085 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9086 			return !!fn->arg_btf_id[i];
9087 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9088 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9089 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9090 		    /* arg_btf_id and arg_size are in a union. */
9091 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9092 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9093 			return false;
9094 	}
9095 
9096 	return true;
9097 }
9098 
9099 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9100 {
9101 	return check_raw_mode_ok(fn) &&
9102 	       check_arg_pair_ok(fn) &&
9103 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9104 }
9105 
9106 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9107  * are now invalid, so turn them into unknown SCALAR_VALUE.
9108  *
9109  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9110  * since these slices point to packet data.
9111  */
9112 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9113 {
9114 	struct bpf_func_state *state;
9115 	struct bpf_reg_state *reg;
9116 
9117 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9118 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9119 			mark_reg_invalid(env, reg);
9120 	}));
9121 }
9122 
9123 enum {
9124 	AT_PKT_END = -1,
9125 	BEYOND_PKT_END = -2,
9126 };
9127 
9128 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9129 {
9130 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9131 	struct bpf_reg_state *reg = &state->regs[regn];
9132 
9133 	if (reg->type != PTR_TO_PACKET)
9134 		/* PTR_TO_PACKET_META is not supported yet */
9135 		return;
9136 
9137 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9138 	 * How far beyond pkt_end it goes is unknown.
9139 	 * if (!range_open) it's the case of pkt >= pkt_end
9140 	 * if (range_open) it's the case of pkt > pkt_end
9141 	 * hence this pointer is at least 1 byte bigger than pkt_end
9142 	 */
9143 	if (range_open)
9144 		reg->range = BEYOND_PKT_END;
9145 	else
9146 		reg->range = AT_PKT_END;
9147 }
9148 
9149 /* The pointer with the specified id has released its reference to kernel
9150  * resources. Identify all copies of the same pointer and clear the reference.
9151  */
9152 static int release_reference(struct bpf_verifier_env *env,
9153 			     int ref_obj_id)
9154 {
9155 	struct bpf_func_state *state;
9156 	struct bpf_reg_state *reg;
9157 	int err;
9158 
9159 	err = release_reference_state(cur_func(env), ref_obj_id);
9160 	if (err)
9161 		return err;
9162 
9163 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9164 		if (reg->ref_obj_id == ref_obj_id)
9165 			mark_reg_invalid(env, reg);
9166 	}));
9167 
9168 	return 0;
9169 }
9170 
9171 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9172 {
9173 	struct bpf_func_state *unused;
9174 	struct bpf_reg_state *reg;
9175 
9176 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9177 		if (type_is_non_owning_ref(reg->type))
9178 			mark_reg_invalid(env, reg);
9179 	}));
9180 }
9181 
9182 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9183 				    struct bpf_reg_state *regs)
9184 {
9185 	int i;
9186 
9187 	/* after the call registers r0 - r5 were scratched */
9188 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9189 		mark_reg_not_init(env, regs, caller_saved[i]);
9190 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9191 	}
9192 }
9193 
9194 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9195 				   struct bpf_func_state *caller,
9196 				   struct bpf_func_state *callee,
9197 				   int insn_idx);
9198 
9199 static int set_callee_state(struct bpf_verifier_env *env,
9200 			    struct bpf_func_state *caller,
9201 			    struct bpf_func_state *callee, int insn_idx);
9202 
9203 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9204 			    set_callee_state_fn set_callee_state_cb,
9205 			    struct bpf_verifier_state *state)
9206 {
9207 	struct bpf_func_state *caller, *callee;
9208 	int err;
9209 
9210 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9211 		verbose(env, "the call stack of %d frames is too deep\n",
9212 			state->curframe + 2);
9213 		return -E2BIG;
9214 	}
9215 
9216 	if (state->frame[state->curframe + 1]) {
9217 		verbose(env, "verifier bug. Frame %d already allocated\n",
9218 			state->curframe + 1);
9219 		return -EFAULT;
9220 	}
9221 
9222 	caller = state->frame[state->curframe];
9223 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9224 	if (!callee)
9225 		return -ENOMEM;
9226 	state->frame[state->curframe + 1] = callee;
9227 
9228 	/* callee cannot access r0, r6 - r9 for reading and has to write
9229 	 * into its own stack before reading from it.
9230 	 * callee can read/write into caller's stack
9231 	 */
9232 	init_func_state(env, callee,
9233 			/* remember the callsite, it will be used by bpf_exit */
9234 			callsite,
9235 			state->curframe + 1 /* frameno within this callchain */,
9236 			subprog /* subprog number within this prog */);
9237 	/* Transfer references to the callee */
9238 	err = copy_reference_state(callee, caller);
9239 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9240 	if (err)
9241 		goto err_out;
9242 
9243 	/* only increment it after check_reg_arg() finished */
9244 	state->curframe++;
9245 
9246 	return 0;
9247 
9248 err_out:
9249 	free_func_state(callee);
9250 	state->frame[state->curframe + 1] = NULL;
9251 	return err;
9252 }
9253 
9254 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9255 			      int insn_idx, int subprog,
9256 			      set_callee_state_fn set_callee_state_cb)
9257 {
9258 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9259 	struct bpf_func_state *caller, *callee;
9260 	int err;
9261 
9262 	caller = state->frame[state->curframe];
9263 	err = btf_check_subprog_call(env, subprog, caller->regs);
9264 	if (err == -EFAULT)
9265 		return err;
9266 
9267 	/* set_callee_state is used for direct subprog calls, but we are
9268 	 * interested in validating only BPF helpers that can call subprogs as
9269 	 * callbacks
9270 	 */
9271 	if (bpf_pseudo_kfunc_call(insn) &&
9272 	    !is_sync_callback_calling_kfunc(insn->imm)) {
9273 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9274 			func_id_name(insn->imm), insn->imm);
9275 		return -EFAULT;
9276 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9277 		   !is_callback_calling_function(insn->imm)) { /* helper */
9278 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9279 			func_id_name(insn->imm), insn->imm);
9280 		return -EFAULT;
9281 	}
9282 
9283 	if (insn->code == (BPF_JMP | BPF_CALL) &&
9284 	    insn->src_reg == 0 &&
9285 	    insn->imm == BPF_FUNC_timer_set_callback) {
9286 		struct bpf_verifier_state *async_cb;
9287 
9288 		/* there is no real recursion here. timer callbacks are async */
9289 		env->subprog_info[subprog].is_async_cb = true;
9290 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9291 					 insn_idx, subprog);
9292 		if (!async_cb)
9293 			return -EFAULT;
9294 		callee = async_cb->frame[0];
9295 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9296 
9297 		/* Convert bpf_timer_set_callback() args into timer callback args */
9298 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9299 		if (err)
9300 			return err;
9301 
9302 		return 0;
9303 	}
9304 
9305 	/* for callback functions enqueue entry to callback and
9306 	 * proceed with next instruction within current frame.
9307 	 */
9308 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9309 	if (!callback_state)
9310 		return -ENOMEM;
9311 
9312 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9313 			       callback_state);
9314 	if (err)
9315 		return err;
9316 
9317 	callback_state->callback_unroll_depth++;
9318 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9319 	caller->callback_depth = 0;
9320 	return 0;
9321 }
9322 
9323 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9324 			   int *insn_idx)
9325 {
9326 	struct bpf_verifier_state *state = env->cur_state;
9327 	struct bpf_func_state *caller;
9328 	int err, subprog, target_insn;
9329 
9330 	target_insn = *insn_idx + insn->imm + 1;
9331 	subprog = find_subprog(env, target_insn);
9332 	if (subprog < 0) {
9333 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9334 		return -EFAULT;
9335 	}
9336 
9337 	caller = state->frame[state->curframe];
9338 	err = btf_check_subprog_call(env, subprog, caller->regs);
9339 	if (err == -EFAULT)
9340 		return err;
9341 	if (subprog_is_global(env, subprog)) {
9342 		if (err) {
9343 			verbose(env, "Caller passes invalid args into func#%d\n", subprog);
9344 			return err;
9345 		}
9346 
9347 		if (env->log.level & BPF_LOG_LEVEL)
9348 			verbose(env, "Func#%d is global and valid. Skipping.\n", subprog);
9349 		clear_caller_saved_regs(env, caller->regs);
9350 
9351 		/* All global functions return a 64-bit SCALAR_VALUE */
9352 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9353 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9354 
9355 		/* continue with next insn after call */
9356 		return 0;
9357 	}
9358 
9359 	/* for regular function entry setup new frame and continue
9360 	 * from that frame.
9361 	 */
9362 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9363 	if (err)
9364 		return err;
9365 
9366 	clear_caller_saved_regs(env, caller->regs);
9367 
9368 	/* and go analyze first insn of the callee */
9369 	*insn_idx = env->subprog_info[subprog].start - 1;
9370 
9371 	if (env->log.level & BPF_LOG_LEVEL) {
9372 		verbose(env, "caller:\n");
9373 		print_verifier_state(env, caller, true);
9374 		verbose(env, "callee:\n");
9375 		print_verifier_state(env, state->frame[state->curframe], true);
9376 	}
9377 
9378 	return 0;
9379 }
9380 
9381 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9382 				   struct bpf_func_state *caller,
9383 				   struct bpf_func_state *callee)
9384 {
9385 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9386 	 *      void *callback_ctx, u64 flags);
9387 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9388 	 *      void *callback_ctx);
9389 	 */
9390 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9391 
9392 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9393 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9394 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9395 
9396 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9397 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9398 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9399 
9400 	/* pointer to stack or null */
9401 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9402 
9403 	/* unused */
9404 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9405 	return 0;
9406 }
9407 
9408 static int set_callee_state(struct bpf_verifier_env *env,
9409 			    struct bpf_func_state *caller,
9410 			    struct bpf_func_state *callee, int insn_idx)
9411 {
9412 	int i;
9413 
9414 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9415 	 * pointers, which connects us up to the liveness chain
9416 	 */
9417 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9418 		callee->regs[i] = caller->regs[i];
9419 	return 0;
9420 }
9421 
9422 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9423 				       struct bpf_func_state *caller,
9424 				       struct bpf_func_state *callee,
9425 				       int insn_idx)
9426 {
9427 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9428 	struct bpf_map *map;
9429 	int err;
9430 
9431 	if (bpf_map_ptr_poisoned(insn_aux)) {
9432 		verbose(env, "tail_call abusing map_ptr\n");
9433 		return -EINVAL;
9434 	}
9435 
9436 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9437 	if (!map->ops->map_set_for_each_callback_args ||
9438 	    !map->ops->map_for_each_callback) {
9439 		verbose(env, "callback function not allowed for map\n");
9440 		return -ENOTSUPP;
9441 	}
9442 
9443 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9444 	if (err)
9445 		return err;
9446 
9447 	callee->in_callback_fn = true;
9448 	callee->callback_ret_range = tnum_range(0, 1);
9449 	return 0;
9450 }
9451 
9452 static int set_loop_callback_state(struct bpf_verifier_env *env,
9453 				   struct bpf_func_state *caller,
9454 				   struct bpf_func_state *callee,
9455 				   int insn_idx)
9456 {
9457 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9458 	 *	    u64 flags);
9459 	 * callback_fn(u32 index, void *callback_ctx);
9460 	 */
9461 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9462 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9463 
9464 	/* unused */
9465 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9466 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9467 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9468 
9469 	callee->in_callback_fn = true;
9470 	callee->callback_ret_range = tnum_range(0, 1);
9471 	return 0;
9472 }
9473 
9474 static int set_timer_callback_state(struct bpf_verifier_env *env,
9475 				    struct bpf_func_state *caller,
9476 				    struct bpf_func_state *callee,
9477 				    int insn_idx)
9478 {
9479 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9480 
9481 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9482 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9483 	 */
9484 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9485 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9486 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9487 
9488 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9489 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9490 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9491 
9492 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9493 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9494 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9495 
9496 	/* unused */
9497 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9498 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9499 	callee->in_async_callback_fn = true;
9500 	callee->callback_ret_range = tnum_range(0, 1);
9501 	return 0;
9502 }
9503 
9504 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9505 				       struct bpf_func_state *caller,
9506 				       struct bpf_func_state *callee,
9507 				       int insn_idx)
9508 {
9509 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9510 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9511 	 * (callback_fn)(struct task_struct *task,
9512 	 *               struct vm_area_struct *vma, void *callback_ctx);
9513 	 */
9514 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9515 
9516 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9517 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9518 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9519 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9520 
9521 	/* pointer to stack or null */
9522 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9523 
9524 	/* unused */
9525 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9526 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9527 	callee->in_callback_fn = true;
9528 	callee->callback_ret_range = tnum_range(0, 1);
9529 	return 0;
9530 }
9531 
9532 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9533 					   struct bpf_func_state *caller,
9534 					   struct bpf_func_state *callee,
9535 					   int insn_idx)
9536 {
9537 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9538 	 *			  callback_ctx, u64 flags);
9539 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9540 	 */
9541 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9542 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9543 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9544 
9545 	/* unused */
9546 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9547 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9548 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9549 
9550 	callee->in_callback_fn = true;
9551 	callee->callback_ret_range = tnum_range(0, 1);
9552 	return 0;
9553 }
9554 
9555 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9556 					 struct bpf_func_state *caller,
9557 					 struct bpf_func_state *callee,
9558 					 int insn_idx)
9559 {
9560 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9561 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9562 	 *
9563 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9564 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9565 	 * by this point, so look at 'root'
9566 	 */
9567 	struct btf_field *field;
9568 
9569 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9570 				      BPF_RB_ROOT);
9571 	if (!field || !field->graph_root.value_btf_id)
9572 		return -EFAULT;
9573 
9574 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9575 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9576 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9577 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9578 
9579 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9580 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9581 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9582 	callee->in_callback_fn = true;
9583 	callee->callback_ret_range = tnum_range(0, 1);
9584 	return 0;
9585 }
9586 
9587 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9588 
9589 /* Are we currently verifying the callback for a rbtree helper that must
9590  * be called with lock held? If so, no need to complain about unreleased
9591  * lock
9592  */
9593 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9594 {
9595 	struct bpf_verifier_state *state = env->cur_state;
9596 	struct bpf_insn *insn = env->prog->insnsi;
9597 	struct bpf_func_state *callee;
9598 	int kfunc_btf_id;
9599 
9600 	if (!state->curframe)
9601 		return false;
9602 
9603 	callee = state->frame[state->curframe];
9604 
9605 	if (!callee->in_callback_fn)
9606 		return false;
9607 
9608 	kfunc_btf_id = insn[callee->callsite].imm;
9609 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9610 }
9611 
9612 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9613 {
9614 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9615 	struct bpf_func_state *caller, *callee;
9616 	struct bpf_reg_state *r0;
9617 	bool in_callback_fn;
9618 	int err;
9619 
9620 	callee = state->frame[state->curframe];
9621 	r0 = &callee->regs[BPF_REG_0];
9622 	if (r0->type == PTR_TO_STACK) {
9623 		/* technically it's ok to return caller's stack pointer
9624 		 * (or caller's caller's pointer) back to the caller,
9625 		 * since these pointers are valid. Only current stack
9626 		 * pointer will be invalid as soon as function exits,
9627 		 * but let's be conservative
9628 		 */
9629 		verbose(env, "cannot return stack pointer to the caller\n");
9630 		return -EINVAL;
9631 	}
9632 
9633 	caller = state->frame[state->curframe - 1];
9634 	if (callee->in_callback_fn) {
9635 		/* enforce R0 return value range [0, 1]. */
9636 		struct tnum range = callee->callback_ret_range;
9637 
9638 		if (r0->type != SCALAR_VALUE) {
9639 			verbose(env, "R0 not a scalar value\n");
9640 			return -EACCES;
9641 		}
9642 
9643 		/* we are going to rely on register's precise value */
9644 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9645 		err = err ?: mark_chain_precision(env, BPF_REG_0);
9646 		if (err)
9647 			return err;
9648 
9649 		if (!tnum_in(range, r0->var_off)) {
9650 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9651 			return -EINVAL;
9652 		}
9653 		if (!calls_callback(env, callee->callsite)) {
9654 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9655 				*insn_idx, callee->callsite);
9656 			return -EFAULT;
9657 		}
9658 	} else {
9659 		/* return to the caller whatever r0 had in the callee */
9660 		caller->regs[BPF_REG_0] = *r0;
9661 	}
9662 
9663 	/* callback_fn frame should have released its own additions to parent's
9664 	 * reference state at this point, or check_reference_leak would
9665 	 * complain, hence it must be the same as the caller. There is no need
9666 	 * to copy it back.
9667 	 */
9668 	if (!callee->in_callback_fn) {
9669 		/* Transfer references to the caller */
9670 		err = copy_reference_state(caller, callee);
9671 		if (err)
9672 			return err;
9673 	}
9674 
9675 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9676 	 * there function call logic would reschedule callback visit. If iteration
9677 	 * converges is_state_visited() would prune that visit eventually.
9678 	 */
9679 	in_callback_fn = callee->in_callback_fn;
9680 	if (in_callback_fn)
9681 		*insn_idx = callee->callsite;
9682 	else
9683 		*insn_idx = callee->callsite + 1;
9684 
9685 	if (env->log.level & BPF_LOG_LEVEL) {
9686 		verbose(env, "returning from callee:\n");
9687 		print_verifier_state(env, callee, true);
9688 		verbose(env, "to caller at %d:\n", *insn_idx);
9689 		print_verifier_state(env, caller, true);
9690 	}
9691 	/* clear everything in the callee */
9692 	free_func_state(callee);
9693 	state->frame[state->curframe--] = NULL;
9694 
9695 	/* for callbacks widen imprecise scalars to make programs like below verify:
9696 	 *
9697 	 *   struct ctx { int i; }
9698 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9699 	 *   ...
9700 	 *   struct ctx = { .i = 0; }
9701 	 *   bpf_loop(100, cb, &ctx, 0);
9702 	 *
9703 	 * This is similar to what is done in process_iter_next_call() for open
9704 	 * coded iterators.
9705 	 */
9706 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9707 	if (prev_st) {
9708 		err = widen_imprecise_scalars(env, prev_st, state);
9709 		if (err)
9710 			return err;
9711 	}
9712 	return 0;
9713 }
9714 
9715 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9716 				   int func_id,
9717 				   struct bpf_call_arg_meta *meta)
9718 {
9719 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9720 
9721 	if (ret_type != RET_INTEGER)
9722 		return;
9723 
9724 	switch (func_id) {
9725 	case BPF_FUNC_get_stack:
9726 	case BPF_FUNC_get_task_stack:
9727 	case BPF_FUNC_probe_read_str:
9728 	case BPF_FUNC_probe_read_kernel_str:
9729 	case BPF_FUNC_probe_read_user_str:
9730 		ret_reg->smax_value = meta->msize_max_value;
9731 		ret_reg->s32_max_value = meta->msize_max_value;
9732 		ret_reg->smin_value = -MAX_ERRNO;
9733 		ret_reg->s32_min_value = -MAX_ERRNO;
9734 		reg_bounds_sync(ret_reg);
9735 		break;
9736 	case BPF_FUNC_get_smp_processor_id:
9737 		ret_reg->umax_value = nr_cpu_ids - 1;
9738 		ret_reg->u32_max_value = nr_cpu_ids - 1;
9739 		ret_reg->smax_value = nr_cpu_ids - 1;
9740 		ret_reg->s32_max_value = nr_cpu_ids - 1;
9741 		ret_reg->umin_value = 0;
9742 		ret_reg->u32_min_value = 0;
9743 		ret_reg->smin_value = 0;
9744 		ret_reg->s32_min_value = 0;
9745 		reg_bounds_sync(ret_reg);
9746 		break;
9747 	}
9748 }
9749 
9750 static int
9751 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9752 		int func_id, int insn_idx)
9753 {
9754 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9755 	struct bpf_map *map = meta->map_ptr;
9756 
9757 	if (func_id != BPF_FUNC_tail_call &&
9758 	    func_id != BPF_FUNC_map_lookup_elem &&
9759 	    func_id != BPF_FUNC_map_update_elem &&
9760 	    func_id != BPF_FUNC_map_delete_elem &&
9761 	    func_id != BPF_FUNC_map_push_elem &&
9762 	    func_id != BPF_FUNC_map_pop_elem &&
9763 	    func_id != BPF_FUNC_map_peek_elem &&
9764 	    func_id != BPF_FUNC_for_each_map_elem &&
9765 	    func_id != BPF_FUNC_redirect_map &&
9766 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9767 		return 0;
9768 
9769 	if (map == NULL) {
9770 		verbose(env, "kernel subsystem misconfigured verifier\n");
9771 		return -EINVAL;
9772 	}
9773 
9774 	/* In case of read-only, some additional restrictions
9775 	 * need to be applied in order to prevent altering the
9776 	 * state of the map from program side.
9777 	 */
9778 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9779 	    (func_id == BPF_FUNC_map_delete_elem ||
9780 	     func_id == BPF_FUNC_map_update_elem ||
9781 	     func_id == BPF_FUNC_map_push_elem ||
9782 	     func_id == BPF_FUNC_map_pop_elem)) {
9783 		verbose(env, "write into map forbidden\n");
9784 		return -EACCES;
9785 	}
9786 
9787 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9788 		bpf_map_ptr_store(aux, meta->map_ptr,
9789 				  !meta->map_ptr->bypass_spec_v1);
9790 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9791 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9792 				  !meta->map_ptr->bypass_spec_v1);
9793 	return 0;
9794 }
9795 
9796 static int
9797 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9798 		int func_id, int insn_idx)
9799 {
9800 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9801 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9802 	struct bpf_map *map = meta->map_ptr;
9803 	u64 val, max;
9804 	int err;
9805 
9806 	if (func_id != BPF_FUNC_tail_call)
9807 		return 0;
9808 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9809 		verbose(env, "kernel subsystem misconfigured verifier\n");
9810 		return -EINVAL;
9811 	}
9812 
9813 	reg = &regs[BPF_REG_3];
9814 	val = reg->var_off.value;
9815 	max = map->max_entries;
9816 
9817 	if (!(register_is_const(reg) && val < max)) {
9818 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9819 		return 0;
9820 	}
9821 
9822 	err = mark_chain_precision(env, BPF_REG_3);
9823 	if (err)
9824 		return err;
9825 	if (bpf_map_key_unseen(aux))
9826 		bpf_map_key_store(aux, val);
9827 	else if (!bpf_map_key_poisoned(aux) &&
9828 		  bpf_map_key_immediate(aux) != val)
9829 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9830 	return 0;
9831 }
9832 
9833 static int check_reference_leak(struct bpf_verifier_env *env)
9834 {
9835 	struct bpf_func_state *state = cur_func(env);
9836 	bool refs_lingering = false;
9837 	int i;
9838 
9839 	if (state->frameno && !state->in_callback_fn)
9840 		return 0;
9841 
9842 	for (i = 0; i < state->acquired_refs; i++) {
9843 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9844 			continue;
9845 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9846 			state->refs[i].id, state->refs[i].insn_idx);
9847 		refs_lingering = true;
9848 	}
9849 	return refs_lingering ? -EINVAL : 0;
9850 }
9851 
9852 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9853 				   struct bpf_reg_state *regs)
9854 {
9855 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9856 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9857 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9858 	struct bpf_bprintf_data data = {};
9859 	int err, fmt_map_off, num_args;
9860 	u64 fmt_addr;
9861 	char *fmt;
9862 
9863 	/* data must be an array of u64 */
9864 	if (data_len_reg->var_off.value % 8)
9865 		return -EINVAL;
9866 	num_args = data_len_reg->var_off.value / 8;
9867 
9868 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9869 	 * and map_direct_value_addr is set.
9870 	 */
9871 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9872 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9873 						  fmt_map_off);
9874 	if (err) {
9875 		verbose(env, "verifier bug\n");
9876 		return -EFAULT;
9877 	}
9878 	fmt = (char *)(long)fmt_addr + fmt_map_off;
9879 
9880 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9881 	 * can focus on validating the format specifiers.
9882 	 */
9883 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9884 	if (err < 0)
9885 		verbose(env, "Invalid format string\n");
9886 
9887 	return err;
9888 }
9889 
9890 static int check_get_func_ip(struct bpf_verifier_env *env)
9891 {
9892 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9893 	int func_id = BPF_FUNC_get_func_ip;
9894 
9895 	if (type == BPF_PROG_TYPE_TRACING) {
9896 		if (!bpf_prog_has_trampoline(env->prog)) {
9897 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9898 				func_id_name(func_id), func_id);
9899 			return -ENOTSUPP;
9900 		}
9901 		return 0;
9902 	} else if (type == BPF_PROG_TYPE_KPROBE) {
9903 		return 0;
9904 	}
9905 
9906 	verbose(env, "func %s#%d not supported for program type %d\n",
9907 		func_id_name(func_id), func_id, type);
9908 	return -ENOTSUPP;
9909 }
9910 
9911 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9912 {
9913 	return &env->insn_aux_data[env->insn_idx];
9914 }
9915 
9916 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9917 {
9918 	struct bpf_reg_state *regs = cur_regs(env);
9919 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9920 	bool reg_is_null = register_is_null(reg);
9921 
9922 	if (reg_is_null)
9923 		mark_chain_precision(env, BPF_REG_4);
9924 
9925 	return reg_is_null;
9926 }
9927 
9928 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9929 {
9930 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9931 
9932 	if (!state->initialized) {
9933 		state->initialized = 1;
9934 		state->fit_for_inline = loop_flag_is_zero(env);
9935 		state->callback_subprogno = subprogno;
9936 		return;
9937 	}
9938 
9939 	if (!state->fit_for_inline)
9940 		return;
9941 
9942 	state->fit_for_inline = (loop_flag_is_zero(env) &&
9943 				 state->callback_subprogno == subprogno);
9944 }
9945 
9946 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9947 			     int *insn_idx_p)
9948 {
9949 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9950 	const struct bpf_func_proto *fn = NULL;
9951 	enum bpf_return_type ret_type;
9952 	enum bpf_type_flag ret_flag;
9953 	struct bpf_reg_state *regs;
9954 	struct bpf_call_arg_meta meta;
9955 	int insn_idx = *insn_idx_p;
9956 	bool changes_data;
9957 	int i, err, func_id;
9958 
9959 	/* find function prototype */
9960 	func_id = insn->imm;
9961 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9962 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9963 			func_id);
9964 		return -EINVAL;
9965 	}
9966 
9967 	if (env->ops->get_func_proto)
9968 		fn = env->ops->get_func_proto(func_id, env->prog);
9969 	if (!fn) {
9970 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9971 			func_id);
9972 		return -EINVAL;
9973 	}
9974 
9975 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9976 	if (!env->prog->gpl_compatible && fn->gpl_only) {
9977 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9978 		return -EINVAL;
9979 	}
9980 
9981 	if (fn->allowed && !fn->allowed(env->prog)) {
9982 		verbose(env, "helper call is not allowed in probe\n");
9983 		return -EINVAL;
9984 	}
9985 
9986 	if (!env->prog->aux->sleepable && fn->might_sleep) {
9987 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
9988 		return -EINVAL;
9989 	}
9990 
9991 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
9992 	changes_data = bpf_helper_changes_pkt_data(fn->func);
9993 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9994 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9995 			func_id_name(func_id), func_id);
9996 		return -EINVAL;
9997 	}
9998 
9999 	memset(&meta, 0, sizeof(meta));
10000 	meta.pkt_access = fn->pkt_access;
10001 
10002 	err = check_func_proto(fn, func_id);
10003 	if (err) {
10004 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10005 			func_id_name(func_id), func_id);
10006 		return err;
10007 	}
10008 
10009 	if (env->cur_state->active_rcu_lock) {
10010 		if (fn->might_sleep) {
10011 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10012 				func_id_name(func_id), func_id);
10013 			return -EINVAL;
10014 		}
10015 
10016 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10017 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10018 	}
10019 
10020 	meta.func_id = func_id;
10021 	/* check args */
10022 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10023 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10024 		if (err)
10025 			return err;
10026 	}
10027 
10028 	err = record_func_map(env, &meta, func_id, insn_idx);
10029 	if (err)
10030 		return err;
10031 
10032 	err = record_func_key(env, &meta, func_id, insn_idx);
10033 	if (err)
10034 		return err;
10035 
10036 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10037 	 * is inferred from register state.
10038 	 */
10039 	for (i = 0; i < meta.access_size; i++) {
10040 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10041 				       BPF_WRITE, -1, false, false);
10042 		if (err)
10043 			return err;
10044 	}
10045 
10046 	regs = cur_regs(env);
10047 
10048 	if (meta.release_regno) {
10049 		err = -EINVAL;
10050 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10051 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10052 		 * is safe to do directly.
10053 		 */
10054 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10055 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10056 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10057 				return -EFAULT;
10058 			}
10059 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10060 		} else if (meta.ref_obj_id) {
10061 			err = release_reference(env, meta.ref_obj_id);
10062 		} else if (register_is_null(&regs[meta.release_regno])) {
10063 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10064 			 * released is NULL, which must be > R0.
10065 			 */
10066 			err = 0;
10067 		}
10068 		if (err) {
10069 			verbose(env, "func %s#%d reference has not been acquired before\n",
10070 				func_id_name(func_id), func_id);
10071 			return err;
10072 		}
10073 	}
10074 
10075 	switch (func_id) {
10076 	case BPF_FUNC_tail_call:
10077 		err = check_reference_leak(env);
10078 		if (err) {
10079 			verbose(env, "tail_call would lead to reference leak\n");
10080 			return err;
10081 		}
10082 		break;
10083 	case BPF_FUNC_get_local_storage:
10084 		/* check that flags argument in get_local_storage(map, flags) is 0,
10085 		 * this is required because get_local_storage() can't return an error.
10086 		 */
10087 		if (!register_is_null(&regs[BPF_REG_2])) {
10088 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10089 			return -EINVAL;
10090 		}
10091 		break;
10092 	case BPF_FUNC_for_each_map_elem:
10093 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10094 					 set_map_elem_callback_state);
10095 		break;
10096 	case BPF_FUNC_timer_set_callback:
10097 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10098 					 set_timer_callback_state);
10099 		break;
10100 	case BPF_FUNC_find_vma:
10101 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10102 					 set_find_vma_callback_state);
10103 		break;
10104 	case BPF_FUNC_snprintf:
10105 		err = check_bpf_snprintf_call(env, regs);
10106 		break;
10107 	case BPF_FUNC_loop:
10108 		update_loop_inline_state(env, meta.subprogno);
10109 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10110 		 * is finished, thus mark it precise.
10111 		 */
10112 		err = mark_chain_precision(env, BPF_REG_1);
10113 		if (err)
10114 			return err;
10115 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10116 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10117 						 set_loop_callback_state);
10118 		} else {
10119 			cur_func(env)->callback_depth = 0;
10120 			if (env->log.level & BPF_LOG_LEVEL2)
10121 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10122 					env->cur_state->curframe);
10123 		}
10124 		break;
10125 	case BPF_FUNC_dynptr_from_mem:
10126 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10127 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10128 				reg_type_str(env, regs[BPF_REG_1].type));
10129 			return -EACCES;
10130 		}
10131 		break;
10132 	case BPF_FUNC_set_retval:
10133 		if (prog_type == BPF_PROG_TYPE_LSM &&
10134 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10135 			if (!env->prog->aux->attach_func_proto->type) {
10136 				/* Make sure programs that attach to void
10137 				 * hooks don't try to modify return value.
10138 				 */
10139 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10140 				return -EINVAL;
10141 			}
10142 		}
10143 		break;
10144 	case BPF_FUNC_dynptr_data:
10145 	{
10146 		struct bpf_reg_state *reg;
10147 		int id, ref_obj_id;
10148 
10149 		reg = get_dynptr_arg_reg(env, fn, regs);
10150 		if (!reg)
10151 			return -EFAULT;
10152 
10153 
10154 		if (meta.dynptr_id) {
10155 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10156 			return -EFAULT;
10157 		}
10158 		if (meta.ref_obj_id) {
10159 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10160 			return -EFAULT;
10161 		}
10162 
10163 		id = dynptr_id(env, reg);
10164 		if (id < 0) {
10165 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10166 			return id;
10167 		}
10168 
10169 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10170 		if (ref_obj_id < 0) {
10171 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10172 			return ref_obj_id;
10173 		}
10174 
10175 		meta.dynptr_id = id;
10176 		meta.ref_obj_id = ref_obj_id;
10177 
10178 		break;
10179 	}
10180 	case BPF_FUNC_dynptr_write:
10181 	{
10182 		enum bpf_dynptr_type dynptr_type;
10183 		struct bpf_reg_state *reg;
10184 
10185 		reg = get_dynptr_arg_reg(env, fn, regs);
10186 		if (!reg)
10187 			return -EFAULT;
10188 
10189 		dynptr_type = dynptr_get_type(env, reg);
10190 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10191 			return -EFAULT;
10192 
10193 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10194 			/* this will trigger clear_all_pkt_pointers(), which will
10195 			 * invalidate all dynptr slices associated with the skb
10196 			 */
10197 			changes_data = true;
10198 
10199 		break;
10200 	}
10201 	case BPF_FUNC_user_ringbuf_drain:
10202 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10203 					 set_user_ringbuf_callback_state);
10204 		break;
10205 	}
10206 
10207 	if (err)
10208 		return err;
10209 
10210 	/* reset caller saved regs */
10211 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10212 		mark_reg_not_init(env, regs, caller_saved[i]);
10213 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10214 	}
10215 
10216 	/* helper call returns 64-bit value. */
10217 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10218 
10219 	/* update return register (already marked as written above) */
10220 	ret_type = fn->ret_type;
10221 	ret_flag = type_flag(ret_type);
10222 
10223 	switch (base_type(ret_type)) {
10224 	case RET_INTEGER:
10225 		/* sets type to SCALAR_VALUE */
10226 		mark_reg_unknown(env, regs, BPF_REG_0);
10227 		break;
10228 	case RET_VOID:
10229 		regs[BPF_REG_0].type = NOT_INIT;
10230 		break;
10231 	case RET_PTR_TO_MAP_VALUE:
10232 		/* There is no offset yet applied, variable or fixed */
10233 		mark_reg_known_zero(env, regs, BPF_REG_0);
10234 		/* remember map_ptr, so that check_map_access()
10235 		 * can check 'value_size' boundary of memory access
10236 		 * to map element returned from bpf_map_lookup_elem()
10237 		 */
10238 		if (meta.map_ptr == NULL) {
10239 			verbose(env,
10240 				"kernel subsystem misconfigured verifier\n");
10241 			return -EINVAL;
10242 		}
10243 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10244 		regs[BPF_REG_0].map_uid = meta.map_uid;
10245 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10246 		if (!type_may_be_null(ret_type) &&
10247 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10248 			regs[BPF_REG_0].id = ++env->id_gen;
10249 		}
10250 		break;
10251 	case RET_PTR_TO_SOCKET:
10252 		mark_reg_known_zero(env, regs, BPF_REG_0);
10253 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10254 		break;
10255 	case RET_PTR_TO_SOCK_COMMON:
10256 		mark_reg_known_zero(env, regs, BPF_REG_0);
10257 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10258 		break;
10259 	case RET_PTR_TO_TCP_SOCK:
10260 		mark_reg_known_zero(env, regs, BPF_REG_0);
10261 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10262 		break;
10263 	case RET_PTR_TO_MEM:
10264 		mark_reg_known_zero(env, regs, BPF_REG_0);
10265 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10266 		regs[BPF_REG_0].mem_size = meta.mem_size;
10267 		break;
10268 	case RET_PTR_TO_MEM_OR_BTF_ID:
10269 	{
10270 		const struct btf_type *t;
10271 
10272 		mark_reg_known_zero(env, regs, BPF_REG_0);
10273 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10274 		if (!btf_type_is_struct(t)) {
10275 			u32 tsize;
10276 			const struct btf_type *ret;
10277 			const char *tname;
10278 
10279 			/* resolve the type size of ksym. */
10280 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10281 			if (IS_ERR(ret)) {
10282 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10283 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10284 					tname, PTR_ERR(ret));
10285 				return -EINVAL;
10286 			}
10287 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10288 			regs[BPF_REG_0].mem_size = tsize;
10289 		} else {
10290 			/* MEM_RDONLY may be carried from ret_flag, but it
10291 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10292 			 * it will confuse the check of PTR_TO_BTF_ID in
10293 			 * check_mem_access().
10294 			 */
10295 			ret_flag &= ~MEM_RDONLY;
10296 
10297 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10298 			regs[BPF_REG_0].btf = meta.ret_btf;
10299 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10300 		}
10301 		break;
10302 	}
10303 	case RET_PTR_TO_BTF_ID:
10304 	{
10305 		struct btf *ret_btf;
10306 		int ret_btf_id;
10307 
10308 		mark_reg_known_zero(env, regs, BPF_REG_0);
10309 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10310 		if (func_id == BPF_FUNC_kptr_xchg) {
10311 			ret_btf = meta.kptr_field->kptr.btf;
10312 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10313 			if (!btf_is_kernel(ret_btf))
10314 				regs[BPF_REG_0].type |= MEM_ALLOC;
10315 		} else {
10316 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10317 				verbose(env, "verifier internal error:");
10318 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10319 					func_id_name(func_id));
10320 				return -EINVAL;
10321 			}
10322 			ret_btf = btf_vmlinux;
10323 			ret_btf_id = *fn->ret_btf_id;
10324 		}
10325 		if (ret_btf_id == 0) {
10326 			verbose(env, "invalid return type %u of func %s#%d\n",
10327 				base_type(ret_type), func_id_name(func_id),
10328 				func_id);
10329 			return -EINVAL;
10330 		}
10331 		regs[BPF_REG_0].btf = ret_btf;
10332 		regs[BPF_REG_0].btf_id = ret_btf_id;
10333 		break;
10334 	}
10335 	default:
10336 		verbose(env, "unknown return type %u of func %s#%d\n",
10337 			base_type(ret_type), func_id_name(func_id), func_id);
10338 		return -EINVAL;
10339 	}
10340 
10341 	if (type_may_be_null(regs[BPF_REG_0].type))
10342 		regs[BPF_REG_0].id = ++env->id_gen;
10343 
10344 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10345 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10346 			func_id_name(func_id), func_id);
10347 		return -EFAULT;
10348 	}
10349 
10350 	if (is_dynptr_ref_function(func_id))
10351 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10352 
10353 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10354 		/* For release_reference() */
10355 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10356 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10357 		int id = acquire_reference_state(env, insn_idx);
10358 
10359 		if (id < 0)
10360 			return id;
10361 		/* For mark_ptr_or_null_reg() */
10362 		regs[BPF_REG_0].id = id;
10363 		/* For release_reference() */
10364 		regs[BPF_REG_0].ref_obj_id = id;
10365 	}
10366 
10367 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
10368 
10369 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10370 	if (err)
10371 		return err;
10372 
10373 	if ((func_id == BPF_FUNC_get_stack ||
10374 	     func_id == BPF_FUNC_get_task_stack) &&
10375 	    !env->prog->has_callchain_buf) {
10376 		const char *err_str;
10377 
10378 #ifdef CONFIG_PERF_EVENTS
10379 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10380 		err_str = "cannot get callchain buffer for func %s#%d\n";
10381 #else
10382 		err = -ENOTSUPP;
10383 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10384 #endif
10385 		if (err) {
10386 			verbose(env, err_str, func_id_name(func_id), func_id);
10387 			return err;
10388 		}
10389 
10390 		env->prog->has_callchain_buf = true;
10391 	}
10392 
10393 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10394 		env->prog->call_get_stack = true;
10395 
10396 	if (func_id == BPF_FUNC_get_func_ip) {
10397 		if (check_get_func_ip(env))
10398 			return -ENOTSUPP;
10399 		env->prog->call_get_func_ip = true;
10400 	}
10401 
10402 	if (changes_data)
10403 		clear_all_pkt_pointers(env);
10404 	return 0;
10405 }
10406 
10407 /* mark_btf_func_reg_size() is used when the reg size is determined by
10408  * the BTF func_proto's return value size and argument.
10409  */
10410 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10411 				   size_t reg_size)
10412 {
10413 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10414 
10415 	if (regno == BPF_REG_0) {
10416 		/* Function return value */
10417 		reg->live |= REG_LIVE_WRITTEN;
10418 		reg->subreg_def = reg_size == sizeof(u64) ?
10419 			DEF_NOT_SUBREG : env->insn_idx + 1;
10420 	} else {
10421 		/* Function argument */
10422 		if (reg_size == sizeof(u64)) {
10423 			mark_insn_zext(env, reg);
10424 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10425 		} else {
10426 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10427 		}
10428 	}
10429 }
10430 
10431 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10432 {
10433 	return meta->kfunc_flags & KF_ACQUIRE;
10434 }
10435 
10436 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10437 {
10438 	return meta->kfunc_flags & KF_RELEASE;
10439 }
10440 
10441 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10442 {
10443 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10444 }
10445 
10446 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10447 {
10448 	return meta->kfunc_flags & KF_SLEEPABLE;
10449 }
10450 
10451 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10452 {
10453 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10454 }
10455 
10456 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10457 {
10458 	return meta->kfunc_flags & KF_RCU;
10459 }
10460 
10461 static bool __kfunc_param_match_suffix(const struct btf *btf,
10462 				       const struct btf_param *arg,
10463 				       const char *suffix)
10464 {
10465 	int suffix_len = strlen(suffix), len;
10466 	const char *param_name;
10467 
10468 	/* In the future, this can be ported to use BTF tagging */
10469 	param_name = btf_name_by_offset(btf, arg->name_off);
10470 	if (str_is_empty(param_name))
10471 		return false;
10472 	len = strlen(param_name);
10473 	if (len < suffix_len)
10474 		return false;
10475 	param_name += len - suffix_len;
10476 	return !strncmp(param_name, suffix, suffix_len);
10477 }
10478 
10479 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10480 				  const struct btf_param *arg,
10481 				  const struct bpf_reg_state *reg)
10482 {
10483 	const struct btf_type *t;
10484 
10485 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10486 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10487 		return false;
10488 
10489 	return __kfunc_param_match_suffix(btf, arg, "__sz");
10490 }
10491 
10492 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10493 					const struct btf_param *arg,
10494 					const struct bpf_reg_state *reg)
10495 {
10496 	const struct btf_type *t;
10497 
10498 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10499 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10500 		return false;
10501 
10502 	return __kfunc_param_match_suffix(btf, arg, "__szk");
10503 }
10504 
10505 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10506 {
10507 	return __kfunc_param_match_suffix(btf, arg, "__opt");
10508 }
10509 
10510 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10511 {
10512 	return __kfunc_param_match_suffix(btf, arg, "__k");
10513 }
10514 
10515 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10516 {
10517 	return __kfunc_param_match_suffix(btf, arg, "__ign");
10518 }
10519 
10520 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10521 {
10522 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
10523 }
10524 
10525 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10526 {
10527 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
10528 }
10529 
10530 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10531 {
10532 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10533 }
10534 
10535 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10536 					  const struct btf_param *arg,
10537 					  const char *name)
10538 {
10539 	int len, target_len = strlen(name);
10540 	const char *param_name;
10541 
10542 	param_name = btf_name_by_offset(btf, arg->name_off);
10543 	if (str_is_empty(param_name))
10544 		return false;
10545 	len = strlen(param_name);
10546 	if (len != target_len)
10547 		return false;
10548 	if (strcmp(param_name, name))
10549 		return false;
10550 
10551 	return true;
10552 }
10553 
10554 enum {
10555 	KF_ARG_DYNPTR_ID,
10556 	KF_ARG_LIST_HEAD_ID,
10557 	KF_ARG_LIST_NODE_ID,
10558 	KF_ARG_RB_ROOT_ID,
10559 	KF_ARG_RB_NODE_ID,
10560 };
10561 
10562 BTF_ID_LIST(kf_arg_btf_ids)
10563 BTF_ID(struct, bpf_dynptr_kern)
10564 BTF_ID(struct, bpf_list_head)
10565 BTF_ID(struct, bpf_list_node)
10566 BTF_ID(struct, bpf_rb_root)
10567 BTF_ID(struct, bpf_rb_node)
10568 
10569 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10570 				    const struct btf_param *arg, int type)
10571 {
10572 	const struct btf_type *t;
10573 	u32 res_id;
10574 
10575 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10576 	if (!t)
10577 		return false;
10578 	if (!btf_type_is_ptr(t))
10579 		return false;
10580 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10581 	if (!t)
10582 		return false;
10583 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10584 }
10585 
10586 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10587 {
10588 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10589 }
10590 
10591 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10592 {
10593 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10594 }
10595 
10596 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10597 {
10598 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10599 }
10600 
10601 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10602 {
10603 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10604 }
10605 
10606 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10607 {
10608 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10609 }
10610 
10611 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10612 				  const struct btf_param *arg)
10613 {
10614 	const struct btf_type *t;
10615 
10616 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10617 	if (!t)
10618 		return false;
10619 
10620 	return true;
10621 }
10622 
10623 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10624 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10625 					const struct btf *btf,
10626 					const struct btf_type *t, int rec)
10627 {
10628 	const struct btf_type *member_type;
10629 	const struct btf_member *member;
10630 	u32 i;
10631 
10632 	if (!btf_type_is_struct(t))
10633 		return false;
10634 
10635 	for_each_member(i, t, member) {
10636 		const struct btf_array *array;
10637 
10638 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10639 		if (btf_type_is_struct(member_type)) {
10640 			if (rec >= 3) {
10641 				verbose(env, "max struct nesting depth exceeded\n");
10642 				return false;
10643 			}
10644 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10645 				return false;
10646 			continue;
10647 		}
10648 		if (btf_type_is_array(member_type)) {
10649 			array = btf_array(member_type);
10650 			if (!array->nelems)
10651 				return false;
10652 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10653 			if (!btf_type_is_scalar(member_type))
10654 				return false;
10655 			continue;
10656 		}
10657 		if (!btf_type_is_scalar(member_type))
10658 			return false;
10659 	}
10660 	return true;
10661 }
10662 
10663 enum kfunc_ptr_arg_type {
10664 	KF_ARG_PTR_TO_CTX,
10665 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10666 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10667 	KF_ARG_PTR_TO_DYNPTR,
10668 	KF_ARG_PTR_TO_ITER,
10669 	KF_ARG_PTR_TO_LIST_HEAD,
10670 	KF_ARG_PTR_TO_LIST_NODE,
10671 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10672 	KF_ARG_PTR_TO_MEM,
10673 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10674 	KF_ARG_PTR_TO_CALLBACK,
10675 	KF_ARG_PTR_TO_RB_ROOT,
10676 	KF_ARG_PTR_TO_RB_NODE,
10677 };
10678 
10679 enum special_kfunc_type {
10680 	KF_bpf_obj_new_impl,
10681 	KF_bpf_obj_drop_impl,
10682 	KF_bpf_refcount_acquire_impl,
10683 	KF_bpf_list_push_front_impl,
10684 	KF_bpf_list_push_back_impl,
10685 	KF_bpf_list_pop_front,
10686 	KF_bpf_list_pop_back,
10687 	KF_bpf_cast_to_kern_ctx,
10688 	KF_bpf_rdonly_cast,
10689 	KF_bpf_rcu_read_lock,
10690 	KF_bpf_rcu_read_unlock,
10691 	KF_bpf_rbtree_remove,
10692 	KF_bpf_rbtree_add_impl,
10693 	KF_bpf_rbtree_first,
10694 	KF_bpf_dynptr_from_skb,
10695 	KF_bpf_dynptr_from_xdp,
10696 	KF_bpf_dynptr_slice,
10697 	KF_bpf_dynptr_slice_rdwr,
10698 	KF_bpf_dynptr_clone,
10699 };
10700 
10701 BTF_SET_START(special_kfunc_set)
10702 BTF_ID(func, bpf_obj_new_impl)
10703 BTF_ID(func, bpf_obj_drop_impl)
10704 BTF_ID(func, bpf_refcount_acquire_impl)
10705 BTF_ID(func, bpf_list_push_front_impl)
10706 BTF_ID(func, bpf_list_push_back_impl)
10707 BTF_ID(func, bpf_list_pop_front)
10708 BTF_ID(func, bpf_list_pop_back)
10709 BTF_ID(func, bpf_cast_to_kern_ctx)
10710 BTF_ID(func, bpf_rdonly_cast)
10711 BTF_ID(func, bpf_rbtree_remove)
10712 BTF_ID(func, bpf_rbtree_add_impl)
10713 BTF_ID(func, bpf_rbtree_first)
10714 BTF_ID(func, bpf_dynptr_from_skb)
10715 BTF_ID(func, bpf_dynptr_from_xdp)
10716 BTF_ID(func, bpf_dynptr_slice)
10717 BTF_ID(func, bpf_dynptr_slice_rdwr)
10718 BTF_ID(func, bpf_dynptr_clone)
10719 BTF_SET_END(special_kfunc_set)
10720 
10721 BTF_ID_LIST(special_kfunc_list)
10722 BTF_ID(func, bpf_obj_new_impl)
10723 BTF_ID(func, bpf_obj_drop_impl)
10724 BTF_ID(func, bpf_refcount_acquire_impl)
10725 BTF_ID(func, bpf_list_push_front_impl)
10726 BTF_ID(func, bpf_list_push_back_impl)
10727 BTF_ID(func, bpf_list_pop_front)
10728 BTF_ID(func, bpf_list_pop_back)
10729 BTF_ID(func, bpf_cast_to_kern_ctx)
10730 BTF_ID(func, bpf_rdonly_cast)
10731 BTF_ID(func, bpf_rcu_read_lock)
10732 BTF_ID(func, bpf_rcu_read_unlock)
10733 BTF_ID(func, bpf_rbtree_remove)
10734 BTF_ID(func, bpf_rbtree_add_impl)
10735 BTF_ID(func, bpf_rbtree_first)
10736 BTF_ID(func, bpf_dynptr_from_skb)
10737 BTF_ID(func, bpf_dynptr_from_xdp)
10738 BTF_ID(func, bpf_dynptr_slice)
10739 BTF_ID(func, bpf_dynptr_slice_rdwr)
10740 BTF_ID(func, bpf_dynptr_clone)
10741 
10742 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10743 {
10744 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10745 	    meta->arg_owning_ref) {
10746 		return false;
10747 	}
10748 
10749 	return meta->kfunc_flags & KF_RET_NULL;
10750 }
10751 
10752 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10753 {
10754 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10755 }
10756 
10757 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10758 {
10759 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10760 }
10761 
10762 static enum kfunc_ptr_arg_type
10763 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10764 		       struct bpf_kfunc_call_arg_meta *meta,
10765 		       const struct btf_type *t, const struct btf_type *ref_t,
10766 		       const char *ref_tname, const struct btf_param *args,
10767 		       int argno, int nargs)
10768 {
10769 	u32 regno = argno + 1;
10770 	struct bpf_reg_state *regs = cur_regs(env);
10771 	struct bpf_reg_state *reg = &regs[regno];
10772 	bool arg_mem_size = false;
10773 
10774 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10775 		return KF_ARG_PTR_TO_CTX;
10776 
10777 	/* In this function, we verify the kfunc's BTF as per the argument type,
10778 	 * leaving the rest of the verification with respect to the register
10779 	 * type to our caller. When a set of conditions hold in the BTF type of
10780 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10781 	 */
10782 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10783 		return KF_ARG_PTR_TO_CTX;
10784 
10785 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10786 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10787 
10788 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10789 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10790 
10791 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10792 		return KF_ARG_PTR_TO_DYNPTR;
10793 
10794 	if (is_kfunc_arg_iter(meta, argno))
10795 		return KF_ARG_PTR_TO_ITER;
10796 
10797 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10798 		return KF_ARG_PTR_TO_LIST_HEAD;
10799 
10800 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10801 		return KF_ARG_PTR_TO_LIST_NODE;
10802 
10803 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10804 		return KF_ARG_PTR_TO_RB_ROOT;
10805 
10806 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10807 		return KF_ARG_PTR_TO_RB_NODE;
10808 
10809 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10810 		if (!btf_type_is_struct(ref_t)) {
10811 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10812 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10813 			return -EINVAL;
10814 		}
10815 		return KF_ARG_PTR_TO_BTF_ID;
10816 	}
10817 
10818 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10819 		return KF_ARG_PTR_TO_CALLBACK;
10820 
10821 
10822 	if (argno + 1 < nargs &&
10823 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10824 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10825 		arg_mem_size = true;
10826 
10827 	/* This is the catch all argument type of register types supported by
10828 	 * check_helper_mem_access. However, we only allow when argument type is
10829 	 * pointer to scalar, or struct composed (recursively) of scalars. When
10830 	 * arg_mem_size is true, the pointer can be void *.
10831 	 */
10832 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10833 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10834 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10835 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10836 		return -EINVAL;
10837 	}
10838 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10839 }
10840 
10841 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10842 					struct bpf_reg_state *reg,
10843 					const struct btf_type *ref_t,
10844 					const char *ref_tname, u32 ref_id,
10845 					struct bpf_kfunc_call_arg_meta *meta,
10846 					int argno)
10847 {
10848 	const struct btf_type *reg_ref_t;
10849 	bool strict_type_match = false;
10850 	const struct btf *reg_btf;
10851 	const char *reg_ref_tname;
10852 	u32 reg_ref_id;
10853 
10854 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
10855 		reg_btf = reg->btf;
10856 		reg_ref_id = reg->btf_id;
10857 	} else {
10858 		reg_btf = btf_vmlinux;
10859 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10860 	}
10861 
10862 	/* Enforce strict type matching for calls to kfuncs that are acquiring
10863 	 * or releasing a reference, or are no-cast aliases. We do _not_
10864 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10865 	 * as we want to enable BPF programs to pass types that are bitwise
10866 	 * equivalent without forcing them to explicitly cast with something
10867 	 * like bpf_cast_to_kern_ctx().
10868 	 *
10869 	 * For example, say we had a type like the following:
10870 	 *
10871 	 * struct bpf_cpumask {
10872 	 *	cpumask_t cpumask;
10873 	 *	refcount_t usage;
10874 	 * };
10875 	 *
10876 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10877 	 * to a struct cpumask, so it would be safe to pass a struct
10878 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10879 	 *
10880 	 * The philosophy here is similar to how we allow scalars of different
10881 	 * types to be passed to kfuncs as long as the size is the same. The
10882 	 * only difference here is that we're simply allowing
10883 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10884 	 * resolve types.
10885 	 */
10886 	if (is_kfunc_acquire(meta) ||
10887 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
10888 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10889 		strict_type_match = true;
10890 
10891 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10892 
10893 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10894 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10895 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10896 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10897 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10898 			btf_type_str(reg_ref_t), reg_ref_tname);
10899 		return -EINVAL;
10900 	}
10901 	return 0;
10902 }
10903 
10904 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10905 {
10906 	struct bpf_verifier_state *state = env->cur_state;
10907 	struct btf_record *rec = reg_btf_record(reg);
10908 
10909 	if (!state->active_lock.ptr) {
10910 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10911 		return -EFAULT;
10912 	}
10913 
10914 	if (type_flag(reg->type) & NON_OWN_REF) {
10915 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10916 		return -EFAULT;
10917 	}
10918 
10919 	reg->type |= NON_OWN_REF;
10920 	if (rec->refcount_off >= 0)
10921 		reg->type |= MEM_RCU;
10922 
10923 	return 0;
10924 }
10925 
10926 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10927 {
10928 	struct bpf_func_state *state, *unused;
10929 	struct bpf_reg_state *reg;
10930 	int i;
10931 
10932 	state = cur_func(env);
10933 
10934 	if (!ref_obj_id) {
10935 		verbose(env, "verifier internal error: ref_obj_id is zero for "
10936 			     "owning -> non-owning conversion\n");
10937 		return -EFAULT;
10938 	}
10939 
10940 	for (i = 0; i < state->acquired_refs; i++) {
10941 		if (state->refs[i].id != ref_obj_id)
10942 			continue;
10943 
10944 		/* Clear ref_obj_id here so release_reference doesn't clobber
10945 		 * the whole reg
10946 		 */
10947 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10948 			if (reg->ref_obj_id == ref_obj_id) {
10949 				reg->ref_obj_id = 0;
10950 				ref_set_non_owning(env, reg);
10951 			}
10952 		}));
10953 		return 0;
10954 	}
10955 
10956 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10957 	return -EFAULT;
10958 }
10959 
10960 /* Implementation details:
10961  *
10962  * Each register points to some region of memory, which we define as an
10963  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10964  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10965  * allocation. The lock and the data it protects are colocated in the same
10966  * memory region.
10967  *
10968  * Hence, everytime a register holds a pointer value pointing to such
10969  * allocation, the verifier preserves a unique reg->id for it.
10970  *
10971  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10972  * bpf_spin_lock is called.
10973  *
10974  * To enable this, lock state in the verifier captures two values:
10975  *	active_lock.ptr = Register's type specific pointer
10976  *	active_lock.id  = A unique ID for each register pointer value
10977  *
10978  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10979  * supported register types.
10980  *
10981  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10982  * allocated objects is the reg->btf pointer.
10983  *
10984  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10985  * can establish the provenance of the map value statically for each distinct
10986  * lookup into such maps. They always contain a single map value hence unique
10987  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10988  *
10989  * So, in case of global variables, they use array maps with max_entries = 1,
10990  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10991  * into the same map value as max_entries is 1, as described above).
10992  *
10993  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10994  * outer map pointer (in verifier context), but each lookup into an inner map
10995  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10996  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10997  * will get different reg->id assigned to each lookup, hence different
10998  * active_lock.id.
10999  *
11000  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11001  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11002  * returned from bpf_obj_new. Each allocation receives a new reg->id.
11003  */
11004 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11005 {
11006 	void *ptr;
11007 	u32 id;
11008 
11009 	switch ((int)reg->type) {
11010 	case PTR_TO_MAP_VALUE:
11011 		ptr = reg->map_ptr;
11012 		break;
11013 	case PTR_TO_BTF_ID | MEM_ALLOC:
11014 		ptr = reg->btf;
11015 		break;
11016 	default:
11017 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11018 		return -EFAULT;
11019 	}
11020 	id = reg->id;
11021 
11022 	if (!env->cur_state->active_lock.ptr)
11023 		return -EINVAL;
11024 	if (env->cur_state->active_lock.ptr != ptr ||
11025 	    env->cur_state->active_lock.id != id) {
11026 		verbose(env, "held lock and object are not in the same allocation\n");
11027 		return -EINVAL;
11028 	}
11029 	return 0;
11030 }
11031 
11032 static bool is_bpf_list_api_kfunc(u32 btf_id)
11033 {
11034 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11035 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11036 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11037 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11038 }
11039 
11040 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11041 {
11042 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11043 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11044 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11045 }
11046 
11047 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11048 {
11049 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11050 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11051 }
11052 
11053 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11054 {
11055 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11056 }
11057 
11058 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11059 {
11060 	return is_bpf_rbtree_api_kfunc(btf_id);
11061 }
11062 
11063 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11064 					  enum btf_field_type head_field_type,
11065 					  u32 kfunc_btf_id)
11066 {
11067 	bool ret;
11068 
11069 	switch (head_field_type) {
11070 	case BPF_LIST_HEAD:
11071 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11072 		break;
11073 	case BPF_RB_ROOT:
11074 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11075 		break;
11076 	default:
11077 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11078 			btf_field_type_name(head_field_type));
11079 		return false;
11080 	}
11081 
11082 	if (!ret)
11083 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11084 			btf_field_type_name(head_field_type));
11085 	return ret;
11086 }
11087 
11088 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11089 					  enum btf_field_type node_field_type,
11090 					  u32 kfunc_btf_id)
11091 {
11092 	bool ret;
11093 
11094 	switch (node_field_type) {
11095 	case BPF_LIST_NODE:
11096 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11097 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11098 		break;
11099 	case BPF_RB_NODE:
11100 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11101 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11102 		break;
11103 	default:
11104 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11105 			btf_field_type_name(node_field_type));
11106 		return false;
11107 	}
11108 
11109 	if (!ret)
11110 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11111 			btf_field_type_name(node_field_type));
11112 	return ret;
11113 }
11114 
11115 static int
11116 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11117 				   struct bpf_reg_state *reg, u32 regno,
11118 				   struct bpf_kfunc_call_arg_meta *meta,
11119 				   enum btf_field_type head_field_type,
11120 				   struct btf_field **head_field)
11121 {
11122 	const char *head_type_name;
11123 	struct btf_field *field;
11124 	struct btf_record *rec;
11125 	u32 head_off;
11126 
11127 	if (meta->btf != btf_vmlinux) {
11128 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11129 		return -EFAULT;
11130 	}
11131 
11132 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11133 		return -EFAULT;
11134 
11135 	head_type_name = btf_field_type_name(head_field_type);
11136 	if (!tnum_is_const(reg->var_off)) {
11137 		verbose(env,
11138 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11139 			regno, head_type_name);
11140 		return -EINVAL;
11141 	}
11142 
11143 	rec = reg_btf_record(reg);
11144 	head_off = reg->off + reg->var_off.value;
11145 	field = btf_record_find(rec, head_off, head_field_type);
11146 	if (!field) {
11147 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11148 		return -EINVAL;
11149 	}
11150 
11151 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11152 	if (check_reg_allocation_locked(env, reg)) {
11153 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11154 			rec->spin_lock_off, head_type_name);
11155 		return -EINVAL;
11156 	}
11157 
11158 	if (*head_field) {
11159 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11160 		return -EFAULT;
11161 	}
11162 	*head_field = field;
11163 	return 0;
11164 }
11165 
11166 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11167 					   struct bpf_reg_state *reg, u32 regno,
11168 					   struct bpf_kfunc_call_arg_meta *meta)
11169 {
11170 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11171 							  &meta->arg_list_head.field);
11172 }
11173 
11174 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11175 					     struct bpf_reg_state *reg, u32 regno,
11176 					     struct bpf_kfunc_call_arg_meta *meta)
11177 {
11178 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11179 							  &meta->arg_rbtree_root.field);
11180 }
11181 
11182 static int
11183 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11184 				   struct bpf_reg_state *reg, u32 regno,
11185 				   struct bpf_kfunc_call_arg_meta *meta,
11186 				   enum btf_field_type head_field_type,
11187 				   enum btf_field_type node_field_type,
11188 				   struct btf_field **node_field)
11189 {
11190 	const char *node_type_name;
11191 	const struct btf_type *et, *t;
11192 	struct btf_field *field;
11193 	u32 node_off;
11194 
11195 	if (meta->btf != btf_vmlinux) {
11196 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11197 		return -EFAULT;
11198 	}
11199 
11200 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11201 		return -EFAULT;
11202 
11203 	node_type_name = btf_field_type_name(node_field_type);
11204 	if (!tnum_is_const(reg->var_off)) {
11205 		verbose(env,
11206 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11207 			regno, node_type_name);
11208 		return -EINVAL;
11209 	}
11210 
11211 	node_off = reg->off + reg->var_off.value;
11212 	field = reg_find_field_offset(reg, node_off, node_field_type);
11213 	if (!field || field->offset != node_off) {
11214 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11215 		return -EINVAL;
11216 	}
11217 
11218 	field = *node_field;
11219 
11220 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11221 	t = btf_type_by_id(reg->btf, reg->btf_id);
11222 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11223 				  field->graph_root.value_btf_id, true)) {
11224 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11225 			"in struct %s, but arg is at offset=%d in struct %s\n",
11226 			btf_field_type_name(head_field_type),
11227 			btf_field_type_name(node_field_type),
11228 			field->graph_root.node_offset,
11229 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11230 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11231 		return -EINVAL;
11232 	}
11233 	meta->arg_btf = reg->btf;
11234 	meta->arg_btf_id = reg->btf_id;
11235 
11236 	if (node_off != field->graph_root.node_offset) {
11237 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11238 			node_off, btf_field_type_name(node_field_type),
11239 			field->graph_root.node_offset,
11240 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11241 		return -EINVAL;
11242 	}
11243 
11244 	return 0;
11245 }
11246 
11247 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11248 					   struct bpf_reg_state *reg, u32 regno,
11249 					   struct bpf_kfunc_call_arg_meta *meta)
11250 {
11251 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11252 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11253 						  &meta->arg_list_head.field);
11254 }
11255 
11256 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11257 					     struct bpf_reg_state *reg, u32 regno,
11258 					     struct bpf_kfunc_call_arg_meta *meta)
11259 {
11260 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11261 						  BPF_RB_ROOT, BPF_RB_NODE,
11262 						  &meta->arg_rbtree_root.field);
11263 }
11264 
11265 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11266 			    int insn_idx)
11267 {
11268 	const char *func_name = meta->func_name, *ref_tname;
11269 	const struct btf *btf = meta->btf;
11270 	const struct btf_param *args;
11271 	struct btf_record *rec;
11272 	u32 i, nargs;
11273 	int ret;
11274 
11275 	args = (const struct btf_param *)(meta->func_proto + 1);
11276 	nargs = btf_type_vlen(meta->func_proto);
11277 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11278 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11279 			MAX_BPF_FUNC_REG_ARGS);
11280 		return -EINVAL;
11281 	}
11282 
11283 	/* Check that BTF function arguments match actual types that the
11284 	 * verifier sees.
11285 	 */
11286 	for (i = 0; i < nargs; i++) {
11287 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11288 		const struct btf_type *t, *ref_t, *resolve_ret;
11289 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11290 		u32 regno = i + 1, ref_id, type_size;
11291 		bool is_ret_buf_sz = false;
11292 		int kf_arg_type;
11293 
11294 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11295 
11296 		if (is_kfunc_arg_ignore(btf, &args[i]))
11297 			continue;
11298 
11299 		if (btf_type_is_scalar(t)) {
11300 			if (reg->type != SCALAR_VALUE) {
11301 				verbose(env, "R%d is not a scalar\n", regno);
11302 				return -EINVAL;
11303 			}
11304 
11305 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11306 				if (meta->arg_constant.found) {
11307 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11308 					return -EFAULT;
11309 				}
11310 				if (!tnum_is_const(reg->var_off)) {
11311 					verbose(env, "R%d must be a known constant\n", regno);
11312 					return -EINVAL;
11313 				}
11314 				ret = mark_chain_precision(env, regno);
11315 				if (ret < 0)
11316 					return ret;
11317 				meta->arg_constant.found = true;
11318 				meta->arg_constant.value = reg->var_off.value;
11319 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11320 				meta->r0_rdonly = true;
11321 				is_ret_buf_sz = true;
11322 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11323 				is_ret_buf_sz = true;
11324 			}
11325 
11326 			if (is_ret_buf_sz) {
11327 				if (meta->r0_size) {
11328 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11329 					return -EINVAL;
11330 				}
11331 
11332 				if (!tnum_is_const(reg->var_off)) {
11333 					verbose(env, "R%d is not a const\n", regno);
11334 					return -EINVAL;
11335 				}
11336 
11337 				meta->r0_size = reg->var_off.value;
11338 				ret = mark_chain_precision(env, regno);
11339 				if (ret)
11340 					return ret;
11341 			}
11342 			continue;
11343 		}
11344 
11345 		if (!btf_type_is_ptr(t)) {
11346 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11347 			return -EINVAL;
11348 		}
11349 
11350 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11351 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
11352 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11353 			return -EACCES;
11354 		}
11355 
11356 		if (reg->ref_obj_id) {
11357 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
11358 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11359 					regno, reg->ref_obj_id,
11360 					meta->ref_obj_id);
11361 				return -EFAULT;
11362 			}
11363 			meta->ref_obj_id = reg->ref_obj_id;
11364 			if (is_kfunc_release(meta))
11365 				meta->release_regno = regno;
11366 		}
11367 
11368 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11369 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11370 
11371 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11372 		if (kf_arg_type < 0)
11373 			return kf_arg_type;
11374 
11375 		switch (kf_arg_type) {
11376 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11377 		case KF_ARG_PTR_TO_BTF_ID:
11378 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11379 				break;
11380 
11381 			if (!is_trusted_reg(reg)) {
11382 				if (!is_kfunc_rcu(meta)) {
11383 					verbose(env, "R%d must be referenced or trusted\n", regno);
11384 					return -EINVAL;
11385 				}
11386 				if (!is_rcu_reg(reg)) {
11387 					verbose(env, "R%d must be a rcu pointer\n", regno);
11388 					return -EINVAL;
11389 				}
11390 			}
11391 
11392 			fallthrough;
11393 		case KF_ARG_PTR_TO_CTX:
11394 			/* Trusted arguments have the same offset checks as release arguments */
11395 			arg_type |= OBJ_RELEASE;
11396 			break;
11397 		case KF_ARG_PTR_TO_DYNPTR:
11398 		case KF_ARG_PTR_TO_ITER:
11399 		case KF_ARG_PTR_TO_LIST_HEAD:
11400 		case KF_ARG_PTR_TO_LIST_NODE:
11401 		case KF_ARG_PTR_TO_RB_ROOT:
11402 		case KF_ARG_PTR_TO_RB_NODE:
11403 		case KF_ARG_PTR_TO_MEM:
11404 		case KF_ARG_PTR_TO_MEM_SIZE:
11405 		case KF_ARG_PTR_TO_CALLBACK:
11406 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11407 			/* Trusted by default */
11408 			break;
11409 		default:
11410 			WARN_ON_ONCE(1);
11411 			return -EFAULT;
11412 		}
11413 
11414 		if (is_kfunc_release(meta) && reg->ref_obj_id)
11415 			arg_type |= OBJ_RELEASE;
11416 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11417 		if (ret < 0)
11418 			return ret;
11419 
11420 		switch (kf_arg_type) {
11421 		case KF_ARG_PTR_TO_CTX:
11422 			if (reg->type != PTR_TO_CTX) {
11423 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11424 				return -EINVAL;
11425 			}
11426 
11427 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11428 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11429 				if (ret < 0)
11430 					return -EINVAL;
11431 				meta->ret_btf_id  = ret;
11432 			}
11433 			break;
11434 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11435 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11436 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11437 				return -EINVAL;
11438 			}
11439 			if (!reg->ref_obj_id) {
11440 				verbose(env, "allocated object must be referenced\n");
11441 				return -EINVAL;
11442 			}
11443 			if (meta->btf == btf_vmlinux &&
11444 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11445 				meta->arg_btf = reg->btf;
11446 				meta->arg_btf_id = reg->btf_id;
11447 			}
11448 			break;
11449 		case KF_ARG_PTR_TO_DYNPTR:
11450 		{
11451 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11452 			int clone_ref_obj_id = 0;
11453 
11454 			if (reg->type != PTR_TO_STACK &&
11455 			    reg->type != CONST_PTR_TO_DYNPTR) {
11456 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11457 				return -EINVAL;
11458 			}
11459 
11460 			if (reg->type == CONST_PTR_TO_DYNPTR)
11461 				dynptr_arg_type |= MEM_RDONLY;
11462 
11463 			if (is_kfunc_arg_uninit(btf, &args[i]))
11464 				dynptr_arg_type |= MEM_UNINIT;
11465 
11466 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11467 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11468 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11469 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
11470 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11471 				   (dynptr_arg_type & MEM_UNINIT)) {
11472 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11473 
11474 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11475 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11476 					return -EFAULT;
11477 				}
11478 
11479 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11480 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11481 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11482 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11483 					return -EFAULT;
11484 				}
11485 			}
11486 
11487 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11488 			if (ret < 0)
11489 				return ret;
11490 
11491 			if (!(dynptr_arg_type & MEM_UNINIT)) {
11492 				int id = dynptr_id(env, reg);
11493 
11494 				if (id < 0) {
11495 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11496 					return id;
11497 				}
11498 				meta->initialized_dynptr.id = id;
11499 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11500 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11501 			}
11502 
11503 			break;
11504 		}
11505 		case KF_ARG_PTR_TO_ITER:
11506 			ret = process_iter_arg(env, regno, insn_idx, meta);
11507 			if (ret < 0)
11508 				return ret;
11509 			break;
11510 		case KF_ARG_PTR_TO_LIST_HEAD:
11511 			if (reg->type != PTR_TO_MAP_VALUE &&
11512 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11513 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11514 				return -EINVAL;
11515 			}
11516 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11517 				verbose(env, "allocated object must be referenced\n");
11518 				return -EINVAL;
11519 			}
11520 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11521 			if (ret < 0)
11522 				return ret;
11523 			break;
11524 		case KF_ARG_PTR_TO_RB_ROOT:
11525 			if (reg->type != PTR_TO_MAP_VALUE &&
11526 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11527 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11528 				return -EINVAL;
11529 			}
11530 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11531 				verbose(env, "allocated object must be referenced\n");
11532 				return -EINVAL;
11533 			}
11534 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11535 			if (ret < 0)
11536 				return ret;
11537 			break;
11538 		case KF_ARG_PTR_TO_LIST_NODE:
11539 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11540 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11541 				return -EINVAL;
11542 			}
11543 			if (!reg->ref_obj_id) {
11544 				verbose(env, "allocated object must be referenced\n");
11545 				return -EINVAL;
11546 			}
11547 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11548 			if (ret < 0)
11549 				return ret;
11550 			break;
11551 		case KF_ARG_PTR_TO_RB_NODE:
11552 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11553 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11554 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
11555 					return -EINVAL;
11556 				}
11557 				if (in_rbtree_lock_required_cb(env)) {
11558 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11559 					return -EINVAL;
11560 				}
11561 			} else {
11562 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11563 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
11564 					return -EINVAL;
11565 				}
11566 				if (!reg->ref_obj_id) {
11567 					verbose(env, "allocated object must be referenced\n");
11568 					return -EINVAL;
11569 				}
11570 			}
11571 
11572 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11573 			if (ret < 0)
11574 				return ret;
11575 			break;
11576 		case KF_ARG_PTR_TO_BTF_ID:
11577 			/* Only base_type is checked, further checks are done here */
11578 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11579 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11580 			    !reg2btf_ids[base_type(reg->type)]) {
11581 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11582 				verbose(env, "expected %s or socket\n",
11583 					reg_type_str(env, base_type(reg->type) |
11584 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11585 				return -EINVAL;
11586 			}
11587 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11588 			if (ret < 0)
11589 				return ret;
11590 			break;
11591 		case KF_ARG_PTR_TO_MEM:
11592 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11593 			if (IS_ERR(resolve_ret)) {
11594 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11595 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11596 				return -EINVAL;
11597 			}
11598 			ret = check_mem_reg(env, reg, regno, type_size);
11599 			if (ret < 0)
11600 				return ret;
11601 			break;
11602 		case KF_ARG_PTR_TO_MEM_SIZE:
11603 		{
11604 			struct bpf_reg_state *buff_reg = &regs[regno];
11605 			const struct btf_param *buff_arg = &args[i];
11606 			struct bpf_reg_state *size_reg = &regs[regno + 1];
11607 			const struct btf_param *size_arg = &args[i + 1];
11608 
11609 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11610 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11611 				if (ret < 0) {
11612 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11613 					return ret;
11614 				}
11615 			}
11616 
11617 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11618 				if (meta->arg_constant.found) {
11619 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11620 					return -EFAULT;
11621 				}
11622 				if (!tnum_is_const(size_reg->var_off)) {
11623 					verbose(env, "R%d must be a known constant\n", regno + 1);
11624 					return -EINVAL;
11625 				}
11626 				meta->arg_constant.found = true;
11627 				meta->arg_constant.value = size_reg->var_off.value;
11628 			}
11629 
11630 			/* Skip next '__sz' or '__szk' argument */
11631 			i++;
11632 			break;
11633 		}
11634 		case KF_ARG_PTR_TO_CALLBACK:
11635 			if (reg->type != PTR_TO_FUNC) {
11636 				verbose(env, "arg%d expected pointer to func\n", i);
11637 				return -EINVAL;
11638 			}
11639 			meta->subprogno = reg->subprogno;
11640 			break;
11641 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11642 			if (!type_is_ptr_alloc_obj(reg->type)) {
11643 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11644 				return -EINVAL;
11645 			}
11646 			if (!type_is_non_owning_ref(reg->type))
11647 				meta->arg_owning_ref = true;
11648 
11649 			rec = reg_btf_record(reg);
11650 			if (!rec) {
11651 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
11652 				return -EFAULT;
11653 			}
11654 
11655 			if (rec->refcount_off < 0) {
11656 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11657 				return -EINVAL;
11658 			}
11659 
11660 			meta->arg_btf = reg->btf;
11661 			meta->arg_btf_id = reg->btf_id;
11662 			break;
11663 		}
11664 	}
11665 
11666 	if (is_kfunc_release(meta) && !meta->release_regno) {
11667 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11668 			func_name);
11669 		return -EINVAL;
11670 	}
11671 
11672 	return 0;
11673 }
11674 
11675 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11676 			    struct bpf_insn *insn,
11677 			    struct bpf_kfunc_call_arg_meta *meta,
11678 			    const char **kfunc_name)
11679 {
11680 	const struct btf_type *func, *func_proto;
11681 	u32 func_id, *kfunc_flags;
11682 	const char *func_name;
11683 	struct btf *desc_btf;
11684 
11685 	if (kfunc_name)
11686 		*kfunc_name = NULL;
11687 
11688 	if (!insn->imm)
11689 		return -EINVAL;
11690 
11691 	desc_btf = find_kfunc_desc_btf(env, insn->off);
11692 	if (IS_ERR(desc_btf))
11693 		return PTR_ERR(desc_btf);
11694 
11695 	func_id = insn->imm;
11696 	func = btf_type_by_id(desc_btf, func_id);
11697 	func_name = btf_name_by_offset(desc_btf, func->name_off);
11698 	if (kfunc_name)
11699 		*kfunc_name = func_name;
11700 	func_proto = btf_type_by_id(desc_btf, func->type);
11701 
11702 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11703 	if (!kfunc_flags) {
11704 		return -EACCES;
11705 	}
11706 
11707 	memset(meta, 0, sizeof(*meta));
11708 	meta->btf = desc_btf;
11709 	meta->func_id = func_id;
11710 	meta->kfunc_flags = *kfunc_flags;
11711 	meta->func_proto = func_proto;
11712 	meta->func_name = func_name;
11713 
11714 	return 0;
11715 }
11716 
11717 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11718 			    int *insn_idx_p)
11719 {
11720 	const struct btf_type *t, *ptr_type;
11721 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
11722 	struct bpf_reg_state *regs = cur_regs(env);
11723 	const char *func_name, *ptr_type_name;
11724 	bool sleepable, rcu_lock, rcu_unlock;
11725 	struct bpf_kfunc_call_arg_meta meta;
11726 	struct bpf_insn_aux_data *insn_aux;
11727 	int err, insn_idx = *insn_idx_p;
11728 	const struct btf_param *args;
11729 	const struct btf_type *ret_t;
11730 	struct btf *desc_btf;
11731 
11732 	/* skip for now, but return error when we find this in fixup_kfunc_call */
11733 	if (!insn->imm)
11734 		return 0;
11735 
11736 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11737 	if (err == -EACCES && func_name)
11738 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
11739 	if (err)
11740 		return err;
11741 	desc_btf = meta.btf;
11742 	insn_aux = &env->insn_aux_data[insn_idx];
11743 
11744 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11745 
11746 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11747 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11748 		return -EACCES;
11749 	}
11750 
11751 	sleepable = is_kfunc_sleepable(&meta);
11752 	if (sleepable && !env->prog->aux->sleepable) {
11753 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11754 		return -EACCES;
11755 	}
11756 
11757 	/* Check the arguments */
11758 	err = check_kfunc_args(env, &meta, insn_idx);
11759 	if (err < 0)
11760 		return err;
11761 
11762 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11763 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11764 					 set_rbtree_add_callback_state);
11765 		if (err) {
11766 			verbose(env, "kfunc %s#%d failed callback verification\n",
11767 				func_name, meta.func_id);
11768 			return err;
11769 		}
11770 	}
11771 
11772 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11773 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11774 
11775 	if (env->cur_state->active_rcu_lock) {
11776 		struct bpf_func_state *state;
11777 		struct bpf_reg_state *reg;
11778 
11779 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11780 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11781 			return -EACCES;
11782 		}
11783 
11784 		if (rcu_lock) {
11785 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11786 			return -EINVAL;
11787 		} else if (rcu_unlock) {
11788 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11789 				if (reg->type & MEM_RCU) {
11790 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11791 					reg->type |= PTR_UNTRUSTED;
11792 				}
11793 			}));
11794 			env->cur_state->active_rcu_lock = false;
11795 		} else if (sleepable) {
11796 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11797 			return -EACCES;
11798 		}
11799 	} else if (rcu_lock) {
11800 		env->cur_state->active_rcu_lock = true;
11801 	} else if (rcu_unlock) {
11802 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11803 		return -EINVAL;
11804 	}
11805 
11806 	/* In case of release function, we get register number of refcounted
11807 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11808 	 */
11809 	if (meta.release_regno) {
11810 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11811 		if (err) {
11812 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11813 				func_name, meta.func_id);
11814 			return err;
11815 		}
11816 	}
11817 
11818 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11819 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11820 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11821 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11822 		insn_aux->insert_off = regs[BPF_REG_2].off;
11823 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11824 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11825 		if (err) {
11826 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11827 				func_name, meta.func_id);
11828 			return err;
11829 		}
11830 
11831 		err = release_reference(env, release_ref_obj_id);
11832 		if (err) {
11833 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11834 				func_name, meta.func_id);
11835 			return err;
11836 		}
11837 	}
11838 
11839 	for (i = 0; i < CALLER_SAVED_REGS; i++)
11840 		mark_reg_not_init(env, regs, caller_saved[i]);
11841 
11842 	/* Check return type */
11843 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11844 
11845 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11846 		/* Only exception is bpf_obj_new_impl */
11847 		if (meta.btf != btf_vmlinux ||
11848 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11849 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11850 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11851 			return -EINVAL;
11852 		}
11853 	}
11854 
11855 	if (btf_type_is_scalar(t)) {
11856 		mark_reg_unknown(env, regs, BPF_REG_0);
11857 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11858 	} else if (btf_type_is_ptr(t)) {
11859 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11860 
11861 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11862 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11863 				struct btf *ret_btf;
11864 				u32 ret_btf_id;
11865 
11866 				if (unlikely(!bpf_global_ma_set))
11867 					return -ENOMEM;
11868 
11869 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11870 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11871 					return -EINVAL;
11872 				}
11873 
11874 				ret_btf = env->prog->aux->btf;
11875 				ret_btf_id = meta.arg_constant.value;
11876 
11877 				/* This may be NULL due to user not supplying a BTF */
11878 				if (!ret_btf) {
11879 					verbose(env, "bpf_obj_new requires prog BTF\n");
11880 					return -EINVAL;
11881 				}
11882 
11883 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11884 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
11885 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11886 					return -EINVAL;
11887 				}
11888 
11889 				mark_reg_known_zero(env, regs, BPF_REG_0);
11890 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11891 				regs[BPF_REG_0].btf = ret_btf;
11892 				regs[BPF_REG_0].btf_id = ret_btf_id;
11893 
11894 				insn_aux->obj_new_size = ret_t->size;
11895 				insn_aux->kptr_struct_meta =
11896 					btf_find_struct_meta(ret_btf, ret_btf_id);
11897 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11898 				mark_reg_known_zero(env, regs, BPF_REG_0);
11899 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11900 				regs[BPF_REG_0].btf = meta.arg_btf;
11901 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11902 
11903 				insn_aux->kptr_struct_meta =
11904 					btf_find_struct_meta(meta.arg_btf,
11905 							     meta.arg_btf_id);
11906 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11907 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11908 				struct btf_field *field = meta.arg_list_head.field;
11909 
11910 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11911 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11912 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11913 				struct btf_field *field = meta.arg_rbtree_root.field;
11914 
11915 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11916 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11917 				mark_reg_known_zero(env, regs, BPF_REG_0);
11918 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11919 				regs[BPF_REG_0].btf = desc_btf;
11920 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11921 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11922 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11923 				if (!ret_t || !btf_type_is_struct(ret_t)) {
11924 					verbose(env,
11925 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11926 					return -EINVAL;
11927 				}
11928 
11929 				mark_reg_known_zero(env, regs, BPF_REG_0);
11930 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11931 				regs[BPF_REG_0].btf = desc_btf;
11932 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11933 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11934 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11935 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11936 
11937 				mark_reg_known_zero(env, regs, BPF_REG_0);
11938 
11939 				if (!meta.arg_constant.found) {
11940 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11941 					return -EFAULT;
11942 				}
11943 
11944 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11945 
11946 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11947 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11948 
11949 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11950 					regs[BPF_REG_0].type |= MEM_RDONLY;
11951 				} else {
11952 					/* this will set env->seen_direct_write to true */
11953 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11954 						verbose(env, "the prog does not allow writes to packet data\n");
11955 						return -EINVAL;
11956 					}
11957 				}
11958 
11959 				if (!meta.initialized_dynptr.id) {
11960 					verbose(env, "verifier internal error: no dynptr id\n");
11961 					return -EFAULT;
11962 				}
11963 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11964 
11965 				/* we don't need to set BPF_REG_0's ref obj id
11966 				 * because packet slices are not refcounted (see
11967 				 * dynptr_type_refcounted)
11968 				 */
11969 			} else {
11970 				verbose(env, "kernel function %s unhandled dynamic return type\n",
11971 					meta.func_name);
11972 				return -EFAULT;
11973 			}
11974 		} else if (!__btf_type_is_struct(ptr_type)) {
11975 			if (!meta.r0_size) {
11976 				__u32 sz;
11977 
11978 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11979 					meta.r0_size = sz;
11980 					meta.r0_rdonly = true;
11981 				}
11982 			}
11983 			if (!meta.r0_size) {
11984 				ptr_type_name = btf_name_by_offset(desc_btf,
11985 								   ptr_type->name_off);
11986 				verbose(env,
11987 					"kernel function %s returns pointer type %s %s is not supported\n",
11988 					func_name,
11989 					btf_type_str(ptr_type),
11990 					ptr_type_name);
11991 				return -EINVAL;
11992 			}
11993 
11994 			mark_reg_known_zero(env, regs, BPF_REG_0);
11995 			regs[BPF_REG_0].type = PTR_TO_MEM;
11996 			regs[BPF_REG_0].mem_size = meta.r0_size;
11997 
11998 			if (meta.r0_rdonly)
11999 				regs[BPF_REG_0].type |= MEM_RDONLY;
12000 
12001 			/* Ensures we don't access the memory after a release_reference() */
12002 			if (meta.ref_obj_id)
12003 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12004 		} else {
12005 			mark_reg_known_zero(env, regs, BPF_REG_0);
12006 			regs[BPF_REG_0].btf = desc_btf;
12007 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12008 			regs[BPF_REG_0].btf_id = ptr_type_id;
12009 
12010 			if (is_iter_next_kfunc(&meta)) {
12011 				struct bpf_reg_state *cur_iter;
12012 
12013 				cur_iter = get_iter_from_state(env->cur_state, &meta);
12014 
12015 				if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
12016 					regs[BPF_REG_0].type |= MEM_RCU;
12017 				else
12018 					regs[BPF_REG_0].type |= PTR_TRUSTED;
12019 			}
12020 		}
12021 
12022 		if (is_kfunc_ret_null(&meta)) {
12023 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12024 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12025 			regs[BPF_REG_0].id = ++env->id_gen;
12026 		}
12027 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12028 		if (is_kfunc_acquire(&meta)) {
12029 			int id = acquire_reference_state(env, insn_idx);
12030 
12031 			if (id < 0)
12032 				return id;
12033 			if (is_kfunc_ret_null(&meta))
12034 				regs[BPF_REG_0].id = id;
12035 			regs[BPF_REG_0].ref_obj_id = id;
12036 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12037 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12038 		}
12039 
12040 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12041 			regs[BPF_REG_0].id = ++env->id_gen;
12042 	} else if (btf_type_is_void(t)) {
12043 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12044 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
12045 				insn_aux->kptr_struct_meta =
12046 					btf_find_struct_meta(meta.arg_btf,
12047 							     meta.arg_btf_id);
12048 			}
12049 		}
12050 	}
12051 
12052 	nargs = btf_type_vlen(meta.func_proto);
12053 	args = (const struct btf_param *)(meta.func_proto + 1);
12054 	for (i = 0; i < nargs; i++) {
12055 		u32 regno = i + 1;
12056 
12057 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12058 		if (btf_type_is_ptr(t))
12059 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12060 		else
12061 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12062 			mark_btf_func_reg_size(env, regno, t->size);
12063 	}
12064 
12065 	if (is_iter_next_kfunc(&meta)) {
12066 		err = process_iter_next_call(env, insn_idx, &meta);
12067 		if (err)
12068 			return err;
12069 	}
12070 
12071 	return 0;
12072 }
12073 
12074 static bool signed_add_overflows(s64 a, s64 b)
12075 {
12076 	/* Do the add in u64, where overflow is well-defined */
12077 	s64 res = (s64)((u64)a + (u64)b);
12078 
12079 	if (b < 0)
12080 		return res > a;
12081 	return res < a;
12082 }
12083 
12084 static bool signed_add32_overflows(s32 a, s32 b)
12085 {
12086 	/* Do the add in u32, where overflow is well-defined */
12087 	s32 res = (s32)((u32)a + (u32)b);
12088 
12089 	if (b < 0)
12090 		return res > a;
12091 	return res < a;
12092 }
12093 
12094 static bool signed_sub_overflows(s64 a, s64 b)
12095 {
12096 	/* Do the sub in u64, where overflow is well-defined */
12097 	s64 res = (s64)((u64)a - (u64)b);
12098 
12099 	if (b < 0)
12100 		return res < a;
12101 	return res > a;
12102 }
12103 
12104 static bool signed_sub32_overflows(s32 a, s32 b)
12105 {
12106 	/* Do the sub in u32, where overflow is well-defined */
12107 	s32 res = (s32)((u32)a - (u32)b);
12108 
12109 	if (b < 0)
12110 		return res < a;
12111 	return res > a;
12112 }
12113 
12114 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12115 				  const struct bpf_reg_state *reg,
12116 				  enum bpf_reg_type type)
12117 {
12118 	bool known = tnum_is_const(reg->var_off);
12119 	s64 val = reg->var_off.value;
12120 	s64 smin = reg->smin_value;
12121 
12122 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12123 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12124 			reg_type_str(env, type), val);
12125 		return false;
12126 	}
12127 
12128 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12129 		verbose(env, "%s pointer offset %d is not allowed\n",
12130 			reg_type_str(env, type), reg->off);
12131 		return false;
12132 	}
12133 
12134 	if (smin == S64_MIN) {
12135 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12136 			reg_type_str(env, type));
12137 		return false;
12138 	}
12139 
12140 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12141 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12142 			smin, reg_type_str(env, type));
12143 		return false;
12144 	}
12145 
12146 	return true;
12147 }
12148 
12149 enum {
12150 	REASON_BOUNDS	= -1,
12151 	REASON_TYPE	= -2,
12152 	REASON_PATHS	= -3,
12153 	REASON_LIMIT	= -4,
12154 	REASON_STACK	= -5,
12155 };
12156 
12157 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12158 			      u32 *alu_limit, bool mask_to_left)
12159 {
12160 	u32 max = 0, ptr_limit = 0;
12161 
12162 	switch (ptr_reg->type) {
12163 	case PTR_TO_STACK:
12164 		/* Offset 0 is out-of-bounds, but acceptable start for the
12165 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12166 		 * offset where we would need to deal with min/max bounds is
12167 		 * currently prohibited for unprivileged.
12168 		 */
12169 		max = MAX_BPF_STACK + mask_to_left;
12170 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12171 		break;
12172 	case PTR_TO_MAP_VALUE:
12173 		max = ptr_reg->map_ptr->value_size;
12174 		ptr_limit = (mask_to_left ?
12175 			     ptr_reg->smin_value :
12176 			     ptr_reg->umax_value) + ptr_reg->off;
12177 		break;
12178 	default:
12179 		return REASON_TYPE;
12180 	}
12181 
12182 	if (ptr_limit >= max)
12183 		return REASON_LIMIT;
12184 	*alu_limit = ptr_limit;
12185 	return 0;
12186 }
12187 
12188 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12189 				    const struct bpf_insn *insn)
12190 {
12191 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12192 }
12193 
12194 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12195 				       u32 alu_state, u32 alu_limit)
12196 {
12197 	/* If we arrived here from different branches with different
12198 	 * state or limits to sanitize, then this won't work.
12199 	 */
12200 	if (aux->alu_state &&
12201 	    (aux->alu_state != alu_state ||
12202 	     aux->alu_limit != alu_limit))
12203 		return REASON_PATHS;
12204 
12205 	/* Corresponding fixup done in do_misc_fixups(). */
12206 	aux->alu_state = alu_state;
12207 	aux->alu_limit = alu_limit;
12208 	return 0;
12209 }
12210 
12211 static int sanitize_val_alu(struct bpf_verifier_env *env,
12212 			    struct bpf_insn *insn)
12213 {
12214 	struct bpf_insn_aux_data *aux = cur_aux(env);
12215 
12216 	if (can_skip_alu_sanitation(env, insn))
12217 		return 0;
12218 
12219 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12220 }
12221 
12222 static bool sanitize_needed(u8 opcode)
12223 {
12224 	return opcode == BPF_ADD || opcode == BPF_SUB;
12225 }
12226 
12227 struct bpf_sanitize_info {
12228 	struct bpf_insn_aux_data aux;
12229 	bool mask_to_left;
12230 };
12231 
12232 static struct bpf_verifier_state *
12233 sanitize_speculative_path(struct bpf_verifier_env *env,
12234 			  const struct bpf_insn *insn,
12235 			  u32 next_idx, u32 curr_idx)
12236 {
12237 	struct bpf_verifier_state *branch;
12238 	struct bpf_reg_state *regs;
12239 
12240 	branch = push_stack(env, next_idx, curr_idx, true);
12241 	if (branch && insn) {
12242 		regs = branch->frame[branch->curframe]->regs;
12243 		if (BPF_SRC(insn->code) == BPF_K) {
12244 			mark_reg_unknown(env, regs, insn->dst_reg);
12245 		} else if (BPF_SRC(insn->code) == BPF_X) {
12246 			mark_reg_unknown(env, regs, insn->dst_reg);
12247 			mark_reg_unknown(env, regs, insn->src_reg);
12248 		}
12249 	}
12250 	return branch;
12251 }
12252 
12253 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12254 			    struct bpf_insn *insn,
12255 			    const struct bpf_reg_state *ptr_reg,
12256 			    const struct bpf_reg_state *off_reg,
12257 			    struct bpf_reg_state *dst_reg,
12258 			    struct bpf_sanitize_info *info,
12259 			    const bool commit_window)
12260 {
12261 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12262 	struct bpf_verifier_state *vstate = env->cur_state;
12263 	bool off_is_imm = tnum_is_const(off_reg->var_off);
12264 	bool off_is_neg = off_reg->smin_value < 0;
12265 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12266 	u8 opcode = BPF_OP(insn->code);
12267 	u32 alu_state, alu_limit;
12268 	struct bpf_reg_state tmp;
12269 	bool ret;
12270 	int err;
12271 
12272 	if (can_skip_alu_sanitation(env, insn))
12273 		return 0;
12274 
12275 	/* We already marked aux for masking from non-speculative
12276 	 * paths, thus we got here in the first place. We only care
12277 	 * to explore bad access from here.
12278 	 */
12279 	if (vstate->speculative)
12280 		goto do_sim;
12281 
12282 	if (!commit_window) {
12283 		if (!tnum_is_const(off_reg->var_off) &&
12284 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12285 			return REASON_BOUNDS;
12286 
12287 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12288 				     (opcode == BPF_SUB && !off_is_neg);
12289 	}
12290 
12291 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12292 	if (err < 0)
12293 		return err;
12294 
12295 	if (commit_window) {
12296 		/* In commit phase we narrow the masking window based on
12297 		 * the observed pointer move after the simulated operation.
12298 		 */
12299 		alu_state = info->aux.alu_state;
12300 		alu_limit = abs(info->aux.alu_limit - alu_limit);
12301 	} else {
12302 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12303 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12304 		alu_state |= ptr_is_dst_reg ?
12305 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12306 
12307 		/* Limit pruning on unknown scalars to enable deep search for
12308 		 * potential masking differences from other program paths.
12309 		 */
12310 		if (!off_is_imm)
12311 			env->explore_alu_limits = true;
12312 	}
12313 
12314 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12315 	if (err < 0)
12316 		return err;
12317 do_sim:
12318 	/* If we're in commit phase, we're done here given we already
12319 	 * pushed the truncated dst_reg into the speculative verification
12320 	 * stack.
12321 	 *
12322 	 * Also, when register is a known constant, we rewrite register-based
12323 	 * operation to immediate-based, and thus do not need masking (and as
12324 	 * a consequence, do not need to simulate the zero-truncation either).
12325 	 */
12326 	if (commit_window || off_is_imm)
12327 		return 0;
12328 
12329 	/* Simulate and find potential out-of-bounds access under
12330 	 * speculative execution from truncation as a result of
12331 	 * masking when off was not within expected range. If off
12332 	 * sits in dst, then we temporarily need to move ptr there
12333 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12334 	 * for cases where we use K-based arithmetic in one direction
12335 	 * and truncated reg-based in the other in order to explore
12336 	 * bad access.
12337 	 */
12338 	if (!ptr_is_dst_reg) {
12339 		tmp = *dst_reg;
12340 		copy_register_state(dst_reg, ptr_reg);
12341 	}
12342 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12343 					env->insn_idx);
12344 	if (!ptr_is_dst_reg && ret)
12345 		*dst_reg = tmp;
12346 	return !ret ? REASON_STACK : 0;
12347 }
12348 
12349 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12350 {
12351 	struct bpf_verifier_state *vstate = env->cur_state;
12352 
12353 	/* If we simulate paths under speculation, we don't update the
12354 	 * insn as 'seen' such that when we verify unreachable paths in
12355 	 * the non-speculative domain, sanitize_dead_code() can still
12356 	 * rewrite/sanitize them.
12357 	 */
12358 	if (!vstate->speculative)
12359 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12360 }
12361 
12362 static int sanitize_err(struct bpf_verifier_env *env,
12363 			const struct bpf_insn *insn, int reason,
12364 			const struct bpf_reg_state *off_reg,
12365 			const struct bpf_reg_state *dst_reg)
12366 {
12367 	static const char *err = "pointer arithmetic with it prohibited for !root";
12368 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12369 	u32 dst = insn->dst_reg, src = insn->src_reg;
12370 
12371 	switch (reason) {
12372 	case REASON_BOUNDS:
12373 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12374 			off_reg == dst_reg ? dst : src, err);
12375 		break;
12376 	case REASON_TYPE:
12377 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12378 			off_reg == dst_reg ? src : dst, err);
12379 		break;
12380 	case REASON_PATHS:
12381 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12382 			dst, op, err);
12383 		break;
12384 	case REASON_LIMIT:
12385 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12386 			dst, op, err);
12387 		break;
12388 	case REASON_STACK:
12389 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12390 			dst, err);
12391 		break;
12392 	default:
12393 		verbose(env, "verifier internal error: unknown reason (%d)\n",
12394 			reason);
12395 		break;
12396 	}
12397 
12398 	return -EACCES;
12399 }
12400 
12401 /* check that stack access falls within stack limits and that 'reg' doesn't
12402  * have a variable offset.
12403  *
12404  * Variable offset is prohibited for unprivileged mode for simplicity since it
12405  * requires corresponding support in Spectre masking for stack ALU.  See also
12406  * retrieve_ptr_limit().
12407  *
12408  *
12409  * 'off' includes 'reg->off'.
12410  */
12411 static int check_stack_access_for_ptr_arithmetic(
12412 				struct bpf_verifier_env *env,
12413 				int regno,
12414 				const struct bpf_reg_state *reg,
12415 				int off)
12416 {
12417 	if (!tnum_is_const(reg->var_off)) {
12418 		char tn_buf[48];
12419 
12420 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12421 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12422 			regno, tn_buf, off);
12423 		return -EACCES;
12424 	}
12425 
12426 	if (off >= 0 || off < -MAX_BPF_STACK) {
12427 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
12428 			"prohibited for !root; off=%d\n", regno, off);
12429 		return -EACCES;
12430 	}
12431 
12432 	return 0;
12433 }
12434 
12435 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12436 				 const struct bpf_insn *insn,
12437 				 const struct bpf_reg_state *dst_reg)
12438 {
12439 	u32 dst = insn->dst_reg;
12440 
12441 	/* For unprivileged we require that resulting offset must be in bounds
12442 	 * in order to be able to sanitize access later on.
12443 	 */
12444 	if (env->bypass_spec_v1)
12445 		return 0;
12446 
12447 	switch (dst_reg->type) {
12448 	case PTR_TO_STACK:
12449 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12450 					dst_reg->off + dst_reg->var_off.value))
12451 			return -EACCES;
12452 		break;
12453 	case PTR_TO_MAP_VALUE:
12454 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12455 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12456 				"prohibited for !root\n", dst);
12457 			return -EACCES;
12458 		}
12459 		break;
12460 	default:
12461 		break;
12462 	}
12463 
12464 	return 0;
12465 }
12466 
12467 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12468  * Caller should also handle BPF_MOV case separately.
12469  * If we return -EACCES, caller may want to try again treating pointer as a
12470  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12471  */
12472 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12473 				   struct bpf_insn *insn,
12474 				   const struct bpf_reg_state *ptr_reg,
12475 				   const struct bpf_reg_state *off_reg)
12476 {
12477 	struct bpf_verifier_state *vstate = env->cur_state;
12478 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12479 	struct bpf_reg_state *regs = state->regs, *dst_reg;
12480 	bool known = tnum_is_const(off_reg->var_off);
12481 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12482 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12483 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12484 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12485 	struct bpf_sanitize_info info = {};
12486 	u8 opcode = BPF_OP(insn->code);
12487 	u32 dst = insn->dst_reg;
12488 	int ret;
12489 
12490 	dst_reg = &regs[dst];
12491 
12492 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12493 	    smin_val > smax_val || umin_val > umax_val) {
12494 		/* Taint dst register if offset had invalid bounds derived from
12495 		 * e.g. dead branches.
12496 		 */
12497 		__mark_reg_unknown(env, dst_reg);
12498 		return 0;
12499 	}
12500 
12501 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
12502 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
12503 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12504 			__mark_reg_unknown(env, dst_reg);
12505 			return 0;
12506 		}
12507 
12508 		verbose(env,
12509 			"R%d 32-bit pointer arithmetic prohibited\n",
12510 			dst);
12511 		return -EACCES;
12512 	}
12513 
12514 	if (ptr_reg->type & PTR_MAYBE_NULL) {
12515 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12516 			dst, reg_type_str(env, ptr_reg->type));
12517 		return -EACCES;
12518 	}
12519 
12520 	switch (base_type(ptr_reg->type)) {
12521 	case PTR_TO_FLOW_KEYS:
12522 		if (known)
12523 			break;
12524 		fallthrough;
12525 	case CONST_PTR_TO_MAP:
12526 		/* smin_val represents the known value */
12527 		if (known && smin_val == 0 && opcode == BPF_ADD)
12528 			break;
12529 		fallthrough;
12530 	case PTR_TO_PACKET_END:
12531 	case PTR_TO_SOCKET:
12532 	case PTR_TO_SOCK_COMMON:
12533 	case PTR_TO_TCP_SOCK:
12534 	case PTR_TO_XDP_SOCK:
12535 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12536 			dst, reg_type_str(env, ptr_reg->type));
12537 		return -EACCES;
12538 	default:
12539 		break;
12540 	}
12541 
12542 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12543 	 * The id may be overwritten later if we create a new variable offset.
12544 	 */
12545 	dst_reg->type = ptr_reg->type;
12546 	dst_reg->id = ptr_reg->id;
12547 
12548 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12549 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12550 		return -EINVAL;
12551 
12552 	/* pointer types do not carry 32-bit bounds at the moment. */
12553 	__mark_reg32_unbounded(dst_reg);
12554 
12555 	if (sanitize_needed(opcode)) {
12556 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12557 				       &info, false);
12558 		if (ret < 0)
12559 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12560 	}
12561 
12562 	switch (opcode) {
12563 	case BPF_ADD:
12564 		/* We can take a fixed offset as long as it doesn't overflow
12565 		 * the s32 'off' field
12566 		 */
12567 		if (known && (ptr_reg->off + smin_val ==
12568 			      (s64)(s32)(ptr_reg->off + smin_val))) {
12569 			/* pointer += K.  Accumulate it into fixed offset */
12570 			dst_reg->smin_value = smin_ptr;
12571 			dst_reg->smax_value = smax_ptr;
12572 			dst_reg->umin_value = umin_ptr;
12573 			dst_reg->umax_value = umax_ptr;
12574 			dst_reg->var_off = ptr_reg->var_off;
12575 			dst_reg->off = ptr_reg->off + smin_val;
12576 			dst_reg->raw = ptr_reg->raw;
12577 			break;
12578 		}
12579 		/* A new variable offset is created.  Note that off_reg->off
12580 		 * == 0, since it's a scalar.
12581 		 * dst_reg gets the pointer type and since some positive
12582 		 * integer value was added to the pointer, give it a new 'id'
12583 		 * if it's a PTR_TO_PACKET.
12584 		 * this creates a new 'base' pointer, off_reg (variable) gets
12585 		 * added into the variable offset, and we copy the fixed offset
12586 		 * from ptr_reg.
12587 		 */
12588 		if (signed_add_overflows(smin_ptr, smin_val) ||
12589 		    signed_add_overflows(smax_ptr, smax_val)) {
12590 			dst_reg->smin_value = S64_MIN;
12591 			dst_reg->smax_value = S64_MAX;
12592 		} else {
12593 			dst_reg->smin_value = smin_ptr + smin_val;
12594 			dst_reg->smax_value = smax_ptr + smax_val;
12595 		}
12596 		if (umin_ptr + umin_val < umin_ptr ||
12597 		    umax_ptr + umax_val < umax_ptr) {
12598 			dst_reg->umin_value = 0;
12599 			dst_reg->umax_value = U64_MAX;
12600 		} else {
12601 			dst_reg->umin_value = umin_ptr + umin_val;
12602 			dst_reg->umax_value = umax_ptr + umax_val;
12603 		}
12604 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12605 		dst_reg->off = ptr_reg->off;
12606 		dst_reg->raw = ptr_reg->raw;
12607 		if (reg_is_pkt_pointer(ptr_reg)) {
12608 			dst_reg->id = ++env->id_gen;
12609 			/* something was added to pkt_ptr, set range to zero */
12610 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12611 		}
12612 		break;
12613 	case BPF_SUB:
12614 		if (dst_reg == off_reg) {
12615 			/* scalar -= pointer.  Creates an unknown scalar */
12616 			verbose(env, "R%d tried to subtract pointer from scalar\n",
12617 				dst);
12618 			return -EACCES;
12619 		}
12620 		/* We don't allow subtraction from FP, because (according to
12621 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
12622 		 * be able to deal with it.
12623 		 */
12624 		if (ptr_reg->type == PTR_TO_STACK) {
12625 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
12626 				dst);
12627 			return -EACCES;
12628 		}
12629 		if (known && (ptr_reg->off - smin_val ==
12630 			      (s64)(s32)(ptr_reg->off - smin_val))) {
12631 			/* pointer -= K.  Subtract it from fixed offset */
12632 			dst_reg->smin_value = smin_ptr;
12633 			dst_reg->smax_value = smax_ptr;
12634 			dst_reg->umin_value = umin_ptr;
12635 			dst_reg->umax_value = umax_ptr;
12636 			dst_reg->var_off = ptr_reg->var_off;
12637 			dst_reg->id = ptr_reg->id;
12638 			dst_reg->off = ptr_reg->off - smin_val;
12639 			dst_reg->raw = ptr_reg->raw;
12640 			break;
12641 		}
12642 		/* A new variable offset is created.  If the subtrahend is known
12643 		 * nonnegative, then any reg->range we had before is still good.
12644 		 */
12645 		if (signed_sub_overflows(smin_ptr, smax_val) ||
12646 		    signed_sub_overflows(smax_ptr, smin_val)) {
12647 			/* Overflow possible, we know nothing */
12648 			dst_reg->smin_value = S64_MIN;
12649 			dst_reg->smax_value = S64_MAX;
12650 		} else {
12651 			dst_reg->smin_value = smin_ptr - smax_val;
12652 			dst_reg->smax_value = smax_ptr - smin_val;
12653 		}
12654 		if (umin_ptr < umax_val) {
12655 			/* Overflow possible, we know nothing */
12656 			dst_reg->umin_value = 0;
12657 			dst_reg->umax_value = U64_MAX;
12658 		} else {
12659 			/* Cannot overflow (as long as bounds are consistent) */
12660 			dst_reg->umin_value = umin_ptr - umax_val;
12661 			dst_reg->umax_value = umax_ptr - umin_val;
12662 		}
12663 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12664 		dst_reg->off = ptr_reg->off;
12665 		dst_reg->raw = ptr_reg->raw;
12666 		if (reg_is_pkt_pointer(ptr_reg)) {
12667 			dst_reg->id = ++env->id_gen;
12668 			/* something was added to pkt_ptr, set range to zero */
12669 			if (smin_val < 0)
12670 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12671 		}
12672 		break;
12673 	case BPF_AND:
12674 	case BPF_OR:
12675 	case BPF_XOR:
12676 		/* bitwise ops on pointers are troublesome, prohibit. */
12677 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12678 			dst, bpf_alu_string[opcode >> 4]);
12679 		return -EACCES;
12680 	default:
12681 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
12682 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12683 			dst, bpf_alu_string[opcode >> 4]);
12684 		return -EACCES;
12685 	}
12686 
12687 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12688 		return -EINVAL;
12689 	reg_bounds_sync(dst_reg);
12690 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12691 		return -EACCES;
12692 	if (sanitize_needed(opcode)) {
12693 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12694 				       &info, true);
12695 		if (ret < 0)
12696 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12697 	}
12698 
12699 	return 0;
12700 }
12701 
12702 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12703 				 struct bpf_reg_state *src_reg)
12704 {
12705 	s32 smin_val = src_reg->s32_min_value;
12706 	s32 smax_val = src_reg->s32_max_value;
12707 	u32 umin_val = src_reg->u32_min_value;
12708 	u32 umax_val = src_reg->u32_max_value;
12709 
12710 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12711 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12712 		dst_reg->s32_min_value = S32_MIN;
12713 		dst_reg->s32_max_value = S32_MAX;
12714 	} else {
12715 		dst_reg->s32_min_value += smin_val;
12716 		dst_reg->s32_max_value += smax_val;
12717 	}
12718 	if (dst_reg->u32_min_value + umin_val < umin_val ||
12719 	    dst_reg->u32_max_value + umax_val < umax_val) {
12720 		dst_reg->u32_min_value = 0;
12721 		dst_reg->u32_max_value = U32_MAX;
12722 	} else {
12723 		dst_reg->u32_min_value += umin_val;
12724 		dst_reg->u32_max_value += umax_val;
12725 	}
12726 }
12727 
12728 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12729 			       struct bpf_reg_state *src_reg)
12730 {
12731 	s64 smin_val = src_reg->smin_value;
12732 	s64 smax_val = src_reg->smax_value;
12733 	u64 umin_val = src_reg->umin_value;
12734 	u64 umax_val = src_reg->umax_value;
12735 
12736 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12737 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
12738 		dst_reg->smin_value = S64_MIN;
12739 		dst_reg->smax_value = S64_MAX;
12740 	} else {
12741 		dst_reg->smin_value += smin_val;
12742 		dst_reg->smax_value += smax_val;
12743 	}
12744 	if (dst_reg->umin_value + umin_val < umin_val ||
12745 	    dst_reg->umax_value + umax_val < umax_val) {
12746 		dst_reg->umin_value = 0;
12747 		dst_reg->umax_value = U64_MAX;
12748 	} else {
12749 		dst_reg->umin_value += umin_val;
12750 		dst_reg->umax_value += umax_val;
12751 	}
12752 }
12753 
12754 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12755 				 struct bpf_reg_state *src_reg)
12756 {
12757 	s32 smin_val = src_reg->s32_min_value;
12758 	s32 smax_val = src_reg->s32_max_value;
12759 	u32 umin_val = src_reg->u32_min_value;
12760 	u32 umax_val = src_reg->u32_max_value;
12761 
12762 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12763 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12764 		/* Overflow possible, we know nothing */
12765 		dst_reg->s32_min_value = S32_MIN;
12766 		dst_reg->s32_max_value = S32_MAX;
12767 	} else {
12768 		dst_reg->s32_min_value -= smax_val;
12769 		dst_reg->s32_max_value -= smin_val;
12770 	}
12771 	if (dst_reg->u32_min_value < umax_val) {
12772 		/* Overflow possible, we know nothing */
12773 		dst_reg->u32_min_value = 0;
12774 		dst_reg->u32_max_value = U32_MAX;
12775 	} else {
12776 		/* Cannot overflow (as long as bounds are consistent) */
12777 		dst_reg->u32_min_value -= umax_val;
12778 		dst_reg->u32_max_value -= umin_val;
12779 	}
12780 }
12781 
12782 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12783 			       struct bpf_reg_state *src_reg)
12784 {
12785 	s64 smin_val = src_reg->smin_value;
12786 	s64 smax_val = src_reg->smax_value;
12787 	u64 umin_val = src_reg->umin_value;
12788 	u64 umax_val = src_reg->umax_value;
12789 
12790 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12791 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12792 		/* Overflow possible, we know nothing */
12793 		dst_reg->smin_value = S64_MIN;
12794 		dst_reg->smax_value = S64_MAX;
12795 	} else {
12796 		dst_reg->smin_value -= smax_val;
12797 		dst_reg->smax_value -= smin_val;
12798 	}
12799 	if (dst_reg->umin_value < umax_val) {
12800 		/* Overflow possible, we know nothing */
12801 		dst_reg->umin_value = 0;
12802 		dst_reg->umax_value = U64_MAX;
12803 	} else {
12804 		/* Cannot overflow (as long as bounds are consistent) */
12805 		dst_reg->umin_value -= umax_val;
12806 		dst_reg->umax_value -= umin_val;
12807 	}
12808 }
12809 
12810 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12811 				 struct bpf_reg_state *src_reg)
12812 {
12813 	s32 smin_val = src_reg->s32_min_value;
12814 	u32 umin_val = src_reg->u32_min_value;
12815 	u32 umax_val = src_reg->u32_max_value;
12816 
12817 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12818 		/* Ain't nobody got time to multiply that sign */
12819 		__mark_reg32_unbounded(dst_reg);
12820 		return;
12821 	}
12822 	/* Both values are positive, so we can work with unsigned and
12823 	 * copy the result to signed (unless it exceeds S32_MAX).
12824 	 */
12825 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12826 		/* Potential overflow, we know nothing */
12827 		__mark_reg32_unbounded(dst_reg);
12828 		return;
12829 	}
12830 	dst_reg->u32_min_value *= umin_val;
12831 	dst_reg->u32_max_value *= umax_val;
12832 	if (dst_reg->u32_max_value > S32_MAX) {
12833 		/* Overflow possible, we know nothing */
12834 		dst_reg->s32_min_value = S32_MIN;
12835 		dst_reg->s32_max_value = S32_MAX;
12836 	} else {
12837 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12838 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12839 	}
12840 }
12841 
12842 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12843 			       struct bpf_reg_state *src_reg)
12844 {
12845 	s64 smin_val = src_reg->smin_value;
12846 	u64 umin_val = src_reg->umin_value;
12847 	u64 umax_val = src_reg->umax_value;
12848 
12849 	if (smin_val < 0 || dst_reg->smin_value < 0) {
12850 		/* Ain't nobody got time to multiply that sign */
12851 		__mark_reg64_unbounded(dst_reg);
12852 		return;
12853 	}
12854 	/* Both values are positive, so we can work with unsigned and
12855 	 * copy the result to signed (unless it exceeds S64_MAX).
12856 	 */
12857 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12858 		/* Potential overflow, we know nothing */
12859 		__mark_reg64_unbounded(dst_reg);
12860 		return;
12861 	}
12862 	dst_reg->umin_value *= umin_val;
12863 	dst_reg->umax_value *= umax_val;
12864 	if (dst_reg->umax_value > S64_MAX) {
12865 		/* Overflow possible, we know nothing */
12866 		dst_reg->smin_value = S64_MIN;
12867 		dst_reg->smax_value = S64_MAX;
12868 	} else {
12869 		dst_reg->smin_value = dst_reg->umin_value;
12870 		dst_reg->smax_value = dst_reg->umax_value;
12871 	}
12872 }
12873 
12874 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12875 				 struct bpf_reg_state *src_reg)
12876 {
12877 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12878 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12879 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12880 	s32 smin_val = src_reg->s32_min_value;
12881 	u32 umax_val = src_reg->u32_max_value;
12882 
12883 	if (src_known && dst_known) {
12884 		__mark_reg32_known(dst_reg, var32_off.value);
12885 		return;
12886 	}
12887 
12888 	/* We get our minimum from the var_off, since that's inherently
12889 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12890 	 */
12891 	dst_reg->u32_min_value = var32_off.value;
12892 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12893 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12894 		/* Lose signed bounds when ANDing negative numbers,
12895 		 * ain't nobody got time for that.
12896 		 */
12897 		dst_reg->s32_min_value = S32_MIN;
12898 		dst_reg->s32_max_value = S32_MAX;
12899 	} else {
12900 		/* ANDing two positives gives a positive, so safe to
12901 		 * cast result into s64.
12902 		 */
12903 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12904 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12905 	}
12906 }
12907 
12908 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12909 			       struct bpf_reg_state *src_reg)
12910 {
12911 	bool src_known = tnum_is_const(src_reg->var_off);
12912 	bool dst_known = tnum_is_const(dst_reg->var_off);
12913 	s64 smin_val = src_reg->smin_value;
12914 	u64 umax_val = src_reg->umax_value;
12915 
12916 	if (src_known && dst_known) {
12917 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12918 		return;
12919 	}
12920 
12921 	/* We get our minimum from the var_off, since that's inherently
12922 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12923 	 */
12924 	dst_reg->umin_value = dst_reg->var_off.value;
12925 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12926 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12927 		/* Lose signed bounds when ANDing negative numbers,
12928 		 * ain't nobody got time for that.
12929 		 */
12930 		dst_reg->smin_value = S64_MIN;
12931 		dst_reg->smax_value = S64_MAX;
12932 	} else {
12933 		/* ANDing two positives gives a positive, so safe to
12934 		 * cast result into s64.
12935 		 */
12936 		dst_reg->smin_value = dst_reg->umin_value;
12937 		dst_reg->smax_value = dst_reg->umax_value;
12938 	}
12939 	/* We may learn something more from the var_off */
12940 	__update_reg_bounds(dst_reg);
12941 }
12942 
12943 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12944 				struct bpf_reg_state *src_reg)
12945 {
12946 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12947 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12948 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12949 	s32 smin_val = src_reg->s32_min_value;
12950 	u32 umin_val = src_reg->u32_min_value;
12951 
12952 	if (src_known && dst_known) {
12953 		__mark_reg32_known(dst_reg, var32_off.value);
12954 		return;
12955 	}
12956 
12957 	/* We get our maximum from the var_off, and our minimum is the
12958 	 * maximum of the operands' minima
12959 	 */
12960 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12961 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12962 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12963 		/* Lose signed bounds when ORing negative numbers,
12964 		 * ain't nobody got time for that.
12965 		 */
12966 		dst_reg->s32_min_value = S32_MIN;
12967 		dst_reg->s32_max_value = S32_MAX;
12968 	} else {
12969 		/* ORing two positives gives a positive, so safe to
12970 		 * cast result into s64.
12971 		 */
12972 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12973 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12974 	}
12975 }
12976 
12977 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12978 			      struct bpf_reg_state *src_reg)
12979 {
12980 	bool src_known = tnum_is_const(src_reg->var_off);
12981 	bool dst_known = tnum_is_const(dst_reg->var_off);
12982 	s64 smin_val = src_reg->smin_value;
12983 	u64 umin_val = src_reg->umin_value;
12984 
12985 	if (src_known && dst_known) {
12986 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12987 		return;
12988 	}
12989 
12990 	/* We get our maximum from the var_off, and our minimum is the
12991 	 * maximum of the operands' minima
12992 	 */
12993 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12994 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12995 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12996 		/* Lose signed bounds when ORing negative numbers,
12997 		 * ain't nobody got time for that.
12998 		 */
12999 		dst_reg->smin_value = S64_MIN;
13000 		dst_reg->smax_value = S64_MAX;
13001 	} else {
13002 		/* ORing two positives gives a positive, so safe to
13003 		 * cast result into s64.
13004 		 */
13005 		dst_reg->smin_value = dst_reg->umin_value;
13006 		dst_reg->smax_value = dst_reg->umax_value;
13007 	}
13008 	/* We may learn something more from the var_off */
13009 	__update_reg_bounds(dst_reg);
13010 }
13011 
13012 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13013 				 struct bpf_reg_state *src_reg)
13014 {
13015 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13016 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13017 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13018 	s32 smin_val = src_reg->s32_min_value;
13019 
13020 	if (src_known && dst_known) {
13021 		__mark_reg32_known(dst_reg, var32_off.value);
13022 		return;
13023 	}
13024 
13025 	/* We get both minimum and maximum from the var32_off. */
13026 	dst_reg->u32_min_value = var32_off.value;
13027 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13028 
13029 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13030 		/* XORing two positive sign numbers gives a positive,
13031 		 * so safe to cast u32 result into s32.
13032 		 */
13033 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13034 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13035 	} else {
13036 		dst_reg->s32_min_value = S32_MIN;
13037 		dst_reg->s32_max_value = S32_MAX;
13038 	}
13039 }
13040 
13041 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13042 			       struct bpf_reg_state *src_reg)
13043 {
13044 	bool src_known = tnum_is_const(src_reg->var_off);
13045 	bool dst_known = tnum_is_const(dst_reg->var_off);
13046 	s64 smin_val = src_reg->smin_value;
13047 
13048 	if (src_known && dst_known) {
13049 		/* dst_reg->var_off.value has been updated earlier */
13050 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13051 		return;
13052 	}
13053 
13054 	/* We get both minimum and maximum from the var_off. */
13055 	dst_reg->umin_value = dst_reg->var_off.value;
13056 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13057 
13058 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13059 		/* XORing two positive sign numbers gives a positive,
13060 		 * so safe to cast u64 result into s64.
13061 		 */
13062 		dst_reg->smin_value = dst_reg->umin_value;
13063 		dst_reg->smax_value = dst_reg->umax_value;
13064 	} else {
13065 		dst_reg->smin_value = S64_MIN;
13066 		dst_reg->smax_value = S64_MAX;
13067 	}
13068 
13069 	__update_reg_bounds(dst_reg);
13070 }
13071 
13072 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13073 				   u64 umin_val, u64 umax_val)
13074 {
13075 	/* We lose all sign bit information (except what we can pick
13076 	 * up from var_off)
13077 	 */
13078 	dst_reg->s32_min_value = S32_MIN;
13079 	dst_reg->s32_max_value = S32_MAX;
13080 	/* If we might shift our top bit out, then we know nothing */
13081 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13082 		dst_reg->u32_min_value = 0;
13083 		dst_reg->u32_max_value = U32_MAX;
13084 	} else {
13085 		dst_reg->u32_min_value <<= umin_val;
13086 		dst_reg->u32_max_value <<= umax_val;
13087 	}
13088 }
13089 
13090 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13091 				 struct bpf_reg_state *src_reg)
13092 {
13093 	u32 umax_val = src_reg->u32_max_value;
13094 	u32 umin_val = src_reg->u32_min_value;
13095 	/* u32 alu operation will zext upper bits */
13096 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13097 
13098 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13099 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13100 	/* Not required but being careful mark reg64 bounds as unknown so
13101 	 * that we are forced to pick them up from tnum and zext later and
13102 	 * if some path skips this step we are still safe.
13103 	 */
13104 	__mark_reg64_unbounded(dst_reg);
13105 	__update_reg32_bounds(dst_reg);
13106 }
13107 
13108 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13109 				   u64 umin_val, u64 umax_val)
13110 {
13111 	/* Special case <<32 because it is a common compiler pattern to sign
13112 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13113 	 * positive we know this shift will also be positive so we can track
13114 	 * bounds correctly. Otherwise we lose all sign bit information except
13115 	 * what we can pick up from var_off. Perhaps we can generalize this
13116 	 * later to shifts of any length.
13117 	 */
13118 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13119 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13120 	else
13121 		dst_reg->smax_value = S64_MAX;
13122 
13123 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13124 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13125 	else
13126 		dst_reg->smin_value = S64_MIN;
13127 
13128 	/* If we might shift our top bit out, then we know nothing */
13129 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13130 		dst_reg->umin_value = 0;
13131 		dst_reg->umax_value = U64_MAX;
13132 	} else {
13133 		dst_reg->umin_value <<= umin_val;
13134 		dst_reg->umax_value <<= umax_val;
13135 	}
13136 }
13137 
13138 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13139 			       struct bpf_reg_state *src_reg)
13140 {
13141 	u64 umax_val = src_reg->umax_value;
13142 	u64 umin_val = src_reg->umin_value;
13143 
13144 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13145 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13146 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13147 
13148 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13149 	/* We may learn something more from the var_off */
13150 	__update_reg_bounds(dst_reg);
13151 }
13152 
13153 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13154 				 struct bpf_reg_state *src_reg)
13155 {
13156 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13157 	u32 umax_val = src_reg->u32_max_value;
13158 	u32 umin_val = src_reg->u32_min_value;
13159 
13160 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13161 	 * be negative, then either:
13162 	 * 1) src_reg might be zero, so the sign bit of the result is
13163 	 *    unknown, so we lose our signed bounds
13164 	 * 2) it's known negative, thus the unsigned bounds capture the
13165 	 *    signed bounds
13166 	 * 3) the signed bounds cross zero, so they tell us nothing
13167 	 *    about the result
13168 	 * If the value in dst_reg is known nonnegative, then again the
13169 	 * unsigned bounds capture the signed bounds.
13170 	 * Thus, in all cases it suffices to blow away our signed bounds
13171 	 * and rely on inferring new ones from the unsigned bounds and
13172 	 * var_off of the result.
13173 	 */
13174 	dst_reg->s32_min_value = S32_MIN;
13175 	dst_reg->s32_max_value = S32_MAX;
13176 
13177 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13178 	dst_reg->u32_min_value >>= umax_val;
13179 	dst_reg->u32_max_value >>= umin_val;
13180 
13181 	__mark_reg64_unbounded(dst_reg);
13182 	__update_reg32_bounds(dst_reg);
13183 }
13184 
13185 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13186 			       struct bpf_reg_state *src_reg)
13187 {
13188 	u64 umax_val = src_reg->umax_value;
13189 	u64 umin_val = src_reg->umin_value;
13190 
13191 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13192 	 * be negative, then either:
13193 	 * 1) src_reg might be zero, so the sign bit of the result is
13194 	 *    unknown, so we lose our signed bounds
13195 	 * 2) it's known negative, thus the unsigned bounds capture the
13196 	 *    signed bounds
13197 	 * 3) the signed bounds cross zero, so they tell us nothing
13198 	 *    about the result
13199 	 * If the value in dst_reg is known nonnegative, then again the
13200 	 * unsigned bounds capture the signed bounds.
13201 	 * Thus, in all cases it suffices to blow away our signed bounds
13202 	 * and rely on inferring new ones from the unsigned bounds and
13203 	 * var_off of the result.
13204 	 */
13205 	dst_reg->smin_value = S64_MIN;
13206 	dst_reg->smax_value = S64_MAX;
13207 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13208 	dst_reg->umin_value >>= umax_val;
13209 	dst_reg->umax_value >>= umin_val;
13210 
13211 	/* Its not easy to operate on alu32 bounds here because it depends
13212 	 * on bits being shifted in. Take easy way out and mark unbounded
13213 	 * so we can recalculate later from tnum.
13214 	 */
13215 	__mark_reg32_unbounded(dst_reg);
13216 	__update_reg_bounds(dst_reg);
13217 }
13218 
13219 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13220 				  struct bpf_reg_state *src_reg)
13221 {
13222 	u64 umin_val = src_reg->u32_min_value;
13223 
13224 	/* Upon reaching here, src_known is true and
13225 	 * umax_val is equal to umin_val.
13226 	 */
13227 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13228 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13229 
13230 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13231 
13232 	/* blow away the dst_reg umin_value/umax_value and rely on
13233 	 * dst_reg var_off to refine the result.
13234 	 */
13235 	dst_reg->u32_min_value = 0;
13236 	dst_reg->u32_max_value = U32_MAX;
13237 
13238 	__mark_reg64_unbounded(dst_reg);
13239 	__update_reg32_bounds(dst_reg);
13240 }
13241 
13242 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13243 				struct bpf_reg_state *src_reg)
13244 {
13245 	u64 umin_val = src_reg->umin_value;
13246 
13247 	/* Upon reaching here, src_known is true and umax_val is equal
13248 	 * to umin_val.
13249 	 */
13250 	dst_reg->smin_value >>= umin_val;
13251 	dst_reg->smax_value >>= umin_val;
13252 
13253 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13254 
13255 	/* blow away the dst_reg umin_value/umax_value and rely on
13256 	 * dst_reg var_off to refine the result.
13257 	 */
13258 	dst_reg->umin_value = 0;
13259 	dst_reg->umax_value = U64_MAX;
13260 
13261 	/* Its not easy to operate on alu32 bounds here because it depends
13262 	 * on bits being shifted in from upper 32-bits. Take easy way out
13263 	 * and mark unbounded so we can recalculate later from tnum.
13264 	 */
13265 	__mark_reg32_unbounded(dst_reg);
13266 	__update_reg_bounds(dst_reg);
13267 }
13268 
13269 /* WARNING: This function does calculations on 64-bit values, but the actual
13270  * execution may occur on 32-bit values. Therefore, things like bitshifts
13271  * need extra checks in the 32-bit case.
13272  */
13273 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13274 				      struct bpf_insn *insn,
13275 				      struct bpf_reg_state *dst_reg,
13276 				      struct bpf_reg_state src_reg)
13277 {
13278 	struct bpf_reg_state *regs = cur_regs(env);
13279 	u8 opcode = BPF_OP(insn->code);
13280 	bool src_known;
13281 	s64 smin_val, smax_val;
13282 	u64 umin_val, umax_val;
13283 	s32 s32_min_val, s32_max_val;
13284 	u32 u32_min_val, u32_max_val;
13285 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13286 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13287 	int ret;
13288 
13289 	smin_val = src_reg.smin_value;
13290 	smax_val = src_reg.smax_value;
13291 	umin_val = src_reg.umin_value;
13292 	umax_val = src_reg.umax_value;
13293 
13294 	s32_min_val = src_reg.s32_min_value;
13295 	s32_max_val = src_reg.s32_max_value;
13296 	u32_min_val = src_reg.u32_min_value;
13297 	u32_max_val = src_reg.u32_max_value;
13298 
13299 	if (alu32) {
13300 		src_known = tnum_subreg_is_const(src_reg.var_off);
13301 		if ((src_known &&
13302 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13303 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13304 			/* Taint dst register if offset had invalid bounds
13305 			 * derived from e.g. dead branches.
13306 			 */
13307 			__mark_reg_unknown(env, dst_reg);
13308 			return 0;
13309 		}
13310 	} else {
13311 		src_known = tnum_is_const(src_reg.var_off);
13312 		if ((src_known &&
13313 		     (smin_val != smax_val || umin_val != umax_val)) ||
13314 		    smin_val > smax_val || umin_val > umax_val) {
13315 			/* Taint dst register if offset had invalid bounds
13316 			 * derived from e.g. dead branches.
13317 			 */
13318 			__mark_reg_unknown(env, dst_reg);
13319 			return 0;
13320 		}
13321 	}
13322 
13323 	if (!src_known &&
13324 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13325 		__mark_reg_unknown(env, dst_reg);
13326 		return 0;
13327 	}
13328 
13329 	if (sanitize_needed(opcode)) {
13330 		ret = sanitize_val_alu(env, insn);
13331 		if (ret < 0)
13332 			return sanitize_err(env, insn, ret, NULL, NULL);
13333 	}
13334 
13335 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13336 	 * There are two classes of instructions: The first class we track both
13337 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13338 	 * greatest amount of precision when alu operations are mixed with jmp32
13339 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13340 	 * and BPF_OR. This is possible because these ops have fairly easy to
13341 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13342 	 * See alu32 verifier tests for examples. The second class of
13343 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13344 	 * with regards to tracking sign/unsigned bounds because the bits may
13345 	 * cross subreg boundaries in the alu64 case. When this happens we mark
13346 	 * the reg unbounded in the subreg bound space and use the resulting
13347 	 * tnum to calculate an approximation of the sign/unsigned bounds.
13348 	 */
13349 	switch (opcode) {
13350 	case BPF_ADD:
13351 		scalar32_min_max_add(dst_reg, &src_reg);
13352 		scalar_min_max_add(dst_reg, &src_reg);
13353 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13354 		break;
13355 	case BPF_SUB:
13356 		scalar32_min_max_sub(dst_reg, &src_reg);
13357 		scalar_min_max_sub(dst_reg, &src_reg);
13358 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13359 		break;
13360 	case BPF_MUL:
13361 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13362 		scalar32_min_max_mul(dst_reg, &src_reg);
13363 		scalar_min_max_mul(dst_reg, &src_reg);
13364 		break;
13365 	case BPF_AND:
13366 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13367 		scalar32_min_max_and(dst_reg, &src_reg);
13368 		scalar_min_max_and(dst_reg, &src_reg);
13369 		break;
13370 	case BPF_OR:
13371 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13372 		scalar32_min_max_or(dst_reg, &src_reg);
13373 		scalar_min_max_or(dst_reg, &src_reg);
13374 		break;
13375 	case BPF_XOR:
13376 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13377 		scalar32_min_max_xor(dst_reg, &src_reg);
13378 		scalar_min_max_xor(dst_reg, &src_reg);
13379 		break;
13380 	case BPF_LSH:
13381 		if (umax_val >= insn_bitness) {
13382 			/* Shifts greater than 31 or 63 are undefined.
13383 			 * This includes shifts by a negative number.
13384 			 */
13385 			mark_reg_unknown(env, regs, insn->dst_reg);
13386 			break;
13387 		}
13388 		if (alu32)
13389 			scalar32_min_max_lsh(dst_reg, &src_reg);
13390 		else
13391 			scalar_min_max_lsh(dst_reg, &src_reg);
13392 		break;
13393 	case BPF_RSH:
13394 		if (umax_val >= insn_bitness) {
13395 			/* Shifts greater than 31 or 63 are undefined.
13396 			 * This includes shifts by a negative number.
13397 			 */
13398 			mark_reg_unknown(env, regs, insn->dst_reg);
13399 			break;
13400 		}
13401 		if (alu32)
13402 			scalar32_min_max_rsh(dst_reg, &src_reg);
13403 		else
13404 			scalar_min_max_rsh(dst_reg, &src_reg);
13405 		break;
13406 	case BPF_ARSH:
13407 		if (umax_val >= insn_bitness) {
13408 			/* Shifts greater than 31 or 63 are undefined.
13409 			 * This includes shifts by a negative number.
13410 			 */
13411 			mark_reg_unknown(env, regs, insn->dst_reg);
13412 			break;
13413 		}
13414 		if (alu32)
13415 			scalar32_min_max_arsh(dst_reg, &src_reg);
13416 		else
13417 			scalar_min_max_arsh(dst_reg, &src_reg);
13418 		break;
13419 	default:
13420 		mark_reg_unknown(env, regs, insn->dst_reg);
13421 		break;
13422 	}
13423 
13424 	/* ALU32 ops are zero extended into 64bit register */
13425 	if (alu32)
13426 		zext_32_to_64(dst_reg);
13427 	reg_bounds_sync(dst_reg);
13428 	return 0;
13429 }
13430 
13431 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13432  * and var_off.
13433  */
13434 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13435 				   struct bpf_insn *insn)
13436 {
13437 	struct bpf_verifier_state *vstate = env->cur_state;
13438 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13439 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13440 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13441 	u8 opcode = BPF_OP(insn->code);
13442 	int err;
13443 
13444 	dst_reg = &regs[insn->dst_reg];
13445 	src_reg = NULL;
13446 	if (dst_reg->type != SCALAR_VALUE)
13447 		ptr_reg = dst_reg;
13448 	else
13449 		/* Make sure ID is cleared otherwise dst_reg min/max could be
13450 		 * incorrectly propagated into other registers by find_equal_scalars()
13451 		 */
13452 		dst_reg->id = 0;
13453 	if (BPF_SRC(insn->code) == BPF_X) {
13454 		src_reg = &regs[insn->src_reg];
13455 		if (src_reg->type != SCALAR_VALUE) {
13456 			if (dst_reg->type != SCALAR_VALUE) {
13457 				/* Combining two pointers by any ALU op yields
13458 				 * an arbitrary scalar. Disallow all math except
13459 				 * pointer subtraction
13460 				 */
13461 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13462 					mark_reg_unknown(env, regs, insn->dst_reg);
13463 					return 0;
13464 				}
13465 				verbose(env, "R%d pointer %s pointer prohibited\n",
13466 					insn->dst_reg,
13467 					bpf_alu_string[opcode >> 4]);
13468 				return -EACCES;
13469 			} else {
13470 				/* scalar += pointer
13471 				 * This is legal, but we have to reverse our
13472 				 * src/dest handling in computing the range
13473 				 */
13474 				err = mark_chain_precision(env, insn->dst_reg);
13475 				if (err)
13476 					return err;
13477 				return adjust_ptr_min_max_vals(env, insn,
13478 							       src_reg, dst_reg);
13479 			}
13480 		} else if (ptr_reg) {
13481 			/* pointer += scalar */
13482 			err = mark_chain_precision(env, insn->src_reg);
13483 			if (err)
13484 				return err;
13485 			return adjust_ptr_min_max_vals(env, insn,
13486 						       dst_reg, src_reg);
13487 		} else if (dst_reg->precise) {
13488 			/* if dst_reg is precise, src_reg should be precise as well */
13489 			err = mark_chain_precision(env, insn->src_reg);
13490 			if (err)
13491 				return err;
13492 		}
13493 	} else {
13494 		/* Pretend the src is a reg with a known value, since we only
13495 		 * need to be able to read from this state.
13496 		 */
13497 		off_reg.type = SCALAR_VALUE;
13498 		__mark_reg_known(&off_reg, insn->imm);
13499 		src_reg = &off_reg;
13500 		if (ptr_reg) /* pointer += K */
13501 			return adjust_ptr_min_max_vals(env, insn,
13502 						       ptr_reg, src_reg);
13503 	}
13504 
13505 	/* Got here implies adding two SCALAR_VALUEs */
13506 	if (WARN_ON_ONCE(ptr_reg)) {
13507 		print_verifier_state(env, state, true);
13508 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
13509 		return -EINVAL;
13510 	}
13511 	if (WARN_ON(!src_reg)) {
13512 		print_verifier_state(env, state, true);
13513 		verbose(env, "verifier internal error: no src_reg\n");
13514 		return -EINVAL;
13515 	}
13516 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13517 }
13518 
13519 /* check validity of 32-bit and 64-bit arithmetic operations */
13520 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13521 {
13522 	struct bpf_reg_state *regs = cur_regs(env);
13523 	u8 opcode = BPF_OP(insn->code);
13524 	int err;
13525 
13526 	if (opcode == BPF_END || opcode == BPF_NEG) {
13527 		if (opcode == BPF_NEG) {
13528 			if (BPF_SRC(insn->code) != BPF_K ||
13529 			    insn->src_reg != BPF_REG_0 ||
13530 			    insn->off != 0 || insn->imm != 0) {
13531 				verbose(env, "BPF_NEG uses reserved fields\n");
13532 				return -EINVAL;
13533 			}
13534 		} else {
13535 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13536 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13537 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
13538 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
13539 				verbose(env, "BPF_END uses reserved fields\n");
13540 				return -EINVAL;
13541 			}
13542 		}
13543 
13544 		/* check src operand */
13545 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13546 		if (err)
13547 			return err;
13548 
13549 		if (is_pointer_value(env, insn->dst_reg)) {
13550 			verbose(env, "R%d pointer arithmetic prohibited\n",
13551 				insn->dst_reg);
13552 			return -EACCES;
13553 		}
13554 
13555 		/* check dest operand */
13556 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
13557 		if (err)
13558 			return err;
13559 
13560 	} else if (opcode == BPF_MOV) {
13561 
13562 		if (BPF_SRC(insn->code) == BPF_X) {
13563 			if (insn->imm != 0) {
13564 				verbose(env, "BPF_MOV uses reserved fields\n");
13565 				return -EINVAL;
13566 			}
13567 
13568 			if (BPF_CLASS(insn->code) == BPF_ALU) {
13569 				if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13570 					verbose(env, "BPF_MOV uses reserved fields\n");
13571 					return -EINVAL;
13572 				}
13573 			} else {
13574 				if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13575 				    insn->off != 32) {
13576 					verbose(env, "BPF_MOV uses reserved fields\n");
13577 					return -EINVAL;
13578 				}
13579 			}
13580 
13581 			/* check src operand */
13582 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13583 			if (err)
13584 				return err;
13585 		} else {
13586 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13587 				verbose(env, "BPF_MOV uses reserved fields\n");
13588 				return -EINVAL;
13589 			}
13590 		}
13591 
13592 		/* check dest operand, mark as required later */
13593 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13594 		if (err)
13595 			return err;
13596 
13597 		if (BPF_SRC(insn->code) == BPF_X) {
13598 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
13599 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13600 			bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13601 				       !tnum_is_const(src_reg->var_off);
13602 
13603 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13604 				if (insn->off == 0) {
13605 					/* case: R1 = R2
13606 					 * copy register state to dest reg
13607 					 */
13608 					if (need_id)
13609 						/* Assign src and dst registers the same ID
13610 						 * that will be used by find_equal_scalars()
13611 						 * to propagate min/max range.
13612 						 */
13613 						src_reg->id = ++env->id_gen;
13614 					copy_register_state(dst_reg, src_reg);
13615 					dst_reg->live |= REG_LIVE_WRITTEN;
13616 					dst_reg->subreg_def = DEF_NOT_SUBREG;
13617 				} else {
13618 					/* case: R1 = (s8, s16 s32)R2 */
13619 					if (is_pointer_value(env, insn->src_reg)) {
13620 						verbose(env,
13621 							"R%d sign-extension part of pointer\n",
13622 							insn->src_reg);
13623 						return -EACCES;
13624 					} else if (src_reg->type == SCALAR_VALUE) {
13625 						bool no_sext;
13626 
13627 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13628 						if (no_sext && need_id)
13629 							src_reg->id = ++env->id_gen;
13630 						copy_register_state(dst_reg, src_reg);
13631 						if (!no_sext)
13632 							dst_reg->id = 0;
13633 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13634 						dst_reg->live |= REG_LIVE_WRITTEN;
13635 						dst_reg->subreg_def = DEF_NOT_SUBREG;
13636 					} else {
13637 						mark_reg_unknown(env, regs, insn->dst_reg);
13638 					}
13639 				}
13640 			} else {
13641 				/* R1 = (u32) R2 */
13642 				if (is_pointer_value(env, insn->src_reg)) {
13643 					verbose(env,
13644 						"R%d partial copy of pointer\n",
13645 						insn->src_reg);
13646 					return -EACCES;
13647 				} else if (src_reg->type == SCALAR_VALUE) {
13648 					if (insn->off == 0) {
13649 						bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13650 
13651 						if (is_src_reg_u32 && need_id)
13652 							src_reg->id = ++env->id_gen;
13653 						copy_register_state(dst_reg, src_reg);
13654 						/* Make sure ID is cleared if src_reg is not in u32
13655 						 * range otherwise dst_reg min/max could be incorrectly
13656 						 * propagated into src_reg by find_equal_scalars()
13657 						 */
13658 						if (!is_src_reg_u32)
13659 							dst_reg->id = 0;
13660 						dst_reg->live |= REG_LIVE_WRITTEN;
13661 						dst_reg->subreg_def = env->insn_idx + 1;
13662 					} else {
13663 						/* case: W1 = (s8, s16)W2 */
13664 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13665 
13666 						if (no_sext && need_id)
13667 							src_reg->id = ++env->id_gen;
13668 						copy_register_state(dst_reg, src_reg);
13669 						if (!no_sext)
13670 							dst_reg->id = 0;
13671 						dst_reg->live |= REG_LIVE_WRITTEN;
13672 						dst_reg->subreg_def = env->insn_idx + 1;
13673 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13674 					}
13675 				} else {
13676 					mark_reg_unknown(env, regs,
13677 							 insn->dst_reg);
13678 				}
13679 				zext_32_to_64(dst_reg);
13680 				reg_bounds_sync(dst_reg);
13681 			}
13682 		} else {
13683 			/* case: R = imm
13684 			 * remember the value we stored into this reg
13685 			 */
13686 			/* clear any state __mark_reg_known doesn't set */
13687 			mark_reg_unknown(env, regs, insn->dst_reg);
13688 			regs[insn->dst_reg].type = SCALAR_VALUE;
13689 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13690 				__mark_reg_known(regs + insn->dst_reg,
13691 						 insn->imm);
13692 			} else {
13693 				__mark_reg_known(regs + insn->dst_reg,
13694 						 (u32)insn->imm);
13695 			}
13696 		}
13697 
13698 	} else if (opcode > BPF_END) {
13699 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13700 		return -EINVAL;
13701 
13702 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
13703 
13704 		if (BPF_SRC(insn->code) == BPF_X) {
13705 			if (insn->imm != 0 || insn->off > 1 ||
13706 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13707 				verbose(env, "BPF_ALU uses reserved fields\n");
13708 				return -EINVAL;
13709 			}
13710 			/* check src1 operand */
13711 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13712 			if (err)
13713 				return err;
13714 		} else {
13715 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13716 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13717 				verbose(env, "BPF_ALU uses reserved fields\n");
13718 				return -EINVAL;
13719 			}
13720 		}
13721 
13722 		/* check src2 operand */
13723 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13724 		if (err)
13725 			return err;
13726 
13727 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13728 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13729 			verbose(env, "div by zero\n");
13730 			return -EINVAL;
13731 		}
13732 
13733 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13734 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13735 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13736 
13737 			if (insn->imm < 0 || insn->imm >= size) {
13738 				verbose(env, "invalid shift %d\n", insn->imm);
13739 				return -EINVAL;
13740 			}
13741 		}
13742 
13743 		/* check dest operand */
13744 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13745 		if (err)
13746 			return err;
13747 
13748 		return adjust_reg_min_max_vals(env, insn);
13749 	}
13750 
13751 	return 0;
13752 }
13753 
13754 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13755 				   struct bpf_reg_state *dst_reg,
13756 				   enum bpf_reg_type type,
13757 				   bool range_right_open)
13758 {
13759 	struct bpf_func_state *state;
13760 	struct bpf_reg_state *reg;
13761 	int new_range;
13762 
13763 	if (dst_reg->off < 0 ||
13764 	    (dst_reg->off == 0 && range_right_open))
13765 		/* This doesn't give us any range */
13766 		return;
13767 
13768 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
13769 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13770 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
13771 		 * than pkt_end, but that's because it's also less than pkt.
13772 		 */
13773 		return;
13774 
13775 	new_range = dst_reg->off;
13776 	if (range_right_open)
13777 		new_range++;
13778 
13779 	/* Examples for register markings:
13780 	 *
13781 	 * pkt_data in dst register:
13782 	 *
13783 	 *   r2 = r3;
13784 	 *   r2 += 8;
13785 	 *   if (r2 > pkt_end) goto <handle exception>
13786 	 *   <access okay>
13787 	 *
13788 	 *   r2 = r3;
13789 	 *   r2 += 8;
13790 	 *   if (r2 < pkt_end) goto <access okay>
13791 	 *   <handle exception>
13792 	 *
13793 	 *   Where:
13794 	 *     r2 == dst_reg, pkt_end == src_reg
13795 	 *     r2=pkt(id=n,off=8,r=0)
13796 	 *     r3=pkt(id=n,off=0,r=0)
13797 	 *
13798 	 * pkt_data in src register:
13799 	 *
13800 	 *   r2 = r3;
13801 	 *   r2 += 8;
13802 	 *   if (pkt_end >= r2) goto <access okay>
13803 	 *   <handle exception>
13804 	 *
13805 	 *   r2 = r3;
13806 	 *   r2 += 8;
13807 	 *   if (pkt_end <= r2) goto <handle exception>
13808 	 *   <access okay>
13809 	 *
13810 	 *   Where:
13811 	 *     pkt_end == dst_reg, r2 == src_reg
13812 	 *     r2=pkt(id=n,off=8,r=0)
13813 	 *     r3=pkt(id=n,off=0,r=0)
13814 	 *
13815 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13816 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13817 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
13818 	 * the check.
13819 	 */
13820 
13821 	/* If our ids match, then we must have the same max_value.  And we
13822 	 * don't care about the other reg's fixed offset, since if it's too big
13823 	 * the range won't allow anything.
13824 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13825 	 */
13826 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13827 		if (reg->type == type && reg->id == dst_reg->id)
13828 			/* keep the maximum range already checked */
13829 			reg->range = max(reg->range, new_range);
13830 	}));
13831 }
13832 
13833 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13834 {
13835 	struct tnum subreg = tnum_subreg(reg->var_off);
13836 	s32 sval = (s32)val;
13837 
13838 	switch (opcode) {
13839 	case BPF_JEQ:
13840 		if (tnum_is_const(subreg))
13841 			return !!tnum_equals_const(subreg, val);
13842 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13843 			return 0;
13844 		break;
13845 	case BPF_JNE:
13846 		if (tnum_is_const(subreg))
13847 			return !tnum_equals_const(subreg, val);
13848 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13849 			return 1;
13850 		break;
13851 	case BPF_JSET:
13852 		if ((~subreg.mask & subreg.value) & val)
13853 			return 1;
13854 		if (!((subreg.mask | subreg.value) & val))
13855 			return 0;
13856 		break;
13857 	case BPF_JGT:
13858 		if (reg->u32_min_value > val)
13859 			return 1;
13860 		else if (reg->u32_max_value <= val)
13861 			return 0;
13862 		break;
13863 	case BPF_JSGT:
13864 		if (reg->s32_min_value > sval)
13865 			return 1;
13866 		else if (reg->s32_max_value <= sval)
13867 			return 0;
13868 		break;
13869 	case BPF_JLT:
13870 		if (reg->u32_max_value < val)
13871 			return 1;
13872 		else if (reg->u32_min_value >= val)
13873 			return 0;
13874 		break;
13875 	case BPF_JSLT:
13876 		if (reg->s32_max_value < sval)
13877 			return 1;
13878 		else if (reg->s32_min_value >= sval)
13879 			return 0;
13880 		break;
13881 	case BPF_JGE:
13882 		if (reg->u32_min_value >= val)
13883 			return 1;
13884 		else if (reg->u32_max_value < val)
13885 			return 0;
13886 		break;
13887 	case BPF_JSGE:
13888 		if (reg->s32_min_value >= sval)
13889 			return 1;
13890 		else if (reg->s32_max_value < sval)
13891 			return 0;
13892 		break;
13893 	case BPF_JLE:
13894 		if (reg->u32_max_value <= val)
13895 			return 1;
13896 		else if (reg->u32_min_value > val)
13897 			return 0;
13898 		break;
13899 	case BPF_JSLE:
13900 		if (reg->s32_max_value <= sval)
13901 			return 1;
13902 		else if (reg->s32_min_value > sval)
13903 			return 0;
13904 		break;
13905 	}
13906 
13907 	return -1;
13908 }
13909 
13910 
13911 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13912 {
13913 	s64 sval = (s64)val;
13914 
13915 	switch (opcode) {
13916 	case BPF_JEQ:
13917 		if (tnum_is_const(reg->var_off))
13918 			return !!tnum_equals_const(reg->var_off, val);
13919 		else if (val < reg->umin_value || val > reg->umax_value)
13920 			return 0;
13921 		break;
13922 	case BPF_JNE:
13923 		if (tnum_is_const(reg->var_off))
13924 			return !tnum_equals_const(reg->var_off, val);
13925 		else if (val < reg->umin_value || val > reg->umax_value)
13926 			return 1;
13927 		break;
13928 	case BPF_JSET:
13929 		if ((~reg->var_off.mask & reg->var_off.value) & val)
13930 			return 1;
13931 		if (!((reg->var_off.mask | reg->var_off.value) & val))
13932 			return 0;
13933 		break;
13934 	case BPF_JGT:
13935 		if (reg->umin_value > val)
13936 			return 1;
13937 		else if (reg->umax_value <= val)
13938 			return 0;
13939 		break;
13940 	case BPF_JSGT:
13941 		if (reg->smin_value > sval)
13942 			return 1;
13943 		else if (reg->smax_value <= sval)
13944 			return 0;
13945 		break;
13946 	case BPF_JLT:
13947 		if (reg->umax_value < val)
13948 			return 1;
13949 		else if (reg->umin_value >= val)
13950 			return 0;
13951 		break;
13952 	case BPF_JSLT:
13953 		if (reg->smax_value < sval)
13954 			return 1;
13955 		else if (reg->smin_value >= sval)
13956 			return 0;
13957 		break;
13958 	case BPF_JGE:
13959 		if (reg->umin_value >= val)
13960 			return 1;
13961 		else if (reg->umax_value < val)
13962 			return 0;
13963 		break;
13964 	case BPF_JSGE:
13965 		if (reg->smin_value >= sval)
13966 			return 1;
13967 		else if (reg->smax_value < sval)
13968 			return 0;
13969 		break;
13970 	case BPF_JLE:
13971 		if (reg->umax_value <= val)
13972 			return 1;
13973 		else if (reg->umin_value > val)
13974 			return 0;
13975 		break;
13976 	case BPF_JSLE:
13977 		if (reg->smax_value <= sval)
13978 			return 1;
13979 		else if (reg->smin_value > sval)
13980 			return 0;
13981 		break;
13982 	}
13983 
13984 	return -1;
13985 }
13986 
13987 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13988  * and return:
13989  *  1 - branch will be taken and "goto target" will be executed
13990  *  0 - branch will not be taken and fall-through to next insn
13991  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13992  *      range [0,10]
13993  */
13994 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13995 			   bool is_jmp32)
13996 {
13997 	if (__is_pointer_value(false, reg)) {
13998 		if (!reg_not_null(reg))
13999 			return -1;
14000 
14001 		/* If pointer is valid tests against zero will fail so we can
14002 		 * use this to direct branch taken.
14003 		 */
14004 		if (val != 0)
14005 			return -1;
14006 
14007 		switch (opcode) {
14008 		case BPF_JEQ:
14009 			return 0;
14010 		case BPF_JNE:
14011 			return 1;
14012 		default:
14013 			return -1;
14014 		}
14015 	}
14016 
14017 	if (is_jmp32)
14018 		return is_branch32_taken(reg, val, opcode);
14019 	return is_branch64_taken(reg, val, opcode);
14020 }
14021 
14022 static int flip_opcode(u32 opcode)
14023 {
14024 	/* How can we transform "a <op> b" into "b <op> a"? */
14025 	static const u8 opcode_flip[16] = {
14026 		/* these stay the same */
14027 		[BPF_JEQ  >> 4] = BPF_JEQ,
14028 		[BPF_JNE  >> 4] = BPF_JNE,
14029 		[BPF_JSET >> 4] = BPF_JSET,
14030 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14031 		[BPF_JGE  >> 4] = BPF_JLE,
14032 		[BPF_JGT  >> 4] = BPF_JLT,
14033 		[BPF_JLE  >> 4] = BPF_JGE,
14034 		[BPF_JLT  >> 4] = BPF_JGT,
14035 		[BPF_JSGE >> 4] = BPF_JSLE,
14036 		[BPF_JSGT >> 4] = BPF_JSLT,
14037 		[BPF_JSLE >> 4] = BPF_JSGE,
14038 		[BPF_JSLT >> 4] = BPF_JSGT
14039 	};
14040 	return opcode_flip[opcode >> 4];
14041 }
14042 
14043 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14044 				   struct bpf_reg_state *src_reg,
14045 				   u8 opcode)
14046 {
14047 	struct bpf_reg_state *pkt;
14048 
14049 	if (src_reg->type == PTR_TO_PACKET_END) {
14050 		pkt = dst_reg;
14051 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14052 		pkt = src_reg;
14053 		opcode = flip_opcode(opcode);
14054 	} else {
14055 		return -1;
14056 	}
14057 
14058 	if (pkt->range >= 0)
14059 		return -1;
14060 
14061 	switch (opcode) {
14062 	case BPF_JLE:
14063 		/* pkt <= pkt_end */
14064 		fallthrough;
14065 	case BPF_JGT:
14066 		/* pkt > pkt_end */
14067 		if (pkt->range == BEYOND_PKT_END)
14068 			/* pkt has at last one extra byte beyond pkt_end */
14069 			return opcode == BPF_JGT;
14070 		break;
14071 	case BPF_JLT:
14072 		/* pkt < pkt_end */
14073 		fallthrough;
14074 	case BPF_JGE:
14075 		/* pkt >= pkt_end */
14076 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14077 			return opcode == BPF_JGE;
14078 		break;
14079 	}
14080 	return -1;
14081 }
14082 
14083 /* Adjusts the register min/max values in the case that the dst_reg is the
14084  * variable register that we are working on, and src_reg is a constant or we're
14085  * simply doing a BPF_K check.
14086  * In JEQ/JNE cases we also adjust the var_off values.
14087  */
14088 static void reg_set_min_max(struct bpf_reg_state *true_reg,
14089 			    struct bpf_reg_state *false_reg,
14090 			    u64 val, u32 val32,
14091 			    u8 opcode, bool is_jmp32)
14092 {
14093 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
14094 	struct tnum false_64off = false_reg->var_off;
14095 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
14096 	struct tnum true_64off = true_reg->var_off;
14097 	s64 sval = (s64)val;
14098 	s32 sval32 = (s32)val32;
14099 
14100 	/* If the dst_reg is a pointer, we can't learn anything about its
14101 	 * variable offset from the compare (unless src_reg were a pointer into
14102 	 * the same object, but we don't bother with that.
14103 	 * Since false_reg and true_reg have the same type by construction, we
14104 	 * only need to check one of them for pointerness.
14105 	 */
14106 	if (__is_pointer_value(false, false_reg))
14107 		return;
14108 
14109 	switch (opcode) {
14110 	/* JEQ/JNE comparison doesn't change the register equivalence.
14111 	 *
14112 	 * r1 = r2;
14113 	 * if (r1 == 42) goto label;
14114 	 * ...
14115 	 * label: // here both r1 and r2 are known to be 42.
14116 	 *
14117 	 * Hence when marking register as known preserve it's ID.
14118 	 */
14119 	case BPF_JEQ:
14120 		if (is_jmp32) {
14121 			__mark_reg32_known(true_reg, val32);
14122 			true_32off = tnum_subreg(true_reg->var_off);
14123 		} else {
14124 			___mark_reg_known(true_reg, val);
14125 			true_64off = true_reg->var_off;
14126 		}
14127 		break;
14128 	case BPF_JNE:
14129 		if (is_jmp32) {
14130 			__mark_reg32_known(false_reg, val32);
14131 			false_32off = tnum_subreg(false_reg->var_off);
14132 		} else {
14133 			___mark_reg_known(false_reg, val);
14134 			false_64off = false_reg->var_off;
14135 		}
14136 		break;
14137 	case BPF_JSET:
14138 		if (is_jmp32) {
14139 			false_32off = tnum_and(false_32off, tnum_const(~val32));
14140 			if (is_power_of_2(val32))
14141 				true_32off = tnum_or(true_32off,
14142 						     tnum_const(val32));
14143 		} else {
14144 			false_64off = tnum_and(false_64off, tnum_const(~val));
14145 			if (is_power_of_2(val))
14146 				true_64off = tnum_or(true_64off,
14147 						     tnum_const(val));
14148 		}
14149 		break;
14150 	case BPF_JGE:
14151 	case BPF_JGT:
14152 	{
14153 		if (is_jmp32) {
14154 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
14155 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
14156 
14157 			false_reg->u32_max_value = min(false_reg->u32_max_value,
14158 						       false_umax);
14159 			true_reg->u32_min_value = max(true_reg->u32_min_value,
14160 						      true_umin);
14161 		} else {
14162 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
14163 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
14164 
14165 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
14166 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
14167 		}
14168 		break;
14169 	}
14170 	case BPF_JSGE:
14171 	case BPF_JSGT:
14172 	{
14173 		if (is_jmp32) {
14174 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
14175 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
14176 
14177 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
14178 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
14179 		} else {
14180 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
14181 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
14182 
14183 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
14184 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
14185 		}
14186 		break;
14187 	}
14188 	case BPF_JLE:
14189 	case BPF_JLT:
14190 	{
14191 		if (is_jmp32) {
14192 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
14193 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
14194 
14195 			false_reg->u32_min_value = max(false_reg->u32_min_value,
14196 						       false_umin);
14197 			true_reg->u32_max_value = min(true_reg->u32_max_value,
14198 						      true_umax);
14199 		} else {
14200 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
14201 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
14202 
14203 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
14204 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
14205 		}
14206 		break;
14207 	}
14208 	case BPF_JSLE:
14209 	case BPF_JSLT:
14210 	{
14211 		if (is_jmp32) {
14212 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
14213 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
14214 
14215 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
14216 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
14217 		} else {
14218 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
14219 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
14220 
14221 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
14222 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
14223 		}
14224 		break;
14225 	}
14226 	default:
14227 		return;
14228 	}
14229 
14230 	if (is_jmp32) {
14231 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
14232 					     tnum_subreg(false_32off));
14233 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
14234 					    tnum_subreg(true_32off));
14235 		__reg_combine_32_into_64(false_reg);
14236 		__reg_combine_32_into_64(true_reg);
14237 	} else {
14238 		false_reg->var_off = false_64off;
14239 		true_reg->var_off = true_64off;
14240 		__reg_combine_64_into_32(false_reg);
14241 		__reg_combine_64_into_32(true_reg);
14242 	}
14243 }
14244 
14245 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
14246  * the variable reg.
14247  */
14248 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
14249 				struct bpf_reg_state *false_reg,
14250 				u64 val, u32 val32,
14251 				u8 opcode, bool is_jmp32)
14252 {
14253 	opcode = flip_opcode(opcode);
14254 	/* This uses zero as "not present in table"; luckily the zero opcode,
14255 	 * BPF_JA, can't get here.
14256 	 */
14257 	if (opcode)
14258 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
14259 }
14260 
14261 /* Regs are known to be equal, so intersect their min/max/var_off */
14262 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
14263 				  struct bpf_reg_state *dst_reg)
14264 {
14265 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
14266 							dst_reg->umin_value);
14267 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
14268 							dst_reg->umax_value);
14269 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
14270 							dst_reg->smin_value);
14271 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
14272 							dst_reg->smax_value);
14273 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
14274 							     dst_reg->var_off);
14275 	reg_bounds_sync(src_reg);
14276 	reg_bounds_sync(dst_reg);
14277 }
14278 
14279 static void reg_combine_min_max(struct bpf_reg_state *true_src,
14280 				struct bpf_reg_state *true_dst,
14281 				struct bpf_reg_state *false_src,
14282 				struct bpf_reg_state *false_dst,
14283 				u8 opcode)
14284 {
14285 	switch (opcode) {
14286 	case BPF_JEQ:
14287 		__reg_combine_min_max(true_src, true_dst);
14288 		break;
14289 	case BPF_JNE:
14290 		__reg_combine_min_max(false_src, false_dst);
14291 		break;
14292 	}
14293 }
14294 
14295 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14296 				 struct bpf_reg_state *reg, u32 id,
14297 				 bool is_null)
14298 {
14299 	if (type_may_be_null(reg->type) && reg->id == id &&
14300 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14301 		/* Old offset (both fixed and variable parts) should have been
14302 		 * known-zero, because we don't allow pointer arithmetic on
14303 		 * pointers that might be NULL. If we see this happening, don't
14304 		 * convert the register.
14305 		 *
14306 		 * But in some cases, some helpers that return local kptrs
14307 		 * advance offset for the returned pointer. In those cases, it
14308 		 * is fine to expect to see reg->off.
14309 		 */
14310 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14311 			return;
14312 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14313 		    WARN_ON_ONCE(reg->off))
14314 			return;
14315 
14316 		if (is_null) {
14317 			reg->type = SCALAR_VALUE;
14318 			/* We don't need id and ref_obj_id from this point
14319 			 * onwards anymore, thus we should better reset it,
14320 			 * so that state pruning has chances to take effect.
14321 			 */
14322 			reg->id = 0;
14323 			reg->ref_obj_id = 0;
14324 
14325 			return;
14326 		}
14327 
14328 		mark_ptr_not_null_reg(reg);
14329 
14330 		if (!reg_may_point_to_spin_lock(reg)) {
14331 			/* For not-NULL ptr, reg->ref_obj_id will be reset
14332 			 * in release_reference().
14333 			 *
14334 			 * reg->id is still used by spin_lock ptr. Other
14335 			 * than spin_lock ptr type, reg->id can be reset.
14336 			 */
14337 			reg->id = 0;
14338 		}
14339 	}
14340 }
14341 
14342 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14343  * be folded together at some point.
14344  */
14345 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14346 				  bool is_null)
14347 {
14348 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14349 	struct bpf_reg_state *regs = state->regs, *reg;
14350 	u32 ref_obj_id = regs[regno].ref_obj_id;
14351 	u32 id = regs[regno].id;
14352 
14353 	if (ref_obj_id && ref_obj_id == id && is_null)
14354 		/* regs[regno] is in the " == NULL" branch.
14355 		 * No one could have freed the reference state before
14356 		 * doing the NULL check.
14357 		 */
14358 		WARN_ON_ONCE(release_reference_state(state, id));
14359 
14360 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14361 		mark_ptr_or_null_reg(state, reg, id, is_null);
14362 	}));
14363 }
14364 
14365 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14366 				   struct bpf_reg_state *dst_reg,
14367 				   struct bpf_reg_state *src_reg,
14368 				   struct bpf_verifier_state *this_branch,
14369 				   struct bpf_verifier_state *other_branch)
14370 {
14371 	if (BPF_SRC(insn->code) != BPF_X)
14372 		return false;
14373 
14374 	/* Pointers are always 64-bit. */
14375 	if (BPF_CLASS(insn->code) == BPF_JMP32)
14376 		return false;
14377 
14378 	switch (BPF_OP(insn->code)) {
14379 	case BPF_JGT:
14380 		if ((dst_reg->type == PTR_TO_PACKET &&
14381 		     src_reg->type == PTR_TO_PACKET_END) ||
14382 		    (dst_reg->type == PTR_TO_PACKET_META &&
14383 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14384 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14385 			find_good_pkt_pointers(this_branch, dst_reg,
14386 					       dst_reg->type, false);
14387 			mark_pkt_end(other_branch, insn->dst_reg, true);
14388 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14389 			    src_reg->type == PTR_TO_PACKET) ||
14390 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14391 			    src_reg->type == PTR_TO_PACKET_META)) {
14392 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
14393 			find_good_pkt_pointers(other_branch, src_reg,
14394 					       src_reg->type, true);
14395 			mark_pkt_end(this_branch, insn->src_reg, false);
14396 		} else {
14397 			return false;
14398 		}
14399 		break;
14400 	case BPF_JLT:
14401 		if ((dst_reg->type == PTR_TO_PACKET &&
14402 		     src_reg->type == PTR_TO_PACKET_END) ||
14403 		    (dst_reg->type == PTR_TO_PACKET_META &&
14404 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14405 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14406 			find_good_pkt_pointers(other_branch, dst_reg,
14407 					       dst_reg->type, true);
14408 			mark_pkt_end(this_branch, insn->dst_reg, false);
14409 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14410 			    src_reg->type == PTR_TO_PACKET) ||
14411 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14412 			    src_reg->type == PTR_TO_PACKET_META)) {
14413 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
14414 			find_good_pkt_pointers(this_branch, src_reg,
14415 					       src_reg->type, false);
14416 			mark_pkt_end(other_branch, insn->src_reg, true);
14417 		} else {
14418 			return false;
14419 		}
14420 		break;
14421 	case BPF_JGE:
14422 		if ((dst_reg->type == PTR_TO_PACKET &&
14423 		     src_reg->type == PTR_TO_PACKET_END) ||
14424 		    (dst_reg->type == PTR_TO_PACKET_META &&
14425 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14426 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14427 			find_good_pkt_pointers(this_branch, dst_reg,
14428 					       dst_reg->type, true);
14429 			mark_pkt_end(other_branch, insn->dst_reg, false);
14430 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14431 			    src_reg->type == PTR_TO_PACKET) ||
14432 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14433 			    src_reg->type == PTR_TO_PACKET_META)) {
14434 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14435 			find_good_pkt_pointers(other_branch, src_reg,
14436 					       src_reg->type, false);
14437 			mark_pkt_end(this_branch, insn->src_reg, true);
14438 		} else {
14439 			return false;
14440 		}
14441 		break;
14442 	case BPF_JLE:
14443 		if ((dst_reg->type == PTR_TO_PACKET &&
14444 		     src_reg->type == PTR_TO_PACKET_END) ||
14445 		    (dst_reg->type == PTR_TO_PACKET_META &&
14446 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14447 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14448 			find_good_pkt_pointers(other_branch, dst_reg,
14449 					       dst_reg->type, false);
14450 			mark_pkt_end(this_branch, insn->dst_reg, true);
14451 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14452 			    src_reg->type == PTR_TO_PACKET) ||
14453 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14454 			    src_reg->type == PTR_TO_PACKET_META)) {
14455 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14456 			find_good_pkt_pointers(this_branch, src_reg,
14457 					       src_reg->type, true);
14458 			mark_pkt_end(other_branch, insn->src_reg, false);
14459 		} else {
14460 			return false;
14461 		}
14462 		break;
14463 	default:
14464 		return false;
14465 	}
14466 
14467 	return true;
14468 }
14469 
14470 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14471 			       struct bpf_reg_state *known_reg)
14472 {
14473 	struct bpf_func_state *state;
14474 	struct bpf_reg_state *reg;
14475 
14476 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14477 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14478 			copy_register_state(reg, known_reg);
14479 	}));
14480 }
14481 
14482 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14483 			     struct bpf_insn *insn, int *insn_idx)
14484 {
14485 	struct bpf_verifier_state *this_branch = env->cur_state;
14486 	struct bpf_verifier_state *other_branch;
14487 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14488 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14489 	struct bpf_reg_state *eq_branch_regs;
14490 	u8 opcode = BPF_OP(insn->code);
14491 	bool is_jmp32;
14492 	int pred = -1;
14493 	int err;
14494 
14495 	/* Only conditional jumps are expected to reach here. */
14496 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
14497 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14498 		return -EINVAL;
14499 	}
14500 
14501 	/* check src2 operand */
14502 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14503 	if (err)
14504 		return err;
14505 
14506 	dst_reg = &regs[insn->dst_reg];
14507 	if (BPF_SRC(insn->code) == BPF_X) {
14508 		if (insn->imm != 0) {
14509 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14510 			return -EINVAL;
14511 		}
14512 
14513 		/* check src1 operand */
14514 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14515 		if (err)
14516 			return err;
14517 
14518 		src_reg = &regs[insn->src_reg];
14519 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14520 		    is_pointer_value(env, insn->src_reg)) {
14521 			verbose(env, "R%d pointer comparison prohibited\n",
14522 				insn->src_reg);
14523 			return -EACCES;
14524 		}
14525 	} else {
14526 		if (insn->src_reg != BPF_REG_0) {
14527 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14528 			return -EINVAL;
14529 		}
14530 	}
14531 
14532 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14533 
14534 	if (BPF_SRC(insn->code) == BPF_K) {
14535 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14536 	} else if (src_reg->type == SCALAR_VALUE &&
14537 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14538 		pred = is_branch_taken(dst_reg,
14539 				       tnum_subreg(src_reg->var_off).value,
14540 				       opcode,
14541 				       is_jmp32);
14542 	} else if (src_reg->type == SCALAR_VALUE &&
14543 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14544 		pred = is_branch_taken(dst_reg,
14545 				       src_reg->var_off.value,
14546 				       opcode,
14547 				       is_jmp32);
14548 	} else if (dst_reg->type == SCALAR_VALUE &&
14549 		   is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14550 		pred = is_branch_taken(src_reg,
14551 				       tnum_subreg(dst_reg->var_off).value,
14552 				       flip_opcode(opcode),
14553 				       is_jmp32);
14554 	} else if (dst_reg->type == SCALAR_VALUE &&
14555 		   !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14556 		pred = is_branch_taken(src_reg,
14557 				       dst_reg->var_off.value,
14558 				       flip_opcode(opcode),
14559 				       is_jmp32);
14560 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
14561 		   reg_is_pkt_pointer_any(src_reg) &&
14562 		   !is_jmp32) {
14563 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14564 	}
14565 
14566 	if (pred >= 0) {
14567 		/* If we get here with a dst_reg pointer type it is because
14568 		 * above is_branch_taken() special cased the 0 comparison.
14569 		 */
14570 		if (!__is_pointer_value(false, dst_reg))
14571 			err = mark_chain_precision(env, insn->dst_reg);
14572 		if (BPF_SRC(insn->code) == BPF_X && !err &&
14573 		    !__is_pointer_value(false, src_reg))
14574 			err = mark_chain_precision(env, insn->src_reg);
14575 		if (err)
14576 			return err;
14577 	}
14578 
14579 	if (pred == 1) {
14580 		/* Only follow the goto, ignore fall-through. If needed, push
14581 		 * the fall-through branch for simulation under speculative
14582 		 * execution.
14583 		 */
14584 		if (!env->bypass_spec_v1 &&
14585 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
14586 					       *insn_idx))
14587 			return -EFAULT;
14588 		if (env->log.level & BPF_LOG_LEVEL)
14589 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14590 		*insn_idx += insn->off;
14591 		return 0;
14592 	} else if (pred == 0) {
14593 		/* Only follow the fall-through branch, since that's where the
14594 		 * program will go. If needed, push the goto branch for
14595 		 * simulation under speculative execution.
14596 		 */
14597 		if (!env->bypass_spec_v1 &&
14598 		    !sanitize_speculative_path(env, insn,
14599 					       *insn_idx + insn->off + 1,
14600 					       *insn_idx))
14601 			return -EFAULT;
14602 		if (env->log.level & BPF_LOG_LEVEL)
14603 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14604 		return 0;
14605 	}
14606 
14607 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14608 				  false);
14609 	if (!other_branch)
14610 		return -EFAULT;
14611 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14612 
14613 	/* detect if we are comparing against a constant value so we can adjust
14614 	 * our min/max values for our dst register.
14615 	 * this is only legit if both are scalars (or pointers to the same
14616 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14617 	 * because otherwise the different base pointers mean the offsets aren't
14618 	 * comparable.
14619 	 */
14620 	if (BPF_SRC(insn->code) == BPF_X) {
14621 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
14622 
14623 		if (dst_reg->type == SCALAR_VALUE &&
14624 		    src_reg->type == SCALAR_VALUE) {
14625 			if (tnum_is_const(src_reg->var_off) ||
14626 			    (is_jmp32 &&
14627 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
14628 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
14629 						dst_reg,
14630 						src_reg->var_off.value,
14631 						tnum_subreg(src_reg->var_off).value,
14632 						opcode, is_jmp32);
14633 			else if (tnum_is_const(dst_reg->var_off) ||
14634 				 (is_jmp32 &&
14635 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
14636 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14637 						    src_reg,
14638 						    dst_reg->var_off.value,
14639 						    tnum_subreg(dst_reg->var_off).value,
14640 						    opcode, is_jmp32);
14641 			else if (!is_jmp32 &&
14642 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
14643 				/* Comparing for equality, we can combine knowledge */
14644 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
14645 						    &other_branch_regs[insn->dst_reg],
14646 						    src_reg, dst_reg, opcode);
14647 			if (src_reg->id &&
14648 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14649 				find_equal_scalars(this_branch, src_reg);
14650 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14651 			}
14652 
14653 		}
14654 	} else if (dst_reg->type == SCALAR_VALUE) {
14655 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
14656 					dst_reg, insn->imm, (u32)insn->imm,
14657 					opcode, is_jmp32);
14658 	}
14659 
14660 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14661 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14662 		find_equal_scalars(this_branch, dst_reg);
14663 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14664 	}
14665 
14666 	/* if one pointer register is compared to another pointer
14667 	 * register check if PTR_MAYBE_NULL could be lifted.
14668 	 * E.g. register A - maybe null
14669 	 *      register B - not null
14670 	 * for JNE A, B, ... - A is not null in the false branch;
14671 	 * for JEQ A, B, ... - A is not null in the true branch.
14672 	 *
14673 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
14674 	 * not need to be null checked by the BPF program, i.e.,
14675 	 * could be null even without PTR_MAYBE_NULL marking, so
14676 	 * only propagate nullness when neither reg is that type.
14677 	 */
14678 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14679 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14680 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14681 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
14682 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14683 		eq_branch_regs = NULL;
14684 		switch (opcode) {
14685 		case BPF_JEQ:
14686 			eq_branch_regs = other_branch_regs;
14687 			break;
14688 		case BPF_JNE:
14689 			eq_branch_regs = regs;
14690 			break;
14691 		default:
14692 			/* do nothing */
14693 			break;
14694 		}
14695 		if (eq_branch_regs) {
14696 			if (type_may_be_null(src_reg->type))
14697 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14698 			else
14699 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14700 		}
14701 	}
14702 
14703 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14704 	 * NOTE: these optimizations below are related with pointer comparison
14705 	 *       which will never be JMP32.
14706 	 */
14707 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14708 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14709 	    type_may_be_null(dst_reg->type)) {
14710 		/* Mark all identical registers in each branch as either
14711 		 * safe or unknown depending R == 0 or R != 0 conditional.
14712 		 */
14713 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14714 				      opcode == BPF_JNE);
14715 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14716 				      opcode == BPF_JEQ);
14717 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14718 					   this_branch, other_branch) &&
14719 		   is_pointer_value(env, insn->dst_reg)) {
14720 		verbose(env, "R%d pointer comparison prohibited\n",
14721 			insn->dst_reg);
14722 		return -EACCES;
14723 	}
14724 	if (env->log.level & BPF_LOG_LEVEL)
14725 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
14726 	return 0;
14727 }
14728 
14729 /* verify BPF_LD_IMM64 instruction */
14730 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14731 {
14732 	struct bpf_insn_aux_data *aux = cur_aux(env);
14733 	struct bpf_reg_state *regs = cur_regs(env);
14734 	struct bpf_reg_state *dst_reg;
14735 	struct bpf_map *map;
14736 	int err;
14737 
14738 	if (BPF_SIZE(insn->code) != BPF_DW) {
14739 		verbose(env, "invalid BPF_LD_IMM insn\n");
14740 		return -EINVAL;
14741 	}
14742 	if (insn->off != 0) {
14743 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14744 		return -EINVAL;
14745 	}
14746 
14747 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
14748 	if (err)
14749 		return err;
14750 
14751 	dst_reg = &regs[insn->dst_reg];
14752 	if (insn->src_reg == 0) {
14753 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14754 
14755 		dst_reg->type = SCALAR_VALUE;
14756 		__mark_reg_known(&regs[insn->dst_reg], imm);
14757 		return 0;
14758 	}
14759 
14760 	/* All special src_reg cases are listed below. From this point onwards
14761 	 * we either succeed and assign a corresponding dst_reg->type after
14762 	 * zeroing the offset, or fail and reject the program.
14763 	 */
14764 	mark_reg_known_zero(env, regs, insn->dst_reg);
14765 
14766 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14767 		dst_reg->type = aux->btf_var.reg_type;
14768 		switch (base_type(dst_reg->type)) {
14769 		case PTR_TO_MEM:
14770 			dst_reg->mem_size = aux->btf_var.mem_size;
14771 			break;
14772 		case PTR_TO_BTF_ID:
14773 			dst_reg->btf = aux->btf_var.btf;
14774 			dst_reg->btf_id = aux->btf_var.btf_id;
14775 			break;
14776 		default:
14777 			verbose(env, "bpf verifier is misconfigured\n");
14778 			return -EFAULT;
14779 		}
14780 		return 0;
14781 	}
14782 
14783 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
14784 		struct bpf_prog_aux *aux = env->prog->aux;
14785 		u32 subprogno = find_subprog(env,
14786 					     env->insn_idx + insn->imm + 1);
14787 
14788 		if (!aux->func_info) {
14789 			verbose(env, "missing btf func_info\n");
14790 			return -EINVAL;
14791 		}
14792 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14793 			verbose(env, "callback function not static\n");
14794 			return -EINVAL;
14795 		}
14796 
14797 		dst_reg->type = PTR_TO_FUNC;
14798 		dst_reg->subprogno = subprogno;
14799 		return 0;
14800 	}
14801 
14802 	map = env->used_maps[aux->map_index];
14803 	dst_reg->map_ptr = map;
14804 
14805 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14806 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14807 		dst_reg->type = PTR_TO_MAP_VALUE;
14808 		dst_reg->off = aux->map_off;
14809 		WARN_ON_ONCE(map->max_entries != 1);
14810 		/* We want reg->id to be same (0) as map_value is not distinct */
14811 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14812 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14813 		dst_reg->type = CONST_PTR_TO_MAP;
14814 	} else {
14815 		verbose(env, "bpf verifier is misconfigured\n");
14816 		return -EINVAL;
14817 	}
14818 
14819 	return 0;
14820 }
14821 
14822 static bool may_access_skb(enum bpf_prog_type type)
14823 {
14824 	switch (type) {
14825 	case BPF_PROG_TYPE_SOCKET_FILTER:
14826 	case BPF_PROG_TYPE_SCHED_CLS:
14827 	case BPF_PROG_TYPE_SCHED_ACT:
14828 		return true;
14829 	default:
14830 		return false;
14831 	}
14832 }
14833 
14834 /* verify safety of LD_ABS|LD_IND instructions:
14835  * - they can only appear in the programs where ctx == skb
14836  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14837  *   preserve R6-R9, and store return value into R0
14838  *
14839  * Implicit input:
14840  *   ctx == skb == R6 == CTX
14841  *
14842  * Explicit input:
14843  *   SRC == any register
14844  *   IMM == 32-bit immediate
14845  *
14846  * Output:
14847  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14848  */
14849 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14850 {
14851 	struct bpf_reg_state *regs = cur_regs(env);
14852 	static const int ctx_reg = BPF_REG_6;
14853 	u8 mode = BPF_MODE(insn->code);
14854 	int i, err;
14855 
14856 	if (!may_access_skb(resolve_prog_type(env->prog))) {
14857 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14858 		return -EINVAL;
14859 	}
14860 
14861 	if (!env->ops->gen_ld_abs) {
14862 		verbose(env, "bpf verifier is misconfigured\n");
14863 		return -EINVAL;
14864 	}
14865 
14866 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14867 	    BPF_SIZE(insn->code) == BPF_DW ||
14868 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14869 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14870 		return -EINVAL;
14871 	}
14872 
14873 	/* check whether implicit source operand (register R6) is readable */
14874 	err = check_reg_arg(env, ctx_reg, SRC_OP);
14875 	if (err)
14876 		return err;
14877 
14878 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14879 	 * gen_ld_abs() may terminate the program at runtime, leading to
14880 	 * reference leak.
14881 	 */
14882 	err = check_reference_leak(env);
14883 	if (err) {
14884 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14885 		return err;
14886 	}
14887 
14888 	if (env->cur_state->active_lock.ptr) {
14889 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14890 		return -EINVAL;
14891 	}
14892 
14893 	if (env->cur_state->active_rcu_lock) {
14894 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14895 		return -EINVAL;
14896 	}
14897 
14898 	if (regs[ctx_reg].type != PTR_TO_CTX) {
14899 		verbose(env,
14900 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14901 		return -EINVAL;
14902 	}
14903 
14904 	if (mode == BPF_IND) {
14905 		/* check explicit source operand */
14906 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14907 		if (err)
14908 			return err;
14909 	}
14910 
14911 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14912 	if (err < 0)
14913 		return err;
14914 
14915 	/* reset caller saved regs to unreadable */
14916 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14917 		mark_reg_not_init(env, regs, caller_saved[i]);
14918 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14919 	}
14920 
14921 	/* mark destination R0 register as readable, since it contains
14922 	 * the value fetched from the packet.
14923 	 * Already marked as written above.
14924 	 */
14925 	mark_reg_unknown(env, regs, BPF_REG_0);
14926 	/* ld_abs load up to 32-bit skb data. */
14927 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14928 	return 0;
14929 }
14930 
14931 static int check_return_code(struct bpf_verifier_env *env)
14932 {
14933 	struct tnum enforce_attach_type_range = tnum_unknown;
14934 	const struct bpf_prog *prog = env->prog;
14935 	struct bpf_reg_state *reg;
14936 	struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
14937 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14938 	int err;
14939 	struct bpf_func_state *frame = env->cur_state->frame[0];
14940 	const bool is_subprog = frame->subprogno;
14941 
14942 	/* LSM and struct_ops func-ptr's return type could be "void" */
14943 	if (!is_subprog) {
14944 		switch (prog_type) {
14945 		case BPF_PROG_TYPE_LSM:
14946 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
14947 				/* See below, can be 0 or 0-1 depending on hook. */
14948 				break;
14949 			fallthrough;
14950 		case BPF_PROG_TYPE_STRUCT_OPS:
14951 			if (!prog->aux->attach_func_proto->type)
14952 				return 0;
14953 			break;
14954 		default:
14955 			break;
14956 		}
14957 	}
14958 
14959 	/* eBPF calling convention is such that R0 is used
14960 	 * to return the value from eBPF program.
14961 	 * Make sure that it's readable at this time
14962 	 * of bpf_exit, which means that program wrote
14963 	 * something into it earlier
14964 	 */
14965 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14966 	if (err)
14967 		return err;
14968 
14969 	if (is_pointer_value(env, BPF_REG_0)) {
14970 		verbose(env, "R0 leaks addr as return value\n");
14971 		return -EACCES;
14972 	}
14973 
14974 	reg = cur_regs(env) + BPF_REG_0;
14975 
14976 	if (frame->in_async_callback_fn) {
14977 		/* enforce return zero from async callbacks like timer */
14978 		if (reg->type != SCALAR_VALUE) {
14979 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14980 				reg_type_str(env, reg->type));
14981 			return -EINVAL;
14982 		}
14983 
14984 		if (!tnum_in(const_0, reg->var_off)) {
14985 			verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
14986 			return -EINVAL;
14987 		}
14988 		return 0;
14989 	}
14990 
14991 	if (is_subprog) {
14992 		if (reg->type != SCALAR_VALUE) {
14993 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14994 				reg_type_str(env, reg->type));
14995 			return -EINVAL;
14996 		}
14997 		return 0;
14998 	}
14999 
15000 	switch (prog_type) {
15001 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15002 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15003 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15004 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15005 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15006 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15007 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
15008 			range = tnum_range(1, 1);
15009 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15010 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15011 			range = tnum_range(0, 3);
15012 		break;
15013 	case BPF_PROG_TYPE_CGROUP_SKB:
15014 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15015 			range = tnum_range(0, 3);
15016 			enforce_attach_type_range = tnum_range(2, 3);
15017 		}
15018 		break;
15019 	case BPF_PROG_TYPE_CGROUP_SOCK:
15020 	case BPF_PROG_TYPE_SOCK_OPS:
15021 	case BPF_PROG_TYPE_CGROUP_DEVICE:
15022 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15023 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15024 		break;
15025 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15026 		if (!env->prog->aux->attach_btf_id)
15027 			return 0;
15028 		range = tnum_const(0);
15029 		break;
15030 	case BPF_PROG_TYPE_TRACING:
15031 		switch (env->prog->expected_attach_type) {
15032 		case BPF_TRACE_FENTRY:
15033 		case BPF_TRACE_FEXIT:
15034 			range = tnum_const(0);
15035 			break;
15036 		case BPF_TRACE_RAW_TP:
15037 		case BPF_MODIFY_RETURN:
15038 			return 0;
15039 		case BPF_TRACE_ITER:
15040 			break;
15041 		default:
15042 			return -ENOTSUPP;
15043 		}
15044 		break;
15045 	case BPF_PROG_TYPE_SK_LOOKUP:
15046 		range = tnum_range(SK_DROP, SK_PASS);
15047 		break;
15048 
15049 	case BPF_PROG_TYPE_LSM:
15050 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15051 			/* Regular BPF_PROG_TYPE_LSM programs can return
15052 			 * any value.
15053 			 */
15054 			return 0;
15055 		}
15056 		if (!env->prog->aux->attach_func_proto->type) {
15057 			/* Make sure programs that attach to void
15058 			 * hooks don't try to modify return value.
15059 			 */
15060 			range = tnum_range(1, 1);
15061 		}
15062 		break;
15063 
15064 	case BPF_PROG_TYPE_NETFILTER:
15065 		range = tnum_range(NF_DROP, NF_ACCEPT);
15066 		break;
15067 	case BPF_PROG_TYPE_EXT:
15068 		/* freplace program can return anything as its return value
15069 		 * depends on the to-be-replaced kernel func or bpf program.
15070 		 */
15071 	default:
15072 		return 0;
15073 	}
15074 
15075 	if (reg->type != SCALAR_VALUE) {
15076 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
15077 			reg_type_str(env, reg->type));
15078 		return -EINVAL;
15079 	}
15080 
15081 	if (!tnum_in(range, reg->var_off)) {
15082 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
15083 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
15084 		    prog_type == BPF_PROG_TYPE_LSM &&
15085 		    !prog->aux->attach_func_proto->type)
15086 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15087 		return -EINVAL;
15088 	}
15089 
15090 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15091 	    tnum_in(enforce_attach_type_range, reg->var_off))
15092 		env->prog->enforce_expected_attach_type = 1;
15093 	return 0;
15094 }
15095 
15096 /* non-recursive DFS pseudo code
15097  * 1  procedure DFS-iterative(G,v):
15098  * 2      label v as discovered
15099  * 3      let S be a stack
15100  * 4      S.push(v)
15101  * 5      while S is not empty
15102  * 6            t <- S.peek()
15103  * 7            if t is what we're looking for:
15104  * 8                return t
15105  * 9            for all edges e in G.adjacentEdges(t) do
15106  * 10               if edge e is already labelled
15107  * 11                   continue with the next edge
15108  * 12               w <- G.adjacentVertex(t,e)
15109  * 13               if vertex w is not discovered and not explored
15110  * 14                   label e as tree-edge
15111  * 15                   label w as discovered
15112  * 16                   S.push(w)
15113  * 17                   continue at 5
15114  * 18               else if vertex w is discovered
15115  * 19                   label e as back-edge
15116  * 20               else
15117  * 21                   // vertex w is explored
15118  * 22                   label e as forward- or cross-edge
15119  * 23           label t as explored
15120  * 24           S.pop()
15121  *
15122  * convention:
15123  * 0x10 - discovered
15124  * 0x11 - discovered and fall-through edge labelled
15125  * 0x12 - discovered and fall-through and branch edges labelled
15126  * 0x20 - explored
15127  */
15128 
15129 enum {
15130 	DISCOVERED = 0x10,
15131 	EXPLORED = 0x20,
15132 	FALLTHROUGH = 1,
15133 	BRANCH = 2,
15134 };
15135 
15136 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15137 {
15138 	env->insn_aux_data[idx].prune_point = true;
15139 }
15140 
15141 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15142 {
15143 	return env->insn_aux_data[insn_idx].prune_point;
15144 }
15145 
15146 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15147 {
15148 	env->insn_aux_data[idx].force_checkpoint = true;
15149 }
15150 
15151 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15152 {
15153 	return env->insn_aux_data[insn_idx].force_checkpoint;
15154 }
15155 
15156 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15157 {
15158 	env->insn_aux_data[idx].calls_callback = true;
15159 }
15160 
15161 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15162 {
15163 	return env->insn_aux_data[insn_idx].calls_callback;
15164 }
15165 
15166 enum {
15167 	DONE_EXPLORING = 0,
15168 	KEEP_EXPLORING = 1,
15169 };
15170 
15171 /* t, w, e - match pseudo-code above:
15172  * t - index of current instruction
15173  * w - next instruction
15174  * e - edge
15175  */
15176 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15177 {
15178 	int *insn_stack = env->cfg.insn_stack;
15179 	int *insn_state = env->cfg.insn_state;
15180 
15181 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15182 		return DONE_EXPLORING;
15183 
15184 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15185 		return DONE_EXPLORING;
15186 
15187 	if (w < 0 || w >= env->prog->len) {
15188 		verbose_linfo(env, t, "%d: ", t);
15189 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15190 		return -EINVAL;
15191 	}
15192 
15193 	if (e == BRANCH) {
15194 		/* mark branch target for state pruning */
15195 		mark_prune_point(env, w);
15196 		mark_jmp_point(env, w);
15197 	}
15198 
15199 	if (insn_state[w] == 0) {
15200 		/* tree-edge */
15201 		insn_state[t] = DISCOVERED | e;
15202 		insn_state[w] = DISCOVERED;
15203 		if (env->cfg.cur_stack >= env->prog->len)
15204 			return -E2BIG;
15205 		insn_stack[env->cfg.cur_stack++] = w;
15206 		return KEEP_EXPLORING;
15207 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15208 		if (env->bpf_capable)
15209 			return DONE_EXPLORING;
15210 		verbose_linfo(env, t, "%d: ", t);
15211 		verbose_linfo(env, w, "%d: ", w);
15212 		verbose(env, "back-edge from insn %d to %d\n", t, w);
15213 		return -EINVAL;
15214 	} else if (insn_state[w] == EXPLORED) {
15215 		/* forward- or cross-edge */
15216 		insn_state[t] = DISCOVERED | e;
15217 	} else {
15218 		verbose(env, "insn state internal bug\n");
15219 		return -EFAULT;
15220 	}
15221 	return DONE_EXPLORING;
15222 }
15223 
15224 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15225 				struct bpf_verifier_env *env,
15226 				bool visit_callee)
15227 {
15228 	int ret, insn_sz;
15229 
15230 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15231 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15232 	if (ret)
15233 		return ret;
15234 
15235 	mark_prune_point(env, t + insn_sz);
15236 	/* when we exit from subprog, we need to record non-linear history */
15237 	mark_jmp_point(env, t + insn_sz);
15238 
15239 	if (visit_callee) {
15240 		mark_prune_point(env, t);
15241 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15242 	}
15243 	return ret;
15244 }
15245 
15246 /* Visits the instruction at index t and returns one of the following:
15247  *  < 0 - an error occurred
15248  *  DONE_EXPLORING - the instruction was fully explored
15249  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15250  */
15251 static int visit_insn(int t, struct bpf_verifier_env *env)
15252 {
15253 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15254 	int ret, off, insn_sz;
15255 
15256 	if (bpf_pseudo_func(insn))
15257 		return visit_func_call_insn(t, insns, env, true);
15258 
15259 	/* All non-branch instructions have a single fall-through edge. */
15260 	if (BPF_CLASS(insn->code) != BPF_JMP &&
15261 	    BPF_CLASS(insn->code) != BPF_JMP32) {
15262 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15263 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15264 	}
15265 
15266 	switch (BPF_OP(insn->code)) {
15267 	case BPF_EXIT:
15268 		return DONE_EXPLORING;
15269 
15270 	case BPF_CALL:
15271 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15272 			/* Mark this call insn as a prune point to trigger
15273 			 * is_state_visited() check before call itself is
15274 			 * processed by __check_func_call(). Otherwise new
15275 			 * async state will be pushed for further exploration.
15276 			 */
15277 			mark_prune_point(env, t);
15278 		/* For functions that invoke callbacks it is not known how many times
15279 		 * callback would be called. Verifier models callback calling functions
15280 		 * by repeatedly visiting callback bodies and returning to origin call
15281 		 * instruction.
15282 		 * In order to stop such iteration verifier needs to identify when a
15283 		 * state identical some state from a previous iteration is reached.
15284 		 * Check below forces creation of checkpoint before callback calling
15285 		 * instruction to allow search for such identical states.
15286 		 */
15287 		if (is_sync_callback_calling_insn(insn)) {
15288 			mark_calls_callback(env, t);
15289 			mark_force_checkpoint(env, t);
15290 			mark_prune_point(env, t);
15291 			mark_jmp_point(env, t);
15292 		}
15293 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15294 			struct bpf_kfunc_call_arg_meta meta;
15295 
15296 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15297 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15298 				mark_prune_point(env, t);
15299 				/* Checking and saving state checkpoints at iter_next() call
15300 				 * is crucial for fast convergence of open-coded iterator loop
15301 				 * logic, so we need to force it. If we don't do that,
15302 				 * is_state_visited() might skip saving a checkpoint, causing
15303 				 * unnecessarily long sequence of not checkpointed
15304 				 * instructions and jumps, leading to exhaustion of jump
15305 				 * history buffer, and potentially other undesired outcomes.
15306 				 * It is expected that with correct open-coded iterators
15307 				 * convergence will happen quickly, so we don't run a risk of
15308 				 * exhausting memory.
15309 				 */
15310 				mark_force_checkpoint(env, t);
15311 			}
15312 		}
15313 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15314 
15315 	case BPF_JA:
15316 		if (BPF_SRC(insn->code) != BPF_K)
15317 			return -EINVAL;
15318 
15319 		if (BPF_CLASS(insn->code) == BPF_JMP)
15320 			off = insn->off;
15321 		else
15322 			off = insn->imm;
15323 
15324 		/* unconditional jump with single edge */
15325 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15326 		if (ret)
15327 			return ret;
15328 
15329 		mark_prune_point(env, t + off + 1);
15330 		mark_jmp_point(env, t + off + 1);
15331 
15332 		return ret;
15333 
15334 	default:
15335 		/* conditional jump with two edges */
15336 		mark_prune_point(env, t);
15337 
15338 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15339 		if (ret)
15340 			return ret;
15341 
15342 		return push_insn(t, t + insn->off + 1, BRANCH, env);
15343 	}
15344 }
15345 
15346 /* non-recursive depth-first-search to detect loops in BPF program
15347  * loop == back-edge in directed graph
15348  */
15349 static int check_cfg(struct bpf_verifier_env *env)
15350 {
15351 	int insn_cnt = env->prog->len;
15352 	int *insn_stack, *insn_state;
15353 	int ret = 0;
15354 	int i;
15355 
15356 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15357 	if (!insn_state)
15358 		return -ENOMEM;
15359 
15360 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15361 	if (!insn_stack) {
15362 		kvfree(insn_state);
15363 		return -ENOMEM;
15364 	}
15365 
15366 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15367 	insn_stack[0] = 0; /* 0 is the first instruction */
15368 	env->cfg.cur_stack = 1;
15369 
15370 	while (env->cfg.cur_stack > 0) {
15371 		int t = insn_stack[env->cfg.cur_stack - 1];
15372 
15373 		ret = visit_insn(t, env);
15374 		switch (ret) {
15375 		case DONE_EXPLORING:
15376 			insn_state[t] = EXPLORED;
15377 			env->cfg.cur_stack--;
15378 			break;
15379 		case KEEP_EXPLORING:
15380 			break;
15381 		default:
15382 			if (ret > 0) {
15383 				verbose(env, "visit_insn internal bug\n");
15384 				ret = -EFAULT;
15385 			}
15386 			goto err_free;
15387 		}
15388 	}
15389 
15390 	if (env->cfg.cur_stack < 0) {
15391 		verbose(env, "pop stack internal bug\n");
15392 		ret = -EFAULT;
15393 		goto err_free;
15394 	}
15395 
15396 	for (i = 0; i < insn_cnt; i++) {
15397 		struct bpf_insn *insn = &env->prog->insnsi[i];
15398 
15399 		if (insn_state[i] != EXPLORED) {
15400 			verbose(env, "unreachable insn %d\n", i);
15401 			ret = -EINVAL;
15402 			goto err_free;
15403 		}
15404 		if (bpf_is_ldimm64(insn)) {
15405 			if (insn_state[i + 1] != 0) {
15406 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15407 				ret = -EINVAL;
15408 				goto err_free;
15409 			}
15410 			i++; /* skip second half of ldimm64 */
15411 		}
15412 	}
15413 	ret = 0; /* cfg looks good */
15414 
15415 err_free:
15416 	kvfree(insn_state);
15417 	kvfree(insn_stack);
15418 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
15419 	return ret;
15420 }
15421 
15422 static int check_abnormal_return(struct bpf_verifier_env *env)
15423 {
15424 	int i;
15425 
15426 	for (i = 1; i < env->subprog_cnt; i++) {
15427 		if (env->subprog_info[i].has_ld_abs) {
15428 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15429 			return -EINVAL;
15430 		}
15431 		if (env->subprog_info[i].has_tail_call) {
15432 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15433 			return -EINVAL;
15434 		}
15435 	}
15436 	return 0;
15437 }
15438 
15439 /* The minimum supported BTF func info size */
15440 #define MIN_BPF_FUNCINFO_SIZE	8
15441 #define MAX_FUNCINFO_REC_SIZE	252
15442 
15443 static int check_btf_func(struct bpf_verifier_env *env,
15444 			  const union bpf_attr *attr,
15445 			  bpfptr_t uattr)
15446 {
15447 	const struct btf_type *type, *func_proto, *ret_type;
15448 	u32 i, nfuncs, urec_size, min_size;
15449 	u32 krec_size = sizeof(struct bpf_func_info);
15450 	struct bpf_func_info *krecord;
15451 	struct bpf_func_info_aux *info_aux = NULL;
15452 	struct bpf_prog *prog;
15453 	const struct btf *btf;
15454 	bpfptr_t urecord;
15455 	u32 prev_offset = 0;
15456 	bool scalar_return;
15457 	int ret = -ENOMEM;
15458 
15459 	nfuncs = attr->func_info_cnt;
15460 	if (!nfuncs) {
15461 		if (check_abnormal_return(env))
15462 			return -EINVAL;
15463 		return 0;
15464 	}
15465 
15466 	if (nfuncs != env->subprog_cnt) {
15467 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15468 		return -EINVAL;
15469 	}
15470 
15471 	urec_size = attr->func_info_rec_size;
15472 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15473 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
15474 	    urec_size % sizeof(u32)) {
15475 		verbose(env, "invalid func info rec size %u\n", urec_size);
15476 		return -EINVAL;
15477 	}
15478 
15479 	prog = env->prog;
15480 	btf = prog->aux->btf;
15481 
15482 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15483 	min_size = min_t(u32, krec_size, urec_size);
15484 
15485 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15486 	if (!krecord)
15487 		return -ENOMEM;
15488 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15489 	if (!info_aux)
15490 		goto err_free;
15491 
15492 	for (i = 0; i < nfuncs; i++) {
15493 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15494 		if (ret) {
15495 			if (ret == -E2BIG) {
15496 				verbose(env, "nonzero tailing record in func info");
15497 				/* set the size kernel expects so loader can zero
15498 				 * out the rest of the record.
15499 				 */
15500 				if (copy_to_bpfptr_offset(uattr,
15501 							  offsetof(union bpf_attr, func_info_rec_size),
15502 							  &min_size, sizeof(min_size)))
15503 					ret = -EFAULT;
15504 			}
15505 			goto err_free;
15506 		}
15507 
15508 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15509 			ret = -EFAULT;
15510 			goto err_free;
15511 		}
15512 
15513 		/* check insn_off */
15514 		ret = -EINVAL;
15515 		if (i == 0) {
15516 			if (krecord[i].insn_off) {
15517 				verbose(env,
15518 					"nonzero insn_off %u for the first func info record",
15519 					krecord[i].insn_off);
15520 				goto err_free;
15521 			}
15522 		} else if (krecord[i].insn_off <= prev_offset) {
15523 			verbose(env,
15524 				"same or smaller insn offset (%u) than previous func info record (%u)",
15525 				krecord[i].insn_off, prev_offset);
15526 			goto err_free;
15527 		}
15528 
15529 		if (env->subprog_info[i].start != krecord[i].insn_off) {
15530 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15531 			goto err_free;
15532 		}
15533 
15534 		/* check type_id */
15535 		type = btf_type_by_id(btf, krecord[i].type_id);
15536 		if (!type || !btf_type_is_func(type)) {
15537 			verbose(env, "invalid type id %d in func info",
15538 				krecord[i].type_id);
15539 			goto err_free;
15540 		}
15541 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15542 
15543 		func_proto = btf_type_by_id(btf, type->type);
15544 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15545 			/* btf_func_check() already verified it during BTF load */
15546 			goto err_free;
15547 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15548 		scalar_return =
15549 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15550 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15551 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15552 			goto err_free;
15553 		}
15554 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15555 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15556 			goto err_free;
15557 		}
15558 
15559 		prev_offset = krecord[i].insn_off;
15560 		bpfptr_add(&urecord, urec_size);
15561 	}
15562 
15563 	prog->aux->func_info = krecord;
15564 	prog->aux->func_info_cnt = nfuncs;
15565 	prog->aux->func_info_aux = info_aux;
15566 	return 0;
15567 
15568 err_free:
15569 	kvfree(krecord);
15570 	kfree(info_aux);
15571 	return ret;
15572 }
15573 
15574 static void adjust_btf_func(struct bpf_verifier_env *env)
15575 {
15576 	struct bpf_prog_aux *aux = env->prog->aux;
15577 	int i;
15578 
15579 	if (!aux->func_info)
15580 		return;
15581 
15582 	for (i = 0; i < env->subprog_cnt; i++)
15583 		aux->func_info[i].insn_off = env->subprog_info[i].start;
15584 }
15585 
15586 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
15587 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
15588 
15589 static int check_btf_line(struct bpf_verifier_env *env,
15590 			  const union bpf_attr *attr,
15591 			  bpfptr_t uattr)
15592 {
15593 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15594 	struct bpf_subprog_info *sub;
15595 	struct bpf_line_info *linfo;
15596 	struct bpf_prog *prog;
15597 	const struct btf *btf;
15598 	bpfptr_t ulinfo;
15599 	int err;
15600 
15601 	nr_linfo = attr->line_info_cnt;
15602 	if (!nr_linfo)
15603 		return 0;
15604 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15605 		return -EINVAL;
15606 
15607 	rec_size = attr->line_info_rec_size;
15608 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15609 	    rec_size > MAX_LINEINFO_REC_SIZE ||
15610 	    rec_size & (sizeof(u32) - 1))
15611 		return -EINVAL;
15612 
15613 	/* Need to zero it in case the userspace may
15614 	 * pass in a smaller bpf_line_info object.
15615 	 */
15616 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15617 			 GFP_KERNEL | __GFP_NOWARN);
15618 	if (!linfo)
15619 		return -ENOMEM;
15620 
15621 	prog = env->prog;
15622 	btf = prog->aux->btf;
15623 
15624 	s = 0;
15625 	sub = env->subprog_info;
15626 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15627 	expected_size = sizeof(struct bpf_line_info);
15628 	ncopy = min_t(u32, expected_size, rec_size);
15629 	for (i = 0; i < nr_linfo; i++) {
15630 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15631 		if (err) {
15632 			if (err == -E2BIG) {
15633 				verbose(env, "nonzero tailing record in line_info");
15634 				if (copy_to_bpfptr_offset(uattr,
15635 							  offsetof(union bpf_attr, line_info_rec_size),
15636 							  &expected_size, sizeof(expected_size)))
15637 					err = -EFAULT;
15638 			}
15639 			goto err_free;
15640 		}
15641 
15642 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15643 			err = -EFAULT;
15644 			goto err_free;
15645 		}
15646 
15647 		/*
15648 		 * Check insn_off to ensure
15649 		 * 1) strictly increasing AND
15650 		 * 2) bounded by prog->len
15651 		 *
15652 		 * The linfo[0].insn_off == 0 check logically falls into
15653 		 * the later "missing bpf_line_info for func..." case
15654 		 * because the first linfo[0].insn_off must be the
15655 		 * first sub also and the first sub must have
15656 		 * subprog_info[0].start == 0.
15657 		 */
15658 		if ((i && linfo[i].insn_off <= prev_offset) ||
15659 		    linfo[i].insn_off >= prog->len) {
15660 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15661 				i, linfo[i].insn_off, prev_offset,
15662 				prog->len);
15663 			err = -EINVAL;
15664 			goto err_free;
15665 		}
15666 
15667 		if (!prog->insnsi[linfo[i].insn_off].code) {
15668 			verbose(env,
15669 				"Invalid insn code at line_info[%u].insn_off\n",
15670 				i);
15671 			err = -EINVAL;
15672 			goto err_free;
15673 		}
15674 
15675 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15676 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15677 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15678 			err = -EINVAL;
15679 			goto err_free;
15680 		}
15681 
15682 		if (s != env->subprog_cnt) {
15683 			if (linfo[i].insn_off == sub[s].start) {
15684 				sub[s].linfo_idx = i;
15685 				s++;
15686 			} else if (sub[s].start < linfo[i].insn_off) {
15687 				verbose(env, "missing bpf_line_info for func#%u\n", s);
15688 				err = -EINVAL;
15689 				goto err_free;
15690 			}
15691 		}
15692 
15693 		prev_offset = linfo[i].insn_off;
15694 		bpfptr_add(&ulinfo, rec_size);
15695 	}
15696 
15697 	if (s != env->subprog_cnt) {
15698 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15699 			env->subprog_cnt - s, s);
15700 		err = -EINVAL;
15701 		goto err_free;
15702 	}
15703 
15704 	prog->aux->linfo = linfo;
15705 	prog->aux->nr_linfo = nr_linfo;
15706 
15707 	return 0;
15708 
15709 err_free:
15710 	kvfree(linfo);
15711 	return err;
15712 }
15713 
15714 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
15715 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
15716 
15717 static int check_core_relo(struct bpf_verifier_env *env,
15718 			   const union bpf_attr *attr,
15719 			   bpfptr_t uattr)
15720 {
15721 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15722 	struct bpf_core_relo core_relo = {};
15723 	struct bpf_prog *prog = env->prog;
15724 	const struct btf *btf = prog->aux->btf;
15725 	struct bpf_core_ctx ctx = {
15726 		.log = &env->log,
15727 		.btf = btf,
15728 	};
15729 	bpfptr_t u_core_relo;
15730 	int err;
15731 
15732 	nr_core_relo = attr->core_relo_cnt;
15733 	if (!nr_core_relo)
15734 		return 0;
15735 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15736 		return -EINVAL;
15737 
15738 	rec_size = attr->core_relo_rec_size;
15739 	if (rec_size < MIN_CORE_RELO_SIZE ||
15740 	    rec_size > MAX_CORE_RELO_SIZE ||
15741 	    rec_size % sizeof(u32))
15742 		return -EINVAL;
15743 
15744 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15745 	expected_size = sizeof(struct bpf_core_relo);
15746 	ncopy = min_t(u32, expected_size, rec_size);
15747 
15748 	/* Unlike func_info and line_info, copy and apply each CO-RE
15749 	 * relocation record one at a time.
15750 	 */
15751 	for (i = 0; i < nr_core_relo; i++) {
15752 		/* future proofing when sizeof(bpf_core_relo) changes */
15753 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15754 		if (err) {
15755 			if (err == -E2BIG) {
15756 				verbose(env, "nonzero tailing record in core_relo");
15757 				if (copy_to_bpfptr_offset(uattr,
15758 							  offsetof(union bpf_attr, core_relo_rec_size),
15759 							  &expected_size, sizeof(expected_size)))
15760 					err = -EFAULT;
15761 			}
15762 			break;
15763 		}
15764 
15765 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15766 			err = -EFAULT;
15767 			break;
15768 		}
15769 
15770 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15771 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15772 				i, core_relo.insn_off, prog->len);
15773 			err = -EINVAL;
15774 			break;
15775 		}
15776 
15777 		err = bpf_core_apply(&ctx, &core_relo, i,
15778 				     &prog->insnsi[core_relo.insn_off / 8]);
15779 		if (err)
15780 			break;
15781 		bpfptr_add(&u_core_relo, rec_size);
15782 	}
15783 	return err;
15784 }
15785 
15786 static int check_btf_info(struct bpf_verifier_env *env,
15787 			  const union bpf_attr *attr,
15788 			  bpfptr_t uattr)
15789 {
15790 	struct btf *btf;
15791 	int err;
15792 
15793 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
15794 		if (check_abnormal_return(env))
15795 			return -EINVAL;
15796 		return 0;
15797 	}
15798 
15799 	btf = btf_get_by_fd(attr->prog_btf_fd);
15800 	if (IS_ERR(btf))
15801 		return PTR_ERR(btf);
15802 	if (btf_is_kernel(btf)) {
15803 		btf_put(btf);
15804 		return -EACCES;
15805 	}
15806 	env->prog->aux->btf = btf;
15807 
15808 	err = check_btf_func(env, attr, uattr);
15809 	if (err)
15810 		return err;
15811 
15812 	err = check_btf_line(env, attr, uattr);
15813 	if (err)
15814 		return err;
15815 
15816 	err = check_core_relo(env, attr, uattr);
15817 	if (err)
15818 		return err;
15819 
15820 	return 0;
15821 }
15822 
15823 /* check %cur's range satisfies %old's */
15824 static bool range_within(struct bpf_reg_state *old,
15825 			 struct bpf_reg_state *cur)
15826 {
15827 	return old->umin_value <= cur->umin_value &&
15828 	       old->umax_value >= cur->umax_value &&
15829 	       old->smin_value <= cur->smin_value &&
15830 	       old->smax_value >= cur->smax_value &&
15831 	       old->u32_min_value <= cur->u32_min_value &&
15832 	       old->u32_max_value >= cur->u32_max_value &&
15833 	       old->s32_min_value <= cur->s32_min_value &&
15834 	       old->s32_max_value >= cur->s32_max_value;
15835 }
15836 
15837 /* If in the old state two registers had the same id, then they need to have
15838  * the same id in the new state as well.  But that id could be different from
15839  * the old state, so we need to track the mapping from old to new ids.
15840  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15841  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15842  * regs with a different old id could still have new id 9, we don't care about
15843  * that.
15844  * So we look through our idmap to see if this old id has been seen before.  If
15845  * so, we require the new id to match; otherwise, we add the id pair to the map.
15846  */
15847 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15848 {
15849 	struct bpf_id_pair *map = idmap->map;
15850 	unsigned int i;
15851 
15852 	/* either both IDs should be set or both should be zero */
15853 	if (!!old_id != !!cur_id)
15854 		return false;
15855 
15856 	if (old_id == 0) /* cur_id == 0 as well */
15857 		return true;
15858 
15859 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15860 		if (!map[i].old) {
15861 			/* Reached an empty slot; haven't seen this id before */
15862 			map[i].old = old_id;
15863 			map[i].cur = cur_id;
15864 			return true;
15865 		}
15866 		if (map[i].old == old_id)
15867 			return map[i].cur == cur_id;
15868 		if (map[i].cur == cur_id)
15869 			return false;
15870 	}
15871 	/* We ran out of idmap slots, which should be impossible */
15872 	WARN_ON_ONCE(1);
15873 	return false;
15874 }
15875 
15876 /* Similar to check_ids(), but allocate a unique temporary ID
15877  * for 'old_id' or 'cur_id' of zero.
15878  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15879  */
15880 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15881 {
15882 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15883 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15884 
15885 	return check_ids(old_id, cur_id, idmap);
15886 }
15887 
15888 static void clean_func_state(struct bpf_verifier_env *env,
15889 			     struct bpf_func_state *st)
15890 {
15891 	enum bpf_reg_liveness live;
15892 	int i, j;
15893 
15894 	for (i = 0; i < BPF_REG_FP; i++) {
15895 		live = st->regs[i].live;
15896 		/* liveness must not touch this register anymore */
15897 		st->regs[i].live |= REG_LIVE_DONE;
15898 		if (!(live & REG_LIVE_READ))
15899 			/* since the register is unused, clear its state
15900 			 * to make further comparison simpler
15901 			 */
15902 			__mark_reg_not_init(env, &st->regs[i]);
15903 	}
15904 
15905 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15906 		live = st->stack[i].spilled_ptr.live;
15907 		/* liveness must not touch this stack slot anymore */
15908 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15909 		if (!(live & REG_LIVE_READ)) {
15910 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15911 			for (j = 0; j < BPF_REG_SIZE; j++)
15912 				st->stack[i].slot_type[j] = STACK_INVALID;
15913 		}
15914 	}
15915 }
15916 
15917 static void clean_verifier_state(struct bpf_verifier_env *env,
15918 				 struct bpf_verifier_state *st)
15919 {
15920 	int i;
15921 
15922 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15923 		/* all regs in this state in all frames were already marked */
15924 		return;
15925 
15926 	for (i = 0; i <= st->curframe; i++)
15927 		clean_func_state(env, st->frame[i]);
15928 }
15929 
15930 /* the parentage chains form a tree.
15931  * the verifier states are added to state lists at given insn and
15932  * pushed into state stack for future exploration.
15933  * when the verifier reaches bpf_exit insn some of the verifer states
15934  * stored in the state lists have their final liveness state already,
15935  * but a lot of states will get revised from liveness point of view when
15936  * the verifier explores other branches.
15937  * Example:
15938  * 1: r0 = 1
15939  * 2: if r1 == 100 goto pc+1
15940  * 3: r0 = 2
15941  * 4: exit
15942  * when the verifier reaches exit insn the register r0 in the state list of
15943  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15944  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15945  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15946  *
15947  * Since the verifier pushes the branch states as it sees them while exploring
15948  * the program the condition of walking the branch instruction for the second
15949  * time means that all states below this branch were already explored and
15950  * their final liveness marks are already propagated.
15951  * Hence when the verifier completes the search of state list in is_state_visited()
15952  * we can call this clean_live_states() function to mark all liveness states
15953  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15954  * will not be used.
15955  * This function also clears the registers and stack for states that !READ
15956  * to simplify state merging.
15957  *
15958  * Important note here that walking the same branch instruction in the callee
15959  * doesn't meant that the states are DONE. The verifier has to compare
15960  * the callsites
15961  */
15962 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15963 			      struct bpf_verifier_state *cur)
15964 {
15965 	struct bpf_verifier_state_list *sl;
15966 
15967 	sl = *explored_state(env, insn);
15968 	while (sl) {
15969 		if (sl->state.branches)
15970 			goto next;
15971 		if (sl->state.insn_idx != insn ||
15972 		    !same_callsites(&sl->state, cur))
15973 			goto next;
15974 		clean_verifier_state(env, &sl->state);
15975 next:
15976 		sl = sl->next;
15977 	}
15978 }
15979 
15980 static bool regs_exact(const struct bpf_reg_state *rold,
15981 		       const struct bpf_reg_state *rcur,
15982 		       struct bpf_idmap *idmap)
15983 {
15984 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15985 	       check_ids(rold->id, rcur->id, idmap) &&
15986 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15987 }
15988 
15989 /* Returns true if (rold safe implies rcur safe) */
15990 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15991 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
15992 {
15993 	if (exact)
15994 		return regs_exact(rold, rcur, idmap);
15995 
15996 	if (!(rold->live & REG_LIVE_READ))
15997 		/* explored state didn't use this */
15998 		return true;
15999 	if (rold->type == NOT_INIT)
16000 		/* explored state can't have used this */
16001 		return true;
16002 	if (rcur->type == NOT_INIT)
16003 		return false;
16004 
16005 	/* Enforce that register types have to match exactly, including their
16006 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16007 	 * rule.
16008 	 *
16009 	 * One can make a point that using a pointer register as unbounded
16010 	 * SCALAR would be technically acceptable, but this could lead to
16011 	 * pointer leaks because scalars are allowed to leak while pointers
16012 	 * are not. We could make this safe in special cases if root is
16013 	 * calling us, but it's probably not worth the hassle.
16014 	 *
16015 	 * Also, register types that are *not* MAYBE_NULL could technically be
16016 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16017 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16018 	 * to the same map).
16019 	 * However, if the old MAYBE_NULL register then got NULL checked,
16020 	 * doing so could have affected others with the same id, and we can't
16021 	 * check for that because we lost the id when we converted to
16022 	 * a non-MAYBE_NULL variant.
16023 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
16024 	 * non-MAYBE_NULL registers as well.
16025 	 */
16026 	if (rold->type != rcur->type)
16027 		return false;
16028 
16029 	switch (base_type(rold->type)) {
16030 	case SCALAR_VALUE:
16031 		if (env->explore_alu_limits) {
16032 			/* explore_alu_limits disables tnum_in() and range_within()
16033 			 * logic and requires everything to be strict
16034 			 */
16035 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16036 			       check_scalar_ids(rold->id, rcur->id, idmap);
16037 		}
16038 		if (!rold->precise)
16039 			return true;
16040 		/* Why check_ids() for scalar registers?
16041 		 *
16042 		 * Consider the following BPF code:
16043 		 *   1: r6 = ... unbound scalar, ID=a ...
16044 		 *   2: r7 = ... unbound scalar, ID=b ...
16045 		 *   3: if (r6 > r7) goto +1
16046 		 *   4: r6 = r7
16047 		 *   5: if (r6 > X) goto ...
16048 		 *   6: ... memory operation using r7 ...
16049 		 *
16050 		 * First verification path is [1-6]:
16051 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16052 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16053 		 *   r7 <= X, because r6 and r7 share same id.
16054 		 * Next verification path is [1-4, 6].
16055 		 *
16056 		 * Instruction (6) would be reached in two states:
16057 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16058 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16059 		 *
16060 		 * Use check_ids() to distinguish these states.
16061 		 * ---
16062 		 * Also verify that new value satisfies old value range knowledge.
16063 		 */
16064 		return range_within(rold, rcur) &&
16065 		       tnum_in(rold->var_off, rcur->var_off) &&
16066 		       check_scalar_ids(rold->id, rcur->id, idmap);
16067 	case PTR_TO_MAP_KEY:
16068 	case PTR_TO_MAP_VALUE:
16069 	case PTR_TO_MEM:
16070 	case PTR_TO_BUF:
16071 	case PTR_TO_TP_BUFFER:
16072 		/* If the new min/max/var_off satisfy the old ones and
16073 		 * everything else matches, we are OK.
16074 		 */
16075 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16076 		       range_within(rold, rcur) &&
16077 		       tnum_in(rold->var_off, rcur->var_off) &&
16078 		       check_ids(rold->id, rcur->id, idmap) &&
16079 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16080 	case PTR_TO_PACKET_META:
16081 	case PTR_TO_PACKET:
16082 		/* We must have at least as much range as the old ptr
16083 		 * did, so that any accesses which were safe before are
16084 		 * still safe.  This is true even if old range < old off,
16085 		 * since someone could have accessed through (ptr - k), or
16086 		 * even done ptr -= k in a register, to get a safe access.
16087 		 */
16088 		if (rold->range > rcur->range)
16089 			return false;
16090 		/* If the offsets don't match, we can't trust our alignment;
16091 		 * nor can we be sure that we won't fall out of range.
16092 		 */
16093 		if (rold->off != rcur->off)
16094 			return false;
16095 		/* id relations must be preserved */
16096 		if (!check_ids(rold->id, rcur->id, idmap))
16097 			return false;
16098 		/* new val must satisfy old val knowledge */
16099 		return range_within(rold, rcur) &&
16100 		       tnum_in(rold->var_off, rcur->var_off);
16101 	case PTR_TO_STACK:
16102 		/* two stack pointers are equal only if they're pointing to
16103 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16104 		 */
16105 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16106 	default:
16107 		return regs_exact(rold, rcur, idmap);
16108 	}
16109 }
16110 
16111 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16112 		      struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16113 {
16114 	int i, spi;
16115 
16116 	/* walk slots of the explored stack and ignore any additional
16117 	 * slots in the current stack, since explored(safe) state
16118 	 * didn't use them
16119 	 */
16120 	for (i = 0; i < old->allocated_stack; i++) {
16121 		struct bpf_reg_state *old_reg, *cur_reg;
16122 
16123 		spi = i / BPF_REG_SIZE;
16124 
16125 		if (exact &&
16126 		    (i >= cur->allocated_stack ||
16127 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16128 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
16129 			return false;
16130 
16131 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16132 			i += BPF_REG_SIZE - 1;
16133 			/* explored state didn't use this */
16134 			continue;
16135 		}
16136 
16137 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16138 			continue;
16139 
16140 		if (env->allow_uninit_stack &&
16141 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16142 			continue;
16143 
16144 		/* explored stack has more populated slots than current stack
16145 		 * and these slots were used
16146 		 */
16147 		if (i >= cur->allocated_stack)
16148 			return false;
16149 
16150 		/* if old state was safe with misc data in the stack
16151 		 * it will be safe with zero-initialized stack.
16152 		 * The opposite is not true
16153 		 */
16154 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16155 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16156 			continue;
16157 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16158 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16159 			/* Ex: old explored (safe) state has STACK_SPILL in
16160 			 * this stack slot, but current has STACK_MISC ->
16161 			 * this verifier states are not equivalent,
16162 			 * return false to continue verification of this path
16163 			 */
16164 			return false;
16165 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16166 			continue;
16167 		/* Both old and cur are having same slot_type */
16168 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16169 		case STACK_SPILL:
16170 			/* when explored and current stack slot are both storing
16171 			 * spilled registers, check that stored pointers types
16172 			 * are the same as well.
16173 			 * Ex: explored safe path could have stored
16174 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16175 			 * but current path has stored:
16176 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16177 			 * such verifier states are not equivalent.
16178 			 * return false to continue verification of this path
16179 			 */
16180 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16181 				     &cur->stack[spi].spilled_ptr, idmap, exact))
16182 				return false;
16183 			break;
16184 		case STACK_DYNPTR:
16185 			old_reg = &old->stack[spi].spilled_ptr;
16186 			cur_reg = &cur->stack[spi].spilled_ptr;
16187 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16188 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16189 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16190 				return false;
16191 			break;
16192 		case STACK_ITER:
16193 			old_reg = &old->stack[spi].spilled_ptr;
16194 			cur_reg = &cur->stack[spi].spilled_ptr;
16195 			/* iter.depth is not compared between states as it
16196 			 * doesn't matter for correctness and would otherwise
16197 			 * prevent convergence; we maintain it only to prevent
16198 			 * infinite loop check triggering, see
16199 			 * iter_active_depths_differ()
16200 			 */
16201 			if (old_reg->iter.btf != cur_reg->iter.btf ||
16202 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16203 			    old_reg->iter.state != cur_reg->iter.state ||
16204 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16205 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16206 				return false;
16207 			break;
16208 		case STACK_MISC:
16209 		case STACK_ZERO:
16210 		case STACK_INVALID:
16211 			continue;
16212 		/* Ensure that new unhandled slot types return false by default */
16213 		default:
16214 			return false;
16215 		}
16216 	}
16217 	return true;
16218 }
16219 
16220 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16221 		    struct bpf_idmap *idmap)
16222 {
16223 	int i;
16224 
16225 	if (old->acquired_refs != cur->acquired_refs)
16226 		return false;
16227 
16228 	for (i = 0; i < old->acquired_refs; i++) {
16229 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16230 			return false;
16231 	}
16232 
16233 	return true;
16234 }
16235 
16236 /* compare two verifier states
16237  *
16238  * all states stored in state_list are known to be valid, since
16239  * verifier reached 'bpf_exit' instruction through them
16240  *
16241  * this function is called when verifier exploring different branches of
16242  * execution popped from the state stack. If it sees an old state that has
16243  * more strict register state and more strict stack state then this execution
16244  * branch doesn't need to be explored further, since verifier already
16245  * concluded that more strict state leads to valid finish.
16246  *
16247  * Therefore two states are equivalent if register state is more conservative
16248  * and explored stack state is more conservative than the current one.
16249  * Example:
16250  *       explored                   current
16251  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16252  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16253  *
16254  * In other words if current stack state (one being explored) has more
16255  * valid slots than old one that already passed validation, it means
16256  * the verifier can stop exploring and conclude that current state is valid too
16257  *
16258  * Similarly with registers. If explored state has register type as invalid
16259  * whereas register type in current state is meaningful, it means that
16260  * the current state will reach 'bpf_exit' instruction safely
16261  */
16262 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16263 			      struct bpf_func_state *cur, bool exact)
16264 {
16265 	int i;
16266 
16267 	if (old->callback_depth > cur->callback_depth)
16268 		return false;
16269 
16270 	for (i = 0; i < MAX_BPF_REG; i++)
16271 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
16272 			     &env->idmap_scratch, exact))
16273 			return false;
16274 
16275 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16276 		return false;
16277 
16278 	if (!refsafe(old, cur, &env->idmap_scratch))
16279 		return false;
16280 
16281 	return true;
16282 }
16283 
16284 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16285 {
16286 	env->idmap_scratch.tmp_id_gen = env->id_gen;
16287 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16288 }
16289 
16290 static bool states_equal(struct bpf_verifier_env *env,
16291 			 struct bpf_verifier_state *old,
16292 			 struct bpf_verifier_state *cur,
16293 			 bool exact)
16294 {
16295 	int i;
16296 
16297 	if (old->curframe != cur->curframe)
16298 		return false;
16299 
16300 	reset_idmap_scratch(env);
16301 
16302 	/* Verification state from speculative execution simulation
16303 	 * must never prune a non-speculative execution one.
16304 	 */
16305 	if (old->speculative && !cur->speculative)
16306 		return false;
16307 
16308 	if (old->active_lock.ptr != cur->active_lock.ptr)
16309 		return false;
16310 
16311 	/* Old and cur active_lock's have to be either both present
16312 	 * or both absent.
16313 	 */
16314 	if (!!old->active_lock.id != !!cur->active_lock.id)
16315 		return false;
16316 
16317 	if (old->active_lock.id &&
16318 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16319 		return false;
16320 
16321 	if (old->active_rcu_lock != cur->active_rcu_lock)
16322 		return false;
16323 
16324 	/* for states to be equal callsites have to be the same
16325 	 * and all frame states need to be equivalent
16326 	 */
16327 	for (i = 0; i <= old->curframe; i++) {
16328 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
16329 			return false;
16330 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16331 			return false;
16332 	}
16333 	return true;
16334 }
16335 
16336 /* Return 0 if no propagation happened. Return negative error code if error
16337  * happened. Otherwise, return the propagated bit.
16338  */
16339 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16340 				  struct bpf_reg_state *reg,
16341 				  struct bpf_reg_state *parent_reg)
16342 {
16343 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16344 	u8 flag = reg->live & REG_LIVE_READ;
16345 	int err;
16346 
16347 	/* When comes here, read flags of PARENT_REG or REG could be any of
16348 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16349 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16350 	 */
16351 	if (parent_flag == REG_LIVE_READ64 ||
16352 	    /* Or if there is no read flag from REG. */
16353 	    !flag ||
16354 	    /* Or if the read flag from REG is the same as PARENT_REG. */
16355 	    parent_flag == flag)
16356 		return 0;
16357 
16358 	err = mark_reg_read(env, reg, parent_reg, flag);
16359 	if (err)
16360 		return err;
16361 
16362 	return flag;
16363 }
16364 
16365 /* A write screens off any subsequent reads; but write marks come from the
16366  * straight-line code between a state and its parent.  When we arrive at an
16367  * equivalent state (jump target or such) we didn't arrive by the straight-line
16368  * code, so read marks in the state must propagate to the parent regardless
16369  * of the state's write marks. That's what 'parent == state->parent' comparison
16370  * in mark_reg_read() is for.
16371  */
16372 static int propagate_liveness(struct bpf_verifier_env *env,
16373 			      const struct bpf_verifier_state *vstate,
16374 			      struct bpf_verifier_state *vparent)
16375 {
16376 	struct bpf_reg_state *state_reg, *parent_reg;
16377 	struct bpf_func_state *state, *parent;
16378 	int i, frame, err = 0;
16379 
16380 	if (vparent->curframe != vstate->curframe) {
16381 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
16382 		     vparent->curframe, vstate->curframe);
16383 		return -EFAULT;
16384 	}
16385 	/* Propagate read liveness of registers... */
16386 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16387 	for (frame = 0; frame <= vstate->curframe; frame++) {
16388 		parent = vparent->frame[frame];
16389 		state = vstate->frame[frame];
16390 		parent_reg = parent->regs;
16391 		state_reg = state->regs;
16392 		/* We don't need to worry about FP liveness, it's read-only */
16393 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16394 			err = propagate_liveness_reg(env, &state_reg[i],
16395 						     &parent_reg[i]);
16396 			if (err < 0)
16397 				return err;
16398 			if (err == REG_LIVE_READ64)
16399 				mark_insn_zext(env, &parent_reg[i]);
16400 		}
16401 
16402 		/* Propagate stack slots. */
16403 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16404 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16405 			parent_reg = &parent->stack[i].spilled_ptr;
16406 			state_reg = &state->stack[i].spilled_ptr;
16407 			err = propagate_liveness_reg(env, state_reg,
16408 						     parent_reg);
16409 			if (err < 0)
16410 				return err;
16411 		}
16412 	}
16413 	return 0;
16414 }
16415 
16416 /* find precise scalars in the previous equivalent state and
16417  * propagate them into the current state
16418  */
16419 static int propagate_precision(struct bpf_verifier_env *env,
16420 			       const struct bpf_verifier_state *old)
16421 {
16422 	struct bpf_reg_state *state_reg;
16423 	struct bpf_func_state *state;
16424 	int i, err = 0, fr;
16425 	bool first;
16426 
16427 	for (fr = old->curframe; fr >= 0; fr--) {
16428 		state = old->frame[fr];
16429 		state_reg = state->regs;
16430 		first = true;
16431 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16432 			if (state_reg->type != SCALAR_VALUE ||
16433 			    !state_reg->precise ||
16434 			    !(state_reg->live & REG_LIVE_READ))
16435 				continue;
16436 			if (env->log.level & BPF_LOG_LEVEL2) {
16437 				if (first)
16438 					verbose(env, "frame %d: propagating r%d", fr, i);
16439 				else
16440 					verbose(env, ",r%d", i);
16441 			}
16442 			bt_set_frame_reg(&env->bt, fr, i);
16443 			first = false;
16444 		}
16445 
16446 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16447 			if (!is_spilled_reg(&state->stack[i]))
16448 				continue;
16449 			state_reg = &state->stack[i].spilled_ptr;
16450 			if (state_reg->type != SCALAR_VALUE ||
16451 			    !state_reg->precise ||
16452 			    !(state_reg->live & REG_LIVE_READ))
16453 				continue;
16454 			if (env->log.level & BPF_LOG_LEVEL2) {
16455 				if (first)
16456 					verbose(env, "frame %d: propagating fp%d",
16457 						fr, (-i - 1) * BPF_REG_SIZE);
16458 				else
16459 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16460 			}
16461 			bt_set_frame_slot(&env->bt, fr, i);
16462 			first = false;
16463 		}
16464 		if (!first)
16465 			verbose(env, "\n");
16466 	}
16467 
16468 	err = mark_chain_precision_batch(env);
16469 	if (err < 0)
16470 		return err;
16471 
16472 	return 0;
16473 }
16474 
16475 static bool states_maybe_looping(struct bpf_verifier_state *old,
16476 				 struct bpf_verifier_state *cur)
16477 {
16478 	struct bpf_func_state *fold, *fcur;
16479 	int i, fr = cur->curframe;
16480 
16481 	if (old->curframe != fr)
16482 		return false;
16483 
16484 	fold = old->frame[fr];
16485 	fcur = cur->frame[fr];
16486 	for (i = 0; i < MAX_BPF_REG; i++)
16487 		if (memcmp(&fold->regs[i], &fcur->regs[i],
16488 			   offsetof(struct bpf_reg_state, parent)))
16489 			return false;
16490 	return true;
16491 }
16492 
16493 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16494 {
16495 	return env->insn_aux_data[insn_idx].is_iter_next;
16496 }
16497 
16498 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16499  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16500  * states to match, which otherwise would look like an infinite loop. So while
16501  * iter_next() calls are taken care of, we still need to be careful and
16502  * prevent erroneous and too eager declaration of "ininite loop", when
16503  * iterators are involved.
16504  *
16505  * Here's a situation in pseudo-BPF assembly form:
16506  *
16507  *   0: again:                          ; set up iter_next() call args
16508  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16509  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16510  *   3:   if r0 == 0 goto done
16511  *   4:   ... something useful here ...
16512  *   5:   goto again                    ; another iteration
16513  *   6: done:
16514  *   7:   r1 = &it
16515  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16516  *   9:   exit
16517  *
16518  * This is a typical loop. Let's assume that we have a prune point at 1:,
16519  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16520  * again`, assuming other heuristics don't get in a way).
16521  *
16522  * When we first time come to 1:, let's say we have some state X. We proceed
16523  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16524  * Now we come back to validate that forked ACTIVE state. We proceed through
16525  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16526  * are converging. But the problem is that we don't know that yet, as this
16527  * convergence has to happen at iter_next() call site only. So if nothing is
16528  * done, at 1: verifier will use bounded loop logic and declare infinite
16529  * looping (and would be *technically* correct, if not for iterator's
16530  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16531  * don't want that. So what we do in process_iter_next_call() when we go on
16532  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16533  * a different iteration. So when we suspect an infinite loop, we additionally
16534  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16535  * pretend we are not looping and wait for next iter_next() call.
16536  *
16537  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16538  * loop, because that would actually mean infinite loop, as DRAINED state is
16539  * "sticky", and so we'll keep returning into the same instruction with the
16540  * same state (at least in one of possible code paths).
16541  *
16542  * This approach allows to keep infinite loop heuristic even in the face of
16543  * active iterator. E.g., C snippet below is and will be detected as
16544  * inifintely looping:
16545  *
16546  *   struct bpf_iter_num it;
16547  *   int *p, x;
16548  *
16549  *   bpf_iter_num_new(&it, 0, 10);
16550  *   while ((p = bpf_iter_num_next(&t))) {
16551  *       x = p;
16552  *       while (x--) {} // <<-- infinite loop here
16553  *   }
16554  *
16555  */
16556 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16557 {
16558 	struct bpf_reg_state *slot, *cur_slot;
16559 	struct bpf_func_state *state;
16560 	int i, fr;
16561 
16562 	for (fr = old->curframe; fr >= 0; fr--) {
16563 		state = old->frame[fr];
16564 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16565 			if (state->stack[i].slot_type[0] != STACK_ITER)
16566 				continue;
16567 
16568 			slot = &state->stack[i].spilled_ptr;
16569 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16570 				continue;
16571 
16572 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16573 			if (cur_slot->iter.depth != slot->iter.depth)
16574 				return true;
16575 		}
16576 	}
16577 	return false;
16578 }
16579 
16580 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16581 {
16582 	struct bpf_verifier_state_list *new_sl;
16583 	struct bpf_verifier_state_list *sl, **pprev;
16584 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16585 	int i, j, n, err, states_cnt = 0;
16586 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16587 	bool add_new_state = force_new_state;
16588 	bool force_exact;
16589 
16590 	/* bpf progs typically have pruning point every 4 instructions
16591 	 * http://vger.kernel.org/bpfconf2019.html#session-1
16592 	 * Do not add new state for future pruning if the verifier hasn't seen
16593 	 * at least 2 jumps and at least 8 instructions.
16594 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16595 	 * In tests that amounts to up to 50% reduction into total verifier
16596 	 * memory consumption and 20% verifier time speedup.
16597 	 */
16598 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16599 	    env->insn_processed - env->prev_insn_processed >= 8)
16600 		add_new_state = true;
16601 
16602 	pprev = explored_state(env, insn_idx);
16603 	sl = *pprev;
16604 
16605 	clean_live_states(env, insn_idx, cur);
16606 
16607 	while (sl) {
16608 		states_cnt++;
16609 		if (sl->state.insn_idx != insn_idx)
16610 			goto next;
16611 
16612 		if (sl->state.branches) {
16613 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16614 
16615 			if (frame->in_async_callback_fn &&
16616 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16617 				/* Different async_entry_cnt means that the verifier is
16618 				 * processing another entry into async callback.
16619 				 * Seeing the same state is not an indication of infinite
16620 				 * loop or infinite recursion.
16621 				 * But finding the same state doesn't mean that it's safe
16622 				 * to stop processing the current state. The previous state
16623 				 * hasn't yet reached bpf_exit, since state.branches > 0.
16624 				 * Checking in_async_callback_fn alone is not enough either.
16625 				 * Since the verifier still needs to catch infinite loops
16626 				 * inside async callbacks.
16627 				 */
16628 				goto skip_inf_loop_check;
16629 			}
16630 			/* BPF open-coded iterators loop detection is special.
16631 			 * states_maybe_looping() logic is too simplistic in detecting
16632 			 * states that *might* be equivalent, because it doesn't know
16633 			 * about ID remapping, so don't even perform it.
16634 			 * See process_iter_next_call() and iter_active_depths_differ()
16635 			 * for overview of the logic. When current and one of parent
16636 			 * states are detected as equivalent, it's a good thing: we prove
16637 			 * convergence and can stop simulating further iterations.
16638 			 * It's safe to assume that iterator loop will finish, taking into
16639 			 * account iter_next() contract of eventually returning
16640 			 * sticky NULL result.
16641 			 *
16642 			 * Note, that states have to be compared exactly in this case because
16643 			 * read and precision marks might not be finalized inside the loop.
16644 			 * E.g. as in the program below:
16645 			 *
16646 			 *     1. r7 = -16
16647 			 *     2. r6 = bpf_get_prandom_u32()
16648 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
16649 			 *     4.   if (r6 != 42) {
16650 			 *     5.     r7 = -32
16651 			 *     6.     r6 = bpf_get_prandom_u32()
16652 			 *     7.     continue
16653 			 *     8.   }
16654 			 *     9.   r0 = r10
16655 			 *    10.   r0 += r7
16656 			 *    11.   r8 = *(u64 *)(r0 + 0)
16657 			 *    12.   r6 = bpf_get_prandom_u32()
16658 			 *    13. }
16659 			 *
16660 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
16661 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16662 			 * not have read or precision mark for r7 yet, thus inexact states
16663 			 * comparison would discard current state with r7=-32
16664 			 * => unsafe memory access at 11 would not be caught.
16665 			 */
16666 			if (is_iter_next_insn(env, insn_idx)) {
16667 				if (states_equal(env, &sl->state, cur, true)) {
16668 					struct bpf_func_state *cur_frame;
16669 					struct bpf_reg_state *iter_state, *iter_reg;
16670 					int spi;
16671 
16672 					cur_frame = cur->frame[cur->curframe];
16673 					/* btf_check_iter_kfuncs() enforces that
16674 					 * iter state pointer is always the first arg
16675 					 */
16676 					iter_reg = &cur_frame->regs[BPF_REG_1];
16677 					/* current state is valid due to states_equal(),
16678 					 * so we can assume valid iter and reg state,
16679 					 * no need for extra (re-)validations
16680 					 */
16681 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16682 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16683 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
16684 						update_loop_entry(cur, &sl->state);
16685 						goto hit;
16686 					}
16687 				}
16688 				goto skip_inf_loop_check;
16689 			}
16690 			if (calls_callback(env, insn_idx)) {
16691 				if (states_equal(env, &sl->state, cur, true))
16692 					goto hit;
16693 				goto skip_inf_loop_check;
16694 			}
16695 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
16696 			if (states_maybe_looping(&sl->state, cur) &&
16697 			    states_equal(env, &sl->state, cur, false) &&
16698 			    !iter_active_depths_differ(&sl->state, cur) &&
16699 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
16700 				verbose_linfo(env, insn_idx, "; ");
16701 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16702 				verbose(env, "cur state:");
16703 				print_verifier_state(env, cur->frame[cur->curframe], true);
16704 				verbose(env, "old state:");
16705 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
16706 				return -EINVAL;
16707 			}
16708 			/* if the verifier is processing a loop, avoid adding new state
16709 			 * too often, since different loop iterations have distinct
16710 			 * states and may not help future pruning.
16711 			 * This threshold shouldn't be too low to make sure that
16712 			 * a loop with large bound will be rejected quickly.
16713 			 * The most abusive loop will be:
16714 			 * r1 += 1
16715 			 * if r1 < 1000000 goto pc-2
16716 			 * 1M insn_procssed limit / 100 == 10k peak states.
16717 			 * This threshold shouldn't be too high either, since states
16718 			 * at the end of the loop are likely to be useful in pruning.
16719 			 */
16720 skip_inf_loop_check:
16721 			if (!force_new_state &&
16722 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
16723 			    env->insn_processed - env->prev_insn_processed < 100)
16724 				add_new_state = false;
16725 			goto miss;
16726 		}
16727 		/* If sl->state is a part of a loop and this loop's entry is a part of
16728 		 * current verification path then states have to be compared exactly.
16729 		 * 'force_exact' is needed to catch the following case:
16730 		 *
16731 		 *                initial     Here state 'succ' was processed first,
16732 		 *                  |         it was eventually tracked to produce a
16733 		 *                  V         state identical to 'hdr'.
16734 		 *     .---------> hdr        All branches from 'succ' had been explored
16735 		 *     |            |         and thus 'succ' has its .branches == 0.
16736 		 *     |            V
16737 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
16738 		 *     |    |       |         to the same instruction + callsites.
16739 		 *     |    V       V         In such case it is necessary to check
16740 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
16741 		 *     |    |       |         If 'succ' and 'cur' are a part of the
16742 		 *     |    V       V         same loop exact flag has to be set.
16743 		 *     |   succ <- cur        To check if that is the case, verify
16744 		 *     |    |                 if loop entry of 'succ' is in current
16745 		 *     |    V                 DFS path.
16746 		 *     |   ...
16747 		 *     |    |
16748 		 *     '----'
16749 		 *
16750 		 * Additional details are in the comment before get_loop_entry().
16751 		 */
16752 		loop_entry = get_loop_entry(&sl->state);
16753 		force_exact = loop_entry && loop_entry->branches > 0;
16754 		if (states_equal(env, &sl->state, cur, force_exact)) {
16755 			if (force_exact)
16756 				update_loop_entry(cur, loop_entry);
16757 hit:
16758 			sl->hit_cnt++;
16759 			/* reached equivalent register/stack state,
16760 			 * prune the search.
16761 			 * Registers read by the continuation are read by us.
16762 			 * If we have any write marks in env->cur_state, they
16763 			 * will prevent corresponding reads in the continuation
16764 			 * from reaching our parent (an explored_state).  Our
16765 			 * own state will get the read marks recorded, but
16766 			 * they'll be immediately forgotten as we're pruning
16767 			 * this state and will pop a new one.
16768 			 */
16769 			err = propagate_liveness(env, &sl->state, cur);
16770 
16771 			/* if previous state reached the exit with precision and
16772 			 * current state is equivalent to it (except precsion marks)
16773 			 * the precision needs to be propagated back in
16774 			 * the current state.
16775 			 */
16776 			err = err ? : push_jmp_history(env, cur);
16777 			err = err ? : propagate_precision(env, &sl->state);
16778 			if (err)
16779 				return err;
16780 			return 1;
16781 		}
16782 miss:
16783 		/* when new state is not going to be added do not increase miss count.
16784 		 * Otherwise several loop iterations will remove the state
16785 		 * recorded earlier. The goal of these heuristics is to have
16786 		 * states from some iterations of the loop (some in the beginning
16787 		 * and some at the end) to help pruning.
16788 		 */
16789 		if (add_new_state)
16790 			sl->miss_cnt++;
16791 		/* heuristic to determine whether this state is beneficial
16792 		 * to keep checking from state equivalence point of view.
16793 		 * Higher numbers increase max_states_per_insn and verification time,
16794 		 * but do not meaningfully decrease insn_processed.
16795 		 * 'n' controls how many times state could miss before eviction.
16796 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
16797 		 * too early would hinder iterator convergence.
16798 		 */
16799 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
16800 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
16801 			/* the state is unlikely to be useful. Remove it to
16802 			 * speed up verification
16803 			 */
16804 			*pprev = sl->next;
16805 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
16806 			    !sl->state.used_as_loop_entry) {
16807 				u32 br = sl->state.branches;
16808 
16809 				WARN_ONCE(br,
16810 					  "BUG live_done but branches_to_explore %d\n",
16811 					  br);
16812 				free_verifier_state(&sl->state, false);
16813 				kfree(sl);
16814 				env->peak_states--;
16815 			} else {
16816 				/* cannot free this state, since parentage chain may
16817 				 * walk it later. Add it for free_list instead to
16818 				 * be freed at the end of verification
16819 				 */
16820 				sl->next = env->free_list;
16821 				env->free_list = sl;
16822 			}
16823 			sl = *pprev;
16824 			continue;
16825 		}
16826 next:
16827 		pprev = &sl->next;
16828 		sl = *pprev;
16829 	}
16830 
16831 	if (env->max_states_per_insn < states_cnt)
16832 		env->max_states_per_insn = states_cnt;
16833 
16834 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16835 		return 0;
16836 
16837 	if (!add_new_state)
16838 		return 0;
16839 
16840 	/* There were no equivalent states, remember the current one.
16841 	 * Technically the current state is not proven to be safe yet,
16842 	 * but it will either reach outer most bpf_exit (which means it's safe)
16843 	 * or it will be rejected. When there are no loops the verifier won't be
16844 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16845 	 * again on the way to bpf_exit.
16846 	 * When looping the sl->state.branches will be > 0 and this state
16847 	 * will not be considered for equivalence until branches == 0.
16848 	 */
16849 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16850 	if (!new_sl)
16851 		return -ENOMEM;
16852 	env->total_states++;
16853 	env->peak_states++;
16854 	env->prev_jmps_processed = env->jmps_processed;
16855 	env->prev_insn_processed = env->insn_processed;
16856 
16857 	/* forget precise markings we inherited, see __mark_chain_precision */
16858 	if (env->bpf_capable)
16859 		mark_all_scalars_imprecise(env, cur);
16860 
16861 	/* add new state to the head of linked list */
16862 	new = &new_sl->state;
16863 	err = copy_verifier_state(new, cur);
16864 	if (err) {
16865 		free_verifier_state(new, false);
16866 		kfree(new_sl);
16867 		return err;
16868 	}
16869 	new->insn_idx = insn_idx;
16870 	WARN_ONCE(new->branches != 1,
16871 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16872 
16873 	cur->parent = new;
16874 	cur->first_insn_idx = insn_idx;
16875 	cur->dfs_depth = new->dfs_depth + 1;
16876 	clear_jmp_history(cur);
16877 	new_sl->next = *explored_state(env, insn_idx);
16878 	*explored_state(env, insn_idx) = new_sl;
16879 	/* connect new state to parentage chain. Current frame needs all
16880 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
16881 	 * to the stack implicitly by JITs) so in callers' frames connect just
16882 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16883 	 * the state of the call instruction (with WRITTEN set), and r0 comes
16884 	 * from callee with its full parentage chain, anyway.
16885 	 */
16886 	/* clear write marks in current state: the writes we did are not writes
16887 	 * our child did, so they don't screen off its reads from us.
16888 	 * (There are no read marks in current state, because reads always mark
16889 	 * their parent and current state never has children yet.  Only
16890 	 * explored_states can get read marks.)
16891 	 */
16892 	for (j = 0; j <= cur->curframe; j++) {
16893 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16894 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16895 		for (i = 0; i < BPF_REG_FP; i++)
16896 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16897 	}
16898 
16899 	/* all stack frames are accessible from callee, clear them all */
16900 	for (j = 0; j <= cur->curframe; j++) {
16901 		struct bpf_func_state *frame = cur->frame[j];
16902 		struct bpf_func_state *newframe = new->frame[j];
16903 
16904 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16905 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16906 			frame->stack[i].spilled_ptr.parent =
16907 						&newframe->stack[i].spilled_ptr;
16908 		}
16909 	}
16910 	return 0;
16911 }
16912 
16913 /* Return true if it's OK to have the same insn return a different type. */
16914 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16915 {
16916 	switch (base_type(type)) {
16917 	case PTR_TO_CTX:
16918 	case PTR_TO_SOCKET:
16919 	case PTR_TO_SOCK_COMMON:
16920 	case PTR_TO_TCP_SOCK:
16921 	case PTR_TO_XDP_SOCK:
16922 	case PTR_TO_BTF_ID:
16923 		return false;
16924 	default:
16925 		return true;
16926 	}
16927 }
16928 
16929 /* If an instruction was previously used with particular pointer types, then we
16930  * need to be careful to avoid cases such as the below, where it may be ok
16931  * for one branch accessing the pointer, but not ok for the other branch:
16932  *
16933  * R1 = sock_ptr
16934  * goto X;
16935  * ...
16936  * R1 = some_other_valid_ptr;
16937  * goto X;
16938  * ...
16939  * R2 = *(u32 *)(R1 + 0);
16940  */
16941 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16942 {
16943 	return src != prev && (!reg_type_mismatch_ok(src) ||
16944 			       !reg_type_mismatch_ok(prev));
16945 }
16946 
16947 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16948 			     bool allow_trust_missmatch)
16949 {
16950 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16951 
16952 	if (*prev_type == NOT_INIT) {
16953 		/* Saw a valid insn
16954 		 * dst_reg = *(u32 *)(src_reg + off)
16955 		 * save type to validate intersecting paths
16956 		 */
16957 		*prev_type = type;
16958 	} else if (reg_type_mismatch(type, *prev_type)) {
16959 		/* Abuser program is trying to use the same insn
16960 		 * dst_reg = *(u32*) (src_reg + off)
16961 		 * with different pointer types:
16962 		 * src_reg == ctx in one branch and
16963 		 * src_reg == stack|map in some other branch.
16964 		 * Reject it.
16965 		 */
16966 		if (allow_trust_missmatch &&
16967 		    base_type(type) == PTR_TO_BTF_ID &&
16968 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
16969 			/*
16970 			 * Have to support a use case when one path through
16971 			 * the program yields TRUSTED pointer while another
16972 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16973 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16974 			 */
16975 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16976 		} else {
16977 			verbose(env, "same insn cannot be used with different pointers\n");
16978 			return -EINVAL;
16979 		}
16980 	}
16981 
16982 	return 0;
16983 }
16984 
16985 static int do_check(struct bpf_verifier_env *env)
16986 {
16987 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16988 	struct bpf_verifier_state *state = env->cur_state;
16989 	struct bpf_insn *insns = env->prog->insnsi;
16990 	struct bpf_reg_state *regs;
16991 	int insn_cnt = env->prog->len;
16992 	bool do_print_state = false;
16993 	int prev_insn_idx = -1;
16994 
16995 	for (;;) {
16996 		struct bpf_insn *insn;
16997 		u8 class;
16998 		int err;
16999 
17000 		env->prev_insn_idx = prev_insn_idx;
17001 		if (env->insn_idx >= insn_cnt) {
17002 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
17003 				env->insn_idx, insn_cnt);
17004 			return -EFAULT;
17005 		}
17006 
17007 		insn = &insns[env->insn_idx];
17008 		class = BPF_CLASS(insn->code);
17009 
17010 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17011 			verbose(env,
17012 				"BPF program is too large. Processed %d insn\n",
17013 				env->insn_processed);
17014 			return -E2BIG;
17015 		}
17016 
17017 		state->last_insn_idx = env->prev_insn_idx;
17018 
17019 		if (is_prune_point(env, env->insn_idx)) {
17020 			err = is_state_visited(env, env->insn_idx);
17021 			if (err < 0)
17022 				return err;
17023 			if (err == 1) {
17024 				/* found equivalent state, can prune the search */
17025 				if (env->log.level & BPF_LOG_LEVEL) {
17026 					if (do_print_state)
17027 						verbose(env, "\nfrom %d to %d%s: safe\n",
17028 							env->prev_insn_idx, env->insn_idx,
17029 							env->cur_state->speculative ?
17030 							" (speculative execution)" : "");
17031 					else
17032 						verbose(env, "%d: safe\n", env->insn_idx);
17033 				}
17034 				goto process_bpf_exit;
17035 			}
17036 		}
17037 
17038 		if (is_jmp_point(env, env->insn_idx)) {
17039 			err = push_jmp_history(env, state);
17040 			if (err)
17041 				return err;
17042 		}
17043 
17044 		if (signal_pending(current))
17045 			return -EAGAIN;
17046 
17047 		if (need_resched())
17048 			cond_resched();
17049 
17050 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17051 			verbose(env, "\nfrom %d to %d%s:",
17052 				env->prev_insn_idx, env->insn_idx,
17053 				env->cur_state->speculative ?
17054 				" (speculative execution)" : "");
17055 			print_verifier_state(env, state->frame[state->curframe], true);
17056 			do_print_state = false;
17057 		}
17058 
17059 		if (env->log.level & BPF_LOG_LEVEL) {
17060 			const struct bpf_insn_cbs cbs = {
17061 				.cb_call	= disasm_kfunc_name,
17062 				.cb_print	= verbose,
17063 				.private_data	= env,
17064 			};
17065 
17066 			if (verifier_state_scratched(env))
17067 				print_insn_state(env, state->frame[state->curframe]);
17068 
17069 			verbose_linfo(env, env->insn_idx, "; ");
17070 			env->prev_log_pos = env->log.end_pos;
17071 			verbose(env, "%d: ", env->insn_idx);
17072 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17073 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17074 			env->prev_log_pos = env->log.end_pos;
17075 		}
17076 
17077 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17078 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17079 							   env->prev_insn_idx);
17080 			if (err)
17081 				return err;
17082 		}
17083 
17084 		regs = cur_regs(env);
17085 		sanitize_mark_insn_seen(env);
17086 		prev_insn_idx = env->insn_idx;
17087 
17088 		if (class == BPF_ALU || class == BPF_ALU64) {
17089 			err = check_alu_op(env, insn);
17090 			if (err)
17091 				return err;
17092 
17093 		} else if (class == BPF_LDX) {
17094 			enum bpf_reg_type src_reg_type;
17095 
17096 			/* check for reserved fields is already done */
17097 
17098 			/* check src operand */
17099 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17100 			if (err)
17101 				return err;
17102 
17103 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17104 			if (err)
17105 				return err;
17106 
17107 			src_reg_type = regs[insn->src_reg].type;
17108 
17109 			/* check that memory (src_reg + off) is readable,
17110 			 * the state of dst_reg will be updated by this func
17111 			 */
17112 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17113 					       insn->off, BPF_SIZE(insn->code),
17114 					       BPF_READ, insn->dst_reg, false,
17115 					       BPF_MODE(insn->code) == BPF_MEMSX);
17116 			if (err)
17117 				return err;
17118 
17119 			err = save_aux_ptr_type(env, src_reg_type, true);
17120 			if (err)
17121 				return err;
17122 		} else if (class == BPF_STX) {
17123 			enum bpf_reg_type dst_reg_type;
17124 
17125 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17126 				err = check_atomic(env, env->insn_idx, insn);
17127 				if (err)
17128 					return err;
17129 				env->insn_idx++;
17130 				continue;
17131 			}
17132 
17133 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17134 				verbose(env, "BPF_STX uses reserved fields\n");
17135 				return -EINVAL;
17136 			}
17137 
17138 			/* check src1 operand */
17139 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17140 			if (err)
17141 				return err;
17142 			/* check src2 operand */
17143 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17144 			if (err)
17145 				return err;
17146 
17147 			dst_reg_type = regs[insn->dst_reg].type;
17148 
17149 			/* check that memory (dst_reg + off) is writeable */
17150 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17151 					       insn->off, BPF_SIZE(insn->code),
17152 					       BPF_WRITE, insn->src_reg, false, false);
17153 			if (err)
17154 				return err;
17155 
17156 			err = save_aux_ptr_type(env, dst_reg_type, false);
17157 			if (err)
17158 				return err;
17159 		} else if (class == BPF_ST) {
17160 			enum bpf_reg_type dst_reg_type;
17161 
17162 			if (BPF_MODE(insn->code) != BPF_MEM ||
17163 			    insn->src_reg != BPF_REG_0) {
17164 				verbose(env, "BPF_ST uses reserved fields\n");
17165 				return -EINVAL;
17166 			}
17167 			/* check src operand */
17168 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17169 			if (err)
17170 				return err;
17171 
17172 			dst_reg_type = regs[insn->dst_reg].type;
17173 
17174 			/* check that memory (dst_reg + off) is writeable */
17175 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17176 					       insn->off, BPF_SIZE(insn->code),
17177 					       BPF_WRITE, -1, false, false);
17178 			if (err)
17179 				return err;
17180 
17181 			err = save_aux_ptr_type(env, dst_reg_type, false);
17182 			if (err)
17183 				return err;
17184 		} else if (class == BPF_JMP || class == BPF_JMP32) {
17185 			u8 opcode = BPF_OP(insn->code);
17186 
17187 			env->jmps_processed++;
17188 			if (opcode == BPF_CALL) {
17189 				if (BPF_SRC(insn->code) != BPF_K ||
17190 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17191 				     && insn->off != 0) ||
17192 				    (insn->src_reg != BPF_REG_0 &&
17193 				     insn->src_reg != BPF_PSEUDO_CALL &&
17194 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17195 				    insn->dst_reg != BPF_REG_0 ||
17196 				    class == BPF_JMP32) {
17197 					verbose(env, "BPF_CALL uses reserved fields\n");
17198 					return -EINVAL;
17199 				}
17200 
17201 				if (env->cur_state->active_lock.ptr) {
17202 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17203 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
17204 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17205 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17206 						verbose(env, "function calls are not allowed while holding a lock\n");
17207 						return -EINVAL;
17208 					}
17209 				}
17210 				if (insn->src_reg == BPF_PSEUDO_CALL)
17211 					err = check_func_call(env, insn, &env->insn_idx);
17212 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
17213 					err = check_kfunc_call(env, insn, &env->insn_idx);
17214 				else
17215 					err = check_helper_call(env, insn, &env->insn_idx);
17216 				if (err)
17217 					return err;
17218 
17219 				mark_reg_scratched(env, BPF_REG_0);
17220 			} else if (opcode == BPF_JA) {
17221 				if (BPF_SRC(insn->code) != BPF_K ||
17222 				    insn->src_reg != BPF_REG_0 ||
17223 				    insn->dst_reg != BPF_REG_0 ||
17224 				    (class == BPF_JMP && insn->imm != 0) ||
17225 				    (class == BPF_JMP32 && insn->off != 0)) {
17226 					verbose(env, "BPF_JA uses reserved fields\n");
17227 					return -EINVAL;
17228 				}
17229 
17230 				if (class == BPF_JMP)
17231 					env->insn_idx += insn->off + 1;
17232 				else
17233 					env->insn_idx += insn->imm + 1;
17234 				continue;
17235 
17236 			} else if (opcode == BPF_EXIT) {
17237 				if (BPF_SRC(insn->code) != BPF_K ||
17238 				    insn->imm != 0 ||
17239 				    insn->src_reg != BPF_REG_0 ||
17240 				    insn->dst_reg != BPF_REG_0 ||
17241 				    class == BPF_JMP32) {
17242 					verbose(env, "BPF_EXIT uses reserved fields\n");
17243 					return -EINVAL;
17244 				}
17245 
17246 				if (env->cur_state->active_lock.ptr &&
17247 				    !in_rbtree_lock_required_cb(env)) {
17248 					verbose(env, "bpf_spin_unlock is missing\n");
17249 					return -EINVAL;
17250 				}
17251 
17252 				if (env->cur_state->active_rcu_lock &&
17253 				    !in_rbtree_lock_required_cb(env)) {
17254 					verbose(env, "bpf_rcu_read_unlock is missing\n");
17255 					return -EINVAL;
17256 				}
17257 
17258 				/* We must do check_reference_leak here before
17259 				 * prepare_func_exit to handle the case when
17260 				 * state->curframe > 0, it may be a callback
17261 				 * function, for which reference_state must
17262 				 * match caller reference state when it exits.
17263 				 */
17264 				err = check_reference_leak(env);
17265 				if (err)
17266 					return err;
17267 
17268 				if (state->curframe) {
17269 					/* exit from nested function */
17270 					err = prepare_func_exit(env, &env->insn_idx);
17271 					if (err)
17272 						return err;
17273 					do_print_state = true;
17274 					continue;
17275 				}
17276 
17277 				err = check_return_code(env);
17278 				if (err)
17279 					return err;
17280 process_bpf_exit:
17281 				mark_verifier_state_scratched(env);
17282 				update_branch_counts(env, env->cur_state);
17283 				err = pop_stack(env, &prev_insn_idx,
17284 						&env->insn_idx, pop_log);
17285 				if (err < 0) {
17286 					if (err != -ENOENT)
17287 						return err;
17288 					break;
17289 				} else {
17290 					do_print_state = true;
17291 					continue;
17292 				}
17293 			} else {
17294 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
17295 				if (err)
17296 					return err;
17297 			}
17298 		} else if (class == BPF_LD) {
17299 			u8 mode = BPF_MODE(insn->code);
17300 
17301 			if (mode == BPF_ABS || mode == BPF_IND) {
17302 				err = check_ld_abs(env, insn);
17303 				if (err)
17304 					return err;
17305 
17306 			} else if (mode == BPF_IMM) {
17307 				err = check_ld_imm(env, insn);
17308 				if (err)
17309 					return err;
17310 
17311 				env->insn_idx++;
17312 				sanitize_mark_insn_seen(env);
17313 			} else {
17314 				verbose(env, "invalid BPF_LD mode\n");
17315 				return -EINVAL;
17316 			}
17317 		} else {
17318 			verbose(env, "unknown insn class %d\n", class);
17319 			return -EINVAL;
17320 		}
17321 
17322 		env->insn_idx++;
17323 	}
17324 
17325 	return 0;
17326 }
17327 
17328 static int find_btf_percpu_datasec(struct btf *btf)
17329 {
17330 	const struct btf_type *t;
17331 	const char *tname;
17332 	int i, n;
17333 
17334 	/*
17335 	 * Both vmlinux and module each have their own ".data..percpu"
17336 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17337 	 * types to look at only module's own BTF types.
17338 	 */
17339 	n = btf_nr_types(btf);
17340 	if (btf_is_module(btf))
17341 		i = btf_nr_types(btf_vmlinux);
17342 	else
17343 		i = 1;
17344 
17345 	for(; i < n; i++) {
17346 		t = btf_type_by_id(btf, i);
17347 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17348 			continue;
17349 
17350 		tname = btf_name_by_offset(btf, t->name_off);
17351 		if (!strcmp(tname, ".data..percpu"))
17352 			return i;
17353 	}
17354 
17355 	return -ENOENT;
17356 }
17357 
17358 /* replace pseudo btf_id with kernel symbol address */
17359 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17360 			       struct bpf_insn *insn,
17361 			       struct bpf_insn_aux_data *aux)
17362 {
17363 	const struct btf_var_secinfo *vsi;
17364 	const struct btf_type *datasec;
17365 	struct btf_mod_pair *btf_mod;
17366 	const struct btf_type *t;
17367 	const char *sym_name;
17368 	bool percpu = false;
17369 	u32 type, id = insn->imm;
17370 	struct btf *btf;
17371 	s32 datasec_id;
17372 	u64 addr;
17373 	int i, btf_fd, err;
17374 
17375 	btf_fd = insn[1].imm;
17376 	if (btf_fd) {
17377 		btf = btf_get_by_fd(btf_fd);
17378 		if (IS_ERR(btf)) {
17379 			verbose(env, "invalid module BTF object FD specified.\n");
17380 			return -EINVAL;
17381 		}
17382 	} else {
17383 		if (!btf_vmlinux) {
17384 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17385 			return -EINVAL;
17386 		}
17387 		btf = btf_vmlinux;
17388 		btf_get(btf);
17389 	}
17390 
17391 	t = btf_type_by_id(btf, id);
17392 	if (!t) {
17393 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17394 		err = -ENOENT;
17395 		goto err_put;
17396 	}
17397 
17398 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17399 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17400 		err = -EINVAL;
17401 		goto err_put;
17402 	}
17403 
17404 	sym_name = btf_name_by_offset(btf, t->name_off);
17405 	addr = kallsyms_lookup_name(sym_name);
17406 	if (!addr) {
17407 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17408 			sym_name);
17409 		err = -ENOENT;
17410 		goto err_put;
17411 	}
17412 	insn[0].imm = (u32)addr;
17413 	insn[1].imm = addr >> 32;
17414 
17415 	if (btf_type_is_func(t)) {
17416 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17417 		aux->btf_var.mem_size = 0;
17418 		goto check_btf;
17419 	}
17420 
17421 	datasec_id = find_btf_percpu_datasec(btf);
17422 	if (datasec_id > 0) {
17423 		datasec = btf_type_by_id(btf, datasec_id);
17424 		for_each_vsi(i, datasec, vsi) {
17425 			if (vsi->type == id) {
17426 				percpu = true;
17427 				break;
17428 			}
17429 		}
17430 	}
17431 
17432 	type = t->type;
17433 	t = btf_type_skip_modifiers(btf, type, NULL);
17434 	if (percpu) {
17435 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17436 		aux->btf_var.btf = btf;
17437 		aux->btf_var.btf_id = type;
17438 	} else if (!btf_type_is_struct(t)) {
17439 		const struct btf_type *ret;
17440 		const char *tname;
17441 		u32 tsize;
17442 
17443 		/* resolve the type size of ksym. */
17444 		ret = btf_resolve_size(btf, t, &tsize);
17445 		if (IS_ERR(ret)) {
17446 			tname = btf_name_by_offset(btf, t->name_off);
17447 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17448 				tname, PTR_ERR(ret));
17449 			err = -EINVAL;
17450 			goto err_put;
17451 		}
17452 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17453 		aux->btf_var.mem_size = tsize;
17454 	} else {
17455 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
17456 		aux->btf_var.btf = btf;
17457 		aux->btf_var.btf_id = type;
17458 	}
17459 check_btf:
17460 	/* check whether we recorded this BTF (and maybe module) already */
17461 	for (i = 0; i < env->used_btf_cnt; i++) {
17462 		if (env->used_btfs[i].btf == btf) {
17463 			btf_put(btf);
17464 			return 0;
17465 		}
17466 	}
17467 
17468 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
17469 		err = -E2BIG;
17470 		goto err_put;
17471 	}
17472 
17473 	btf_mod = &env->used_btfs[env->used_btf_cnt];
17474 	btf_mod->btf = btf;
17475 	btf_mod->module = NULL;
17476 
17477 	/* if we reference variables from kernel module, bump its refcount */
17478 	if (btf_is_module(btf)) {
17479 		btf_mod->module = btf_try_get_module(btf);
17480 		if (!btf_mod->module) {
17481 			err = -ENXIO;
17482 			goto err_put;
17483 		}
17484 	}
17485 
17486 	env->used_btf_cnt++;
17487 
17488 	return 0;
17489 err_put:
17490 	btf_put(btf);
17491 	return err;
17492 }
17493 
17494 static bool is_tracing_prog_type(enum bpf_prog_type type)
17495 {
17496 	switch (type) {
17497 	case BPF_PROG_TYPE_KPROBE:
17498 	case BPF_PROG_TYPE_TRACEPOINT:
17499 	case BPF_PROG_TYPE_PERF_EVENT:
17500 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17501 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17502 		return true;
17503 	default:
17504 		return false;
17505 	}
17506 }
17507 
17508 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17509 					struct bpf_map *map,
17510 					struct bpf_prog *prog)
17511 
17512 {
17513 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17514 
17515 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17516 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
17517 		if (is_tracing_prog_type(prog_type)) {
17518 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17519 			return -EINVAL;
17520 		}
17521 	}
17522 
17523 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17524 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17525 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17526 			return -EINVAL;
17527 		}
17528 
17529 		if (is_tracing_prog_type(prog_type)) {
17530 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17531 			return -EINVAL;
17532 		}
17533 	}
17534 
17535 	if (btf_record_has_field(map->record, BPF_TIMER)) {
17536 		if (is_tracing_prog_type(prog_type)) {
17537 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
17538 			return -EINVAL;
17539 		}
17540 	}
17541 
17542 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17543 	    !bpf_offload_prog_map_match(prog, map)) {
17544 		verbose(env, "offload device mismatch between prog and map\n");
17545 		return -EINVAL;
17546 	}
17547 
17548 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17549 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17550 		return -EINVAL;
17551 	}
17552 
17553 	if (prog->aux->sleepable)
17554 		switch (map->map_type) {
17555 		case BPF_MAP_TYPE_HASH:
17556 		case BPF_MAP_TYPE_LRU_HASH:
17557 		case BPF_MAP_TYPE_ARRAY:
17558 		case BPF_MAP_TYPE_PERCPU_HASH:
17559 		case BPF_MAP_TYPE_PERCPU_ARRAY:
17560 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17561 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17562 		case BPF_MAP_TYPE_HASH_OF_MAPS:
17563 		case BPF_MAP_TYPE_RINGBUF:
17564 		case BPF_MAP_TYPE_USER_RINGBUF:
17565 		case BPF_MAP_TYPE_INODE_STORAGE:
17566 		case BPF_MAP_TYPE_SK_STORAGE:
17567 		case BPF_MAP_TYPE_TASK_STORAGE:
17568 		case BPF_MAP_TYPE_CGRP_STORAGE:
17569 			break;
17570 		default:
17571 			verbose(env,
17572 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17573 			return -EINVAL;
17574 		}
17575 
17576 	return 0;
17577 }
17578 
17579 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17580 {
17581 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17582 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17583 }
17584 
17585 /* find and rewrite pseudo imm in ld_imm64 instructions:
17586  *
17587  * 1. if it accesses map FD, replace it with actual map pointer.
17588  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17589  *
17590  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17591  */
17592 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17593 {
17594 	struct bpf_insn *insn = env->prog->insnsi;
17595 	int insn_cnt = env->prog->len;
17596 	int i, j, err;
17597 
17598 	err = bpf_prog_calc_tag(env->prog);
17599 	if (err)
17600 		return err;
17601 
17602 	for (i = 0; i < insn_cnt; i++, insn++) {
17603 		if (BPF_CLASS(insn->code) == BPF_LDX &&
17604 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17605 		    insn->imm != 0)) {
17606 			verbose(env, "BPF_LDX uses reserved fields\n");
17607 			return -EINVAL;
17608 		}
17609 
17610 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17611 			struct bpf_insn_aux_data *aux;
17612 			struct bpf_map *map;
17613 			struct fd f;
17614 			u64 addr;
17615 			u32 fd;
17616 
17617 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
17618 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17619 			    insn[1].off != 0) {
17620 				verbose(env, "invalid bpf_ld_imm64 insn\n");
17621 				return -EINVAL;
17622 			}
17623 
17624 			if (insn[0].src_reg == 0)
17625 				/* valid generic load 64-bit imm */
17626 				goto next_insn;
17627 
17628 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17629 				aux = &env->insn_aux_data[i];
17630 				err = check_pseudo_btf_id(env, insn, aux);
17631 				if (err)
17632 					return err;
17633 				goto next_insn;
17634 			}
17635 
17636 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17637 				aux = &env->insn_aux_data[i];
17638 				aux->ptr_type = PTR_TO_FUNC;
17639 				goto next_insn;
17640 			}
17641 
17642 			/* In final convert_pseudo_ld_imm64() step, this is
17643 			 * converted into regular 64-bit imm load insn.
17644 			 */
17645 			switch (insn[0].src_reg) {
17646 			case BPF_PSEUDO_MAP_VALUE:
17647 			case BPF_PSEUDO_MAP_IDX_VALUE:
17648 				break;
17649 			case BPF_PSEUDO_MAP_FD:
17650 			case BPF_PSEUDO_MAP_IDX:
17651 				if (insn[1].imm == 0)
17652 					break;
17653 				fallthrough;
17654 			default:
17655 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17656 				return -EINVAL;
17657 			}
17658 
17659 			switch (insn[0].src_reg) {
17660 			case BPF_PSEUDO_MAP_IDX_VALUE:
17661 			case BPF_PSEUDO_MAP_IDX:
17662 				if (bpfptr_is_null(env->fd_array)) {
17663 					verbose(env, "fd_idx without fd_array is invalid\n");
17664 					return -EPROTO;
17665 				}
17666 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
17667 							    insn[0].imm * sizeof(fd),
17668 							    sizeof(fd)))
17669 					return -EFAULT;
17670 				break;
17671 			default:
17672 				fd = insn[0].imm;
17673 				break;
17674 			}
17675 
17676 			f = fdget(fd);
17677 			map = __bpf_map_get(f);
17678 			if (IS_ERR(map)) {
17679 				verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
17680 				return PTR_ERR(map);
17681 			}
17682 
17683 			err = check_map_prog_compatibility(env, map, env->prog);
17684 			if (err) {
17685 				fdput(f);
17686 				return err;
17687 			}
17688 
17689 			aux = &env->insn_aux_data[i];
17690 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17691 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17692 				addr = (unsigned long)map;
17693 			} else {
17694 				u32 off = insn[1].imm;
17695 
17696 				if (off >= BPF_MAX_VAR_OFF) {
17697 					verbose(env, "direct value offset of %u is not allowed\n", off);
17698 					fdput(f);
17699 					return -EINVAL;
17700 				}
17701 
17702 				if (!map->ops->map_direct_value_addr) {
17703 					verbose(env, "no direct value access support for this map type\n");
17704 					fdput(f);
17705 					return -EINVAL;
17706 				}
17707 
17708 				err = map->ops->map_direct_value_addr(map, &addr, off);
17709 				if (err) {
17710 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17711 						map->value_size, off);
17712 					fdput(f);
17713 					return err;
17714 				}
17715 
17716 				aux->map_off = off;
17717 				addr += off;
17718 			}
17719 
17720 			insn[0].imm = (u32)addr;
17721 			insn[1].imm = addr >> 32;
17722 
17723 			/* check whether we recorded this map already */
17724 			for (j = 0; j < env->used_map_cnt; j++) {
17725 				if (env->used_maps[j] == map) {
17726 					aux->map_index = j;
17727 					fdput(f);
17728 					goto next_insn;
17729 				}
17730 			}
17731 
17732 			if (env->used_map_cnt >= MAX_USED_MAPS) {
17733 				fdput(f);
17734 				return -E2BIG;
17735 			}
17736 
17737 			if (env->prog->aux->sleepable)
17738 				atomic64_inc(&map->sleepable_refcnt);
17739 			/* hold the map. If the program is rejected by verifier,
17740 			 * the map will be released by release_maps() or it
17741 			 * will be used by the valid program until it's unloaded
17742 			 * and all maps are released in bpf_free_used_maps()
17743 			 */
17744 			bpf_map_inc(map);
17745 
17746 			aux->map_index = env->used_map_cnt;
17747 			env->used_maps[env->used_map_cnt++] = map;
17748 
17749 			if (bpf_map_is_cgroup_storage(map) &&
17750 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
17751 				verbose(env, "only one cgroup storage of each type is allowed\n");
17752 				fdput(f);
17753 				return -EBUSY;
17754 			}
17755 
17756 			fdput(f);
17757 next_insn:
17758 			insn++;
17759 			i++;
17760 			continue;
17761 		}
17762 
17763 		/* Basic sanity check before we invest more work here. */
17764 		if (!bpf_opcode_in_insntable(insn->code)) {
17765 			verbose(env, "unknown opcode %02x\n", insn->code);
17766 			return -EINVAL;
17767 		}
17768 	}
17769 
17770 	/* now all pseudo BPF_LD_IMM64 instructions load valid
17771 	 * 'struct bpf_map *' into a register instead of user map_fd.
17772 	 * These pointers will be used later by verifier to validate map access.
17773 	 */
17774 	return 0;
17775 }
17776 
17777 /* drop refcnt of maps used by the rejected program */
17778 static void release_maps(struct bpf_verifier_env *env)
17779 {
17780 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
17781 			     env->used_map_cnt);
17782 }
17783 
17784 /* drop refcnt of maps used by the rejected program */
17785 static void release_btfs(struct bpf_verifier_env *env)
17786 {
17787 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17788 			     env->used_btf_cnt);
17789 }
17790 
17791 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17792 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17793 {
17794 	struct bpf_insn *insn = env->prog->insnsi;
17795 	int insn_cnt = env->prog->len;
17796 	int i;
17797 
17798 	for (i = 0; i < insn_cnt; i++, insn++) {
17799 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17800 			continue;
17801 		if (insn->src_reg == BPF_PSEUDO_FUNC)
17802 			continue;
17803 		insn->src_reg = 0;
17804 	}
17805 }
17806 
17807 /* single env->prog->insni[off] instruction was replaced with the range
17808  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17809  * [0, off) and [off, end) to new locations, so the patched range stays zero
17810  */
17811 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17812 				 struct bpf_insn_aux_data *new_data,
17813 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
17814 {
17815 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17816 	struct bpf_insn *insn = new_prog->insnsi;
17817 	u32 old_seen = old_data[off].seen;
17818 	u32 prog_len;
17819 	int i;
17820 
17821 	/* aux info at OFF always needs adjustment, no matter fast path
17822 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17823 	 * original insn at old prog.
17824 	 */
17825 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17826 
17827 	if (cnt == 1)
17828 		return;
17829 	prog_len = new_prog->len;
17830 
17831 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17832 	memcpy(new_data + off + cnt - 1, old_data + off,
17833 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17834 	for (i = off; i < off + cnt - 1; i++) {
17835 		/* Expand insni[off]'s seen count to the patched range. */
17836 		new_data[i].seen = old_seen;
17837 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
17838 	}
17839 	env->insn_aux_data = new_data;
17840 	vfree(old_data);
17841 }
17842 
17843 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17844 {
17845 	int i;
17846 
17847 	if (len == 1)
17848 		return;
17849 	/* NOTE: fake 'exit' subprog should be updated as well. */
17850 	for (i = 0; i <= env->subprog_cnt; i++) {
17851 		if (env->subprog_info[i].start <= off)
17852 			continue;
17853 		env->subprog_info[i].start += len - 1;
17854 	}
17855 }
17856 
17857 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17858 {
17859 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17860 	int i, sz = prog->aux->size_poke_tab;
17861 	struct bpf_jit_poke_descriptor *desc;
17862 
17863 	for (i = 0; i < sz; i++) {
17864 		desc = &tab[i];
17865 		if (desc->insn_idx <= off)
17866 			continue;
17867 		desc->insn_idx += len - 1;
17868 	}
17869 }
17870 
17871 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17872 					    const struct bpf_insn *patch, u32 len)
17873 {
17874 	struct bpf_prog *new_prog;
17875 	struct bpf_insn_aux_data *new_data = NULL;
17876 
17877 	if (len > 1) {
17878 		new_data = vzalloc(array_size(env->prog->len + len - 1,
17879 					      sizeof(struct bpf_insn_aux_data)));
17880 		if (!new_data)
17881 			return NULL;
17882 	}
17883 
17884 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17885 	if (IS_ERR(new_prog)) {
17886 		if (PTR_ERR(new_prog) == -ERANGE)
17887 			verbose(env,
17888 				"insn %d cannot be patched due to 16-bit range\n",
17889 				env->insn_aux_data[off].orig_idx);
17890 		vfree(new_data);
17891 		return NULL;
17892 	}
17893 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
17894 	adjust_subprog_starts(env, off, len);
17895 	adjust_poke_descs(new_prog, off, len);
17896 	return new_prog;
17897 }
17898 
17899 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17900 					      u32 off, u32 cnt)
17901 {
17902 	int i, j;
17903 
17904 	/* find first prog starting at or after off (first to remove) */
17905 	for (i = 0; i < env->subprog_cnt; i++)
17906 		if (env->subprog_info[i].start >= off)
17907 			break;
17908 	/* find first prog starting at or after off + cnt (first to stay) */
17909 	for (j = i; j < env->subprog_cnt; j++)
17910 		if (env->subprog_info[j].start >= off + cnt)
17911 			break;
17912 	/* if j doesn't start exactly at off + cnt, we are just removing
17913 	 * the front of previous prog
17914 	 */
17915 	if (env->subprog_info[j].start != off + cnt)
17916 		j--;
17917 
17918 	if (j > i) {
17919 		struct bpf_prog_aux *aux = env->prog->aux;
17920 		int move;
17921 
17922 		/* move fake 'exit' subprog as well */
17923 		move = env->subprog_cnt + 1 - j;
17924 
17925 		memmove(env->subprog_info + i,
17926 			env->subprog_info + j,
17927 			sizeof(*env->subprog_info) * move);
17928 		env->subprog_cnt -= j - i;
17929 
17930 		/* remove func_info */
17931 		if (aux->func_info) {
17932 			move = aux->func_info_cnt - j;
17933 
17934 			memmove(aux->func_info + i,
17935 				aux->func_info + j,
17936 				sizeof(*aux->func_info) * move);
17937 			aux->func_info_cnt -= j - i;
17938 			/* func_info->insn_off is set after all code rewrites,
17939 			 * in adjust_btf_func() - no need to adjust
17940 			 */
17941 		}
17942 	} else {
17943 		/* convert i from "first prog to remove" to "first to adjust" */
17944 		if (env->subprog_info[i].start == off)
17945 			i++;
17946 	}
17947 
17948 	/* update fake 'exit' subprog as well */
17949 	for (; i <= env->subprog_cnt; i++)
17950 		env->subprog_info[i].start -= cnt;
17951 
17952 	return 0;
17953 }
17954 
17955 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17956 				      u32 cnt)
17957 {
17958 	struct bpf_prog *prog = env->prog;
17959 	u32 i, l_off, l_cnt, nr_linfo;
17960 	struct bpf_line_info *linfo;
17961 
17962 	nr_linfo = prog->aux->nr_linfo;
17963 	if (!nr_linfo)
17964 		return 0;
17965 
17966 	linfo = prog->aux->linfo;
17967 
17968 	/* find first line info to remove, count lines to be removed */
17969 	for (i = 0; i < nr_linfo; i++)
17970 		if (linfo[i].insn_off >= off)
17971 			break;
17972 
17973 	l_off = i;
17974 	l_cnt = 0;
17975 	for (; i < nr_linfo; i++)
17976 		if (linfo[i].insn_off < off + cnt)
17977 			l_cnt++;
17978 		else
17979 			break;
17980 
17981 	/* First live insn doesn't match first live linfo, it needs to "inherit"
17982 	 * last removed linfo.  prog is already modified, so prog->len == off
17983 	 * means no live instructions after (tail of the program was removed).
17984 	 */
17985 	if (prog->len != off && l_cnt &&
17986 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17987 		l_cnt--;
17988 		linfo[--i].insn_off = off + cnt;
17989 	}
17990 
17991 	/* remove the line info which refer to the removed instructions */
17992 	if (l_cnt) {
17993 		memmove(linfo + l_off, linfo + i,
17994 			sizeof(*linfo) * (nr_linfo - i));
17995 
17996 		prog->aux->nr_linfo -= l_cnt;
17997 		nr_linfo = prog->aux->nr_linfo;
17998 	}
17999 
18000 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
18001 	for (i = l_off; i < nr_linfo; i++)
18002 		linfo[i].insn_off -= cnt;
18003 
18004 	/* fix up all subprogs (incl. 'exit') which start >= off */
18005 	for (i = 0; i <= env->subprog_cnt; i++)
18006 		if (env->subprog_info[i].linfo_idx > l_off) {
18007 			/* program may have started in the removed region but
18008 			 * may not be fully removed
18009 			 */
18010 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18011 				env->subprog_info[i].linfo_idx -= l_cnt;
18012 			else
18013 				env->subprog_info[i].linfo_idx = l_off;
18014 		}
18015 
18016 	return 0;
18017 }
18018 
18019 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18020 {
18021 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18022 	unsigned int orig_prog_len = env->prog->len;
18023 	int err;
18024 
18025 	if (bpf_prog_is_offloaded(env->prog->aux))
18026 		bpf_prog_offload_remove_insns(env, off, cnt);
18027 
18028 	err = bpf_remove_insns(env->prog, off, cnt);
18029 	if (err)
18030 		return err;
18031 
18032 	err = adjust_subprog_starts_after_remove(env, off, cnt);
18033 	if (err)
18034 		return err;
18035 
18036 	err = bpf_adj_linfo_after_remove(env, off, cnt);
18037 	if (err)
18038 		return err;
18039 
18040 	memmove(aux_data + off,	aux_data + off + cnt,
18041 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18042 
18043 	return 0;
18044 }
18045 
18046 /* The verifier does more data flow analysis than llvm and will not
18047  * explore branches that are dead at run time. Malicious programs can
18048  * have dead code too. Therefore replace all dead at-run-time code
18049  * with 'ja -1'.
18050  *
18051  * Just nops are not optimal, e.g. if they would sit at the end of the
18052  * program and through another bug we would manage to jump there, then
18053  * we'd execute beyond program memory otherwise. Returning exception
18054  * code also wouldn't work since we can have subprogs where the dead
18055  * code could be located.
18056  */
18057 static void sanitize_dead_code(struct bpf_verifier_env *env)
18058 {
18059 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18060 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18061 	struct bpf_insn *insn = env->prog->insnsi;
18062 	const int insn_cnt = env->prog->len;
18063 	int i;
18064 
18065 	for (i = 0; i < insn_cnt; i++) {
18066 		if (aux_data[i].seen)
18067 			continue;
18068 		memcpy(insn + i, &trap, sizeof(trap));
18069 		aux_data[i].zext_dst = false;
18070 	}
18071 }
18072 
18073 static bool insn_is_cond_jump(u8 code)
18074 {
18075 	u8 op;
18076 
18077 	op = BPF_OP(code);
18078 	if (BPF_CLASS(code) == BPF_JMP32)
18079 		return op != BPF_JA;
18080 
18081 	if (BPF_CLASS(code) != BPF_JMP)
18082 		return false;
18083 
18084 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18085 }
18086 
18087 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18088 {
18089 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18090 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18091 	struct bpf_insn *insn = env->prog->insnsi;
18092 	const int insn_cnt = env->prog->len;
18093 	int i;
18094 
18095 	for (i = 0; i < insn_cnt; i++, insn++) {
18096 		if (!insn_is_cond_jump(insn->code))
18097 			continue;
18098 
18099 		if (!aux_data[i + 1].seen)
18100 			ja.off = insn->off;
18101 		else if (!aux_data[i + 1 + insn->off].seen)
18102 			ja.off = 0;
18103 		else
18104 			continue;
18105 
18106 		if (bpf_prog_is_offloaded(env->prog->aux))
18107 			bpf_prog_offload_replace_insn(env, i, &ja);
18108 
18109 		memcpy(insn, &ja, sizeof(ja));
18110 	}
18111 }
18112 
18113 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18114 {
18115 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18116 	int insn_cnt = env->prog->len;
18117 	int i, err;
18118 
18119 	for (i = 0; i < insn_cnt; i++) {
18120 		int j;
18121 
18122 		j = 0;
18123 		while (i + j < insn_cnt && !aux_data[i + j].seen)
18124 			j++;
18125 		if (!j)
18126 			continue;
18127 
18128 		err = verifier_remove_insns(env, i, j);
18129 		if (err)
18130 			return err;
18131 		insn_cnt = env->prog->len;
18132 	}
18133 
18134 	return 0;
18135 }
18136 
18137 static int opt_remove_nops(struct bpf_verifier_env *env)
18138 {
18139 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18140 	struct bpf_insn *insn = env->prog->insnsi;
18141 	int insn_cnt = env->prog->len;
18142 	int i, err;
18143 
18144 	for (i = 0; i < insn_cnt; i++) {
18145 		if (memcmp(&insn[i], &ja, sizeof(ja)))
18146 			continue;
18147 
18148 		err = verifier_remove_insns(env, i, 1);
18149 		if (err)
18150 			return err;
18151 		insn_cnt--;
18152 		i--;
18153 	}
18154 
18155 	return 0;
18156 }
18157 
18158 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18159 					 const union bpf_attr *attr)
18160 {
18161 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18162 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18163 	int i, patch_len, delta = 0, len = env->prog->len;
18164 	struct bpf_insn *insns = env->prog->insnsi;
18165 	struct bpf_prog *new_prog;
18166 	bool rnd_hi32;
18167 
18168 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18169 	zext_patch[1] = BPF_ZEXT_REG(0);
18170 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18171 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18172 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18173 	for (i = 0; i < len; i++) {
18174 		int adj_idx = i + delta;
18175 		struct bpf_insn insn;
18176 		int load_reg;
18177 
18178 		insn = insns[adj_idx];
18179 		load_reg = insn_def_regno(&insn);
18180 		if (!aux[adj_idx].zext_dst) {
18181 			u8 code, class;
18182 			u32 imm_rnd;
18183 
18184 			if (!rnd_hi32)
18185 				continue;
18186 
18187 			code = insn.code;
18188 			class = BPF_CLASS(code);
18189 			if (load_reg == -1)
18190 				continue;
18191 
18192 			/* NOTE: arg "reg" (the fourth one) is only used for
18193 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
18194 			 *       here.
18195 			 */
18196 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18197 				if (class == BPF_LD &&
18198 				    BPF_MODE(code) == BPF_IMM)
18199 					i++;
18200 				continue;
18201 			}
18202 
18203 			/* ctx load could be transformed into wider load. */
18204 			if (class == BPF_LDX &&
18205 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
18206 				continue;
18207 
18208 			imm_rnd = get_random_u32();
18209 			rnd_hi32_patch[0] = insn;
18210 			rnd_hi32_patch[1].imm = imm_rnd;
18211 			rnd_hi32_patch[3].dst_reg = load_reg;
18212 			patch = rnd_hi32_patch;
18213 			patch_len = 4;
18214 			goto apply_patch_buffer;
18215 		}
18216 
18217 		/* Add in an zero-extend instruction if a) the JIT has requested
18218 		 * it or b) it's a CMPXCHG.
18219 		 *
18220 		 * The latter is because: BPF_CMPXCHG always loads a value into
18221 		 * R0, therefore always zero-extends. However some archs'
18222 		 * equivalent instruction only does this load when the
18223 		 * comparison is successful. This detail of CMPXCHG is
18224 		 * orthogonal to the general zero-extension behaviour of the
18225 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
18226 		 */
18227 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18228 			continue;
18229 
18230 		/* Zero-extension is done by the caller. */
18231 		if (bpf_pseudo_kfunc_call(&insn))
18232 			continue;
18233 
18234 		if (WARN_ON(load_reg == -1)) {
18235 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18236 			return -EFAULT;
18237 		}
18238 
18239 		zext_patch[0] = insn;
18240 		zext_patch[1].dst_reg = load_reg;
18241 		zext_patch[1].src_reg = load_reg;
18242 		patch = zext_patch;
18243 		patch_len = 2;
18244 apply_patch_buffer:
18245 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18246 		if (!new_prog)
18247 			return -ENOMEM;
18248 		env->prog = new_prog;
18249 		insns = new_prog->insnsi;
18250 		aux = env->insn_aux_data;
18251 		delta += patch_len - 1;
18252 	}
18253 
18254 	return 0;
18255 }
18256 
18257 /* convert load instructions that access fields of a context type into a
18258  * sequence of instructions that access fields of the underlying structure:
18259  *     struct __sk_buff    -> struct sk_buff
18260  *     struct bpf_sock_ops -> struct sock
18261  */
18262 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18263 {
18264 	const struct bpf_verifier_ops *ops = env->ops;
18265 	int i, cnt, size, ctx_field_size, delta = 0;
18266 	const int insn_cnt = env->prog->len;
18267 	struct bpf_insn insn_buf[16], *insn;
18268 	u32 target_size, size_default, off;
18269 	struct bpf_prog *new_prog;
18270 	enum bpf_access_type type;
18271 	bool is_narrower_load;
18272 
18273 	if (ops->gen_prologue || env->seen_direct_write) {
18274 		if (!ops->gen_prologue) {
18275 			verbose(env, "bpf verifier is misconfigured\n");
18276 			return -EINVAL;
18277 		}
18278 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18279 					env->prog);
18280 		if (cnt >= ARRAY_SIZE(insn_buf)) {
18281 			verbose(env, "bpf verifier is misconfigured\n");
18282 			return -EINVAL;
18283 		} else if (cnt) {
18284 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18285 			if (!new_prog)
18286 				return -ENOMEM;
18287 
18288 			env->prog = new_prog;
18289 			delta += cnt - 1;
18290 		}
18291 	}
18292 
18293 	if (bpf_prog_is_offloaded(env->prog->aux))
18294 		return 0;
18295 
18296 	insn = env->prog->insnsi + delta;
18297 
18298 	for (i = 0; i < insn_cnt; i++, insn++) {
18299 		bpf_convert_ctx_access_t convert_ctx_access;
18300 		u8 mode;
18301 
18302 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18303 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18304 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18305 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18306 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18307 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18308 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18309 			type = BPF_READ;
18310 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18311 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18312 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18313 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18314 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18315 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18316 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18317 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18318 			type = BPF_WRITE;
18319 		} else {
18320 			continue;
18321 		}
18322 
18323 		if (type == BPF_WRITE &&
18324 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
18325 			struct bpf_insn patch[] = {
18326 				*insn,
18327 				BPF_ST_NOSPEC(),
18328 			};
18329 
18330 			cnt = ARRAY_SIZE(patch);
18331 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18332 			if (!new_prog)
18333 				return -ENOMEM;
18334 
18335 			delta    += cnt - 1;
18336 			env->prog = new_prog;
18337 			insn      = new_prog->insnsi + i + delta;
18338 			continue;
18339 		}
18340 
18341 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18342 		case PTR_TO_CTX:
18343 			if (!ops->convert_ctx_access)
18344 				continue;
18345 			convert_ctx_access = ops->convert_ctx_access;
18346 			break;
18347 		case PTR_TO_SOCKET:
18348 		case PTR_TO_SOCK_COMMON:
18349 			convert_ctx_access = bpf_sock_convert_ctx_access;
18350 			break;
18351 		case PTR_TO_TCP_SOCK:
18352 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18353 			break;
18354 		case PTR_TO_XDP_SOCK:
18355 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18356 			break;
18357 		case PTR_TO_BTF_ID:
18358 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18359 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18360 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18361 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18362 		 * any faults for loads into such types. BPF_WRITE is disallowed
18363 		 * for this case.
18364 		 */
18365 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18366 			if (type == BPF_READ) {
18367 				if (BPF_MODE(insn->code) == BPF_MEM)
18368 					insn->code = BPF_LDX | BPF_PROBE_MEM |
18369 						     BPF_SIZE((insn)->code);
18370 				else
18371 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18372 						     BPF_SIZE((insn)->code);
18373 				env->prog->aux->num_exentries++;
18374 			}
18375 			continue;
18376 		default:
18377 			continue;
18378 		}
18379 
18380 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18381 		size = BPF_LDST_BYTES(insn);
18382 		mode = BPF_MODE(insn->code);
18383 
18384 		/* If the read access is a narrower load of the field,
18385 		 * convert to a 4/8-byte load, to minimum program type specific
18386 		 * convert_ctx_access changes. If conversion is successful,
18387 		 * we will apply proper mask to the result.
18388 		 */
18389 		is_narrower_load = size < ctx_field_size;
18390 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18391 		off = insn->off;
18392 		if (is_narrower_load) {
18393 			u8 size_code;
18394 
18395 			if (type == BPF_WRITE) {
18396 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18397 				return -EINVAL;
18398 			}
18399 
18400 			size_code = BPF_H;
18401 			if (ctx_field_size == 4)
18402 				size_code = BPF_W;
18403 			else if (ctx_field_size == 8)
18404 				size_code = BPF_DW;
18405 
18406 			insn->off = off & ~(size_default - 1);
18407 			insn->code = BPF_LDX | BPF_MEM | size_code;
18408 		}
18409 
18410 		target_size = 0;
18411 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18412 					 &target_size);
18413 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18414 		    (ctx_field_size && !target_size)) {
18415 			verbose(env, "bpf verifier is misconfigured\n");
18416 			return -EINVAL;
18417 		}
18418 
18419 		if (is_narrower_load && size < target_size) {
18420 			u8 shift = bpf_ctx_narrow_access_offset(
18421 				off, size, size_default) * 8;
18422 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18423 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18424 				return -EINVAL;
18425 			}
18426 			if (ctx_field_size <= 4) {
18427 				if (shift)
18428 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18429 									insn->dst_reg,
18430 									shift);
18431 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18432 								(1 << size * 8) - 1);
18433 			} else {
18434 				if (shift)
18435 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18436 									insn->dst_reg,
18437 									shift);
18438 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18439 								(1ULL << size * 8) - 1);
18440 			}
18441 		}
18442 		if (mode == BPF_MEMSX)
18443 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18444 						       insn->dst_reg, insn->dst_reg,
18445 						       size * 8, 0);
18446 
18447 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18448 		if (!new_prog)
18449 			return -ENOMEM;
18450 
18451 		delta += cnt - 1;
18452 
18453 		/* keep walking new program and skip insns we just inserted */
18454 		env->prog = new_prog;
18455 		insn      = new_prog->insnsi + i + delta;
18456 	}
18457 
18458 	return 0;
18459 }
18460 
18461 static int jit_subprogs(struct bpf_verifier_env *env)
18462 {
18463 	struct bpf_prog *prog = env->prog, **func, *tmp;
18464 	int i, j, subprog_start, subprog_end = 0, len, subprog;
18465 	struct bpf_map *map_ptr;
18466 	struct bpf_insn *insn;
18467 	void *old_bpf_func;
18468 	int err, num_exentries;
18469 
18470 	if (env->subprog_cnt <= 1)
18471 		return 0;
18472 
18473 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18474 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18475 			continue;
18476 
18477 		/* Upon error here we cannot fall back to interpreter but
18478 		 * need a hard reject of the program. Thus -EFAULT is
18479 		 * propagated in any case.
18480 		 */
18481 		subprog = find_subprog(env, i + insn->imm + 1);
18482 		if (subprog < 0) {
18483 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18484 				  i + insn->imm + 1);
18485 			return -EFAULT;
18486 		}
18487 		/* temporarily remember subprog id inside insn instead of
18488 		 * aux_data, since next loop will split up all insns into funcs
18489 		 */
18490 		insn->off = subprog;
18491 		/* remember original imm in case JIT fails and fallback
18492 		 * to interpreter will be needed
18493 		 */
18494 		env->insn_aux_data[i].call_imm = insn->imm;
18495 		/* point imm to __bpf_call_base+1 from JITs point of view */
18496 		insn->imm = 1;
18497 		if (bpf_pseudo_func(insn))
18498 			/* jit (e.g. x86_64) may emit fewer instructions
18499 			 * if it learns a u32 imm is the same as a u64 imm.
18500 			 * Force a non zero here.
18501 			 */
18502 			insn[1].imm = 1;
18503 	}
18504 
18505 	err = bpf_prog_alloc_jited_linfo(prog);
18506 	if (err)
18507 		goto out_undo_insn;
18508 
18509 	err = -ENOMEM;
18510 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18511 	if (!func)
18512 		goto out_undo_insn;
18513 
18514 	for (i = 0; i < env->subprog_cnt; i++) {
18515 		subprog_start = subprog_end;
18516 		subprog_end = env->subprog_info[i + 1].start;
18517 
18518 		len = subprog_end - subprog_start;
18519 		/* bpf_prog_run() doesn't call subprogs directly,
18520 		 * hence main prog stats include the runtime of subprogs.
18521 		 * subprogs don't have IDs and not reachable via prog_get_next_id
18522 		 * func[i]->stats will never be accessed and stays NULL
18523 		 */
18524 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18525 		if (!func[i])
18526 			goto out_free;
18527 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18528 		       len * sizeof(struct bpf_insn));
18529 		func[i]->type = prog->type;
18530 		func[i]->len = len;
18531 		if (bpf_prog_calc_tag(func[i]))
18532 			goto out_free;
18533 		func[i]->is_func = 1;
18534 		func[i]->aux->func_idx = i;
18535 		/* Below members will be freed only at prog->aux */
18536 		func[i]->aux->btf = prog->aux->btf;
18537 		func[i]->aux->func_info = prog->aux->func_info;
18538 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18539 		func[i]->aux->poke_tab = prog->aux->poke_tab;
18540 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18541 
18542 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
18543 			struct bpf_jit_poke_descriptor *poke;
18544 
18545 			poke = &prog->aux->poke_tab[j];
18546 			if (poke->insn_idx < subprog_end &&
18547 			    poke->insn_idx >= subprog_start)
18548 				poke->aux = func[i]->aux;
18549 		}
18550 
18551 		func[i]->aux->name[0] = 'F';
18552 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18553 		func[i]->jit_requested = 1;
18554 		func[i]->blinding_requested = prog->blinding_requested;
18555 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18556 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18557 		func[i]->aux->linfo = prog->aux->linfo;
18558 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18559 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18560 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18561 		num_exentries = 0;
18562 		insn = func[i]->insnsi;
18563 		for (j = 0; j < func[i]->len; j++, insn++) {
18564 			if (BPF_CLASS(insn->code) == BPF_LDX &&
18565 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18566 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18567 				num_exentries++;
18568 		}
18569 		func[i]->aux->num_exentries = num_exentries;
18570 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18571 		func[i] = bpf_int_jit_compile(func[i]);
18572 		if (!func[i]->jited) {
18573 			err = -ENOTSUPP;
18574 			goto out_free;
18575 		}
18576 		cond_resched();
18577 	}
18578 
18579 	/* at this point all bpf functions were successfully JITed
18580 	 * now populate all bpf_calls with correct addresses and
18581 	 * run last pass of JIT
18582 	 */
18583 	for (i = 0; i < env->subprog_cnt; i++) {
18584 		insn = func[i]->insnsi;
18585 		for (j = 0; j < func[i]->len; j++, insn++) {
18586 			if (bpf_pseudo_func(insn)) {
18587 				subprog = insn->off;
18588 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18589 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18590 				continue;
18591 			}
18592 			if (!bpf_pseudo_call(insn))
18593 				continue;
18594 			subprog = insn->off;
18595 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18596 		}
18597 
18598 		/* we use the aux data to keep a list of the start addresses
18599 		 * of the JITed images for each function in the program
18600 		 *
18601 		 * for some architectures, such as powerpc64, the imm field
18602 		 * might not be large enough to hold the offset of the start
18603 		 * address of the callee's JITed image from __bpf_call_base
18604 		 *
18605 		 * in such cases, we can lookup the start address of a callee
18606 		 * by using its subprog id, available from the off field of
18607 		 * the call instruction, as an index for this list
18608 		 */
18609 		func[i]->aux->func = func;
18610 		func[i]->aux->func_cnt = env->subprog_cnt;
18611 	}
18612 	for (i = 0; i < env->subprog_cnt; i++) {
18613 		old_bpf_func = func[i]->bpf_func;
18614 		tmp = bpf_int_jit_compile(func[i]);
18615 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18616 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18617 			err = -ENOTSUPP;
18618 			goto out_free;
18619 		}
18620 		cond_resched();
18621 	}
18622 
18623 	/* finally lock prog and jit images for all functions and
18624 	 * populate kallsysm. Begin at the first subprogram, since
18625 	 * bpf_prog_load will add the kallsyms for the main program.
18626 	 */
18627 	for (i = 1; i < env->subprog_cnt; i++) {
18628 		bpf_prog_lock_ro(func[i]);
18629 		bpf_prog_kallsyms_add(func[i]);
18630 	}
18631 
18632 	/* Last step: make now unused interpreter insns from main
18633 	 * prog consistent for later dump requests, so they can
18634 	 * later look the same as if they were interpreted only.
18635 	 */
18636 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18637 		if (bpf_pseudo_func(insn)) {
18638 			insn[0].imm = env->insn_aux_data[i].call_imm;
18639 			insn[1].imm = insn->off;
18640 			insn->off = 0;
18641 			continue;
18642 		}
18643 		if (!bpf_pseudo_call(insn))
18644 			continue;
18645 		insn->off = env->insn_aux_data[i].call_imm;
18646 		subprog = find_subprog(env, i + insn->off + 1);
18647 		insn->imm = subprog;
18648 	}
18649 
18650 	prog->jited = 1;
18651 	prog->bpf_func = func[0]->bpf_func;
18652 	prog->jited_len = func[0]->jited_len;
18653 	prog->aux->extable = func[0]->aux->extable;
18654 	prog->aux->num_exentries = func[0]->aux->num_exentries;
18655 	prog->aux->func = func;
18656 	prog->aux->func_cnt = env->subprog_cnt;
18657 	bpf_prog_jit_attempt_done(prog);
18658 	return 0;
18659 out_free:
18660 	/* We failed JIT'ing, so at this point we need to unregister poke
18661 	 * descriptors from subprogs, so that kernel is not attempting to
18662 	 * patch it anymore as we're freeing the subprog JIT memory.
18663 	 */
18664 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18665 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18666 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18667 	}
18668 	/* At this point we're guaranteed that poke descriptors are not
18669 	 * live anymore. We can just unlink its descriptor table as it's
18670 	 * released with the main prog.
18671 	 */
18672 	for (i = 0; i < env->subprog_cnt; i++) {
18673 		if (!func[i])
18674 			continue;
18675 		func[i]->aux->poke_tab = NULL;
18676 		bpf_jit_free(func[i]);
18677 	}
18678 	kfree(func);
18679 out_undo_insn:
18680 	/* cleanup main prog to be interpreted */
18681 	prog->jit_requested = 0;
18682 	prog->blinding_requested = 0;
18683 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18684 		if (!bpf_pseudo_call(insn))
18685 			continue;
18686 		insn->off = 0;
18687 		insn->imm = env->insn_aux_data[i].call_imm;
18688 	}
18689 	bpf_prog_jit_attempt_done(prog);
18690 	return err;
18691 }
18692 
18693 static int fixup_call_args(struct bpf_verifier_env *env)
18694 {
18695 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18696 	struct bpf_prog *prog = env->prog;
18697 	struct bpf_insn *insn = prog->insnsi;
18698 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18699 	int i, depth;
18700 #endif
18701 	int err = 0;
18702 
18703 	if (env->prog->jit_requested &&
18704 	    !bpf_prog_is_offloaded(env->prog->aux)) {
18705 		err = jit_subprogs(env);
18706 		if (err == 0)
18707 			return 0;
18708 		if (err == -EFAULT)
18709 			return err;
18710 	}
18711 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18712 	if (has_kfunc_call) {
18713 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18714 		return -EINVAL;
18715 	}
18716 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18717 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
18718 		 * have to be rejected, since interpreter doesn't support them yet.
18719 		 */
18720 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18721 		return -EINVAL;
18722 	}
18723 	for (i = 0; i < prog->len; i++, insn++) {
18724 		if (bpf_pseudo_func(insn)) {
18725 			/* When JIT fails the progs with callback calls
18726 			 * have to be rejected, since interpreter doesn't support them yet.
18727 			 */
18728 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
18729 			return -EINVAL;
18730 		}
18731 
18732 		if (!bpf_pseudo_call(insn))
18733 			continue;
18734 		depth = get_callee_stack_depth(env, insn, i);
18735 		if (depth < 0)
18736 			return depth;
18737 		bpf_patch_call_args(insn, depth);
18738 	}
18739 	err = 0;
18740 #endif
18741 	return err;
18742 }
18743 
18744 /* replace a generic kfunc with a specialized version if necessary */
18745 static void specialize_kfunc(struct bpf_verifier_env *env,
18746 			     u32 func_id, u16 offset, unsigned long *addr)
18747 {
18748 	struct bpf_prog *prog = env->prog;
18749 	bool seen_direct_write;
18750 	void *xdp_kfunc;
18751 	bool is_rdonly;
18752 
18753 	if (bpf_dev_bound_kfunc_id(func_id)) {
18754 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18755 		if (xdp_kfunc) {
18756 			*addr = (unsigned long)xdp_kfunc;
18757 			return;
18758 		}
18759 		/* fallback to default kfunc when not supported by netdev */
18760 	}
18761 
18762 	if (offset)
18763 		return;
18764 
18765 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18766 		seen_direct_write = env->seen_direct_write;
18767 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18768 
18769 		if (is_rdonly)
18770 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18771 
18772 		/* restore env->seen_direct_write to its original value, since
18773 		 * may_access_direct_pkt_data mutates it
18774 		 */
18775 		env->seen_direct_write = seen_direct_write;
18776 	}
18777 }
18778 
18779 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18780 					    u16 struct_meta_reg,
18781 					    u16 node_offset_reg,
18782 					    struct bpf_insn *insn,
18783 					    struct bpf_insn *insn_buf,
18784 					    int *cnt)
18785 {
18786 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18787 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18788 
18789 	insn_buf[0] = addr[0];
18790 	insn_buf[1] = addr[1];
18791 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18792 	insn_buf[3] = *insn;
18793 	*cnt = 4;
18794 }
18795 
18796 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18797 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18798 {
18799 	const struct bpf_kfunc_desc *desc;
18800 
18801 	if (!insn->imm) {
18802 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18803 		return -EINVAL;
18804 	}
18805 
18806 	*cnt = 0;
18807 
18808 	/* insn->imm has the btf func_id. Replace it with an offset relative to
18809 	 * __bpf_call_base, unless the JIT needs to call functions that are
18810 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18811 	 */
18812 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18813 	if (!desc) {
18814 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18815 			insn->imm);
18816 		return -EFAULT;
18817 	}
18818 
18819 	if (!bpf_jit_supports_far_kfunc_call())
18820 		insn->imm = BPF_CALL_IMM(desc->addr);
18821 	if (insn->off)
18822 		return 0;
18823 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18824 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18825 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18826 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18827 
18828 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18829 		insn_buf[1] = addr[0];
18830 		insn_buf[2] = addr[1];
18831 		insn_buf[3] = *insn;
18832 		*cnt = 4;
18833 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18834 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18835 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18836 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18837 
18838 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
18839 		    !kptr_struct_meta) {
18840 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18841 				insn_idx);
18842 			return -EFAULT;
18843 		}
18844 
18845 		insn_buf[0] = addr[0];
18846 		insn_buf[1] = addr[1];
18847 		insn_buf[2] = *insn;
18848 		*cnt = 3;
18849 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18850 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18851 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18852 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18853 		int struct_meta_reg = BPF_REG_3;
18854 		int node_offset_reg = BPF_REG_4;
18855 
18856 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18857 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18858 			struct_meta_reg = BPF_REG_4;
18859 			node_offset_reg = BPF_REG_5;
18860 		}
18861 
18862 		if (!kptr_struct_meta) {
18863 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18864 				insn_idx);
18865 			return -EFAULT;
18866 		}
18867 
18868 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18869 						node_offset_reg, insn, insn_buf, cnt);
18870 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18871 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18872 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18873 		*cnt = 1;
18874 	}
18875 	return 0;
18876 }
18877 
18878 /* Do various post-verification rewrites in a single program pass.
18879  * These rewrites simplify JIT and interpreter implementations.
18880  */
18881 static int do_misc_fixups(struct bpf_verifier_env *env)
18882 {
18883 	struct bpf_prog *prog = env->prog;
18884 	enum bpf_attach_type eatype = prog->expected_attach_type;
18885 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18886 	struct bpf_insn *insn = prog->insnsi;
18887 	const struct bpf_func_proto *fn;
18888 	const int insn_cnt = prog->len;
18889 	const struct bpf_map_ops *ops;
18890 	struct bpf_insn_aux_data *aux;
18891 	struct bpf_insn insn_buf[16];
18892 	struct bpf_prog *new_prog;
18893 	struct bpf_map *map_ptr;
18894 	int i, ret, cnt, delta = 0;
18895 
18896 	for (i = 0; i < insn_cnt; i++, insn++) {
18897 		/* Make divide-by-zero exceptions impossible. */
18898 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18899 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18900 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18901 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18902 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18903 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18904 			struct bpf_insn *patchlet;
18905 			struct bpf_insn chk_and_div[] = {
18906 				/* [R,W]x div 0 -> 0 */
18907 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18908 					     BPF_JNE | BPF_K, insn->src_reg,
18909 					     0, 2, 0),
18910 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18911 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18912 				*insn,
18913 			};
18914 			struct bpf_insn chk_and_mod[] = {
18915 				/* [R,W]x mod 0 -> [R,W]x */
18916 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18917 					     BPF_JEQ | BPF_K, insn->src_reg,
18918 					     0, 1 + (is64 ? 0 : 1), 0),
18919 				*insn,
18920 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18921 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18922 			};
18923 
18924 			patchlet = isdiv ? chk_and_div : chk_and_mod;
18925 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18926 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18927 
18928 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18929 			if (!new_prog)
18930 				return -ENOMEM;
18931 
18932 			delta    += cnt - 1;
18933 			env->prog = prog = new_prog;
18934 			insn      = new_prog->insnsi + i + delta;
18935 			continue;
18936 		}
18937 
18938 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18939 		if (BPF_CLASS(insn->code) == BPF_LD &&
18940 		    (BPF_MODE(insn->code) == BPF_ABS ||
18941 		     BPF_MODE(insn->code) == BPF_IND)) {
18942 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
18943 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18944 				verbose(env, "bpf verifier is misconfigured\n");
18945 				return -EINVAL;
18946 			}
18947 
18948 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18949 			if (!new_prog)
18950 				return -ENOMEM;
18951 
18952 			delta    += cnt - 1;
18953 			env->prog = prog = new_prog;
18954 			insn      = new_prog->insnsi + i + delta;
18955 			continue;
18956 		}
18957 
18958 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
18959 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18960 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18961 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18962 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18963 			struct bpf_insn *patch = &insn_buf[0];
18964 			bool issrc, isneg, isimm;
18965 			u32 off_reg;
18966 
18967 			aux = &env->insn_aux_data[i + delta];
18968 			if (!aux->alu_state ||
18969 			    aux->alu_state == BPF_ALU_NON_POINTER)
18970 				continue;
18971 
18972 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18973 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18974 				BPF_ALU_SANITIZE_SRC;
18975 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18976 
18977 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
18978 			if (isimm) {
18979 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18980 			} else {
18981 				if (isneg)
18982 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18983 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18984 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18985 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18986 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18987 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18988 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18989 			}
18990 			if (!issrc)
18991 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18992 			insn->src_reg = BPF_REG_AX;
18993 			if (isneg)
18994 				insn->code = insn->code == code_add ?
18995 					     code_sub : code_add;
18996 			*patch++ = *insn;
18997 			if (issrc && isneg && !isimm)
18998 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18999 			cnt = patch - insn_buf;
19000 
19001 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19002 			if (!new_prog)
19003 				return -ENOMEM;
19004 
19005 			delta    += cnt - 1;
19006 			env->prog = prog = new_prog;
19007 			insn      = new_prog->insnsi + i + delta;
19008 			continue;
19009 		}
19010 
19011 		if (insn->code != (BPF_JMP | BPF_CALL))
19012 			continue;
19013 		if (insn->src_reg == BPF_PSEUDO_CALL)
19014 			continue;
19015 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19016 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19017 			if (ret)
19018 				return ret;
19019 			if (cnt == 0)
19020 				continue;
19021 
19022 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19023 			if (!new_prog)
19024 				return -ENOMEM;
19025 
19026 			delta	 += cnt - 1;
19027 			env->prog = prog = new_prog;
19028 			insn	  = new_prog->insnsi + i + delta;
19029 			continue;
19030 		}
19031 
19032 		if (insn->imm == BPF_FUNC_get_route_realm)
19033 			prog->dst_needed = 1;
19034 		if (insn->imm == BPF_FUNC_get_prandom_u32)
19035 			bpf_user_rnd_init_once();
19036 		if (insn->imm == BPF_FUNC_override_return)
19037 			prog->kprobe_override = 1;
19038 		if (insn->imm == BPF_FUNC_tail_call) {
19039 			/* If we tail call into other programs, we
19040 			 * cannot make any assumptions since they can
19041 			 * be replaced dynamically during runtime in
19042 			 * the program array.
19043 			 */
19044 			prog->cb_access = 1;
19045 			if (!allow_tail_call_in_subprogs(env))
19046 				prog->aux->stack_depth = MAX_BPF_STACK;
19047 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19048 
19049 			/* mark bpf_tail_call as different opcode to avoid
19050 			 * conditional branch in the interpreter for every normal
19051 			 * call and to prevent accidental JITing by JIT compiler
19052 			 * that doesn't support bpf_tail_call yet
19053 			 */
19054 			insn->imm = 0;
19055 			insn->code = BPF_JMP | BPF_TAIL_CALL;
19056 
19057 			aux = &env->insn_aux_data[i + delta];
19058 			if (env->bpf_capable && !prog->blinding_requested &&
19059 			    prog->jit_requested &&
19060 			    !bpf_map_key_poisoned(aux) &&
19061 			    !bpf_map_ptr_poisoned(aux) &&
19062 			    !bpf_map_ptr_unpriv(aux)) {
19063 				struct bpf_jit_poke_descriptor desc = {
19064 					.reason = BPF_POKE_REASON_TAIL_CALL,
19065 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19066 					.tail_call.key = bpf_map_key_immediate(aux),
19067 					.insn_idx = i + delta,
19068 				};
19069 
19070 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
19071 				if (ret < 0) {
19072 					verbose(env, "adding tail call poke descriptor failed\n");
19073 					return ret;
19074 				}
19075 
19076 				insn->imm = ret + 1;
19077 				continue;
19078 			}
19079 
19080 			if (!bpf_map_ptr_unpriv(aux))
19081 				continue;
19082 
19083 			/* instead of changing every JIT dealing with tail_call
19084 			 * emit two extra insns:
19085 			 * if (index >= max_entries) goto out;
19086 			 * index &= array->index_mask;
19087 			 * to avoid out-of-bounds cpu speculation
19088 			 */
19089 			if (bpf_map_ptr_poisoned(aux)) {
19090 				verbose(env, "tail_call abusing map_ptr\n");
19091 				return -EINVAL;
19092 			}
19093 
19094 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19095 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19096 						  map_ptr->max_entries, 2);
19097 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19098 						    container_of(map_ptr,
19099 								 struct bpf_array,
19100 								 map)->index_mask);
19101 			insn_buf[2] = *insn;
19102 			cnt = 3;
19103 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19104 			if (!new_prog)
19105 				return -ENOMEM;
19106 
19107 			delta    += cnt - 1;
19108 			env->prog = prog = new_prog;
19109 			insn      = new_prog->insnsi + i + delta;
19110 			continue;
19111 		}
19112 
19113 		if (insn->imm == BPF_FUNC_timer_set_callback) {
19114 			/* The verifier will process callback_fn as many times as necessary
19115 			 * with different maps and the register states prepared by
19116 			 * set_timer_callback_state will be accurate.
19117 			 *
19118 			 * The following use case is valid:
19119 			 *   map1 is shared by prog1, prog2, prog3.
19120 			 *   prog1 calls bpf_timer_init for some map1 elements
19121 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
19122 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
19123 			 *   prog3 calls bpf_timer_start for some map1 elements.
19124 			 *     Those that were not both bpf_timer_init-ed and
19125 			 *     bpf_timer_set_callback-ed will return -EINVAL.
19126 			 */
19127 			struct bpf_insn ld_addrs[2] = {
19128 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19129 			};
19130 
19131 			insn_buf[0] = ld_addrs[0];
19132 			insn_buf[1] = ld_addrs[1];
19133 			insn_buf[2] = *insn;
19134 			cnt = 3;
19135 
19136 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19137 			if (!new_prog)
19138 				return -ENOMEM;
19139 
19140 			delta    += cnt - 1;
19141 			env->prog = prog = new_prog;
19142 			insn      = new_prog->insnsi + i + delta;
19143 			goto patch_call_imm;
19144 		}
19145 
19146 		if (is_storage_get_function(insn->imm)) {
19147 			if (!env->prog->aux->sleepable ||
19148 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
19149 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19150 			else
19151 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19152 			insn_buf[1] = *insn;
19153 			cnt = 2;
19154 
19155 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19156 			if (!new_prog)
19157 				return -ENOMEM;
19158 
19159 			delta += cnt - 1;
19160 			env->prog = prog = new_prog;
19161 			insn = new_prog->insnsi + i + delta;
19162 			goto patch_call_imm;
19163 		}
19164 
19165 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19166 		 * and other inlining handlers are currently limited to 64 bit
19167 		 * only.
19168 		 */
19169 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19170 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
19171 		     insn->imm == BPF_FUNC_map_update_elem ||
19172 		     insn->imm == BPF_FUNC_map_delete_elem ||
19173 		     insn->imm == BPF_FUNC_map_push_elem   ||
19174 		     insn->imm == BPF_FUNC_map_pop_elem    ||
19175 		     insn->imm == BPF_FUNC_map_peek_elem   ||
19176 		     insn->imm == BPF_FUNC_redirect_map    ||
19177 		     insn->imm == BPF_FUNC_for_each_map_elem ||
19178 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19179 			aux = &env->insn_aux_data[i + delta];
19180 			if (bpf_map_ptr_poisoned(aux))
19181 				goto patch_call_imm;
19182 
19183 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19184 			ops = map_ptr->ops;
19185 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
19186 			    ops->map_gen_lookup) {
19187 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19188 				if (cnt == -EOPNOTSUPP)
19189 					goto patch_map_ops_generic;
19190 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19191 					verbose(env, "bpf verifier is misconfigured\n");
19192 					return -EINVAL;
19193 				}
19194 
19195 				new_prog = bpf_patch_insn_data(env, i + delta,
19196 							       insn_buf, cnt);
19197 				if (!new_prog)
19198 					return -ENOMEM;
19199 
19200 				delta    += cnt - 1;
19201 				env->prog = prog = new_prog;
19202 				insn      = new_prog->insnsi + i + delta;
19203 				continue;
19204 			}
19205 
19206 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19207 				     (void *(*)(struct bpf_map *map, void *key))NULL));
19208 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19209 				     (long (*)(struct bpf_map *map, void *key))NULL));
19210 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19211 				     (long (*)(struct bpf_map *map, void *key, void *value,
19212 					      u64 flags))NULL));
19213 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19214 				     (long (*)(struct bpf_map *map, void *value,
19215 					      u64 flags))NULL));
19216 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19217 				     (long (*)(struct bpf_map *map, void *value))NULL));
19218 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19219 				     (long (*)(struct bpf_map *map, void *value))NULL));
19220 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
19221 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19222 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19223 				     (long (*)(struct bpf_map *map,
19224 					      bpf_callback_t callback_fn,
19225 					      void *callback_ctx,
19226 					      u64 flags))NULL));
19227 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19228 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19229 
19230 patch_map_ops_generic:
19231 			switch (insn->imm) {
19232 			case BPF_FUNC_map_lookup_elem:
19233 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19234 				continue;
19235 			case BPF_FUNC_map_update_elem:
19236 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19237 				continue;
19238 			case BPF_FUNC_map_delete_elem:
19239 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19240 				continue;
19241 			case BPF_FUNC_map_push_elem:
19242 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19243 				continue;
19244 			case BPF_FUNC_map_pop_elem:
19245 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19246 				continue;
19247 			case BPF_FUNC_map_peek_elem:
19248 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19249 				continue;
19250 			case BPF_FUNC_redirect_map:
19251 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
19252 				continue;
19253 			case BPF_FUNC_for_each_map_elem:
19254 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19255 				continue;
19256 			case BPF_FUNC_map_lookup_percpu_elem:
19257 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19258 				continue;
19259 			}
19260 
19261 			goto patch_call_imm;
19262 		}
19263 
19264 		/* Implement bpf_jiffies64 inline. */
19265 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19266 		    insn->imm == BPF_FUNC_jiffies64) {
19267 			struct bpf_insn ld_jiffies_addr[2] = {
19268 				BPF_LD_IMM64(BPF_REG_0,
19269 					     (unsigned long)&jiffies),
19270 			};
19271 
19272 			insn_buf[0] = ld_jiffies_addr[0];
19273 			insn_buf[1] = ld_jiffies_addr[1];
19274 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19275 						  BPF_REG_0, 0);
19276 			cnt = 3;
19277 
19278 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19279 						       cnt);
19280 			if (!new_prog)
19281 				return -ENOMEM;
19282 
19283 			delta    += cnt - 1;
19284 			env->prog = prog = new_prog;
19285 			insn      = new_prog->insnsi + i + delta;
19286 			continue;
19287 		}
19288 
19289 		/* Implement bpf_get_func_arg inline. */
19290 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19291 		    insn->imm == BPF_FUNC_get_func_arg) {
19292 			/* Load nr_args from ctx - 8 */
19293 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19294 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19295 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19296 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19297 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19298 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19299 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19300 			insn_buf[7] = BPF_JMP_A(1);
19301 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19302 			cnt = 9;
19303 
19304 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19305 			if (!new_prog)
19306 				return -ENOMEM;
19307 
19308 			delta    += cnt - 1;
19309 			env->prog = prog = new_prog;
19310 			insn      = new_prog->insnsi + i + delta;
19311 			continue;
19312 		}
19313 
19314 		/* Implement bpf_get_func_ret inline. */
19315 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19316 		    insn->imm == BPF_FUNC_get_func_ret) {
19317 			if (eatype == BPF_TRACE_FEXIT ||
19318 			    eatype == BPF_MODIFY_RETURN) {
19319 				/* Load nr_args from ctx - 8 */
19320 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19321 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19322 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19323 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19324 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19325 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19326 				cnt = 6;
19327 			} else {
19328 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19329 				cnt = 1;
19330 			}
19331 
19332 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19333 			if (!new_prog)
19334 				return -ENOMEM;
19335 
19336 			delta    += cnt - 1;
19337 			env->prog = prog = new_prog;
19338 			insn      = new_prog->insnsi + i + delta;
19339 			continue;
19340 		}
19341 
19342 		/* Implement get_func_arg_cnt inline. */
19343 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19344 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
19345 			/* Load nr_args from ctx - 8 */
19346 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19347 
19348 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19349 			if (!new_prog)
19350 				return -ENOMEM;
19351 
19352 			env->prog = prog = new_prog;
19353 			insn      = new_prog->insnsi + i + delta;
19354 			continue;
19355 		}
19356 
19357 		/* Implement bpf_get_func_ip inline. */
19358 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19359 		    insn->imm == BPF_FUNC_get_func_ip) {
19360 			/* Load IP address from ctx - 16 */
19361 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19362 
19363 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19364 			if (!new_prog)
19365 				return -ENOMEM;
19366 
19367 			env->prog = prog = new_prog;
19368 			insn      = new_prog->insnsi + i + delta;
19369 			continue;
19370 		}
19371 
19372 patch_call_imm:
19373 		fn = env->ops->get_func_proto(insn->imm, env->prog);
19374 		/* all functions that have prototype and verifier allowed
19375 		 * programs to call them, must be real in-kernel functions
19376 		 */
19377 		if (!fn->func) {
19378 			verbose(env,
19379 				"kernel subsystem misconfigured func %s#%d\n",
19380 				func_id_name(insn->imm), insn->imm);
19381 			return -EFAULT;
19382 		}
19383 		insn->imm = fn->func - __bpf_call_base;
19384 	}
19385 
19386 	/* Since poke tab is now finalized, publish aux to tracker. */
19387 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19388 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19389 		if (!map_ptr->ops->map_poke_track ||
19390 		    !map_ptr->ops->map_poke_untrack ||
19391 		    !map_ptr->ops->map_poke_run) {
19392 			verbose(env, "bpf verifier is misconfigured\n");
19393 			return -EINVAL;
19394 		}
19395 
19396 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19397 		if (ret < 0) {
19398 			verbose(env, "tracking tail call prog failed\n");
19399 			return ret;
19400 		}
19401 	}
19402 
19403 	sort_kfunc_descs_by_imm_off(env->prog);
19404 
19405 	return 0;
19406 }
19407 
19408 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19409 					int position,
19410 					s32 stack_base,
19411 					u32 callback_subprogno,
19412 					u32 *cnt)
19413 {
19414 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19415 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19416 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19417 	int reg_loop_max = BPF_REG_6;
19418 	int reg_loop_cnt = BPF_REG_7;
19419 	int reg_loop_ctx = BPF_REG_8;
19420 
19421 	struct bpf_prog *new_prog;
19422 	u32 callback_start;
19423 	u32 call_insn_offset;
19424 	s32 callback_offset;
19425 
19426 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
19427 	 * be careful to modify this code in sync.
19428 	 */
19429 	struct bpf_insn insn_buf[] = {
19430 		/* Return error and jump to the end of the patch if
19431 		 * expected number of iterations is too big.
19432 		 */
19433 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19434 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19435 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19436 		/* spill R6, R7, R8 to use these as loop vars */
19437 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19438 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19439 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19440 		/* initialize loop vars */
19441 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19442 		BPF_MOV32_IMM(reg_loop_cnt, 0),
19443 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19444 		/* loop header,
19445 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
19446 		 */
19447 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19448 		/* callback call,
19449 		 * correct callback offset would be set after patching
19450 		 */
19451 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19452 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19453 		BPF_CALL_REL(0),
19454 		/* increment loop counter */
19455 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19456 		/* jump to loop header if callback returned 0 */
19457 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19458 		/* return value of bpf_loop,
19459 		 * set R0 to the number of iterations
19460 		 */
19461 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19462 		/* restore original values of R6, R7, R8 */
19463 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19464 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19465 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19466 	};
19467 
19468 	*cnt = ARRAY_SIZE(insn_buf);
19469 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19470 	if (!new_prog)
19471 		return new_prog;
19472 
19473 	/* callback start is known only after patching */
19474 	callback_start = env->subprog_info[callback_subprogno].start;
19475 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19476 	call_insn_offset = position + 12;
19477 	callback_offset = callback_start - call_insn_offset - 1;
19478 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
19479 
19480 	return new_prog;
19481 }
19482 
19483 static bool is_bpf_loop_call(struct bpf_insn *insn)
19484 {
19485 	return insn->code == (BPF_JMP | BPF_CALL) &&
19486 		insn->src_reg == 0 &&
19487 		insn->imm == BPF_FUNC_loop;
19488 }
19489 
19490 /* For all sub-programs in the program (including main) check
19491  * insn_aux_data to see if there are bpf_loop calls that require
19492  * inlining. If such calls are found the calls are replaced with a
19493  * sequence of instructions produced by `inline_bpf_loop` function and
19494  * subprog stack_depth is increased by the size of 3 registers.
19495  * This stack space is used to spill values of the R6, R7, R8.  These
19496  * registers are used to store the loop bound, counter and context
19497  * variables.
19498  */
19499 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19500 {
19501 	struct bpf_subprog_info *subprogs = env->subprog_info;
19502 	int i, cur_subprog = 0, cnt, delta = 0;
19503 	struct bpf_insn *insn = env->prog->insnsi;
19504 	int insn_cnt = env->prog->len;
19505 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
19506 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19507 	u16 stack_depth_extra = 0;
19508 
19509 	for (i = 0; i < insn_cnt; i++, insn++) {
19510 		struct bpf_loop_inline_state *inline_state =
19511 			&env->insn_aux_data[i + delta].loop_inline_state;
19512 
19513 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19514 			struct bpf_prog *new_prog;
19515 
19516 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19517 			new_prog = inline_bpf_loop(env,
19518 						   i + delta,
19519 						   -(stack_depth + stack_depth_extra),
19520 						   inline_state->callback_subprogno,
19521 						   &cnt);
19522 			if (!new_prog)
19523 				return -ENOMEM;
19524 
19525 			delta     += cnt - 1;
19526 			env->prog  = new_prog;
19527 			insn       = new_prog->insnsi + i + delta;
19528 		}
19529 
19530 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19531 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
19532 			cur_subprog++;
19533 			stack_depth = subprogs[cur_subprog].stack_depth;
19534 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19535 			stack_depth_extra = 0;
19536 		}
19537 	}
19538 
19539 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19540 
19541 	return 0;
19542 }
19543 
19544 static void free_states(struct bpf_verifier_env *env)
19545 {
19546 	struct bpf_verifier_state_list *sl, *sln;
19547 	int i;
19548 
19549 	sl = env->free_list;
19550 	while (sl) {
19551 		sln = sl->next;
19552 		free_verifier_state(&sl->state, false);
19553 		kfree(sl);
19554 		sl = sln;
19555 	}
19556 	env->free_list = NULL;
19557 
19558 	if (!env->explored_states)
19559 		return;
19560 
19561 	for (i = 0; i < state_htab_size(env); i++) {
19562 		sl = env->explored_states[i];
19563 
19564 		while (sl) {
19565 			sln = sl->next;
19566 			free_verifier_state(&sl->state, false);
19567 			kfree(sl);
19568 			sl = sln;
19569 		}
19570 		env->explored_states[i] = NULL;
19571 	}
19572 }
19573 
19574 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19575 {
19576 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19577 	struct bpf_verifier_state *state;
19578 	struct bpf_reg_state *regs;
19579 	int ret, i;
19580 
19581 	env->prev_linfo = NULL;
19582 	env->pass_cnt++;
19583 
19584 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19585 	if (!state)
19586 		return -ENOMEM;
19587 	state->curframe = 0;
19588 	state->speculative = false;
19589 	state->branches = 1;
19590 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19591 	if (!state->frame[0]) {
19592 		kfree(state);
19593 		return -ENOMEM;
19594 	}
19595 	env->cur_state = state;
19596 	init_func_state(env, state->frame[0],
19597 			BPF_MAIN_FUNC /* callsite */,
19598 			0 /* frameno */,
19599 			subprog);
19600 	state->first_insn_idx = env->subprog_info[subprog].start;
19601 	state->last_insn_idx = -1;
19602 
19603 	regs = state->frame[state->curframe]->regs;
19604 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19605 		ret = btf_prepare_func_args(env, subprog, regs);
19606 		if (ret)
19607 			goto out;
19608 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19609 			if (regs[i].type == PTR_TO_CTX)
19610 				mark_reg_known_zero(env, regs, i);
19611 			else if (regs[i].type == SCALAR_VALUE)
19612 				mark_reg_unknown(env, regs, i);
19613 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
19614 				const u32 mem_size = regs[i].mem_size;
19615 
19616 				mark_reg_known_zero(env, regs, i);
19617 				regs[i].mem_size = mem_size;
19618 				regs[i].id = ++env->id_gen;
19619 			}
19620 		}
19621 	} else {
19622 		/* 1st arg to a function */
19623 		regs[BPF_REG_1].type = PTR_TO_CTX;
19624 		mark_reg_known_zero(env, regs, BPF_REG_1);
19625 		ret = btf_check_subprog_arg_match(env, subprog, regs);
19626 		if (ret == -EFAULT)
19627 			/* unlikely verifier bug. abort.
19628 			 * ret == 0 and ret < 0 are sadly acceptable for
19629 			 * main() function due to backward compatibility.
19630 			 * Like socket filter program may be written as:
19631 			 * int bpf_prog(struct pt_regs *ctx)
19632 			 * and never dereference that ctx in the program.
19633 			 * 'struct pt_regs' is a type mismatch for socket
19634 			 * filter that should be using 'struct __sk_buff'.
19635 			 */
19636 			goto out;
19637 	}
19638 
19639 	ret = do_check(env);
19640 out:
19641 	/* check for NULL is necessary, since cur_state can be freed inside
19642 	 * do_check() under memory pressure.
19643 	 */
19644 	if (env->cur_state) {
19645 		free_verifier_state(env->cur_state, true);
19646 		env->cur_state = NULL;
19647 	}
19648 	while (!pop_stack(env, NULL, NULL, false));
19649 	if (!ret && pop_log)
19650 		bpf_vlog_reset(&env->log, 0);
19651 	free_states(env);
19652 	return ret;
19653 }
19654 
19655 /* Verify all global functions in a BPF program one by one based on their BTF.
19656  * All global functions must pass verification. Otherwise the whole program is rejected.
19657  * Consider:
19658  * int bar(int);
19659  * int foo(int f)
19660  * {
19661  *    return bar(f);
19662  * }
19663  * int bar(int b)
19664  * {
19665  *    ...
19666  * }
19667  * foo() will be verified first for R1=any_scalar_value. During verification it
19668  * will be assumed that bar() already verified successfully and call to bar()
19669  * from foo() will be checked for type match only. Later bar() will be verified
19670  * independently to check that it's safe for R1=any_scalar_value.
19671  */
19672 static int do_check_subprogs(struct bpf_verifier_env *env)
19673 {
19674 	struct bpf_prog_aux *aux = env->prog->aux;
19675 	int i, ret;
19676 
19677 	if (!aux->func_info)
19678 		return 0;
19679 
19680 	for (i = 1; i < env->subprog_cnt; i++) {
19681 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19682 			continue;
19683 		env->insn_idx = env->subprog_info[i].start;
19684 		WARN_ON_ONCE(env->insn_idx == 0);
19685 		ret = do_check_common(env, i);
19686 		if (ret) {
19687 			return ret;
19688 		} else if (env->log.level & BPF_LOG_LEVEL) {
19689 			verbose(env,
19690 				"Func#%d is safe for any args that match its prototype\n",
19691 				i);
19692 		}
19693 	}
19694 	return 0;
19695 }
19696 
19697 static int do_check_main(struct bpf_verifier_env *env)
19698 {
19699 	int ret;
19700 
19701 	env->insn_idx = 0;
19702 	ret = do_check_common(env, 0);
19703 	if (!ret)
19704 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19705 	return ret;
19706 }
19707 
19708 
19709 static void print_verification_stats(struct bpf_verifier_env *env)
19710 {
19711 	int i;
19712 
19713 	if (env->log.level & BPF_LOG_STATS) {
19714 		verbose(env, "verification time %lld usec\n",
19715 			div_u64(env->verification_time, 1000));
19716 		verbose(env, "stack depth ");
19717 		for (i = 0; i < env->subprog_cnt; i++) {
19718 			u32 depth = env->subprog_info[i].stack_depth;
19719 
19720 			verbose(env, "%d", depth);
19721 			if (i + 1 < env->subprog_cnt)
19722 				verbose(env, "+");
19723 		}
19724 		verbose(env, "\n");
19725 	}
19726 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19727 		"total_states %d peak_states %d mark_read %d\n",
19728 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19729 		env->max_states_per_insn, env->total_states,
19730 		env->peak_states, env->longest_mark_read_walk);
19731 }
19732 
19733 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19734 {
19735 	const struct btf_type *t, *func_proto;
19736 	const struct bpf_struct_ops *st_ops;
19737 	const struct btf_member *member;
19738 	struct bpf_prog *prog = env->prog;
19739 	u32 btf_id, member_idx;
19740 	const char *mname;
19741 
19742 	if (!prog->gpl_compatible) {
19743 		verbose(env, "struct ops programs must have a GPL compatible license\n");
19744 		return -EINVAL;
19745 	}
19746 
19747 	btf_id = prog->aux->attach_btf_id;
19748 	st_ops = bpf_struct_ops_find(btf_id);
19749 	if (!st_ops) {
19750 		verbose(env, "attach_btf_id %u is not a supported struct\n",
19751 			btf_id);
19752 		return -ENOTSUPP;
19753 	}
19754 
19755 	t = st_ops->type;
19756 	member_idx = prog->expected_attach_type;
19757 	if (member_idx >= btf_type_vlen(t)) {
19758 		verbose(env, "attach to invalid member idx %u of struct %s\n",
19759 			member_idx, st_ops->name);
19760 		return -EINVAL;
19761 	}
19762 
19763 	member = &btf_type_member(t)[member_idx];
19764 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19765 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19766 					       NULL);
19767 	if (!func_proto) {
19768 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19769 			mname, member_idx, st_ops->name);
19770 		return -EINVAL;
19771 	}
19772 
19773 	if (st_ops->check_member) {
19774 		int err = st_ops->check_member(t, member, prog);
19775 
19776 		if (err) {
19777 			verbose(env, "attach to unsupported member %s of struct %s\n",
19778 				mname, st_ops->name);
19779 			return err;
19780 		}
19781 	}
19782 
19783 	prog->aux->attach_func_proto = func_proto;
19784 	prog->aux->attach_func_name = mname;
19785 	env->ops = st_ops->verifier_ops;
19786 
19787 	return 0;
19788 }
19789 #define SECURITY_PREFIX "security_"
19790 
19791 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19792 {
19793 	if (within_error_injection_list(addr) ||
19794 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19795 		return 0;
19796 
19797 	return -EINVAL;
19798 }
19799 
19800 /* list of non-sleepable functions that are otherwise on
19801  * ALLOW_ERROR_INJECTION list
19802  */
19803 BTF_SET_START(btf_non_sleepable_error_inject)
19804 /* Three functions below can be called from sleepable and non-sleepable context.
19805  * Assume non-sleepable from bpf safety point of view.
19806  */
19807 BTF_ID(func, __filemap_add_folio)
19808 BTF_ID(func, should_fail_alloc_page)
19809 BTF_ID(func, should_failslab)
19810 BTF_SET_END(btf_non_sleepable_error_inject)
19811 
19812 static int check_non_sleepable_error_inject(u32 btf_id)
19813 {
19814 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19815 }
19816 
19817 int bpf_check_attach_target(struct bpf_verifier_log *log,
19818 			    const struct bpf_prog *prog,
19819 			    const struct bpf_prog *tgt_prog,
19820 			    u32 btf_id,
19821 			    struct bpf_attach_target_info *tgt_info)
19822 {
19823 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19824 	const char prefix[] = "btf_trace_";
19825 	int ret = 0, subprog = -1, i;
19826 	const struct btf_type *t;
19827 	bool conservative = true;
19828 	const char *tname;
19829 	struct btf *btf;
19830 	long addr = 0;
19831 	struct module *mod = NULL;
19832 
19833 	if (!btf_id) {
19834 		bpf_log(log, "Tracing programs must provide btf_id\n");
19835 		return -EINVAL;
19836 	}
19837 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19838 	if (!btf) {
19839 		bpf_log(log,
19840 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19841 		return -EINVAL;
19842 	}
19843 	t = btf_type_by_id(btf, btf_id);
19844 	if (!t) {
19845 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19846 		return -EINVAL;
19847 	}
19848 	tname = btf_name_by_offset(btf, t->name_off);
19849 	if (!tname) {
19850 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19851 		return -EINVAL;
19852 	}
19853 	if (tgt_prog) {
19854 		struct bpf_prog_aux *aux = tgt_prog->aux;
19855 
19856 		if (bpf_prog_is_dev_bound(prog->aux) &&
19857 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19858 			bpf_log(log, "Target program bound device mismatch");
19859 			return -EINVAL;
19860 		}
19861 
19862 		for (i = 0; i < aux->func_info_cnt; i++)
19863 			if (aux->func_info[i].type_id == btf_id) {
19864 				subprog = i;
19865 				break;
19866 			}
19867 		if (subprog == -1) {
19868 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
19869 			return -EINVAL;
19870 		}
19871 		conservative = aux->func_info_aux[subprog].unreliable;
19872 		if (prog_extension) {
19873 			if (conservative) {
19874 				bpf_log(log,
19875 					"Cannot replace static functions\n");
19876 				return -EINVAL;
19877 			}
19878 			if (!prog->jit_requested) {
19879 				bpf_log(log,
19880 					"Extension programs should be JITed\n");
19881 				return -EINVAL;
19882 			}
19883 		}
19884 		if (!tgt_prog->jited) {
19885 			bpf_log(log, "Can attach to only JITed progs\n");
19886 			return -EINVAL;
19887 		}
19888 		if (tgt_prog->type == prog->type) {
19889 			/* Cannot fentry/fexit another fentry/fexit program.
19890 			 * Cannot attach program extension to another extension.
19891 			 * It's ok to attach fentry/fexit to extension program.
19892 			 */
19893 			bpf_log(log, "Cannot recursively attach\n");
19894 			return -EINVAL;
19895 		}
19896 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19897 		    prog_extension &&
19898 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19899 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19900 			/* Program extensions can extend all program types
19901 			 * except fentry/fexit. The reason is the following.
19902 			 * The fentry/fexit programs are used for performance
19903 			 * analysis, stats and can be attached to any program
19904 			 * type except themselves. When extension program is
19905 			 * replacing XDP function it is necessary to allow
19906 			 * performance analysis of all functions. Both original
19907 			 * XDP program and its program extension. Hence
19908 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19909 			 * allowed. If extending of fentry/fexit was allowed it
19910 			 * would be possible to create long call chain
19911 			 * fentry->extension->fentry->extension beyond
19912 			 * reasonable stack size. Hence extending fentry is not
19913 			 * allowed.
19914 			 */
19915 			bpf_log(log, "Cannot extend fentry/fexit\n");
19916 			return -EINVAL;
19917 		}
19918 	} else {
19919 		if (prog_extension) {
19920 			bpf_log(log, "Cannot replace kernel functions\n");
19921 			return -EINVAL;
19922 		}
19923 	}
19924 
19925 	switch (prog->expected_attach_type) {
19926 	case BPF_TRACE_RAW_TP:
19927 		if (tgt_prog) {
19928 			bpf_log(log,
19929 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19930 			return -EINVAL;
19931 		}
19932 		if (!btf_type_is_typedef(t)) {
19933 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
19934 				btf_id);
19935 			return -EINVAL;
19936 		}
19937 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19938 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19939 				btf_id, tname);
19940 			return -EINVAL;
19941 		}
19942 		tname += sizeof(prefix) - 1;
19943 		t = btf_type_by_id(btf, t->type);
19944 		if (!btf_type_is_ptr(t))
19945 			/* should never happen in valid vmlinux build */
19946 			return -EINVAL;
19947 		t = btf_type_by_id(btf, t->type);
19948 		if (!btf_type_is_func_proto(t))
19949 			/* should never happen in valid vmlinux build */
19950 			return -EINVAL;
19951 
19952 		break;
19953 	case BPF_TRACE_ITER:
19954 		if (!btf_type_is_func(t)) {
19955 			bpf_log(log, "attach_btf_id %u is not a function\n",
19956 				btf_id);
19957 			return -EINVAL;
19958 		}
19959 		t = btf_type_by_id(btf, t->type);
19960 		if (!btf_type_is_func_proto(t))
19961 			return -EINVAL;
19962 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19963 		if (ret)
19964 			return ret;
19965 		break;
19966 	default:
19967 		if (!prog_extension)
19968 			return -EINVAL;
19969 		fallthrough;
19970 	case BPF_MODIFY_RETURN:
19971 	case BPF_LSM_MAC:
19972 	case BPF_LSM_CGROUP:
19973 	case BPF_TRACE_FENTRY:
19974 	case BPF_TRACE_FEXIT:
19975 		if (!btf_type_is_func(t)) {
19976 			bpf_log(log, "attach_btf_id %u is not a function\n",
19977 				btf_id);
19978 			return -EINVAL;
19979 		}
19980 		if (prog_extension &&
19981 		    btf_check_type_match(log, prog, btf, t))
19982 			return -EINVAL;
19983 		t = btf_type_by_id(btf, t->type);
19984 		if (!btf_type_is_func_proto(t))
19985 			return -EINVAL;
19986 
19987 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19988 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19989 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19990 			return -EINVAL;
19991 
19992 		if (tgt_prog && conservative)
19993 			t = NULL;
19994 
19995 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19996 		if (ret < 0)
19997 			return ret;
19998 
19999 		if (tgt_prog) {
20000 			if (subprog == 0)
20001 				addr = (long) tgt_prog->bpf_func;
20002 			else
20003 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20004 		} else {
20005 			if (btf_is_module(btf)) {
20006 				mod = btf_try_get_module(btf);
20007 				if (mod)
20008 					addr = find_kallsyms_symbol_value(mod, tname);
20009 				else
20010 					addr = 0;
20011 			} else {
20012 				addr = kallsyms_lookup_name(tname);
20013 			}
20014 			if (!addr) {
20015 				module_put(mod);
20016 				bpf_log(log,
20017 					"The address of function %s cannot be found\n",
20018 					tname);
20019 				return -ENOENT;
20020 			}
20021 		}
20022 
20023 		if (prog->aux->sleepable) {
20024 			ret = -EINVAL;
20025 			switch (prog->type) {
20026 			case BPF_PROG_TYPE_TRACING:
20027 
20028 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
20029 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20030 				 */
20031 				if (!check_non_sleepable_error_inject(btf_id) &&
20032 				    within_error_injection_list(addr))
20033 					ret = 0;
20034 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
20035 				 * in the fmodret id set with the KF_SLEEPABLE flag.
20036 				 */
20037 				else {
20038 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20039 										prog);
20040 
20041 					if (flags && (*flags & KF_SLEEPABLE))
20042 						ret = 0;
20043 				}
20044 				break;
20045 			case BPF_PROG_TYPE_LSM:
20046 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
20047 				 * Only some of them are sleepable.
20048 				 */
20049 				if (bpf_lsm_is_sleepable_hook(btf_id))
20050 					ret = 0;
20051 				break;
20052 			default:
20053 				break;
20054 			}
20055 			if (ret) {
20056 				module_put(mod);
20057 				bpf_log(log, "%s is not sleepable\n", tname);
20058 				return ret;
20059 			}
20060 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20061 			if (tgt_prog) {
20062 				module_put(mod);
20063 				bpf_log(log, "can't modify return codes of BPF programs\n");
20064 				return -EINVAL;
20065 			}
20066 			ret = -EINVAL;
20067 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20068 			    !check_attach_modify_return(addr, tname))
20069 				ret = 0;
20070 			if (ret) {
20071 				module_put(mod);
20072 				bpf_log(log, "%s() is not modifiable\n", tname);
20073 				return ret;
20074 			}
20075 		}
20076 
20077 		break;
20078 	}
20079 	tgt_info->tgt_addr = addr;
20080 	tgt_info->tgt_name = tname;
20081 	tgt_info->tgt_type = t;
20082 	tgt_info->tgt_mod = mod;
20083 	return 0;
20084 }
20085 
20086 BTF_SET_START(btf_id_deny)
20087 BTF_ID_UNUSED
20088 #ifdef CONFIG_SMP
20089 BTF_ID(func, migrate_disable)
20090 BTF_ID(func, migrate_enable)
20091 #endif
20092 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20093 BTF_ID(func, rcu_read_unlock_strict)
20094 #endif
20095 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20096 BTF_ID(func, preempt_count_add)
20097 BTF_ID(func, preempt_count_sub)
20098 #endif
20099 #ifdef CONFIG_PREEMPT_RCU
20100 BTF_ID(func, __rcu_read_lock)
20101 BTF_ID(func, __rcu_read_unlock)
20102 #endif
20103 BTF_SET_END(btf_id_deny)
20104 
20105 static bool can_be_sleepable(struct bpf_prog *prog)
20106 {
20107 	if (prog->type == BPF_PROG_TYPE_TRACING) {
20108 		switch (prog->expected_attach_type) {
20109 		case BPF_TRACE_FENTRY:
20110 		case BPF_TRACE_FEXIT:
20111 		case BPF_MODIFY_RETURN:
20112 		case BPF_TRACE_ITER:
20113 			return true;
20114 		default:
20115 			return false;
20116 		}
20117 	}
20118 	return prog->type == BPF_PROG_TYPE_LSM ||
20119 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20120 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20121 }
20122 
20123 static int check_attach_btf_id(struct bpf_verifier_env *env)
20124 {
20125 	struct bpf_prog *prog = env->prog;
20126 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20127 	struct bpf_attach_target_info tgt_info = {};
20128 	u32 btf_id = prog->aux->attach_btf_id;
20129 	struct bpf_trampoline *tr;
20130 	int ret;
20131 	u64 key;
20132 
20133 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20134 		if (prog->aux->sleepable)
20135 			/* attach_btf_id checked to be zero already */
20136 			return 0;
20137 		verbose(env, "Syscall programs can only be sleepable\n");
20138 		return -EINVAL;
20139 	}
20140 
20141 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20142 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20143 		return -EINVAL;
20144 	}
20145 
20146 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20147 		return check_struct_ops_btf_id(env);
20148 
20149 	if (prog->type != BPF_PROG_TYPE_TRACING &&
20150 	    prog->type != BPF_PROG_TYPE_LSM &&
20151 	    prog->type != BPF_PROG_TYPE_EXT)
20152 		return 0;
20153 
20154 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20155 	if (ret)
20156 		return ret;
20157 
20158 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20159 		/* to make freplace equivalent to their targets, they need to
20160 		 * inherit env->ops and expected_attach_type for the rest of the
20161 		 * verification
20162 		 */
20163 		env->ops = bpf_verifier_ops[tgt_prog->type];
20164 		prog->expected_attach_type = tgt_prog->expected_attach_type;
20165 	}
20166 
20167 	/* store info about the attachment target that will be used later */
20168 	prog->aux->attach_func_proto = tgt_info.tgt_type;
20169 	prog->aux->attach_func_name = tgt_info.tgt_name;
20170 	prog->aux->mod = tgt_info.tgt_mod;
20171 
20172 	if (tgt_prog) {
20173 		prog->aux->saved_dst_prog_type = tgt_prog->type;
20174 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20175 	}
20176 
20177 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20178 		prog->aux->attach_btf_trace = true;
20179 		return 0;
20180 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20181 		if (!bpf_iter_prog_supported(prog))
20182 			return -EINVAL;
20183 		return 0;
20184 	}
20185 
20186 	if (prog->type == BPF_PROG_TYPE_LSM) {
20187 		ret = bpf_lsm_verify_prog(&env->log, prog);
20188 		if (ret < 0)
20189 			return ret;
20190 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
20191 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
20192 		return -EINVAL;
20193 	}
20194 
20195 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20196 	tr = bpf_trampoline_get(key, &tgt_info);
20197 	if (!tr)
20198 		return -ENOMEM;
20199 
20200 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20201 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20202 
20203 	prog->aux->dst_trampoline = tr;
20204 	return 0;
20205 }
20206 
20207 struct btf *bpf_get_btf_vmlinux(void)
20208 {
20209 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20210 		mutex_lock(&bpf_verifier_lock);
20211 		if (!btf_vmlinux)
20212 			btf_vmlinux = btf_parse_vmlinux();
20213 		mutex_unlock(&bpf_verifier_lock);
20214 	}
20215 	return btf_vmlinux;
20216 }
20217 
20218 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20219 {
20220 	u64 start_time = ktime_get_ns();
20221 	struct bpf_verifier_env *env;
20222 	int i, len, ret = -EINVAL, err;
20223 	u32 log_true_size;
20224 	bool is_priv;
20225 
20226 	/* no program is valid */
20227 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20228 		return -EINVAL;
20229 
20230 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
20231 	 * allocate/free it every time bpf_check() is called
20232 	 */
20233 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20234 	if (!env)
20235 		return -ENOMEM;
20236 
20237 	env->bt.env = env;
20238 
20239 	len = (*prog)->len;
20240 	env->insn_aux_data =
20241 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20242 	ret = -ENOMEM;
20243 	if (!env->insn_aux_data)
20244 		goto err_free_env;
20245 	for (i = 0; i < len; i++)
20246 		env->insn_aux_data[i].orig_idx = i;
20247 	env->prog = *prog;
20248 	env->ops = bpf_verifier_ops[env->prog->type];
20249 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20250 	is_priv = bpf_capable();
20251 
20252 	bpf_get_btf_vmlinux();
20253 
20254 	/* grab the mutex to protect few globals used by verifier */
20255 	if (!is_priv)
20256 		mutex_lock(&bpf_verifier_lock);
20257 
20258 	/* user could have requested verbose verifier output
20259 	 * and supplied buffer to store the verification trace
20260 	 */
20261 	ret = bpf_vlog_init(&env->log, attr->log_level,
20262 			    (char __user *) (unsigned long) attr->log_buf,
20263 			    attr->log_size);
20264 	if (ret)
20265 		goto err_unlock;
20266 
20267 	mark_verifier_state_clean(env);
20268 
20269 	if (IS_ERR(btf_vmlinux)) {
20270 		/* Either gcc or pahole or kernel are broken. */
20271 		verbose(env, "in-kernel BTF is malformed\n");
20272 		ret = PTR_ERR(btf_vmlinux);
20273 		goto skip_full_check;
20274 	}
20275 
20276 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20277 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20278 		env->strict_alignment = true;
20279 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20280 		env->strict_alignment = false;
20281 
20282 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20283 	env->allow_uninit_stack = bpf_allow_uninit_stack();
20284 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
20285 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
20286 	env->bpf_capable = bpf_capable();
20287 
20288 	if (is_priv)
20289 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20290 
20291 	env->explored_states = kvcalloc(state_htab_size(env),
20292 				       sizeof(struct bpf_verifier_state_list *),
20293 				       GFP_USER);
20294 	ret = -ENOMEM;
20295 	if (!env->explored_states)
20296 		goto skip_full_check;
20297 
20298 	ret = add_subprog_and_kfunc(env);
20299 	if (ret < 0)
20300 		goto skip_full_check;
20301 
20302 	ret = check_subprogs(env);
20303 	if (ret < 0)
20304 		goto skip_full_check;
20305 
20306 	ret = check_btf_info(env, attr, uattr);
20307 	if (ret < 0)
20308 		goto skip_full_check;
20309 
20310 	ret = check_attach_btf_id(env);
20311 	if (ret)
20312 		goto skip_full_check;
20313 
20314 	ret = resolve_pseudo_ldimm64(env);
20315 	if (ret < 0)
20316 		goto skip_full_check;
20317 
20318 	if (bpf_prog_is_offloaded(env->prog->aux)) {
20319 		ret = bpf_prog_offload_verifier_prep(env->prog);
20320 		if (ret)
20321 			goto skip_full_check;
20322 	}
20323 
20324 	ret = check_cfg(env);
20325 	if (ret < 0)
20326 		goto skip_full_check;
20327 
20328 	ret = do_check_subprogs(env);
20329 	ret = ret ?: do_check_main(env);
20330 
20331 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20332 		ret = bpf_prog_offload_finalize(env);
20333 
20334 skip_full_check:
20335 	kvfree(env->explored_states);
20336 
20337 	if (ret == 0)
20338 		ret = check_max_stack_depth(env);
20339 
20340 	/* instruction rewrites happen after this point */
20341 	if (ret == 0)
20342 		ret = optimize_bpf_loop(env);
20343 
20344 	if (is_priv) {
20345 		if (ret == 0)
20346 			opt_hard_wire_dead_code_branches(env);
20347 		if (ret == 0)
20348 			ret = opt_remove_dead_code(env);
20349 		if (ret == 0)
20350 			ret = opt_remove_nops(env);
20351 	} else {
20352 		if (ret == 0)
20353 			sanitize_dead_code(env);
20354 	}
20355 
20356 	if (ret == 0)
20357 		/* program is valid, convert *(u32*)(ctx + off) accesses */
20358 		ret = convert_ctx_accesses(env);
20359 
20360 	if (ret == 0)
20361 		ret = do_misc_fixups(env);
20362 
20363 	/* do 32-bit optimization after insn patching has done so those patched
20364 	 * insns could be handled correctly.
20365 	 */
20366 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20367 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20368 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20369 								     : false;
20370 	}
20371 
20372 	if (ret == 0)
20373 		ret = fixup_call_args(env);
20374 
20375 	env->verification_time = ktime_get_ns() - start_time;
20376 	print_verification_stats(env);
20377 	env->prog->aux->verified_insns = env->insn_processed;
20378 
20379 	/* preserve original error even if log finalization is successful */
20380 	err = bpf_vlog_finalize(&env->log, &log_true_size);
20381 	if (err)
20382 		ret = err;
20383 
20384 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20385 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20386 				  &log_true_size, sizeof(log_true_size))) {
20387 		ret = -EFAULT;
20388 		goto err_release_maps;
20389 	}
20390 
20391 	if (ret)
20392 		goto err_release_maps;
20393 
20394 	if (env->used_map_cnt) {
20395 		/* if program passed verifier, update used_maps in bpf_prog_info */
20396 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20397 							  sizeof(env->used_maps[0]),
20398 							  GFP_KERNEL);
20399 
20400 		if (!env->prog->aux->used_maps) {
20401 			ret = -ENOMEM;
20402 			goto err_release_maps;
20403 		}
20404 
20405 		memcpy(env->prog->aux->used_maps, env->used_maps,
20406 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
20407 		env->prog->aux->used_map_cnt = env->used_map_cnt;
20408 	}
20409 	if (env->used_btf_cnt) {
20410 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
20411 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20412 							  sizeof(env->used_btfs[0]),
20413 							  GFP_KERNEL);
20414 		if (!env->prog->aux->used_btfs) {
20415 			ret = -ENOMEM;
20416 			goto err_release_maps;
20417 		}
20418 
20419 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
20420 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20421 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20422 	}
20423 	if (env->used_map_cnt || env->used_btf_cnt) {
20424 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
20425 		 * bpf_ld_imm64 instructions
20426 		 */
20427 		convert_pseudo_ld_imm64(env);
20428 	}
20429 
20430 	adjust_btf_func(env);
20431 
20432 err_release_maps:
20433 	if (!env->prog->aux->used_maps)
20434 		/* if we didn't copy map pointers into bpf_prog_info, release
20435 		 * them now. Otherwise free_used_maps() will release them.
20436 		 */
20437 		release_maps(env);
20438 	if (!env->prog->aux->used_btfs)
20439 		release_btfs(env);
20440 
20441 	/* extension progs temporarily inherit the attach_type of their targets
20442 	   for verification purposes, so set it back to zero before returning
20443 	 */
20444 	if (env->prog->type == BPF_PROG_TYPE_EXT)
20445 		env->prog->expected_attach_type = 0;
20446 
20447 	*prog = env->prog;
20448 err_unlock:
20449 	if (!is_priv)
20450 		mutex_unlock(&bpf_verifier_lock);
20451 	vfree(env->insn_aux_data);
20452 err_free_env:
20453 	kfree(env);
20454 	return ret;
20455 }
20456