xref: /linux/kernel/bpf/verifier.c (revision 8ade3356b25ab2522892a21832a709e7ad5f8168)
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 <linux/bpf_mem_alloc.h>
30 #include <net/xdp.h>
31 
32 #include "disasm.h"
33 
34 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
35 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
36 	[_id] = & _name ## _verifier_ops,
37 #define BPF_MAP_TYPE(_id, _ops)
38 #define BPF_LINK_TYPE(_id, _name)
39 #include <linux/bpf_types.h>
40 #undef BPF_PROG_TYPE
41 #undef BPF_MAP_TYPE
42 #undef BPF_LINK_TYPE
43 };
44 
45 struct bpf_mem_alloc bpf_global_percpu_ma;
46 static bool bpf_global_percpu_ma_set;
47 
48 /* bpf_check() is a static code analyzer that walks eBPF program
49  * instruction by instruction and updates register/stack state.
50  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
51  *
52  * The first pass is depth-first-search to check that the program is a DAG.
53  * It rejects the following programs:
54  * - larger than BPF_MAXINSNS insns
55  * - if loop is present (detected via back-edge)
56  * - unreachable insns exist (shouldn't be a forest. program = one function)
57  * - out of bounds or malformed jumps
58  * The second pass is all possible path descent from the 1st insn.
59  * Since it's analyzing all paths through the program, the length of the
60  * analysis is limited to 64k insn, which may be hit even if total number of
61  * insn is less then 4K, but there are too many branches that change stack/regs.
62  * Number of 'branches to be analyzed' is limited to 1k
63  *
64  * On entry to each instruction, each register has a type, and the instruction
65  * changes the types of the registers depending on instruction semantics.
66  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
67  * copied to R1.
68  *
69  * All registers are 64-bit.
70  * R0 - return register
71  * R1-R5 argument passing registers
72  * R6-R9 callee saved registers
73  * R10 - frame pointer read-only
74  *
75  * At the start of BPF program the register R1 contains a pointer to bpf_context
76  * and has type PTR_TO_CTX.
77  *
78  * Verifier tracks arithmetic operations on pointers in case:
79  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
80  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
81  * 1st insn copies R10 (which has FRAME_PTR) type into R1
82  * and 2nd arithmetic instruction is pattern matched to recognize
83  * that it wants to construct a pointer to some element within stack.
84  * So after 2nd insn, the register R1 has type PTR_TO_STACK
85  * (and -20 constant is saved for further stack bounds checking).
86  * Meaning that this reg is a pointer to stack plus known immediate constant.
87  *
88  * Most of the time the registers have SCALAR_VALUE type, which
89  * means the register has some value, but it's not a valid pointer.
90  * (like pointer plus pointer becomes SCALAR_VALUE type)
91  *
92  * When verifier sees load or store instructions the type of base register
93  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
94  * four pointer types recognized by check_mem_access() function.
95  *
96  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
97  * and the range of [ptr, ptr + map's value_size) is accessible.
98  *
99  * registers used to pass values to function calls are checked against
100  * function argument constraints.
101  *
102  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
103  * It means that the register type passed to this function must be
104  * PTR_TO_STACK and it will be used inside the function as
105  * 'pointer to map element key'
106  *
107  * For example the argument constraints for bpf_map_lookup_elem():
108  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
109  *   .arg1_type = ARG_CONST_MAP_PTR,
110  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
111  *
112  * ret_type says that this function returns 'pointer to map elem value or null'
113  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
114  * 2nd argument should be a pointer to stack, which will be used inside
115  * the helper function as a pointer to map element key.
116  *
117  * On the kernel side the helper function looks like:
118  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
119  * {
120  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
121  *    void *key = (void *) (unsigned long) r2;
122  *    void *value;
123  *
124  *    here kernel can access 'key' and 'map' pointers safely, knowing that
125  *    [key, key + map->key_size) bytes are valid and were initialized on
126  *    the stack of eBPF program.
127  * }
128  *
129  * Corresponding eBPF program may look like:
130  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
131  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
132  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
133  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
134  * here verifier looks at prototype of map_lookup_elem() and sees:
135  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
136  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
137  *
138  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
139  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
140  * and were initialized prior to this call.
141  * If it's ok, then verifier allows this BPF_CALL insn and looks at
142  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
143  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
144  * returns either pointer to map value or NULL.
145  *
146  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
147  * insn, the register holding that pointer in the true branch changes state to
148  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
149  * branch. See check_cond_jmp_op().
150  *
151  * After the call R0 is set to return type of the function and registers R1-R5
152  * are set to NOT_INIT to indicate that they are no longer readable.
153  *
154  * The following reference types represent a potential reference to a kernel
155  * resource which, after first being allocated, must be checked and freed by
156  * the BPF program:
157  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
158  *
159  * When the verifier sees a helper call return a reference type, it allocates a
160  * pointer id for the reference and stores it in the current function state.
161  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
162  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
163  * passes through a NULL-check conditional. For the branch wherein the state is
164  * changed to CONST_IMM, the verifier releases the reference.
165  *
166  * For each helper function that allocates a reference, such as
167  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
168  * bpf_sk_release(). When a reference type passes into the release function,
169  * the verifier also releases the reference. If any unchecked or unreleased
170  * reference remains at the end of the program, the verifier rejects it.
171  */
172 
173 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
174 struct bpf_verifier_stack_elem {
175 	/* verifer state is 'st'
176 	 * before processing instruction 'insn_idx'
177 	 * and after processing instruction 'prev_insn_idx'
178 	 */
179 	struct bpf_verifier_state st;
180 	int insn_idx;
181 	int prev_insn_idx;
182 	struct bpf_verifier_stack_elem *next;
183 	/* length of verifier log at the time this state was pushed on stack */
184 	u32 log_pos;
185 };
186 
187 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
188 #define BPF_COMPLEXITY_LIMIT_STATES	64
189 
190 #define BPF_MAP_KEY_POISON	(1ULL << 63)
191 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
192 
193 #define BPF_MAP_PTR_UNPRIV	1UL
194 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
195 					  POISON_POINTER_DELTA))
196 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
197 
198 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
199 
200 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
201 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
202 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
203 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
204 static int ref_set_non_owning(struct bpf_verifier_env *env,
205 			      struct bpf_reg_state *reg);
206 static void specialize_kfunc(struct bpf_verifier_env *env,
207 			     u32 func_id, u16 offset, unsigned long *addr);
208 static bool is_trusted_reg(const struct bpf_reg_state *reg);
209 
210 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
211 {
212 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
213 }
214 
215 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
216 {
217 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
218 }
219 
220 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
221 			      const struct bpf_map *map, bool unpriv)
222 {
223 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
224 	unpriv |= bpf_map_ptr_unpriv(aux);
225 	aux->map_ptr_state = (unsigned long)map |
226 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
227 }
228 
229 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
230 {
231 	return aux->map_key_state & BPF_MAP_KEY_POISON;
232 }
233 
234 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
235 {
236 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
237 }
238 
239 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
240 {
241 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
242 }
243 
244 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
245 {
246 	bool poisoned = bpf_map_key_poisoned(aux);
247 
248 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
249 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
250 }
251 
252 static bool bpf_helper_call(const struct bpf_insn *insn)
253 {
254 	return insn->code == (BPF_JMP | BPF_CALL) &&
255 	       insn->src_reg == 0;
256 }
257 
258 static bool bpf_pseudo_call(const struct bpf_insn *insn)
259 {
260 	return insn->code == (BPF_JMP | BPF_CALL) &&
261 	       insn->src_reg == BPF_PSEUDO_CALL;
262 }
263 
264 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
265 {
266 	return insn->code == (BPF_JMP | BPF_CALL) &&
267 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
268 }
269 
270 struct bpf_call_arg_meta {
271 	struct bpf_map *map_ptr;
272 	bool raw_mode;
273 	bool pkt_access;
274 	u8 release_regno;
275 	int regno;
276 	int access_size;
277 	int mem_size;
278 	u64 msize_max_value;
279 	int ref_obj_id;
280 	int dynptr_id;
281 	int map_uid;
282 	int func_id;
283 	struct btf *btf;
284 	u32 btf_id;
285 	struct btf *ret_btf;
286 	u32 ret_btf_id;
287 	u32 subprogno;
288 	struct btf_field *kptr_field;
289 };
290 
291 struct bpf_kfunc_call_arg_meta {
292 	/* In parameters */
293 	struct btf *btf;
294 	u32 func_id;
295 	u32 kfunc_flags;
296 	const struct btf_type *func_proto;
297 	const char *func_name;
298 	/* Out parameters */
299 	u32 ref_obj_id;
300 	u8 release_regno;
301 	bool r0_rdonly;
302 	u32 ret_btf_id;
303 	u64 r0_size;
304 	u32 subprogno;
305 	struct {
306 		u64 value;
307 		bool found;
308 	} arg_constant;
309 
310 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
311 	 * generally to pass info about user-defined local kptr types to later
312 	 * verification logic
313 	 *   bpf_obj_drop/bpf_percpu_obj_drop
314 	 *     Record the local kptr type to be drop'd
315 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
316 	 *     Record the local kptr type to be refcount_incr'd and use
317 	 *     arg_owning_ref to determine whether refcount_acquire should be
318 	 *     fallible
319 	 */
320 	struct btf *arg_btf;
321 	u32 arg_btf_id;
322 	bool arg_owning_ref;
323 
324 	struct {
325 		struct btf_field *field;
326 	} arg_list_head;
327 	struct {
328 		struct btf_field *field;
329 	} arg_rbtree_root;
330 	struct {
331 		enum bpf_dynptr_type type;
332 		u32 id;
333 		u32 ref_obj_id;
334 	} initialized_dynptr;
335 	struct {
336 		u8 spi;
337 		u8 frameno;
338 	} iter;
339 	u64 mem_size;
340 };
341 
342 struct btf *btf_vmlinux;
343 
344 static const char *btf_type_name(const struct btf *btf, u32 id)
345 {
346 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
347 }
348 
349 static DEFINE_MUTEX(bpf_verifier_lock);
350 static DEFINE_MUTEX(bpf_percpu_ma_lock);
351 
352 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
353 {
354 	struct bpf_verifier_env *env = private_data;
355 	va_list args;
356 
357 	if (!bpf_verifier_log_needed(&env->log))
358 		return;
359 
360 	va_start(args, fmt);
361 	bpf_verifier_vlog(&env->log, fmt, args);
362 	va_end(args);
363 }
364 
365 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
366 				   struct bpf_reg_state *reg,
367 				   struct bpf_retval_range range, const char *ctx,
368 				   const char *reg_name)
369 {
370 	bool unknown = true;
371 
372 	verbose(env, "%s the register %s has", ctx, reg_name);
373 	if (reg->smin_value > S64_MIN) {
374 		verbose(env, " smin=%lld", reg->smin_value);
375 		unknown = false;
376 	}
377 	if (reg->smax_value < S64_MAX) {
378 		verbose(env, " smax=%lld", reg->smax_value);
379 		unknown = false;
380 	}
381 	if (unknown)
382 		verbose(env, " unknown scalar value");
383 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
384 }
385 
386 static bool type_may_be_null(u32 type)
387 {
388 	return type & PTR_MAYBE_NULL;
389 }
390 
391 static bool reg_not_null(const struct bpf_reg_state *reg)
392 {
393 	enum bpf_reg_type type;
394 
395 	type = reg->type;
396 	if (type_may_be_null(type))
397 		return false;
398 
399 	type = base_type(type);
400 	return type == PTR_TO_SOCKET ||
401 		type == PTR_TO_TCP_SOCK ||
402 		type == PTR_TO_MAP_VALUE ||
403 		type == PTR_TO_MAP_KEY ||
404 		type == PTR_TO_SOCK_COMMON ||
405 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
406 		type == PTR_TO_MEM;
407 }
408 
409 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
410 {
411 	struct btf_record *rec = NULL;
412 	struct btf_struct_meta *meta;
413 
414 	if (reg->type == PTR_TO_MAP_VALUE) {
415 		rec = reg->map_ptr->record;
416 	} else if (type_is_ptr_alloc_obj(reg->type)) {
417 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
418 		if (meta)
419 			rec = meta->record;
420 	}
421 	return rec;
422 }
423 
424 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
425 {
426 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
427 
428 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
429 }
430 
431 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
432 {
433 	struct bpf_func_info *info;
434 
435 	if (!env->prog->aux->func_info)
436 		return "";
437 
438 	info = &env->prog->aux->func_info[subprog];
439 	return btf_type_name(env->prog->aux->btf, info->type_id);
440 }
441 
442 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
443 {
444 	struct bpf_subprog_info *info = subprog_info(env, subprog);
445 
446 	info->is_cb = true;
447 	info->is_async_cb = true;
448 	info->is_exception_cb = true;
449 }
450 
451 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
452 {
453 	return subprog_info(env, subprog)->is_exception_cb;
454 }
455 
456 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
457 {
458 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
459 }
460 
461 static bool type_is_rdonly_mem(u32 type)
462 {
463 	return type & MEM_RDONLY;
464 }
465 
466 static bool is_acquire_function(enum bpf_func_id func_id,
467 				const struct bpf_map *map)
468 {
469 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
470 
471 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
472 	    func_id == BPF_FUNC_sk_lookup_udp ||
473 	    func_id == BPF_FUNC_skc_lookup_tcp ||
474 	    func_id == BPF_FUNC_ringbuf_reserve ||
475 	    func_id == BPF_FUNC_kptr_xchg)
476 		return true;
477 
478 	if (func_id == BPF_FUNC_map_lookup_elem &&
479 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
480 	     map_type == BPF_MAP_TYPE_SOCKHASH))
481 		return true;
482 
483 	return false;
484 }
485 
486 static bool is_ptr_cast_function(enum bpf_func_id func_id)
487 {
488 	return func_id == BPF_FUNC_tcp_sock ||
489 		func_id == BPF_FUNC_sk_fullsock ||
490 		func_id == BPF_FUNC_skc_to_tcp_sock ||
491 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
492 		func_id == BPF_FUNC_skc_to_udp6_sock ||
493 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
494 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
495 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
496 }
497 
498 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
499 {
500 	return func_id == BPF_FUNC_dynptr_data;
501 }
502 
503 static bool is_sync_callback_calling_kfunc(u32 btf_id);
504 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
505 
506 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
507 {
508 	return func_id == BPF_FUNC_for_each_map_elem ||
509 	       func_id == BPF_FUNC_find_vma ||
510 	       func_id == BPF_FUNC_loop ||
511 	       func_id == BPF_FUNC_user_ringbuf_drain;
512 }
513 
514 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
515 {
516 	return func_id == BPF_FUNC_timer_set_callback;
517 }
518 
519 static bool is_callback_calling_function(enum bpf_func_id func_id)
520 {
521 	return is_sync_callback_calling_function(func_id) ||
522 	       is_async_callback_calling_function(func_id);
523 }
524 
525 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
526 {
527 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
528 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
529 }
530 
531 static bool is_storage_get_function(enum bpf_func_id func_id)
532 {
533 	return func_id == BPF_FUNC_sk_storage_get ||
534 	       func_id == BPF_FUNC_inode_storage_get ||
535 	       func_id == BPF_FUNC_task_storage_get ||
536 	       func_id == BPF_FUNC_cgrp_storage_get;
537 }
538 
539 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
540 					const struct bpf_map *map)
541 {
542 	int ref_obj_uses = 0;
543 
544 	if (is_ptr_cast_function(func_id))
545 		ref_obj_uses++;
546 	if (is_acquire_function(func_id, map))
547 		ref_obj_uses++;
548 	if (is_dynptr_ref_function(func_id))
549 		ref_obj_uses++;
550 
551 	return ref_obj_uses > 1;
552 }
553 
554 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
555 {
556 	return BPF_CLASS(insn->code) == BPF_STX &&
557 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
558 	       insn->imm == BPF_CMPXCHG;
559 }
560 
561 static int __get_spi(s32 off)
562 {
563 	return (-off - 1) / BPF_REG_SIZE;
564 }
565 
566 static struct bpf_func_state *func(struct bpf_verifier_env *env,
567 				   const struct bpf_reg_state *reg)
568 {
569 	struct bpf_verifier_state *cur = env->cur_state;
570 
571 	return cur->frame[reg->frameno];
572 }
573 
574 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
575 {
576        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
577 
578        /* We need to check that slots between [spi - nr_slots + 1, spi] are
579 	* within [0, allocated_stack).
580 	*
581 	* Please note that the spi grows downwards. For example, a dynptr
582 	* takes the size of two stack slots; the first slot will be at
583 	* spi and the second slot will be at spi - 1.
584 	*/
585        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
586 }
587 
588 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
589 			          const char *obj_kind, int nr_slots)
590 {
591 	int off, spi;
592 
593 	if (!tnum_is_const(reg->var_off)) {
594 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
595 		return -EINVAL;
596 	}
597 
598 	off = reg->off + reg->var_off.value;
599 	if (off % BPF_REG_SIZE) {
600 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
601 		return -EINVAL;
602 	}
603 
604 	spi = __get_spi(off);
605 	if (spi + 1 < nr_slots) {
606 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
607 		return -EINVAL;
608 	}
609 
610 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
611 		return -ERANGE;
612 	return spi;
613 }
614 
615 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
616 {
617 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
618 }
619 
620 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
621 {
622 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
623 }
624 
625 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
626 {
627 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
628 	case DYNPTR_TYPE_LOCAL:
629 		return BPF_DYNPTR_TYPE_LOCAL;
630 	case DYNPTR_TYPE_RINGBUF:
631 		return BPF_DYNPTR_TYPE_RINGBUF;
632 	case DYNPTR_TYPE_SKB:
633 		return BPF_DYNPTR_TYPE_SKB;
634 	case DYNPTR_TYPE_XDP:
635 		return BPF_DYNPTR_TYPE_XDP;
636 	default:
637 		return BPF_DYNPTR_TYPE_INVALID;
638 	}
639 }
640 
641 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
642 {
643 	switch (type) {
644 	case BPF_DYNPTR_TYPE_LOCAL:
645 		return DYNPTR_TYPE_LOCAL;
646 	case BPF_DYNPTR_TYPE_RINGBUF:
647 		return DYNPTR_TYPE_RINGBUF;
648 	case BPF_DYNPTR_TYPE_SKB:
649 		return DYNPTR_TYPE_SKB;
650 	case BPF_DYNPTR_TYPE_XDP:
651 		return DYNPTR_TYPE_XDP;
652 	default:
653 		return 0;
654 	}
655 }
656 
657 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
658 {
659 	return type == BPF_DYNPTR_TYPE_RINGBUF;
660 }
661 
662 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
663 			      enum bpf_dynptr_type type,
664 			      bool first_slot, int dynptr_id);
665 
666 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
667 				struct bpf_reg_state *reg);
668 
669 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
670 				   struct bpf_reg_state *sreg1,
671 				   struct bpf_reg_state *sreg2,
672 				   enum bpf_dynptr_type type)
673 {
674 	int id = ++env->id_gen;
675 
676 	__mark_dynptr_reg(sreg1, type, true, id);
677 	__mark_dynptr_reg(sreg2, type, false, id);
678 }
679 
680 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
681 			       struct bpf_reg_state *reg,
682 			       enum bpf_dynptr_type type)
683 {
684 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
685 }
686 
687 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
688 				        struct bpf_func_state *state, int spi);
689 
690 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
691 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
692 {
693 	struct bpf_func_state *state = func(env, reg);
694 	enum bpf_dynptr_type type;
695 	int spi, i, err;
696 
697 	spi = dynptr_get_spi(env, reg);
698 	if (spi < 0)
699 		return spi;
700 
701 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
702 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
703 	 * to ensure that for the following example:
704 	 *	[d1][d1][d2][d2]
705 	 * spi    3   2   1   0
706 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
707 	 * case they do belong to same dynptr, second call won't see slot_type
708 	 * as STACK_DYNPTR and will simply skip destruction.
709 	 */
710 	err = destroy_if_dynptr_stack_slot(env, state, spi);
711 	if (err)
712 		return err;
713 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
714 	if (err)
715 		return err;
716 
717 	for (i = 0; i < BPF_REG_SIZE; i++) {
718 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
719 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
720 	}
721 
722 	type = arg_to_dynptr_type(arg_type);
723 	if (type == BPF_DYNPTR_TYPE_INVALID)
724 		return -EINVAL;
725 
726 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
727 			       &state->stack[spi - 1].spilled_ptr, type);
728 
729 	if (dynptr_type_refcounted(type)) {
730 		/* The id is used to track proper releasing */
731 		int id;
732 
733 		if (clone_ref_obj_id)
734 			id = clone_ref_obj_id;
735 		else
736 			id = acquire_reference_state(env, insn_idx);
737 
738 		if (id < 0)
739 			return id;
740 
741 		state->stack[spi].spilled_ptr.ref_obj_id = id;
742 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
743 	}
744 
745 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
746 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
747 
748 	return 0;
749 }
750 
751 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
752 {
753 	int i;
754 
755 	for (i = 0; i < BPF_REG_SIZE; i++) {
756 		state->stack[spi].slot_type[i] = STACK_INVALID;
757 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
758 	}
759 
760 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
761 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
762 
763 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
764 	 *
765 	 * While we don't allow reading STACK_INVALID, it is still possible to
766 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
767 	 * helpers or insns can do partial read of that part without failing,
768 	 * but check_stack_range_initialized, check_stack_read_var_off, and
769 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
770 	 * the slot conservatively. Hence we need to prevent those liveness
771 	 * marking walks.
772 	 *
773 	 * This was not a problem before because STACK_INVALID is only set by
774 	 * default (where the default reg state has its reg->parent as NULL), or
775 	 * in clean_live_states after REG_LIVE_DONE (at which point
776 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
777 	 * verifier state exploration (like we did above). Hence, for our case
778 	 * parentage chain will still be live (i.e. reg->parent may be
779 	 * non-NULL), while earlier reg->parent was NULL, so we need
780 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
781 	 * done later on reads or by mark_dynptr_read as well to unnecessary
782 	 * mark registers in verifier state.
783 	 */
784 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
785 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
786 }
787 
788 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
789 {
790 	struct bpf_func_state *state = func(env, reg);
791 	int spi, ref_obj_id, i;
792 
793 	spi = dynptr_get_spi(env, reg);
794 	if (spi < 0)
795 		return spi;
796 
797 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
798 		invalidate_dynptr(env, state, spi);
799 		return 0;
800 	}
801 
802 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
803 
804 	/* If the dynptr has a ref_obj_id, then we need to invalidate
805 	 * two things:
806 	 *
807 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
808 	 * 2) Any slices derived from this dynptr.
809 	 */
810 
811 	/* Invalidate any slices associated with this dynptr */
812 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
813 
814 	/* Invalidate any dynptr clones */
815 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
816 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
817 			continue;
818 
819 		/* it should always be the case that if the ref obj id
820 		 * matches then the stack slot also belongs to a
821 		 * dynptr
822 		 */
823 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
824 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
825 			return -EFAULT;
826 		}
827 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
828 			invalidate_dynptr(env, state, i);
829 	}
830 
831 	return 0;
832 }
833 
834 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
835 			       struct bpf_reg_state *reg);
836 
837 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
838 {
839 	if (!env->allow_ptr_leaks)
840 		__mark_reg_not_init(env, reg);
841 	else
842 		__mark_reg_unknown(env, reg);
843 }
844 
845 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
846 				        struct bpf_func_state *state, int spi)
847 {
848 	struct bpf_func_state *fstate;
849 	struct bpf_reg_state *dreg;
850 	int i, dynptr_id;
851 
852 	/* We always ensure that STACK_DYNPTR is never set partially,
853 	 * hence just checking for slot_type[0] is enough. This is
854 	 * different for STACK_SPILL, where it may be only set for
855 	 * 1 byte, so code has to use is_spilled_reg.
856 	 */
857 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
858 		return 0;
859 
860 	/* Reposition spi to first slot */
861 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
862 		spi = spi + 1;
863 
864 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
865 		verbose(env, "cannot overwrite referenced dynptr\n");
866 		return -EINVAL;
867 	}
868 
869 	mark_stack_slot_scratched(env, spi);
870 	mark_stack_slot_scratched(env, spi - 1);
871 
872 	/* Writing partially to one dynptr stack slot destroys both. */
873 	for (i = 0; i < BPF_REG_SIZE; i++) {
874 		state->stack[spi].slot_type[i] = STACK_INVALID;
875 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
876 	}
877 
878 	dynptr_id = state->stack[spi].spilled_ptr.id;
879 	/* Invalidate any slices associated with this dynptr */
880 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
881 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
882 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
883 			continue;
884 		if (dreg->dynptr_id == dynptr_id)
885 			mark_reg_invalid(env, dreg);
886 	}));
887 
888 	/* Do not release reference state, we are destroying dynptr on stack,
889 	 * not using some helper to release it. Just reset register.
890 	 */
891 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
892 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
893 
894 	/* Same reason as unmark_stack_slots_dynptr above */
895 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
896 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
897 
898 	return 0;
899 }
900 
901 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
902 {
903 	int spi;
904 
905 	if (reg->type == CONST_PTR_TO_DYNPTR)
906 		return false;
907 
908 	spi = dynptr_get_spi(env, reg);
909 
910 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
911 	 * error because this just means the stack state hasn't been updated yet.
912 	 * We will do check_mem_access to check and update stack bounds later.
913 	 */
914 	if (spi < 0 && spi != -ERANGE)
915 		return false;
916 
917 	/* We don't need to check if the stack slots are marked by previous
918 	 * dynptr initializations because we allow overwriting existing unreferenced
919 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
920 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
921 	 * touching are completely destructed before we reinitialize them for a new
922 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
923 	 * instead of delaying it until the end where the user will get "Unreleased
924 	 * reference" error.
925 	 */
926 	return true;
927 }
928 
929 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
930 {
931 	struct bpf_func_state *state = func(env, reg);
932 	int i, spi;
933 
934 	/* This already represents first slot of initialized bpf_dynptr.
935 	 *
936 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
937 	 * check_func_arg_reg_off's logic, so we don't need to check its
938 	 * offset and alignment.
939 	 */
940 	if (reg->type == CONST_PTR_TO_DYNPTR)
941 		return true;
942 
943 	spi = dynptr_get_spi(env, reg);
944 	if (spi < 0)
945 		return false;
946 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
947 		return false;
948 
949 	for (i = 0; i < BPF_REG_SIZE; i++) {
950 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
951 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
952 			return false;
953 	}
954 
955 	return true;
956 }
957 
958 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
959 				    enum bpf_arg_type arg_type)
960 {
961 	struct bpf_func_state *state = func(env, reg);
962 	enum bpf_dynptr_type dynptr_type;
963 	int spi;
964 
965 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
966 	if (arg_type == ARG_PTR_TO_DYNPTR)
967 		return true;
968 
969 	dynptr_type = arg_to_dynptr_type(arg_type);
970 	if (reg->type == CONST_PTR_TO_DYNPTR) {
971 		return reg->dynptr.type == dynptr_type;
972 	} else {
973 		spi = dynptr_get_spi(env, reg);
974 		if (spi < 0)
975 			return false;
976 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
977 	}
978 }
979 
980 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
981 
982 static bool in_rcu_cs(struct bpf_verifier_env *env);
983 
984 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
985 
986 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
987 				 struct bpf_kfunc_call_arg_meta *meta,
988 				 struct bpf_reg_state *reg, int insn_idx,
989 				 struct btf *btf, u32 btf_id, int nr_slots)
990 {
991 	struct bpf_func_state *state = func(env, reg);
992 	int spi, i, j, id;
993 
994 	spi = iter_get_spi(env, reg, nr_slots);
995 	if (spi < 0)
996 		return spi;
997 
998 	id = acquire_reference_state(env, insn_idx);
999 	if (id < 0)
1000 		return id;
1001 
1002 	for (i = 0; i < nr_slots; i++) {
1003 		struct bpf_stack_state *slot = &state->stack[spi - i];
1004 		struct bpf_reg_state *st = &slot->spilled_ptr;
1005 
1006 		__mark_reg_known_zero(st);
1007 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1008 		if (is_kfunc_rcu_protected(meta)) {
1009 			if (in_rcu_cs(env))
1010 				st->type |= MEM_RCU;
1011 			else
1012 				st->type |= PTR_UNTRUSTED;
1013 		}
1014 		st->live |= REG_LIVE_WRITTEN;
1015 		st->ref_obj_id = i == 0 ? id : 0;
1016 		st->iter.btf = btf;
1017 		st->iter.btf_id = btf_id;
1018 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1019 		st->iter.depth = 0;
1020 
1021 		for (j = 0; j < BPF_REG_SIZE; j++)
1022 			slot->slot_type[j] = STACK_ITER;
1023 
1024 		mark_stack_slot_scratched(env, spi - i);
1025 	}
1026 
1027 	return 0;
1028 }
1029 
1030 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1031 				   struct bpf_reg_state *reg, int nr_slots)
1032 {
1033 	struct bpf_func_state *state = func(env, reg);
1034 	int spi, i, j;
1035 
1036 	spi = iter_get_spi(env, reg, nr_slots);
1037 	if (spi < 0)
1038 		return spi;
1039 
1040 	for (i = 0; i < nr_slots; i++) {
1041 		struct bpf_stack_state *slot = &state->stack[spi - i];
1042 		struct bpf_reg_state *st = &slot->spilled_ptr;
1043 
1044 		if (i == 0)
1045 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1046 
1047 		__mark_reg_not_init(env, st);
1048 
1049 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1050 		st->live |= REG_LIVE_WRITTEN;
1051 
1052 		for (j = 0; j < BPF_REG_SIZE; j++)
1053 			slot->slot_type[j] = STACK_INVALID;
1054 
1055 		mark_stack_slot_scratched(env, spi - i);
1056 	}
1057 
1058 	return 0;
1059 }
1060 
1061 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1062 				     struct bpf_reg_state *reg, int nr_slots)
1063 {
1064 	struct bpf_func_state *state = func(env, reg);
1065 	int spi, i, j;
1066 
1067 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1068 	 * will do check_mem_access to check and update stack bounds later, so
1069 	 * return true for that case.
1070 	 */
1071 	spi = iter_get_spi(env, reg, nr_slots);
1072 	if (spi == -ERANGE)
1073 		return true;
1074 	if (spi < 0)
1075 		return false;
1076 
1077 	for (i = 0; i < nr_slots; i++) {
1078 		struct bpf_stack_state *slot = &state->stack[spi - i];
1079 
1080 		for (j = 0; j < BPF_REG_SIZE; j++)
1081 			if (slot->slot_type[j] == STACK_ITER)
1082 				return false;
1083 	}
1084 
1085 	return true;
1086 }
1087 
1088 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1089 				   struct btf *btf, u32 btf_id, int nr_slots)
1090 {
1091 	struct bpf_func_state *state = func(env, reg);
1092 	int spi, i, j;
1093 
1094 	spi = iter_get_spi(env, reg, nr_slots);
1095 	if (spi < 0)
1096 		return -EINVAL;
1097 
1098 	for (i = 0; i < nr_slots; i++) {
1099 		struct bpf_stack_state *slot = &state->stack[spi - i];
1100 		struct bpf_reg_state *st = &slot->spilled_ptr;
1101 
1102 		if (st->type & PTR_UNTRUSTED)
1103 			return -EPROTO;
1104 		/* only main (first) slot has ref_obj_id set */
1105 		if (i == 0 && !st->ref_obj_id)
1106 			return -EINVAL;
1107 		if (i != 0 && st->ref_obj_id)
1108 			return -EINVAL;
1109 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1110 			return -EINVAL;
1111 
1112 		for (j = 0; j < BPF_REG_SIZE; j++)
1113 			if (slot->slot_type[j] != STACK_ITER)
1114 				return -EINVAL;
1115 	}
1116 
1117 	return 0;
1118 }
1119 
1120 /* Check if given stack slot is "special":
1121  *   - spilled register state (STACK_SPILL);
1122  *   - dynptr state (STACK_DYNPTR);
1123  *   - iter state (STACK_ITER).
1124  */
1125 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1126 {
1127 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1128 
1129 	switch (type) {
1130 	case STACK_SPILL:
1131 	case STACK_DYNPTR:
1132 	case STACK_ITER:
1133 		return true;
1134 	case STACK_INVALID:
1135 	case STACK_MISC:
1136 	case STACK_ZERO:
1137 		return false;
1138 	default:
1139 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1140 		return true;
1141 	}
1142 }
1143 
1144 /* The reg state of a pointer or a bounded scalar was saved when
1145  * it was spilled to the stack.
1146  */
1147 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1148 {
1149 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1150 }
1151 
1152 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1153 {
1154 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1155 	       stack->spilled_ptr.type == SCALAR_VALUE;
1156 }
1157 
1158 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1159  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1160  * more precise STACK_ZERO.
1161  * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take
1162  * env->allow_ptr_leaks into account and force STACK_MISC, if necessary.
1163  */
1164 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1165 {
1166 	if (*stype == STACK_ZERO)
1167 		return;
1168 	if (env->allow_ptr_leaks && *stype == STACK_INVALID)
1169 		return;
1170 	*stype = STACK_MISC;
1171 }
1172 
1173 static void scrub_spilled_slot(u8 *stype)
1174 {
1175 	if (*stype != STACK_INVALID)
1176 		*stype = STACK_MISC;
1177 }
1178 
1179 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1180  * small to hold src. This is different from krealloc since we don't want to preserve
1181  * the contents of dst.
1182  *
1183  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1184  * not be allocated.
1185  */
1186 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1187 {
1188 	size_t alloc_bytes;
1189 	void *orig = dst;
1190 	size_t bytes;
1191 
1192 	if (ZERO_OR_NULL_PTR(src))
1193 		goto out;
1194 
1195 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1196 		return NULL;
1197 
1198 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1199 	dst = krealloc(orig, alloc_bytes, flags);
1200 	if (!dst) {
1201 		kfree(orig);
1202 		return NULL;
1203 	}
1204 
1205 	memcpy(dst, src, bytes);
1206 out:
1207 	return dst ? dst : ZERO_SIZE_PTR;
1208 }
1209 
1210 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1211  * small to hold new_n items. new items are zeroed out if the array grows.
1212  *
1213  * Contrary to krealloc_array, does not free arr if new_n is zero.
1214  */
1215 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1216 {
1217 	size_t alloc_size;
1218 	void *new_arr;
1219 
1220 	if (!new_n || old_n == new_n)
1221 		goto out;
1222 
1223 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1224 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1225 	if (!new_arr) {
1226 		kfree(arr);
1227 		return NULL;
1228 	}
1229 	arr = new_arr;
1230 
1231 	if (new_n > old_n)
1232 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1233 
1234 out:
1235 	return arr ? arr : ZERO_SIZE_PTR;
1236 }
1237 
1238 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1239 {
1240 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1241 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1242 	if (!dst->refs)
1243 		return -ENOMEM;
1244 
1245 	dst->acquired_refs = src->acquired_refs;
1246 	return 0;
1247 }
1248 
1249 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1250 {
1251 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1252 
1253 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1254 				GFP_KERNEL);
1255 	if (!dst->stack)
1256 		return -ENOMEM;
1257 
1258 	dst->allocated_stack = src->allocated_stack;
1259 	return 0;
1260 }
1261 
1262 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1263 {
1264 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1265 				    sizeof(struct bpf_reference_state));
1266 	if (!state->refs)
1267 		return -ENOMEM;
1268 
1269 	state->acquired_refs = n;
1270 	return 0;
1271 }
1272 
1273 /* Possibly update state->allocated_stack to be at least size bytes. Also
1274  * possibly update the function's high-water mark in its bpf_subprog_info.
1275  */
1276 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1277 {
1278 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1279 
1280 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1281 	size = round_up(size, BPF_REG_SIZE);
1282 	n = size / BPF_REG_SIZE;
1283 
1284 	if (old_n >= n)
1285 		return 0;
1286 
1287 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1288 	if (!state->stack)
1289 		return -ENOMEM;
1290 
1291 	state->allocated_stack = size;
1292 
1293 	/* update known max for given subprogram */
1294 	if (env->subprog_info[state->subprogno].stack_depth < size)
1295 		env->subprog_info[state->subprogno].stack_depth = size;
1296 
1297 	return 0;
1298 }
1299 
1300 /* Acquire a pointer id from the env and update the state->refs to include
1301  * this new pointer reference.
1302  * On success, returns a valid pointer id to associate with the register
1303  * On failure, returns a negative errno.
1304  */
1305 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1306 {
1307 	struct bpf_func_state *state = cur_func(env);
1308 	int new_ofs = state->acquired_refs;
1309 	int id, err;
1310 
1311 	err = resize_reference_state(state, state->acquired_refs + 1);
1312 	if (err)
1313 		return err;
1314 	id = ++env->id_gen;
1315 	state->refs[new_ofs].id = id;
1316 	state->refs[new_ofs].insn_idx = insn_idx;
1317 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1318 
1319 	return id;
1320 }
1321 
1322 /* release function corresponding to acquire_reference_state(). Idempotent. */
1323 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1324 {
1325 	int i, last_idx;
1326 
1327 	last_idx = state->acquired_refs - 1;
1328 	for (i = 0; i < state->acquired_refs; i++) {
1329 		if (state->refs[i].id == ptr_id) {
1330 			/* Cannot release caller references in callbacks */
1331 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1332 				return -EINVAL;
1333 			if (last_idx && i != last_idx)
1334 				memcpy(&state->refs[i], &state->refs[last_idx],
1335 				       sizeof(*state->refs));
1336 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1337 			state->acquired_refs--;
1338 			return 0;
1339 		}
1340 	}
1341 	return -EINVAL;
1342 }
1343 
1344 static void free_func_state(struct bpf_func_state *state)
1345 {
1346 	if (!state)
1347 		return;
1348 	kfree(state->refs);
1349 	kfree(state->stack);
1350 	kfree(state);
1351 }
1352 
1353 static void clear_jmp_history(struct bpf_verifier_state *state)
1354 {
1355 	kfree(state->jmp_history);
1356 	state->jmp_history = NULL;
1357 	state->jmp_history_cnt = 0;
1358 }
1359 
1360 static void free_verifier_state(struct bpf_verifier_state *state,
1361 				bool free_self)
1362 {
1363 	int i;
1364 
1365 	for (i = 0; i <= state->curframe; i++) {
1366 		free_func_state(state->frame[i]);
1367 		state->frame[i] = NULL;
1368 	}
1369 	clear_jmp_history(state);
1370 	if (free_self)
1371 		kfree(state);
1372 }
1373 
1374 /* copy verifier state from src to dst growing dst stack space
1375  * when necessary to accommodate larger src stack
1376  */
1377 static int copy_func_state(struct bpf_func_state *dst,
1378 			   const struct bpf_func_state *src)
1379 {
1380 	int err;
1381 
1382 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1383 	err = copy_reference_state(dst, src);
1384 	if (err)
1385 		return err;
1386 	return copy_stack_state(dst, src);
1387 }
1388 
1389 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1390 			       const struct bpf_verifier_state *src)
1391 {
1392 	struct bpf_func_state *dst;
1393 	int i, err;
1394 
1395 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1396 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1397 					  GFP_USER);
1398 	if (!dst_state->jmp_history)
1399 		return -ENOMEM;
1400 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1401 
1402 	/* if dst has more stack frames then src frame, free them, this is also
1403 	 * necessary in case of exceptional exits using bpf_throw.
1404 	 */
1405 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1406 		free_func_state(dst_state->frame[i]);
1407 		dst_state->frame[i] = NULL;
1408 	}
1409 	dst_state->speculative = src->speculative;
1410 	dst_state->active_rcu_lock = src->active_rcu_lock;
1411 	dst_state->curframe = src->curframe;
1412 	dst_state->active_lock.ptr = src->active_lock.ptr;
1413 	dst_state->active_lock.id = src->active_lock.id;
1414 	dst_state->branches = src->branches;
1415 	dst_state->parent = src->parent;
1416 	dst_state->first_insn_idx = src->first_insn_idx;
1417 	dst_state->last_insn_idx = src->last_insn_idx;
1418 	dst_state->dfs_depth = src->dfs_depth;
1419 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1420 	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1421 	for (i = 0; i <= src->curframe; i++) {
1422 		dst = dst_state->frame[i];
1423 		if (!dst) {
1424 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1425 			if (!dst)
1426 				return -ENOMEM;
1427 			dst_state->frame[i] = dst;
1428 		}
1429 		err = copy_func_state(dst, src->frame[i]);
1430 		if (err)
1431 			return err;
1432 	}
1433 	return 0;
1434 }
1435 
1436 static u32 state_htab_size(struct bpf_verifier_env *env)
1437 {
1438 	return env->prog->len;
1439 }
1440 
1441 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1442 {
1443 	struct bpf_verifier_state *cur = env->cur_state;
1444 	struct bpf_func_state *state = cur->frame[cur->curframe];
1445 
1446 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1447 }
1448 
1449 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1450 {
1451 	int fr;
1452 
1453 	if (a->curframe != b->curframe)
1454 		return false;
1455 
1456 	for (fr = a->curframe; fr >= 0; fr--)
1457 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1458 			return false;
1459 
1460 	return true;
1461 }
1462 
1463 /* Open coded iterators allow back-edges in the state graph in order to
1464  * check unbounded loops that iterators.
1465  *
1466  * In is_state_visited() it is necessary to know if explored states are
1467  * part of some loops in order to decide whether non-exact states
1468  * comparison could be used:
1469  * - non-exact states comparison establishes sub-state relation and uses
1470  *   read and precision marks to do so, these marks are propagated from
1471  *   children states and thus are not guaranteed to be final in a loop;
1472  * - exact states comparison just checks if current and explored states
1473  *   are identical (and thus form a back-edge).
1474  *
1475  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1476  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1477  * algorithm for loop structure detection and gives an overview of
1478  * relevant terminology. It also has helpful illustrations.
1479  *
1480  * [1] https://api.semanticscholar.org/CorpusID:15784067
1481  *
1482  * We use a similar algorithm but because loop nested structure is
1483  * irrelevant for verifier ours is significantly simpler and resembles
1484  * strongly connected components algorithm from Sedgewick's textbook.
1485  *
1486  * Define topmost loop entry as a first node of the loop traversed in a
1487  * depth first search starting from initial state. The goal of the loop
1488  * tracking algorithm is to associate topmost loop entries with states
1489  * derived from these entries.
1490  *
1491  * For each step in the DFS states traversal algorithm needs to identify
1492  * the following situations:
1493  *
1494  *          initial                     initial                   initial
1495  *            |                           |                         |
1496  *            V                           V                         V
1497  *           ...                         ...           .---------> hdr
1498  *            |                           |            |            |
1499  *            V                           V            |            V
1500  *           cur                     .-> succ          |    .------...
1501  *            |                      |    |            |    |       |
1502  *            V                      |    V            |    V       V
1503  *           succ                    '-- cur           |   ...     ...
1504  *                                                     |    |       |
1505  *                                                     |    V       V
1506  *                                                     |   succ <- cur
1507  *                                                     |    |
1508  *                                                     |    V
1509  *                                                     |   ...
1510  *                                                     |    |
1511  *                                                     '----'
1512  *
1513  *  (A) successor state of cur   (B) successor state of cur or it's entry
1514  *      not yet traversed            are in current DFS path, thus cur and succ
1515  *                                   are members of the same outermost loop
1516  *
1517  *                      initial                  initial
1518  *                        |                        |
1519  *                        V                        V
1520  *                       ...                      ...
1521  *                        |                        |
1522  *                        V                        V
1523  *                .------...               .------...
1524  *                |       |                |       |
1525  *                V       V                V       V
1526  *           .-> hdr     ...              ...     ...
1527  *           |    |       |                |       |
1528  *           |    V       V                V       V
1529  *           |   succ <- cur              succ <- cur
1530  *           |    |                        |
1531  *           |    V                        V
1532  *           |   ...                      ...
1533  *           |    |                        |
1534  *           '----'                       exit
1535  *
1536  * (C) successor state of cur is a part of some loop but this loop
1537  *     does not include cur or successor state is not in a loop at all.
1538  *
1539  * Algorithm could be described as the following python code:
1540  *
1541  *     traversed = set()   # Set of traversed nodes
1542  *     entries = {}        # Mapping from node to loop entry
1543  *     depths = {}         # Depth level assigned to graph node
1544  *     path = set()        # Current DFS path
1545  *
1546  *     # Find outermost loop entry known for n
1547  *     def get_loop_entry(n):
1548  *         h = entries.get(n, None)
1549  *         while h in entries and entries[h] != h:
1550  *             h = entries[h]
1551  *         return h
1552  *
1553  *     # Update n's loop entry if h's outermost entry comes
1554  *     # before n's outermost entry in current DFS path.
1555  *     def update_loop_entry(n, h):
1556  *         n1 = get_loop_entry(n) or n
1557  *         h1 = get_loop_entry(h) or h
1558  *         if h1 in path and depths[h1] <= depths[n1]:
1559  *             entries[n] = h1
1560  *
1561  *     def dfs(n, depth):
1562  *         traversed.add(n)
1563  *         path.add(n)
1564  *         depths[n] = depth
1565  *         for succ in G.successors(n):
1566  *             if succ not in traversed:
1567  *                 # Case A: explore succ and update cur's loop entry
1568  *                 #         only if succ's entry is in current DFS path.
1569  *                 dfs(succ, depth + 1)
1570  *                 h = get_loop_entry(succ)
1571  *                 update_loop_entry(n, h)
1572  *             else:
1573  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1574  *                 update_loop_entry(n, succ)
1575  *         path.remove(n)
1576  *
1577  * To adapt this algorithm for use with verifier:
1578  * - use st->branch == 0 as a signal that DFS of succ had been finished
1579  *   and cur's loop entry has to be updated (case A), handle this in
1580  *   update_branch_counts();
1581  * - use st->branch > 0 as a signal that st is in the current DFS path;
1582  * - handle cases B and C in is_state_visited();
1583  * - update topmost loop entry for intermediate states in get_loop_entry().
1584  */
1585 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1586 {
1587 	struct bpf_verifier_state *topmost = st->loop_entry, *old;
1588 
1589 	while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1590 		topmost = topmost->loop_entry;
1591 	/* Update loop entries for intermediate states to avoid this
1592 	 * traversal in future get_loop_entry() calls.
1593 	 */
1594 	while (st && st->loop_entry != topmost) {
1595 		old = st->loop_entry;
1596 		st->loop_entry = topmost;
1597 		st = old;
1598 	}
1599 	return topmost;
1600 }
1601 
1602 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1603 {
1604 	struct bpf_verifier_state *cur1, *hdr1;
1605 
1606 	cur1 = get_loop_entry(cur) ?: cur;
1607 	hdr1 = get_loop_entry(hdr) ?: hdr;
1608 	/* The head1->branches check decides between cases B and C in
1609 	 * comment for get_loop_entry(). If hdr1->branches == 0 then
1610 	 * head's topmost loop entry is not in current DFS path,
1611 	 * hence 'cur' and 'hdr' are not in the same loop and there is
1612 	 * no need to update cur->loop_entry.
1613 	 */
1614 	if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1615 		cur->loop_entry = hdr;
1616 		hdr->used_as_loop_entry = true;
1617 	}
1618 }
1619 
1620 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1621 {
1622 	while (st) {
1623 		u32 br = --st->branches;
1624 
1625 		/* br == 0 signals that DFS exploration for 'st' is finished,
1626 		 * thus it is necessary to update parent's loop entry if it
1627 		 * turned out that st is a part of some loop.
1628 		 * This is a part of 'case A' in get_loop_entry() comment.
1629 		 */
1630 		if (br == 0 && st->parent && st->loop_entry)
1631 			update_loop_entry(st->parent, st->loop_entry);
1632 
1633 		/* WARN_ON(br > 1) technically makes sense here,
1634 		 * but see comment in push_stack(), hence:
1635 		 */
1636 		WARN_ONCE((int)br < 0,
1637 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1638 			  br);
1639 		if (br)
1640 			break;
1641 		st = st->parent;
1642 	}
1643 }
1644 
1645 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1646 		     int *insn_idx, bool pop_log)
1647 {
1648 	struct bpf_verifier_state *cur = env->cur_state;
1649 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1650 	int err;
1651 
1652 	if (env->head == NULL)
1653 		return -ENOENT;
1654 
1655 	if (cur) {
1656 		err = copy_verifier_state(cur, &head->st);
1657 		if (err)
1658 			return err;
1659 	}
1660 	if (pop_log)
1661 		bpf_vlog_reset(&env->log, head->log_pos);
1662 	if (insn_idx)
1663 		*insn_idx = head->insn_idx;
1664 	if (prev_insn_idx)
1665 		*prev_insn_idx = head->prev_insn_idx;
1666 	elem = head->next;
1667 	free_verifier_state(&head->st, false);
1668 	kfree(head);
1669 	env->head = elem;
1670 	env->stack_size--;
1671 	return 0;
1672 }
1673 
1674 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1675 					     int insn_idx, int prev_insn_idx,
1676 					     bool speculative)
1677 {
1678 	struct bpf_verifier_state *cur = env->cur_state;
1679 	struct bpf_verifier_stack_elem *elem;
1680 	int err;
1681 
1682 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1683 	if (!elem)
1684 		goto err;
1685 
1686 	elem->insn_idx = insn_idx;
1687 	elem->prev_insn_idx = prev_insn_idx;
1688 	elem->next = env->head;
1689 	elem->log_pos = env->log.end_pos;
1690 	env->head = elem;
1691 	env->stack_size++;
1692 	err = copy_verifier_state(&elem->st, cur);
1693 	if (err)
1694 		goto err;
1695 	elem->st.speculative |= speculative;
1696 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1697 		verbose(env, "The sequence of %d jumps is too complex.\n",
1698 			env->stack_size);
1699 		goto err;
1700 	}
1701 	if (elem->st.parent) {
1702 		++elem->st.parent->branches;
1703 		/* WARN_ON(branches > 2) technically makes sense here,
1704 		 * but
1705 		 * 1. speculative states will bump 'branches' for non-branch
1706 		 * instructions
1707 		 * 2. is_state_visited() heuristics may decide not to create
1708 		 * a new state for a sequence of branches and all such current
1709 		 * and cloned states will be pointing to a single parent state
1710 		 * which might have large 'branches' count.
1711 		 */
1712 	}
1713 	return &elem->st;
1714 err:
1715 	free_verifier_state(env->cur_state, true);
1716 	env->cur_state = NULL;
1717 	/* pop all elements and return */
1718 	while (!pop_stack(env, NULL, NULL, false));
1719 	return NULL;
1720 }
1721 
1722 #define CALLER_SAVED_REGS 6
1723 static const int caller_saved[CALLER_SAVED_REGS] = {
1724 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1725 };
1726 
1727 /* This helper doesn't clear reg->id */
1728 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1729 {
1730 	reg->var_off = tnum_const(imm);
1731 	reg->smin_value = (s64)imm;
1732 	reg->smax_value = (s64)imm;
1733 	reg->umin_value = imm;
1734 	reg->umax_value = imm;
1735 
1736 	reg->s32_min_value = (s32)imm;
1737 	reg->s32_max_value = (s32)imm;
1738 	reg->u32_min_value = (u32)imm;
1739 	reg->u32_max_value = (u32)imm;
1740 }
1741 
1742 /* Mark the unknown part of a register (variable offset or scalar value) as
1743  * known to have the value @imm.
1744  */
1745 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1746 {
1747 	/* Clear off and union(map_ptr, range) */
1748 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1749 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1750 	reg->id = 0;
1751 	reg->ref_obj_id = 0;
1752 	___mark_reg_known(reg, imm);
1753 }
1754 
1755 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1756 {
1757 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1758 	reg->s32_min_value = (s32)imm;
1759 	reg->s32_max_value = (s32)imm;
1760 	reg->u32_min_value = (u32)imm;
1761 	reg->u32_max_value = (u32)imm;
1762 }
1763 
1764 /* Mark the 'variable offset' part of a register as zero.  This should be
1765  * used only on registers holding a pointer type.
1766  */
1767 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1768 {
1769 	__mark_reg_known(reg, 0);
1770 }
1771 
1772 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1773 {
1774 	__mark_reg_known(reg, 0);
1775 	reg->type = SCALAR_VALUE;
1776 	/* all scalars are assumed imprecise initially (unless unprivileged,
1777 	 * in which case everything is forced to be precise)
1778 	 */
1779 	reg->precise = !env->bpf_capable;
1780 }
1781 
1782 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1783 				struct bpf_reg_state *regs, u32 regno)
1784 {
1785 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1786 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1787 		/* Something bad happened, let's kill all regs */
1788 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1789 			__mark_reg_not_init(env, regs + regno);
1790 		return;
1791 	}
1792 	__mark_reg_known_zero(regs + regno);
1793 }
1794 
1795 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1796 			      bool first_slot, int dynptr_id)
1797 {
1798 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1799 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1800 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1801 	 */
1802 	__mark_reg_known_zero(reg);
1803 	reg->type = CONST_PTR_TO_DYNPTR;
1804 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1805 	reg->id = dynptr_id;
1806 	reg->dynptr.type = type;
1807 	reg->dynptr.first_slot = first_slot;
1808 }
1809 
1810 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1811 {
1812 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1813 		const struct bpf_map *map = reg->map_ptr;
1814 
1815 		if (map->inner_map_meta) {
1816 			reg->type = CONST_PTR_TO_MAP;
1817 			reg->map_ptr = map->inner_map_meta;
1818 			/* transfer reg's id which is unique for every map_lookup_elem
1819 			 * as UID of the inner map.
1820 			 */
1821 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1822 				reg->map_uid = reg->id;
1823 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1824 			reg->type = PTR_TO_XDP_SOCK;
1825 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1826 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1827 			reg->type = PTR_TO_SOCKET;
1828 		} else {
1829 			reg->type = PTR_TO_MAP_VALUE;
1830 		}
1831 		return;
1832 	}
1833 
1834 	reg->type &= ~PTR_MAYBE_NULL;
1835 }
1836 
1837 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1838 				struct btf_field_graph_root *ds_head)
1839 {
1840 	__mark_reg_known_zero(&regs[regno]);
1841 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1842 	regs[regno].btf = ds_head->btf;
1843 	regs[regno].btf_id = ds_head->value_btf_id;
1844 	regs[regno].off = ds_head->node_offset;
1845 }
1846 
1847 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1848 {
1849 	return type_is_pkt_pointer(reg->type);
1850 }
1851 
1852 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1853 {
1854 	return reg_is_pkt_pointer(reg) ||
1855 	       reg->type == PTR_TO_PACKET_END;
1856 }
1857 
1858 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1859 {
1860 	return base_type(reg->type) == PTR_TO_MEM &&
1861 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1862 }
1863 
1864 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1865 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1866 				    enum bpf_reg_type which)
1867 {
1868 	/* The register can already have a range from prior markings.
1869 	 * This is fine as long as it hasn't been advanced from its
1870 	 * origin.
1871 	 */
1872 	return reg->type == which &&
1873 	       reg->id == 0 &&
1874 	       reg->off == 0 &&
1875 	       tnum_equals_const(reg->var_off, 0);
1876 }
1877 
1878 /* Reset the min/max bounds of a register */
1879 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1880 {
1881 	reg->smin_value = S64_MIN;
1882 	reg->smax_value = S64_MAX;
1883 	reg->umin_value = 0;
1884 	reg->umax_value = U64_MAX;
1885 
1886 	reg->s32_min_value = S32_MIN;
1887 	reg->s32_max_value = S32_MAX;
1888 	reg->u32_min_value = 0;
1889 	reg->u32_max_value = U32_MAX;
1890 }
1891 
1892 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1893 {
1894 	reg->smin_value = S64_MIN;
1895 	reg->smax_value = S64_MAX;
1896 	reg->umin_value = 0;
1897 	reg->umax_value = U64_MAX;
1898 }
1899 
1900 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1901 {
1902 	reg->s32_min_value = S32_MIN;
1903 	reg->s32_max_value = S32_MAX;
1904 	reg->u32_min_value = 0;
1905 	reg->u32_max_value = U32_MAX;
1906 }
1907 
1908 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1909 {
1910 	struct tnum var32_off = tnum_subreg(reg->var_off);
1911 
1912 	/* min signed is max(sign bit) | min(other bits) */
1913 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1914 			var32_off.value | (var32_off.mask & S32_MIN));
1915 	/* max signed is min(sign bit) | max(other bits) */
1916 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1917 			var32_off.value | (var32_off.mask & S32_MAX));
1918 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1919 	reg->u32_max_value = min(reg->u32_max_value,
1920 				 (u32)(var32_off.value | var32_off.mask));
1921 }
1922 
1923 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1924 {
1925 	/* min signed is max(sign bit) | min(other bits) */
1926 	reg->smin_value = max_t(s64, reg->smin_value,
1927 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1928 	/* max signed is min(sign bit) | max(other bits) */
1929 	reg->smax_value = min_t(s64, reg->smax_value,
1930 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1931 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1932 	reg->umax_value = min(reg->umax_value,
1933 			      reg->var_off.value | reg->var_off.mask);
1934 }
1935 
1936 static void __update_reg_bounds(struct bpf_reg_state *reg)
1937 {
1938 	__update_reg32_bounds(reg);
1939 	__update_reg64_bounds(reg);
1940 }
1941 
1942 /* Uses signed min/max values to inform unsigned, and vice-versa */
1943 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1944 {
1945 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
1946 	 * bits to improve our u32/s32 boundaries.
1947 	 *
1948 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
1949 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
1950 	 * [10, 20] range. But this property holds for any 64-bit range as
1951 	 * long as upper 32 bits in that entire range of values stay the same.
1952 	 *
1953 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
1954 	 * in decimal) has the same upper 32 bits throughout all the values in
1955 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
1956 	 * range.
1957 	 *
1958 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
1959 	 * following the rules outlined below about u64/s64 correspondence
1960 	 * (which equally applies to u32 vs s32 correspondence). In general it
1961 	 * depends on actual hexadecimal values of 32-bit range. They can form
1962 	 * only valid u32, or only valid s32 ranges in some cases.
1963 	 *
1964 	 * So we use all these insights to derive bounds for subregisters here.
1965 	 */
1966 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
1967 		/* u64 to u32 casting preserves validity of low 32 bits as
1968 		 * a range, if upper 32 bits are the same
1969 		 */
1970 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
1971 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
1972 
1973 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
1974 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
1975 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
1976 		}
1977 	}
1978 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
1979 		/* low 32 bits should form a proper u32 range */
1980 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
1981 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
1982 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
1983 		}
1984 		/* low 32 bits should form a proper s32 range */
1985 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
1986 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
1987 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
1988 		}
1989 	}
1990 	/* Special case where upper bits form a small sequence of two
1991 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
1992 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
1993 	 * going from negative numbers to positive numbers. E.g., let's say we
1994 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
1995 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
1996 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
1997 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
1998 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
1999 	 * upper 32 bits. As a random example, s64 range
2000 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2001 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2002 	 */
2003 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2004 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2005 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2006 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2007 	}
2008 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2009 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2010 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2011 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2012 	}
2013 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2014 	 * try to learn from that
2015 	 */
2016 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2017 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2018 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2019 	}
2020 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2021 	 * are the same, so combine.  This works even in the negative case, e.g.
2022 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2023 	 */
2024 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2025 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2026 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2027 	}
2028 }
2029 
2030 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2031 {
2032 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2033 	 * try to learn from that. Let's do a bit of ASCII art to see when
2034 	 * this is happening. Let's take u64 range first:
2035 	 *
2036 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2037 	 * |-------------------------------|--------------------------------|
2038 	 *
2039 	 * Valid u64 range is formed when umin and umax are anywhere in the
2040 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2041 	 * straightforward. Let's see how s64 range maps onto the same range
2042 	 * of values, annotated below the line for comparison:
2043 	 *
2044 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2045 	 * |-------------------------------|--------------------------------|
2046 	 * 0                        S64_MAX S64_MIN                        -1
2047 	 *
2048 	 * So s64 values basically start in the middle and they are logically
2049 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2050 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2051 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2052 	 * more visually as mapped to sign-agnostic range of hex values.
2053 	 *
2054 	 *  u64 start                                               u64 end
2055 	 *  _______________________________________________________________
2056 	 * /                                                               \
2057 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2058 	 * |-------------------------------|--------------------------------|
2059 	 * 0                        S64_MAX S64_MIN                        -1
2060 	 *                                / \
2061 	 * >------------------------------   ------------------------------->
2062 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2063 	 *
2064 	 * What this means is that, in general, we can't always derive
2065 	 * something new about u64 from any random s64 range, and vice versa.
2066 	 *
2067 	 * But we can do that in two particular cases. One is when entire
2068 	 * u64/s64 range is *entirely* contained within left half of the above
2069 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2070 	 *
2071 	 * |-------------------------------|--------------------------------|
2072 	 *     ^                   ^            ^                 ^
2073 	 *     A                   B            C                 D
2074 	 *
2075 	 * [A, B] and [C, D] are contained entirely in their respective halves
2076 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2077 	 * will be non-negative both as u64 and s64 (and in fact it will be
2078 	 * identical ranges no matter the signedness). [C, D] treated as s64
2079 	 * will be a range of negative values, while in u64 it will be
2080 	 * non-negative range of values larger than 0x8000000000000000.
2081 	 *
2082 	 * Now, any other range here can't be represented in both u64 and s64
2083 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2084 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2085 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2086 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2087 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2088 	 * ranges as u64. Currently reg_state can't represent two segments per
2089 	 * numeric domain, so in such situations we can only derive maximal
2090 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2091 	 *
2092 	 * So we use these facts to derive umin/umax from smin/smax and vice
2093 	 * versa only if they stay within the same "half". This is equivalent
2094 	 * to checking sign bit: lower half will have sign bit as zero, upper
2095 	 * half have sign bit 1. Below in code we simplify this by just
2096 	 * casting umin/umax as smin/smax and checking if they form valid
2097 	 * range, and vice versa. Those are equivalent checks.
2098 	 */
2099 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2100 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2101 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2102 	}
2103 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2104 	 * are the same, so combine.  This works even in the negative case, e.g.
2105 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2106 	 */
2107 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2108 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2109 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2110 	}
2111 }
2112 
2113 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2114 {
2115 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2116 	 * values on both sides of 64-bit range in hope to have tigher range.
2117 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2118 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2119 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2120 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2121 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2122 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2123 	 * We just need to make sure that derived bounds we are intersecting
2124 	 * with are well-formed ranges in respecitve s64 or u64 domain, just
2125 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2126 	 */
2127 	__u64 new_umin, new_umax;
2128 	__s64 new_smin, new_smax;
2129 
2130 	/* u32 -> u64 tightening, it's always well-formed */
2131 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2132 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2133 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2134 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2135 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2136 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2137 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2138 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2139 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2140 
2141 	/* if s32 can be treated as valid u32 range, we can use it as well */
2142 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2143 		/* s32 -> u64 tightening */
2144 		new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2145 		new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2146 		reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2147 		reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2148 		/* s32 -> s64 tightening */
2149 		new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2150 		new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2151 		reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2152 		reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2153 	}
2154 }
2155 
2156 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2157 {
2158 	__reg32_deduce_bounds(reg);
2159 	__reg64_deduce_bounds(reg);
2160 	__reg_deduce_mixed_bounds(reg);
2161 }
2162 
2163 /* Attempts to improve var_off based on unsigned min/max information */
2164 static void __reg_bound_offset(struct bpf_reg_state *reg)
2165 {
2166 	struct tnum var64_off = tnum_intersect(reg->var_off,
2167 					       tnum_range(reg->umin_value,
2168 							  reg->umax_value));
2169 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2170 					       tnum_range(reg->u32_min_value,
2171 							  reg->u32_max_value));
2172 
2173 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2174 }
2175 
2176 static void reg_bounds_sync(struct bpf_reg_state *reg)
2177 {
2178 	/* We might have learned new bounds from the var_off. */
2179 	__update_reg_bounds(reg);
2180 	/* We might have learned something about the sign bit. */
2181 	__reg_deduce_bounds(reg);
2182 	__reg_deduce_bounds(reg);
2183 	/* We might have learned some bits from the bounds. */
2184 	__reg_bound_offset(reg);
2185 	/* Intersecting with the old var_off might have improved our bounds
2186 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2187 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2188 	 */
2189 	__update_reg_bounds(reg);
2190 }
2191 
2192 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2193 				   struct bpf_reg_state *reg, const char *ctx)
2194 {
2195 	const char *msg;
2196 
2197 	if (reg->umin_value > reg->umax_value ||
2198 	    reg->smin_value > reg->smax_value ||
2199 	    reg->u32_min_value > reg->u32_max_value ||
2200 	    reg->s32_min_value > reg->s32_max_value) {
2201 		    msg = "range bounds violation";
2202 		    goto out;
2203 	}
2204 
2205 	if (tnum_is_const(reg->var_off)) {
2206 		u64 uval = reg->var_off.value;
2207 		s64 sval = (s64)uval;
2208 
2209 		if (reg->umin_value != uval || reg->umax_value != uval ||
2210 		    reg->smin_value != sval || reg->smax_value != sval) {
2211 			msg = "const tnum out of sync with range bounds";
2212 			goto out;
2213 		}
2214 	}
2215 
2216 	if (tnum_subreg_is_const(reg->var_off)) {
2217 		u32 uval32 = tnum_subreg(reg->var_off).value;
2218 		s32 sval32 = (s32)uval32;
2219 
2220 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2221 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2222 			msg = "const subreg tnum out of sync with range bounds";
2223 			goto out;
2224 		}
2225 	}
2226 
2227 	return 0;
2228 out:
2229 	verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2230 		"s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n",
2231 		ctx, msg, reg->umin_value, reg->umax_value,
2232 		reg->smin_value, reg->smax_value,
2233 		reg->u32_min_value, reg->u32_max_value,
2234 		reg->s32_min_value, reg->s32_max_value,
2235 		reg->var_off.value, reg->var_off.mask);
2236 	if (env->test_reg_invariants)
2237 		return -EFAULT;
2238 	__mark_reg_unbounded(reg);
2239 	return 0;
2240 }
2241 
2242 static bool __reg32_bound_s64(s32 a)
2243 {
2244 	return a >= 0 && a <= S32_MAX;
2245 }
2246 
2247 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2248 {
2249 	reg->umin_value = reg->u32_min_value;
2250 	reg->umax_value = reg->u32_max_value;
2251 
2252 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2253 	 * be positive otherwise set to worse case bounds and refine later
2254 	 * from tnum.
2255 	 */
2256 	if (__reg32_bound_s64(reg->s32_min_value) &&
2257 	    __reg32_bound_s64(reg->s32_max_value)) {
2258 		reg->smin_value = reg->s32_min_value;
2259 		reg->smax_value = reg->s32_max_value;
2260 	} else {
2261 		reg->smin_value = 0;
2262 		reg->smax_value = U32_MAX;
2263 	}
2264 }
2265 
2266 /* Mark a register as having a completely unknown (scalar) value. */
2267 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2268 			       struct bpf_reg_state *reg)
2269 {
2270 	/*
2271 	 * Clear type, off, and union(map_ptr, range) and
2272 	 * padding between 'type' and union
2273 	 */
2274 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2275 	reg->type = SCALAR_VALUE;
2276 	reg->id = 0;
2277 	reg->ref_obj_id = 0;
2278 	reg->var_off = tnum_unknown;
2279 	reg->frameno = 0;
2280 	reg->precise = !env->bpf_capable;
2281 	__mark_reg_unbounded(reg);
2282 }
2283 
2284 static void mark_reg_unknown(struct bpf_verifier_env *env,
2285 			     struct bpf_reg_state *regs, u32 regno)
2286 {
2287 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2288 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2289 		/* Something bad happened, let's kill all regs except FP */
2290 		for (regno = 0; regno < BPF_REG_FP; regno++)
2291 			__mark_reg_not_init(env, regs + regno);
2292 		return;
2293 	}
2294 	__mark_reg_unknown(env, regs + regno);
2295 }
2296 
2297 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2298 				struct bpf_reg_state *reg)
2299 {
2300 	__mark_reg_unknown(env, reg);
2301 	reg->type = NOT_INIT;
2302 }
2303 
2304 static void mark_reg_not_init(struct bpf_verifier_env *env,
2305 			      struct bpf_reg_state *regs, u32 regno)
2306 {
2307 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2308 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2309 		/* Something bad happened, let's kill all regs except FP */
2310 		for (regno = 0; regno < BPF_REG_FP; regno++)
2311 			__mark_reg_not_init(env, regs + regno);
2312 		return;
2313 	}
2314 	__mark_reg_not_init(env, regs + regno);
2315 }
2316 
2317 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2318 			    struct bpf_reg_state *regs, u32 regno,
2319 			    enum bpf_reg_type reg_type,
2320 			    struct btf *btf, u32 btf_id,
2321 			    enum bpf_type_flag flag)
2322 {
2323 	if (reg_type == SCALAR_VALUE) {
2324 		mark_reg_unknown(env, regs, regno);
2325 		return;
2326 	}
2327 	mark_reg_known_zero(env, regs, regno);
2328 	regs[regno].type = PTR_TO_BTF_ID | flag;
2329 	regs[regno].btf = btf;
2330 	regs[regno].btf_id = btf_id;
2331 }
2332 
2333 #define DEF_NOT_SUBREG	(0)
2334 static void init_reg_state(struct bpf_verifier_env *env,
2335 			   struct bpf_func_state *state)
2336 {
2337 	struct bpf_reg_state *regs = state->regs;
2338 	int i;
2339 
2340 	for (i = 0; i < MAX_BPF_REG; i++) {
2341 		mark_reg_not_init(env, regs, i);
2342 		regs[i].live = REG_LIVE_NONE;
2343 		regs[i].parent = NULL;
2344 		regs[i].subreg_def = DEF_NOT_SUBREG;
2345 	}
2346 
2347 	/* frame pointer */
2348 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2349 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2350 	regs[BPF_REG_FP].frameno = state->frameno;
2351 }
2352 
2353 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2354 {
2355 	return (struct bpf_retval_range){ minval, maxval };
2356 }
2357 
2358 #define BPF_MAIN_FUNC (-1)
2359 static void init_func_state(struct bpf_verifier_env *env,
2360 			    struct bpf_func_state *state,
2361 			    int callsite, int frameno, int subprogno)
2362 {
2363 	state->callsite = callsite;
2364 	state->frameno = frameno;
2365 	state->subprogno = subprogno;
2366 	state->callback_ret_range = retval_range(0, 0);
2367 	init_reg_state(env, state);
2368 	mark_verifier_state_scratched(env);
2369 }
2370 
2371 /* Similar to push_stack(), but for async callbacks */
2372 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2373 						int insn_idx, int prev_insn_idx,
2374 						int subprog)
2375 {
2376 	struct bpf_verifier_stack_elem *elem;
2377 	struct bpf_func_state *frame;
2378 
2379 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2380 	if (!elem)
2381 		goto err;
2382 
2383 	elem->insn_idx = insn_idx;
2384 	elem->prev_insn_idx = prev_insn_idx;
2385 	elem->next = env->head;
2386 	elem->log_pos = env->log.end_pos;
2387 	env->head = elem;
2388 	env->stack_size++;
2389 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2390 		verbose(env,
2391 			"The sequence of %d jumps is too complex for async cb.\n",
2392 			env->stack_size);
2393 		goto err;
2394 	}
2395 	/* Unlike push_stack() do not copy_verifier_state().
2396 	 * The caller state doesn't matter.
2397 	 * This is async callback. It starts in a fresh stack.
2398 	 * Initialize it similar to do_check_common().
2399 	 */
2400 	elem->st.branches = 1;
2401 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2402 	if (!frame)
2403 		goto err;
2404 	init_func_state(env, frame,
2405 			BPF_MAIN_FUNC /* callsite */,
2406 			0 /* frameno within this callchain */,
2407 			subprog /* subprog number within this prog */);
2408 	elem->st.frame[0] = frame;
2409 	return &elem->st;
2410 err:
2411 	free_verifier_state(env->cur_state, true);
2412 	env->cur_state = NULL;
2413 	/* pop all elements and return */
2414 	while (!pop_stack(env, NULL, NULL, false));
2415 	return NULL;
2416 }
2417 
2418 
2419 enum reg_arg_type {
2420 	SRC_OP,		/* register is used as source operand */
2421 	DST_OP,		/* register is used as destination operand */
2422 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2423 };
2424 
2425 static int cmp_subprogs(const void *a, const void *b)
2426 {
2427 	return ((struct bpf_subprog_info *)a)->start -
2428 	       ((struct bpf_subprog_info *)b)->start;
2429 }
2430 
2431 static int find_subprog(struct bpf_verifier_env *env, int off)
2432 {
2433 	struct bpf_subprog_info *p;
2434 
2435 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2436 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2437 	if (!p)
2438 		return -ENOENT;
2439 	return p - env->subprog_info;
2440 
2441 }
2442 
2443 static int add_subprog(struct bpf_verifier_env *env, int off)
2444 {
2445 	int insn_cnt = env->prog->len;
2446 	int ret;
2447 
2448 	if (off >= insn_cnt || off < 0) {
2449 		verbose(env, "call to invalid destination\n");
2450 		return -EINVAL;
2451 	}
2452 	ret = find_subprog(env, off);
2453 	if (ret >= 0)
2454 		return ret;
2455 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2456 		verbose(env, "too many subprograms\n");
2457 		return -E2BIG;
2458 	}
2459 	/* determine subprog starts. The end is one before the next starts */
2460 	env->subprog_info[env->subprog_cnt++].start = off;
2461 	sort(env->subprog_info, env->subprog_cnt,
2462 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2463 	return env->subprog_cnt - 1;
2464 }
2465 
2466 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2467 {
2468 	struct bpf_prog_aux *aux = env->prog->aux;
2469 	struct btf *btf = aux->btf;
2470 	const struct btf_type *t;
2471 	u32 main_btf_id, id;
2472 	const char *name;
2473 	int ret, i;
2474 
2475 	/* Non-zero func_info_cnt implies valid btf */
2476 	if (!aux->func_info_cnt)
2477 		return 0;
2478 	main_btf_id = aux->func_info[0].type_id;
2479 
2480 	t = btf_type_by_id(btf, main_btf_id);
2481 	if (!t) {
2482 		verbose(env, "invalid btf id for main subprog in func_info\n");
2483 		return -EINVAL;
2484 	}
2485 
2486 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2487 	if (IS_ERR(name)) {
2488 		ret = PTR_ERR(name);
2489 		/* If there is no tag present, there is no exception callback */
2490 		if (ret == -ENOENT)
2491 			ret = 0;
2492 		else if (ret == -EEXIST)
2493 			verbose(env, "multiple exception callback tags for main subprog\n");
2494 		return ret;
2495 	}
2496 
2497 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2498 	if (ret < 0) {
2499 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2500 		return ret;
2501 	}
2502 	id = ret;
2503 	t = btf_type_by_id(btf, id);
2504 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2505 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2506 		return -EINVAL;
2507 	}
2508 	ret = 0;
2509 	for (i = 0; i < aux->func_info_cnt; i++) {
2510 		if (aux->func_info[i].type_id != id)
2511 			continue;
2512 		ret = aux->func_info[i].insn_off;
2513 		/* Further func_info and subprog checks will also happen
2514 		 * later, so assume this is the right insn_off for now.
2515 		 */
2516 		if (!ret) {
2517 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2518 			ret = -EINVAL;
2519 		}
2520 	}
2521 	if (!ret) {
2522 		verbose(env, "exception callback type id not found in func_info\n");
2523 		ret = -EINVAL;
2524 	}
2525 	return ret;
2526 }
2527 
2528 #define MAX_KFUNC_DESCS 256
2529 #define MAX_KFUNC_BTFS	256
2530 
2531 struct bpf_kfunc_desc {
2532 	struct btf_func_model func_model;
2533 	u32 func_id;
2534 	s32 imm;
2535 	u16 offset;
2536 	unsigned long addr;
2537 };
2538 
2539 struct bpf_kfunc_btf {
2540 	struct btf *btf;
2541 	struct module *module;
2542 	u16 offset;
2543 };
2544 
2545 struct bpf_kfunc_desc_tab {
2546 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2547 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2548 	 * available, therefore at the end of verification do_misc_fixups()
2549 	 * sorts this by imm and offset.
2550 	 */
2551 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2552 	u32 nr_descs;
2553 };
2554 
2555 struct bpf_kfunc_btf_tab {
2556 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2557 	u32 nr_descs;
2558 };
2559 
2560 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2561 {
2562 	const struct bpf_kfunc_desc *d0 = a;
2563 	const struct bpf_kfunc_desc *d1 = b;
2564 
2565 	/* func_id is not greater than BTF_MAX_TYPE */
2566 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2567 }
2568 
2569 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2570 {
2571 	const struct bpf_kfunc_btf *d0 = a;
2572 	const struct bpf_kfunc_btf *d1 = b;
2573 
2574 	return d0->offset - d1->offset;
2575 }
2576 
2577 static const struct bpf_kfunc_desc *
2578 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2579 {
2580 	struct bpf_kfunc_desc desc = {
2581 		.func_id = func_id,
2582 		.offset = offset,
2583 	};
2584 	struct bpf_kfunc_desc_tab *tab;
2585 
2586 	tab = prog->aux->kfunc_tab;
2587 	return bsearch(&desc, tab->descs, tab->nr_descs,
2588 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2589 }
2590 
2591 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2592 		       u16 btf_fd_idx, u8 **func_addr)
2593 {
2594 	const struct bpf_kfunc_desc *desc;
2595 
2596 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2597 	if (!desc)
2598 		return -EFAULT;
2599 
2600 	*func_addr = (u8 *)desc->addr;
2601 	return 0;
2602 }
2603 
2604 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2605 					 s16 offset)
2606 {
2607 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2608 	struct bpf_kfunc_btf_tab *tab;
2609 	struct bpf_kfunc_btf *b;
2610 	struct module *mod;
2611 	struct btf *btf;
2612 	int btf_fd;
2613 
2614 	tab = env->prog->aux->kfunc_btf_tab;
2615 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2616 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2617 	if (!b) {
2618 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2619 			verbose(env, "too many different module BTFs\n");
2620 			return ERR_PTR(-E2BIG);
2621 		}
2622 
2623 		if (bpfptr_is_null(env->fd_array)) {
2624 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2625 			return ERR_PTR(-EPROTO);
2626 		}
2627 
2628 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2629 					    offset * sizeof(btf_fd),
2630 					    sizeof(btf_fd)))
2631 			return ERR_PTR(-EFAULT);
2632 
2633 		btf = btf_get_by_fd(btf_fd);
2634 		if (IS_ERR(btf)) {
2635 			verbose(env, "invalid module BTF fd specified\n");
2636 			return btf;
2637 		}
2638 
2639 		if (!btf_is_module(btf)) {
2640 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2641 			btf_put(btf);
2642 			return ERR_PTR(-EINVAL);
2643 		}
2644 
2645 		mod = btf_try_get_module(btf);
2646 		if (!mod) {
2647 			btf_put(btf);
2648 			return ERR_PTR(-ENXIO);
2649 		}
2650 
2651 		b = &tab->descs[tab->nr_descs++];
2652 		b->btf = btf;
2653 		b->module = mod;
2654 		b->offset = offset;
2655 
2656 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2657 		     kfunc_btf_cmp_by_off, NULL);
2658 	}
2659 	return b->btf;
2660 }
2661 
2662 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2663 {
2664 	if (!tab)
2665 		return;
2666 
2667 	while (tab->nr_descs--) {
2668 		module_put(tab->descs[tab->nr_descs].module);
2669 		btf_put(tab->descs[tab->nr_descs].btf);
2670 	}
2671 	kfree(tab);
2672 }
2673 
2674 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2675 {
2676 	if (offset) {
2677 		if (offset < 0) {
2678 			/* In the future, this can be allowed to increase limit
2679 			 * of fd index into fd_array, interpreted as u16.
2680 			 */
2681 			verbose(env, "negative offset disallowed for kernel module function call\n");
2682 			return ERR_PTR(-EINVAL);
2683 		}
2684 
2685 		return __find_kfunc_desc_btf(env, offset);
2686 	}
2687 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2688 }
2689 
2690 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2691 {
2692 	const struct btf_type *func, *func_proto;
2693 	struct bpf_kfunc_btf_tab *btf_tab;
2694 	struct bpf_kfunc_desc_tab *tab;
2695 	struct bpf_prog_aux *prog_aux;
2696 	struct bpf_kfunc_desc *desc;
2697 	const char *func_name;
2698 	struct btf *desc_btf;
2699 	unsigned long call_imm;
2700 	unsigned long addr;
2701 	int err;
2702 
2703 	prog_aux = env->prog->aux;
2704 	tab = prog_aux->kfunc_tab;
2705 	btf_tab = prog_aux->kfunc_btf_tab;
2706 	if (!tab) {
2707 		if (!btf_vmlinux) {
2708 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2709 			return -ENOTSUPP;
2710 		}
2711 
2712 		if (!env->prog->jit_requested) {
2713 			verbose(env, "JIT is required for calling kernel function\n");
2714 			return -ENOTSUPP;
2715 		}
2716 
2717 		if (!bpf_jit_supports_kfunc_call()) {
2718 			verbose(env, "JIT does not support calling kernel function\n");
2719 			return -ENOTSUPP;
2720 		}
2721 
2722 		if (!env->prog->gpl_compatible) {
2723 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2724 			return -EINVAL;
2725 		}
2726 
2727 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2728 		if (!tab)
2729 			return -ENOMEM;
2730 		prog_aux->kfunc_tab = tab;
2731 	}
2732 
2733 	/* func_id == 0 is always invalid, but instead of returning an error, be
2734 	 * conservative and wait until the code elimination pass before returning
2735 	 * error, so that invalid calls that get pruned out can be in BPF programs
2736 	 * loaded from userspace.  It is also required that offset be untouched
2737 	 * for such calls.
2738 	 */
2739 	if (!func_id && !offset)
2740 		return 0;
2741 
2742 	if (!btf_tab && offset) {
2743 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2744 		if (!btf_tab)
2745 			return -ENOMEM;
2746 		prog_aux->kfunc_btf_tab = btf_tab;
2747 	}
2748 
2749 	desc_btf = find_kfunc_desc_btf(env, offset);
2750 	if (IS_ERR(desc_btf)) {
2751 		verbose(env, "failed to find BTF for kernel function\n");
2752 		return PTR_ERR(desc_btf);
2753 	}
2754 
2755 	if (find_kfunc_desc(env->prog, func_id, offset))
2756 		return 0;
2757 
2758 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2759 		verbose(env, "too many different kernel function calls\n");
2760 		return -E2BIG;
2761 	}
2762 
2763 	func = btf_type_by_id(desc_btf, func_id);
2764 	if (!func || !btf_type_is_func(func)) {
2765 		verbose(env, "kernel btf_id %u is not a function\n",
2766 			func_id);
2767 		return -EINVAL;
2768 	}
2769 	func_proto = btf_type_by_id(desc_btf, func->type);
2770 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2771 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2772 			func_id);
2773 		return -EINVAL;
2774 	}
2775 
2776 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2777 	addr = kallsyms_lookup_name(func_name);
2778 	if (!addr) {
2779 		verbose(env, "cannot find address for kernel function %s\n",
2780 			func_name);
2781 		return -EINVAL;
2782 	}
2783 	specialize_kfunc(env, func_id, offset, &addr);
2784 
2785 	if (bpf_jit_supports_far_kfunc_call()) {
2786 		call_imm = func_id;
2787 	} else {
2788 		call_imm = BPF_CALL_IMM(addr);
2789 		/* Check whether the relative offset overflows desc->imm */
2790 		if ((unsigned long)(s32)call_imm != call_imm) {
2791 			verbose(env, "address of kernel function %s is out of range\n",
2792 				func_name);
2793 			return -EINVAL;
2794 		}
2795 	}
2796 
2797 	if (bpf_dev_bound_kfunc_id(func_id)) {
2798 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2799 		if (err)
2800 			return err;
2801 	}
2802 
2803 	desc = &tab->descs[tab->nr_descs++];
2804 	desc->func_id = func_id;
2805 	desc->imm = call_imm;
2806 	desc->offset = offset;
2807 	desc->addr = addr;
2808 	err = btf_distill_func_proto(&env->log, desc_btf,
2809 				     func_proto, func_name,
2810 				     &desc->func_model);
2811 	if (!err)
2812 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2813 		     kfunc_desc_cmp_by_id_off, NULL);
2814 	return err;
2815 }
2816 
2817 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2818 {
2819 	const struct bpf_kfunc_desc *d0 = a;
2820 	const struct bpf_kfunc_desc *d1 = b;
2821 
2822 	if (d0->imm != d1->imm)
2823 		return d0->imm < d1->imm ? -1 : 1;
2824 	if (d0->offset != d1->offset)
2825 		return d0->offset < d1->offset ? -1 : 1;
2826 	return 0;
2827 }
2828 
2829 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2830 {
2831 	struct bpf_kfunc_desc_tab *tab;
2832 
2833 	tab = prog->aux->kfunc_tab;
2834 	if (!tab)
2835 		return;
2836 
2837 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2838 	     kfunc_desc_cmp_by_imm_off, NULL);
2839 }
2840 
2841 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2842 {
2843 	return !!prog->aux->kfunc_tab;
2844 }
2845 
2846 const struct btf_func_model *
2847 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2848 			 const struct bpf_insn *insn)
2849 {
2850 	const struct bpf_kfunc_desc desc = {
2851 		.imm = insn->imm,
2852 		.offset = insn->off,
2853 	};
2854 	const struct bpf_kfunc_desc *res;
2855 	struct bpf_kfunc_desc_tab *tab;
2856 
2857 	tab = prog->aux->kfunc_tab;
2858 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2859 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2860 
2861 	return res ? &res->func_model : NULL;
2862 }
2863 
2864 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2865 {
2866 	struct bpf_subprog_info *subprog = env->subprog_info;
2867 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
2868 	struct bpf_insn *insn = env->prog->insnsi;
2869 
2870 	/* Add entry function. */
2871 	ret = add_subprog(env, 0);
2872 	if (ret)
2873 		return ret;
2874 
2875 	for (i = 0; i < insn_cnt; i++, insn++) {
2876 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2877 		    !bpf_pseudo_kfunc_call(insn))
2878 			continue;
2879 
2880 		if (!env->bpf_capable) {
2881 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2882 			return -EPERM;
2883 		}
2884 
2885 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2886 			ret = add_subprog(env, i + insn->imm + 1);
2887 		else
2888 			ret = add_kfunc_call(env, insn->imm, insn->off);
2889 
2890 		if (ret < 0)
2891 			return ret;
2892 	}
2893 
2894 	ret = bpf_find_exception_callback_insn_off(env);
2895 	if (ret < 0)
2896 		return ret;
2897 	ex_cb_insn = ret;
2898 
2899 	/* If ex_cb_insn > 0, this means that the main program has a subprog
2900 	 * marked using BTF decl tag to serve as the exception callback.
2901 	 */
2902 	if (ex_cb_insn) {
2903 		ret = add_subprog(env, ex_cb_insn);
2904 		if (ret < 0)
2905 			return ret;
2906 		for (i = 1; i < env->subprog_cnt; i++) {
2907 			if (env->subprog_info[i].start != ex_cb_insn)
2908 				continue;
2909 			env->exception_callback_subprog = i;
2910 			mark_subprog_exc_cb(env, i);
2911 			break;
2912 		}
2913 	}
2914 
2915 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2916 	 * logic. 'subprog_cnt' should not be increased.
2917 	 */
2918 	subprog[env->subprog_cnt].start = insn_cnt;
2919 
2920 	if (env->log.level & BPF_LOG_LEVEL2)
2921 		for (i = 0; i < env->subprog_cnt; i++)
2922 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2923 
2924 	return 0;
2925 }
2926 
2927 static int check_subprogs(struct bpf_verifier_env *env)
2928 {
2929 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2930 	struct bpf_subprog_info *subprog = env->subprog_info;
2931 	struct bpf_insn *insn = env->prog->insnsi;
2932 	int insn_cnt = env->prog->len;
2933 
2934 	/* now check that all jumps are within the same subprog */
2935 	subprog_start = subprog[cur_subprog].start;
2936 	subprog_end = subprog[cur_subprog + 1].start;
2937 	for (i = 0; i < insn_cnt; i++) {
2938 		u8 code = insn[i].code;
2939 
2940 		if (code == (BPF_JMP | BPF_CALL) &&
2941 		    insn[i].src_reg == 0 &&
2942 		    insn[i].imm == BPF_FUNC_tail_call)
2943 			subprog[cur_subprog].has_tail_call = true;
2944 		if (BPF_CLASS(code) == BPF_LD &&
2945 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2946 			subprog[cur_subprog].has_ld_abs = true;
2947 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2948 			goto next;
2949 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2950 			goto next;
2951 		if (code == (BPF_JMP32 | BPF_JA))
2952 			off = i + insn[i].imm + 1;
2953 		else
2954 			off = i + insn[i].off + 1;
2955 		if (off < subprog_start || off >= subprog_end) {
2956 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2957 			return -EINVAL;
2958 		}
2959 next:
2960 		if (i == subprog_end - 1) {
2961 			/* to avoid fall-through from one subprog into another
2962 			 * the last insn of the subprog should be either exit
2963 			 * or unconditional jump back or bpf_throw call
2964 			 */
2965 			if (code != (BPF_JMP | BPF_EXIT) &&
2966 			    code != (BPF_JMP32 | BPF_JA) &&
2967 			    code != (BPF_JMP | BPF_JA)) {
2968 				verbose(env, "last insn is not an exit or jmp\n");
2969 				return -EINVAL;
2970 			}
2971 			subprog_start = subprog_end;
2972 			cur_subprog++;
2973 			if (cur_subprog < env->subprog_cnt)
2974 				subprog_end = subprog[cur_subprog + 1].start;
2975 		}
2976 	}
2977 	return 0;
2978 }
2979 
2980 /* Parentage chain of this register (or stack slot) should take care of all
2981  * issues like callee-saved registers, stack slot allocation time, etc.
2982  */
2983 static int mark_reg_read(struct bpf_verifier_env *env,
2984 			 const struct bpf_reg_state *state,
2985 			 struct bpf_reg_state *parent, u8 flag)
2986 {
2987 	bool writes = parent == state->parent; /* Observe write marks */
2988 	int cnt = 0;
2989 
2990 	while (parent) {
2991 		/* if read wasn't screened by an earlier write ... */
2992 		if (writes && state->live & REG_LIVE_WRITTEN)
2993 			break;
2994 		if (parent->live & REG_LIVE_DONE) {
2995 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2996 				reg_type_str(env, parent->type),
2997 				parent->var_off.value, parent->off);
2998 			return -EFAULT;
2999 		}
3000 		/* The first condition is more likely to be true than the
3001 		 * second, checked it first.
3002 		 */
3003 		if ((parent->live & REG_LIVE_READ) == flag ||
3004 		    parent->live & REG_LIVE_READ64)
3005 			/* The parentage chain never changes and
3006 			 * this parent was already marked as LIVE_READ.
3007 			 * There is no need to keep walking the chain again and
3008 			 * keep re-marking all parents as LIVE_READ.
3009 			 * This case happens when the same register is read
3010 			 * multiple times without writes into it in-between.
3011 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3012 			 * then no need to set the weak REG_LIVE_READ32.
3013 			 */
3014 			break;
3015 		/* ... then we depend on parent's value */
3016 		parent->live |= flag;
3017 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3018 		if (flag == REG_LIVE_READ64)
3019 			parent->live &= ~REG_LIVE_READ32;
3020 		state = parent;
3021 		parent = state->parent;
3022 		writes = true;
3023 		cnt++;
3024 	}
3025 
3026 	if (env->longest_mark_read_walk < cnt)
3027 		env->longest_mark_read_walk = cnt;
3028 	return 0;
3029 }
3030 
3031 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3032 {
3033 	struct bpf_func_state *state = func(env, reg);
3034 	int spi, ret;
3035 
3036 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3037 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3038 	 * check_kfunc_call.
3039 	 */
3040 	if (reg->type == CONST_PTR_TO_DYNPTR)
3041 		return 0;
3042 	spi = dynptr_get_spi(env, reg);
3043 	if (spi < 0)
3044 		return spi;
3045 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3046 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3047 	 * read.
3048 	 */
3049 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3050 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3051 	if (ret)
3052 		return ret;
3053 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3054 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3055 }
3056 
3057 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3058 			  int spi, int nr_slots)
3059 {
3060 	struct bpf_func_state *state = func(env, reg);
3061 	int err, i;
3062 
3063 	for (i = 0; i < nr_slots; i++) {
3064 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3065 
3066 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3067 		if (err)
3068 			return err;
3069 
3070 		mark_stack_slot_scratched(env, spi - i);
3071 	}
3072 
3073 	return 0;
3074 }
3075 
3076 /* This function is supposed to be used by the following 32-bit optimization
3077  * code only. It returns TRUE if the source or destination register operates
3078  * on 64-bit, otherwise return FALSE.
3079  */
3080 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3081 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3082 {
3083 	u8 code, class, op;
3084 
3085 	code = insn->code;
3086 	class = BPF_CLASS(code);
3087 	op = BPF_OP(code);
3088 	if (class == BPF_JMP) {
3089 		/* BPF_EXIT for "main" will reach here. Return TRUE
3090 		 * conservatively.
3091 		 */
3092 		if (op == BPF_EXIT)
3093 			return true;
3094 		if (op == BPF_CALL) {
3095 			/* BPF to BPF call will reach here because of marking
3096 			 * caller saved clobber with DST_OP_NO_MARK for which we
3097 			 * don't care the register def because they are anyway
3098 			 * marked as NOT_INIT already.
3099 			 */
3100 			if (insn->src_reg == BPF_PSEUDO_CALL)
3101 				return false;
3102 			/* Helper call will reach here because of arg type
3103 			 * check, conservatively return TRUE.
3104 			 */
3105 			if (t == SRC_OP)
3106 				return true;
3107 
3108 			return false;
3109 		}
3110 	}
3111 
3112 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3113 		return false;
3114 
3115 	if (class == BPF_ALU64 || class == BPF_JMP ||
3116 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3117 		return true;
3118 
3119 	if (class == BPF_ALU || class == BPF_JMP32)
3120 		return false;
3121 
3122 	if (class == BPF_LDX) {
3123 		if (t != SRC_OP)
3124 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3125 		/* LDX source must be ptr. */
3126 		return true;
3127 	}
3128 
3129 	if (class == BPF_STX) {
3130 		/* BPF_STX (including atomic variants) has multiple source
3131 		 * operands, one of which is a ptr. Check whether the caller is
3132 		 * asking about it.
3133 		 */
3134 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3135 			return true;
3136 		return BPF_SIZE(code) == BPF_DW;
3137 	}
3138 
3139 	if (class == BPF_LD) {
3140 		u8 mode = BPF_MODE(code);
3141 
3142 		/* LD_IMM64 */
3143 		if (mode == BPF_IMM)
3144 			return true;
3145 
3146 		/* Both LD_IND and LD_ABS return 32-bit data. */
3147 		if (t != SRC_OP)
3148 			return  false;
3149 
3150 		/* Implicit ctx ptr. */
3151 		if (regno == BPF_REG_6)
3152 			return true;
3153 
3154 		/* Explicit source could be any width. */
3155 		return true;
3156 	}
3157 
3158 	if (class == BPF_ST)
3159 		/* The only source register for BPF_ST is a ptr. */
3160 		return true;
3161 
3162 	/* Conservatively return true at default. */
3163 	return true;
3164 }
3165 
3166 /* Return the regno defined by the insn, or -1. */
3167 static int insn_def_regno(const struct bpf_insn *insn)
3168 {
3169 	switch (BPF_CLASS(insn->code)) {
3170 	case BPF_JMP:
3171 	case BPF_JMP32:
3172 	case BPF_ST:
3173 		return -1;
3174 	case BPF_STX:
3175 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3176 		    (insn->imm & BPF_FETCH)) {
3177 			if (insn->imm == BPF_CMPXCHG)
3178 				return BPF_REG_0;
3179 			else
3180 				return insn->src_reg;
3181 		} else {
3182 			return -1;
3183 		}
3184 	default:
3185 		return insn->dst_reg;
3186 	}
3187 }
3188 
3189 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3190 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3191 {
3192 	int dst_reg = insn_def_regno(insn);
3193 
3194 	if (dst_reg == -1)
3195 		return false;
3196 
3197 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3198 }
3199 
3200 static void mark_insn_zext(struct bpf_verifier_env *env,
3201 			   struct bpf_reg_state *reg)
3202 {
3203 	s32 def_idx = reg->subreg_def;
3204 
3205 	if (def_idx == DEF_NOT_SUBREG)
3206 		return;
3207 
3208 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3209 	/* The dst will be zero extended, so won't be sub-register anymore. */
3210 	reg->subreg_def = DEF_NOT_SUBREG;
3211 }
3212 
3213 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3214 			   enum reg_arg_type t)
3215 {
3216 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3217 	struct bpf_reg_state *reg;
3218 	bool rw64;
3219 
3220 	if (regno >= MAX_BPF_REG) {
3221 		verbose(env, "R%d is invalid\n", regno);
3222 		return -EINVAL;
3223 	}
3224 
3225 	mark_reg_scratched(env, regno);
3226 
3227 	reg = &regs[regno];
3228 	rw64 = is_reg64(env, insn, regno, reg, t);
3229 	if (t == SRC_OP) {
3230 		/* check whether register used as source operand can be read */
3231 		if (reg->type == NOT_INIT) {
3232 			verbose(env, "R%d !read_ok\n", regno);
3233 			return -EACCES;
3234 		}
3235 		/* We don't need to worry about FP liveness because it's read-only */
3236 		if (regno == BPF_REG_FP)
3237 			return 0;
3238 
3239 		if (rw64)
3240 			mark_insn_zext(env, reg);
3241 
3242 		return mark_reg_read(env, reg, reg->parent,
3243 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3244 	} else {
3245 		/* check whether register used as dest operand can be written to */
3246 		if (regno == BPF_REG_FP) {
3247 			verbose(env, "frame pointer is read only\n");
3248 			return -EACCES;
3249 		}
3250 		reg->live |= REG_LIVE_WRITTEN;
3251 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3252 		if (t == DST_OP)
3253 			mark_reg_unknown(env, regs, regno);
3254 	}
3255 	return 0;
3256 }
3257 
3258 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3259 			 enum reg_arg_type t)
3260 {
3261 	struct bpf_verifier_state *vstate = env->cur_state;
3262 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3263 
3264 	return __check_reg_arg(env, state->regs, regno, t);
3265 }
3266 
3267 static int insn_stack_access_flags(int frameno, int spi)
3268 {
3269 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3270 }
3271 
3272 static int insn_stack_access_spi(int insn_flags)
3273 {
3274 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3275 }
3276 
3277 static int insn_stack_access_frameno(int insn_flags)
3278 {
3279 	return insn_flags & INSN_F_FRAMENO_MASK;
3280 }
3281 
3282 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3283 {
3284 	env->insn_aux_data[idx].jmp_point = true;
3285 }
3286 
3287 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3288 {
3289 	return env->insn_aux_data[insn_idx].jmp_point;
3290 }
3291 
3292 /* for any branch, call, exit record the history of jmps in the given state */
3293 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3294 			    int insn_flags)
3295 {
3296 	u32 cnt = cur->jmp_history_cnt;
3297 	struct bpf_jmp_history_entry *p;
3298 	size_t alloc_size;
3299 
3300 	/* combine instruction flags if we already recorded this instruction */
3301 	if (env->cur_hist_ent) {
3302 		/* atomic instructions push insn_flags twice, for READ and
3303 		 * WRITE sides, but they should agree on stack slot
3304 		 */
3305 		WARN_ONCE((env->cur_hist_ent->flags & insn_flags) &&
3306 			  (env->cur_hist_ent->flags & insn_flags) != insn_flags,
3307 			  "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n",
3308 			  env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3309 		env->cur_hist_ent->flags |= insn_flags;
3310 		return 0;
3311 	}
3312 
3313 	cnt++;
3314 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3315 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3316 	if (!p)
3317 		return -ENOMEM;
3318 	cur->jmp_history = p;
3319 
3320 	p = &cur->jmp_history[cnt - 1];
3321 	p->idx = env->insn_idx;
3322 	p->prev_idx = env->prev_insn_idx;
3323 	p->flags = insn_flags;
3324 	cur->jmp_history_cnt = cnt;
3325 	env->cur_hist_ent = p;
3326 
3327 	return 0;
3328 }
3329 
3330 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3331 						        u32 hist_end, int insn_idx)
3332 {
3333 	if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3334 		return &st->jmp_history[hist_end - 1];
3335 	return NULL;
3336 }
3337 
3338 /* Backtrack one insn at a time. If idx is not at the top of recorded
3339  * history then previous instruction came from straight line execution.
3340  * Return -ENOENT if we exhausted all instructions within given state.
3341  *
3342  * It's legal to have a bit of a looping with the same starting and ending
3343  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3344  * instruction index is the same as state's first_idx doesn't mean we are
3345  * done. If there is still some jump history left, we should keep going. We
3346  * need to take into account that we might have a jump history between given
3347  * state's parent and itself, due to checkpointing. In this case, we'll have
3348  * history entry recording a jump from last instruction of parent state and
3349  * first instruction of given state.
3350  */
3351 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3352 			     u32 *history)
3353 {
3354 	u32 cnt = *history;
3355 
3356 	if (i == st->first_insn_idx) {
3357 		if (cnt == 0)
3358 			return -ENOENT;
3359 		if (cnt == 1 && st->jmp_history[0].idx == i)
3360 			return -ENOENT;
3361 	}
3362 
3363 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3364 		i = st->jmp_history[cnt - 1].prev_idx;
3365 		(*history)--;
3366 	} else {
3367 		i--;
3368 	}
3369 	return i;
3370 }
3371 
3372 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3373 {
3374 	const struct btf_type *func;
3375 	struct btf *desc_btf;
3376 
3377 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3378 		return NULL;
3379 
3380 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3381 	if (IS_ERR(desc_btf))
3382 		return "<error>";
3383 
3384 	func = btf_type_by_id(desc_btf, insn->imm);
3385 	return btf_name_by_offset(desc_btf, func->name_off);
3386 }
3387 
3388 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3389 {
3390 	bt->frame = frame;
3391 }
3392 
3393 static inline void bt_reset(struct backtrack_state *bt)
3394 {
3395 	struct bpf_verifier_env *env = bt->env;
3396 
3397 	memset(bt, 0, sizeof(*bt));
3398 	bt->env = env;
3399 }
3400 
3401 static inline u32 bt_empty(struct backtrack_state *bt)
3402 {
3403 	u64 mask = 0;
3404 	int i;
3405 
3406 	for (i = 0; i <= bt->frame; i++)
3407 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3408 
3409 	return mask == 0;
3410 }
3411 
3412 static inline int bt_subprog_enter(struct backtrack_state *bt)
3413 {
3414 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3415 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3416 		WARN_ONCE(1, "verifier backtracking bug");
3417 		return -EFAULT;
3418 	}
3419 	bt->frame++;
3420 	return 0;
3421 }
3422 
3423 static inline int bt_subprog_exit(struct backtrack_state *bt)
3424 {
3425 	if (bt->frame == 0) {
3426 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3427 		WARN_ONCE(1, "verifier backtracking bug");
3428 		return -EFAULT;
3429 	}
3430 	bt->frame--;
3431 	return 0;
3432 }
3433 
3434 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3435 {
3436 	bt->reg_masks[frame] |= 1 << reg;
3437 }
3438 
3439 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3440 {
3441 	bt->reg_masks[frame] &= ~(1 << reg);
3442 }
3443 
3444 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3445 {
3446 	bt_set_frame_reg(bt, bt->frame, reg);
3447 }
3448 
3449 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3450 {
3451 	bt_clear_frame_reg(bt, bt->frame, reg);
3452 }
3453 
3454 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3455 {
3456 	bt->stack_masks[frame] |= 1ull << slot;
3457 }
3458 
3459 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3460 {
3461 	bt->stack_masks[frame] &= ~(1ull << slot);
3462 }
3463 
3464 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3465 {
3466 	return bt->reg_masks[frame];
3467 }
3468 
3469 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3470 {
3471 	return bt->reg_masks[bt->frame];
3472 }
3473 
3474 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3475 {
3476 	return bt->stack_masks[frame];
3477 }
3478 
3479 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3480 {
3481 	return bt->stack_masks[bt->frame];
3482 }
3483 
3484 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3485 {
3486 	return bt->reg_masks[bt->frame] & (1 << reg);
3487 }
3488 
3489 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
3490 {
3491 	return bt->stack_masks[frame] & (1ull << slot);
3492 }
3493 
3494 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3495 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3496 {
3497 	DECLARE_BITMAP(mask, 64);
3498 	bool first = true;
3499 	int i, n;
3500 
3501 	buf[0] = '\0';
3502 
3503 	bitmap_from_u64(mask, reg_mask);
3504 	for_each_set_bit(i, mask, 32) {
3505 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3506 		first = false;
3507 		buf += n;
3508 		buf_sz -= n;
3509 		if (buf_sz < 0)
3510 			break;
3511 	}
3512 }
3513 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3514 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3515 {
3516 	DECLARE_BITMAP(mask, 64);
3517 	bool first = true;
3518 	int i, n;
3519 
3520 	buf[0] = '\0';
3521 
3522 	bitmap_from_u64(mask, stack_mask);
3523 	for_each_set_bit(i, mask, 64) {
3524 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3525 		first = false;
3526 		buf += n;
3527 		buf_sz -= n;
3528 		if (buf_sz < 0)
3529 			break;
3530 	}
3531 }
3532 
3533 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3534 
3535 /* For given verifier state backtrack_insn() is called from the last insn to
3536  * the first insn. Its purpose is to compute a bitmask of registers and
3537  * stack slots that needs precision in the parent verifier state.
3538  *
3539  * @idx is an index of the instruction we are currently processing;
3540  * @subseq_idx is an index of the subsequent instruction that:
3541  *   - *would be* executed next, if jump history is viewed in forward order;
3542  *   - *was* processed previously during backtracking.
3543  */
3544 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3545 			  struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
3546 {
3547 	const struct bpf_insn_cbs cbs = {
3548 		.cb_call	= disasm_kfunc_name,
3549 		.cb_print	= verbose,
3550 		.private_data	= env,
3551 	};
3552 	struct bpf_insn *insn = env->prog->insnsi + idx;
3553 	u8 class = BPF_CLASS(insn->code);
3554 	u8 opcode = BPF_OP(insn->code);
3555 	u8 mode = BPF_MODE(insn->code);
3556 	u32 dreg = insn->dst_reg;
3557 	u32 sreg = insn->src_reg;
3558 	u32 spi, i, fr;
3559 
3560 	if (insn->code == 0)
3561 		return 0;
3562 	if (env->log.level & BPF_LOG_LEVEL2) {
3563 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3564 		verbose(env, "mark_precise: frame%d: regs=%s ",
3565 			bt->frame, env->tmp_str_buf);
3566 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3567 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3568 		verbose(env, "%d: ", idx);
3569 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3570 	}
3571 
3572 	if (class == BPF_ALU || class == BPF_ALU64) {
3573 		if (!bt_is_reg_set(bt, dreg))
3574 			return 0;
3575 		if (opcode == BPF_END || opcode == BPF_NEG) {
3576 			/* sreg is reserved and unused
3577 			 * dreg still need precision before this insn
3578 			 */
3579 			return 0;
3580 		} else if (opcode == BPF_MOV) {
3581 			if (BPF_SRC(insn->code) == BPF_X) {
3582 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3583 				 * dreg needs precision after this insn
3584 				 * sreg needs precision before this insn
3585 				 */
3586 				bt_clear_reg(bt, dreg);
3587 				bt_set_reg(bt, sreg);
3588 			} else {
3589 				/* dreg = K
3590 				 * dreg needs precision after this insn.
3591 				 * Corresponding register is already marked
3592 				 * as precise=true in this verifier state.
3593 				 * No further markings in parent are necessary
3594 				 */
3595 				bt_clear_reg(bt, dreg);
3596 			}
3597 		} else {
3598 			if (BPF_SRC(insn->code) == BPF_X) {
3599 				/* dreg += sreg
3600 				 * both dreg and sreg need precision
3601 				 * before this insn
3602 				 */
3603 				bt_set_reg(bt, sreg);
3604 			} /* else dreg += K
3605 			   * dreg still needs precision before this insn
3606 			   */
3607 		}
3608 	} else if (class == BPF_LDX) {
3609 		if (!bt_is_reg_set(bt, dreg))
3610 			return 0;
3611 		bt_clear_reg(bt, dreg);
3612 
3613 		/* scalars can only be spilled into stack w/o losing precision.
3614 		 * Load from any other memory can be zero extended.
3615 		 * The desire to keep that precision is already indicated
3616 		 * by 'precise' mark in corresponding register of this state.
3617 		 * No further tracking necessary.
3618 		 */
3619 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3620 			return 0;
3621 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3622 		 * that [fp - off] slot contains scalar that needs to be
3623 		 * tracked with precision
3624 		 */
3625 		spi = insn_stack_access_spi(hist->flags);
3626 		fr = insn_stack_access_frameno(hist->flags);
3627 		bt_set_frame_slot(bt, fr, spi);
3628 	} else if (class == BPF_STX || class == BPF_ST) {
3629 		if (bt_is_reg_set(bt, dreg))
3630 			/* stx & st shouldn't be using _scalar_ dst_reg
3631 			 * to access memory. It means backtracking
3632 			 * encountered a case of pointer subtraction.
3633 			 */
3634 			return -ENOTSUPP;
3635 		/* scalars can only be spilled into stack */
3636 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3637 			return 0;
3638 		spi = insn_stack_access_spi(hist->flags);
3639 		fr = insn_stack_access_frameno(hist->flags);
3640 		if (!bt_is_frame_slot_set(bt, fr, spi))
3641 			return 0;
3642 		bt_clear_frame_slot(bt, fr, spi);
3643 		if (class == BPF_STX)
3644 			bt_set_reg(bt, sreg);
3645 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3646 		if (bpf_pseudo_call(insn)) {
3647 			int subprog_insn_idx, subprog;
3648 
3649 			subprog_insn_idx = idx + insn->imm + 1;
3650 			subprog = find_subprog(env, subprog_insn_idx);
3651 			if (subprog < 0)
3652 				return -EFAULT;
3653 
3654 			if (subprog_is_global(env, subprog)) {
3655 				/* check that jump history doesn't have any
3656 				 * extra instructions from subprog; the next
3657 				 * instruction after call to global subprog
3658 				 * should be literally next instruction in
3659 				 * caller program
3660 				 */
3661 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3662 				/* r1-r5 are invalidated after subprog call,
3663 				 * so for global func call it shouldn't be set
3664 				 * anymore
3665 				 */
3666 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3667 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3668 					WARN_ONCE(1, "verifier backtracking bug");
3669 					return -EFAULT;
3670 				}
3671 				/* global subprog always sets R0 */
3672 				bt_clear_reg(bt, BPF_REG_0);
3673 				return 0;
3674 			} else {
3675 				/* static subprog call instruction, which
3676 				 * means that we are exiting current subprog,
3677 				 * so only r1-r5 could be still requested as
3678 				 * precise, r0 and r6-r10 or any stack slot in
3679 				 * the current frame should be zero by now
3680 				 */
3681 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3682 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3683 					WARN_ONCE(1, "verifier backtracking bug");
3684 					return -EFAULT;
3685 				}
3686 				/* we are now tracking register spills correctly,
3687 				 * so any instance of leftover slots is a bug
3688 				 */
3689 				if (bt_stack_mask(bt) != 0) {
3690 					verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3691 					WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)");
3692 					return -EFAULT;
3693 				}
3694 				/* propagate r1-r5 to the caller */
3695 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3696 					if (bt_is_reg_set(bt, i)) {
3697 						bt_clear_reg(bt, i);
3698 						bt_set_frame_reg(bt, bt->frame - 1, i);
3699 					}
3700 				}
3701 				if (bt_subprog_exit(bt))
3702 					return -EFAULT;
3703 				return 0;
3704 			}
3705 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3706 			/* exit from callback subprog to callback-calling helper or
3707 			 * kfunc call. Use idx/subseq_idx check to discern it from
3708 			 * straight line code backtracking.
3709 			 * Unlike the subprog call handling above, we shouldn't
3710 			 * propagate precision of r1-r5 (if any requested), as they are
3711 			 * not actually arguments passed directly to callback subprogs
3712 			 */
3713 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3714 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3715 				WARN_ONCE(1, "verifier backtracking bug");
3716 				return -EFAULT;
3717 			}
3718 			if (bt_stack_mask(bt) != 0) {
3719 				verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3720 				WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)");
3721 				return -EFAULT;
3722 			}
3723 			/* clear r1-r5 in callback subprog's mask */
3724 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3725 				bt_clear_reg(bt, i);
3726 			if (bt_subprog_exit(bt))
3727 				return -EFAULT;
3728 			return 0;
3729 		} else if (opcode == BPF_CALL) {
3730 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3731 			 * catch this error later. Make backtracking conservative
3732 			 * with ENOTSUPP.
3733 			 */
3734 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3735 				return -ENOTSUPP;
3736 			/* regular helper call sets R0 */
3737 			bt_clear_reg(bt, BPF_REG_0);
3738 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3739 				/* if backtracing was looking for registers R1-R5
3740 				 * they should have been found already.
3741 				 */
3742 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3743 				WARN_ONCE(1, "verifier backtracking bug");
3744 				return -EFAULT;
3745 			}
3746 		} else if (opcode == BPF_EXIT) {
3747 			bool r0_precise;
3748 
3749 			/* Backtracking to a nested function call, 'idx' is a part of
3750 			 * the inner frame 'subseq_idx' is a part of the outer frame.
3751 			 * In case of a regular function call, instructions giving
3752 			 * precision to registers R1-R5 should have been found already.
3753 			 * In case of a callback, it is ok to have R1-R5 marked for
3754 			 * backtracking, as these registers are set by the function
3755 			 * invoking callback.
3756 			 */
3757 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3758 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3759 					bt_clear_reg(bt, i);
3760 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3761 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3762 				WARN_ONCE(1, "verifier backtracking bug");
3763 				return -EFAULT;
3764 			}
3765 
3766 			/* BPF_EXIT in subprog or callback always returns
3767 			 * right after the call instruction, so by checking
3768 			 * whether the instruction at subseq_idx-1 is subprog
3769 			 * call or not we can distinguish actual exit from
3770 			 * *subprog* from exit from *callback*. In the former
3771 			 * case, we need to propagate r0 precision, if
3772 			 * necessary. In the former we never do that.
3773 			 */
3774 			r0_precise = subseq_idx - 1 >= 0 &&
3775 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3776 				     bt_is_reg_set(bt, BPF_REG_0);
3777 
3778 			bt_clear_reg(bt, BPF_REG_0);
3779 			if (bt_subprog_enter(bt))
3780 				return -EFAULT;
3781 
3782 			if (r0_precise)
3783 				bt_set_reg(bt, BPF_REG_0);
3784 			/* r6-r9 and stack slots will stay set in caller frame
3785 			 * bitmasks until we return back from callee(s)
3786 			 */
3787 			return 0;
3788 		} else if (BPF_SRC(insn->code) == BPF_X) {
3789 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3790 				return 0;
3791 			/* dreg <cond> sreg
3792 			 * Both dreg and sreg need precision before
3793 			 * this insn. If only sreg was marked precise
3794 			 * before it would be equally necessary to
3795 			 * propagate it to dreg.
3796 			 */
3797 			bt_set_reg(bt, dreg);
3798 			bt_set_reg(bt, sreg);
3799 			 /* else dreg <cond> K
3800 			  * Only dreg still needs precision before
3801 			  * this insn, so for the K-based conditional
3802 			  * there is nothing new to be marked.
3803 			  */
3804 		}
3805 	} else if (class == BPF_LD) {
3806 		if (!bt_is_reg_set(bt, dreg))
3807 			return 0;
3808 		bt_clear_reg(bt, dreg);
3809 		/* It's ld_imm64 or ld_abs or ld_ind.
3810 		 * For ld_imm64 no further tracking of precision
3811 		 * into parent is necessary
3812 		 */
3813 		if (mode == BPF_IND || mode == BPF_ABS)
3814 			/* to be analyzed */
3815 			return -ENOTSUPP;
3816 	}
3817 	return 0;
3818 }
3819 
3820 /* the scalar precision tracking algorithm:
3821  * . at the start all registers have precise=false.
3822  * . scalar ranges are tracked as normal through alu and jmp insns.
3823  * . once precise value of the scalar register is used in:
3824  *   .  ptr + scalar alu
3825  *   . if (scalar cond K|scalar)
3826  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3827  *   backtrack through the verifier states and mark all registers and
3828  *   stack slots with spilled constants that these scalar regisers
3829  *   should be precise.
3830  * . during state pruning two registers (or spilled stack slots)
3831  *   are equivalent if both are not precise.
3832  *
3833  * Note the verifier cannot simply walk register parentage chain,
3834  * since many different registers and stack slots could have been
3835  * used to compute single precise scalar.
3836  *
3837  * The approach of starting with precise=true for all registers and then
3838  * backtrack to mark a register as not precise when the verifier detects
3839  * that program doesn't care about specific value (e.g., when helper
3840  * takes register as ARG_ANYTHING parameter) is not safe.
3841  *
3842  * It's ok to walk single parentage chain of the verifier states.
3843  * It's possible that this backtracking will go all the way till 1st insn.
3844  * All other branches will be explored for needing precision later.
3845  *
3846  * The backtracking needs to deal with cases like:
3847  *   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)
3848  * r9 -= r8
3849  * r5 = r9
3850  * if r5 > 0x79f goto pc+7
3851  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3852  * r5 += 1
3853  * ...
3854  * call bpf_perf_event_output#25
3855  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3856  *
3857  * and this case:
3858  * r6 = 1
3859  * call foo // uses callee's r6 inside to compute r0
3860  * r0 += r6
3861  * if r0 == 0 goto
3862  *
3863  * to track above reg_mask/stack_mask needs to be independent for each frame.
3864  *
3865  * Also if parent's curframe > frame where backtracking started,
3866  * the verifier need to mark registers in both frames, otherwise callees
3867  * may incorrectly prune callers. This is similar to
3868  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3869  *
3870  * For now backtracking falls back into conservative marking.
3871  */
3872 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3873 				     struct bpf_verifier_state *st)
3874 {
3875 	struct bpf_func_state *func;
3876 	struct bpf_reg_state *reg;
3877 	int i, j;
3878 
3879 	if (env->log.level & BPF_LOG_LEVEL2) {
3880 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3881 			st->curframe);
3882 	}
3883 
3884 	/* big hammer: mark all scalars precise in this path.
3885 	 * pop_stack may still get !precise scalars.
3886 	 * We also skip current state and go straight to first parent state,
3887 	 * because precision markings in current non-checkpointed state are
3888 	 * not needed. See why in the comment in __mark_chain_precision below.
3889 	 */
3890 	for (st = st->parent; st; st = st->parent) {
3891 		for (i = 0; i <= st->curframe; i++) {
3892 			func = st->frame[i];
3893 			for (j = 0; j < BPF_REG_FP; j++) {
3894 				reg = &func->regs[j];
3895 				if (reg->type != SCALAR_VALUE || reg->precise)
3896 					continue;
3897 				reg->precise = true;
3898 				if (env->log.level & BPF_LOG_LEVEL2) {
3899 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3900 						i, j);
3901 				}
3902 			}
3903 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3904 				if (!is_spilled_reg(&func->stack[j]))
3905 					continue;
3906 				reg = &func->stack[j].spilled_ptr;
3907 				if (reg->type != SCALAR_VALUE || reg->precise)
3908 					continue;
3909 				reg->precise = true;
3910 				if (env->log.level & BPF_LOG_LEVEL2) {
3911 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3912 						i, -(j + 1) * 8);
3913 				}
3914 			}
3915 		}
3916 	}
3917 }
3918 
3919 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3920 {
3921 	struct bpf_func_state *func;
3922 	struct bpf_reg_state *reg;
3923 	int i, j;
3924 
3925 	for (i = 0; i <= st->curframe; i++) {
3926 		func = st->frame[i];
3927 		for (j = 0; j < BPF_REG_FP; j++) {
3928 			reg = &func->regs[j];
3929 			if (reg->type != SCALAR_VALUE)
3930 				continue;
3931 			reg->precise = false;
3932 		}
3933 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3934 			if (!is_spilled_reg(&func->stack[j]))
3935 				continue;
3936 			reg = &func->stack[j].spilled_ptr;
3937 			if (reg->type != SCALAR_VALUE)
3938 				continue;
3939 			reg->precise = false;
3940 		}
3941 	}
3942 }
3943 
3944 static bool idset_contains(struct bpf_idset *s, u32 id)
3945 {
3946 	u32 i;
3947 
3948 	for (i = 0; i < s->count; ++i)
3949 		if (s->ids[i] == id)
3950 			return true;
3951 
3952 	return false;
3953 }
3954 
3955 static int idset_push(struct bpf_idset *s, u32 id)
3956 {
3957 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3958 		return -EFAULT;
3959 	s->ids[s->count++] = id;
3960 	return 0;
3961 }
3962 
3963 static void idset_reset(struct bpf_idset *s)
3964 {
3965 	s->count = 0;
3966 }
3967 
3968 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3969  * Mark all registers with these IDs as precise.
3970  */
3971 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3972 {
3973 	struct bpf_idset *precise_ids = &env->idset_scratch;
3974 	struct backtrack_state *bt = &env->bt;
3975 	struct bpf_func_state *func;
3976 	struct bpf_reg_state *reg;
3977 	DECLARE_BITMAP(mask, 64);
3978 	int i, fr;
3979 
3980 	idset_reset(precise_ids);
3981 
3982 	for (fr = bt->frame; fr >= 0; fr--) {
3983 		func = st->frame[fr];
3984 
3985 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3986 		for_each_set_bit(i, mask, 32) {
3987 			reg = &func->regs[i];
3988 			if (!reg->id || reg->type != SCALAR_VALUE)
3989 				continue;
3990 			if (idset_push(precise_ids, reg->id))
3991 				return -EFAULT;
3992 		}
3993 
3994 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3995 		for_each_set_bit(i, mask, 64) {
3996 			if (i >= func->allocated_stack / BPF_REG_SIZE)
3997 				break;
3998 			if (!is_spilled_scalar_reg(&func->stack[i]))
3999 				continue;
4000 			reg = &func->stack[i].spilled_ptr;
4001 			if (!reg->id)
4002 				continue;
4003 			if (idset_push(precise_ids, reg->id))
4004 				return -EFAULT;
4005 		}
4006 	}
4007 
4008 	for (fr = 0; fr <= st->curframe; ++fr) {
4009 		func = st->frame[fr];
4010 
4011 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4012 			reg = &func->regs[i];
4013 			if (!reg->id)
4014 				continue;
4015 			if (!idset_contains(precise_ids, reg->id))
4016 				continue;
4017 			bt_set_frame_reg(bt, fr, i);
4018 		}
4019 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4020 			if (!is_spilled_scalar_reg(&func->stack[i]))
4021 				continue;
4022 			reg = &func->stack[i].spilled_ptr;
4023 			if (!reg->id)
4024 				continue;
4025 			if (!idset_contains(precise_ids, reg->id))
4026 				continue;
4027 			bt_set_frame_slot(bt, fr, i);
4028 		}
4029 	}
4030 
4031 	return 0;
4032 }
4033 
4034 /*
4035  * __mark_chain_precision() backtracks BPF program instruction sequence and
4036  * chain of verifier states making sure that register *regno* (if regno >= 0)
4037  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4038  * SCALARS, as well as any other registers and slots that contribute to
4039  * a tracked state of given registers/stack slots, depending on specific BPF
4040  * assembly instructions (see backtrack_insns() for exact instruction handling
4041  * logic). This backtracking relies on recorded jmp_history and is able to
4042  * traverse entire chain of parent states. This process ends only when all the
4043  * necessary registers/slots and their transitive dependencies are marked as
4044  * precise.
4045  *
4046  * One important and subtle aspect is that precise marks *do not matter* in
4047  * the currently verified state (current state). It is important to understand
4048  * why this is the case.
4049  *
4050  * First, note that current state is the state that is not yet "checkpointed",
4051  * i.e., it is not yet put into env->explored_states, and it has no children
4052  * states as well. It's ephemeral, and can end up either a) being discarded if
4053  * compatible explored state is found at some point or BPF_EXIT instruction is
4054  * reached or b) checkpointed and put into env->explored_states, branching out
4055  * into one or more children states.
4056  *
4057  * In the former case, precise markings in current state are completely
4058  * ignored by state comparison code (see regsafe() for details). Only
4059  * checkpointed ("old") state precise markings are important, and if old
4060  * state's register/slot is precise, regsafe() assumes current state's
4061  * register/slot as precise and checks value ranges exactly and precisely. If
4062  * states turn out to be compatible, current state's necessary precise
4063  * markings and any required parent states' precise markings are enforced
4064  * after the fact with propagate_precision() logic, after the fact. But it's
4065  * important to realize that in this case, even after marking current state
4066  * registers/slots as precise, we immediately discard current state. So what
4067  * actually matters is any of the precise markings propagated into current
4068  * state's parent states, which are always checkpointed (due to b) case above).
4069  * As such, for scenario a) it doesn't matter if current state has precise
4070  * markings set or not.
4071  *
4072  * Now, for the scenario b), checkpointing and forking into child(ren)
4073  * state(s). Note that before current state gets to checkpointing step, any
4074  * processed instruction always assumes precise SCALAR register/slot
4075  * knowledge: if precise value or range is useful to prune jump branch, BPF
4076  * verifier takes this opportunity enthusiastically. Similarly, when
4077  * register's value is used to calculate offset or memory address, exact
4078  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4079  * what we mentioned above about state comparison ignoring precise markings
4080  * during state comparison, BPF verifier ignores and also assumes precise
4081  * markings *at will* during instruction verification process. But as verifier
4082  * assumes precision, it also propagates any precision dependencies across
4083  * parent states, which are not yet finalized, so can be further restricted
4084  * based on new knowledge gained from restrictions enforced by their children
4085  * states. This is so that once those parent states are finalized, i.e., when
4086  * they have no more active children state, state comparison logic in
4087  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4088  * required for correctness.
4089  *
4090  * To build a bit more intuition, note also that once a state is checkpointed,
4091  * the path we took to get to that state is not important. This is crucial
4092  * property for state pruning. When state is checkpointed and finalized at
4093  * some instruction index, it can be correctly and safely used to "short
4094  * circuit" any *compatible* state that reaches exactly the same instruction
4095  * index. I.e., if we jumped to that instruction from a completely different
4096  * code path than original finalized state was derived from, it doesn't
4097  * matter, current state can be discarded because from that instruction
4098  * forward having a compatible state will ensure we will safely reach the
4099  * exit. States describe preconditions for further exploration, but completely
4100  * forget the history of how we got here.
4101  *
4102  * This also means that even if we needed precise SCALAR range to get to
4103  * finalized state, but from that point forward *that same* SCALAR register is
4104  * never used in a precise context (i.e., it's precise value is not needed for
4105  * correctness), it's correct and safe to mark such register as "imprecise"
4106  * (i.e., precise marking set to false). This is what we rely on when we do
4107  * not set precise marking in current state. If no child state requires
4108  * precision for any given SCALAR register, it's safe to dictate that it can
4109  * be imprecise. If any child state does require this register to be precise,
4110  * we'll mark it precise later retroactively during precise markings
4111  * propagation from child state to parent states.
4112  *
4113  * Skipping precise marking setting in current state is a mild version of
4114  * relying on the above observation. But we can utilize this property even
4115  * more aggressively by proactively forgetting any precise marking in the
4116  * current state (which we inherited from the parent state), right before we
4117  * checkpoint it and branch off into new child state. This is done by
4118  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4119  * finalized states which help in short circuiting more future states.
4120  */
4121 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4122 {
4123 	struct backtrack_state *bt = &env->bt;
4124 	struct bpf_verifier_state *st = env->cur_state;
4125 	int first_idx = st->first_insn_idx;
4126 	int last_idx = env->insn_idx;
4127 	int subseq_idx = -1;
4128 	struct bpf_func_state *func;
4129 	struct bpf_reg_state *reg;
4130 	bool skip_first = true;
4131 	int i, fr, err;
4132 
4133 	if (!env->bpf_capable)
4134 		return 0;
4135 
4136 	/* set frame number from which we are starting to backtrack */
4137 	bt_init(bt, env->cur_state->curframe);
4138 
4139 	/* Do sanity checks against current state of register and/or stack
4140 	 * slot, but don't set precise flag in current state, as precision
4141 	 * tracking in the current state is unnecessary.
4142 	 */
4143 	func = st->frame[bt->frame];
4144 	if (regno >= 0) {
4145 		reg = &func->regs[regno];
4146 		if (reg->type != SCALAR_VALUE) {
4147 			WARN_ONCE(1, "backtracing misuse");
4148 			return -EFAULT;
4149 		}
4150 		bt_set_reg(bt, regno);
4151 	}
4152 
4153 	if (bt_empty(bt))
4154 		return 0;
4155 
4156 	for (;;) {
4157 		DECLARE_BITMAP(mask, 64);
4158 		u32 history = st->jmp_history_cnt;
4159 		struct bpf_jmp_history_entry *hist;
4160 
4161 		if (env->log.level & BPF_LOG_LEVEL2) {
4162 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4163 				bt->frame, last_idx, first_idx, subseq_idx);
4164 		}
4165 
4166 		/* If some register with scalar ID is marked as precise,
4167 		 * make sure that all registers sharing this ID are also precise.
4168 		 * This is needed to estimate effect of find_equal_scalars().
4169 		 * Do this at the last instruction of each state,
4170 		 * bpf_reg_state::id fields are valid for these instructions.
4171 		 *
4172 		 * Allows to track precision in situation like below:
4173 		 *
4174 		 *     r2 = unknown value
4175 		 *     ...
4176 		 *   --- state #0 ---
4177 		 *     ...
4178 		 *     r1 = r2                 // r1 and r2 now share the same ID
4179 		 *     ...
4180 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4181 		 *     ...
4182 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4183 		 *     ...
4184 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4185 		 *     r3 = r10
4186 		 *     r3 += r1                // need to mark both r1 and r2
4187 		 */
4188 		if (mark_precise_scalar_ids(env, st))
4189 			return -EFAULT;
4190 
4191 		if (last_idx < 0) {
4192 			/* we are at the entry into subprog, which
4193 			 * is expected for global funcs, but only if
4194 			 * requested precise registers are R1-R5
4195 			 * (which are global func's input arguments)
4196 			 */
4197 			if (st->curframe == 0 &&
4198 			    st->frame[0]->subprogno > 0 &&
4199 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4200 			    bt_stack_mask(bt) == 0 &&
4201 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4202 				bitmap_from_u64(mask, bt_reg_mask(bt));
4203 				for_each_set_bit(i, mask, 32) {
4204 					reg = &st->frame[0]->regs[i];
4205 					bt_clear_reg(bt, i);
4206 					if (reg->type == SCALAR_VALUE)
4207 						reg->precise = true;
4208 				}
4209 				return 0;
4210 			}
4211 
4212 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4213 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4214 			WARN_ONCE(1, "verifier backtracking bug");
4215 			return -EFAULT;
4216 		}
4217 
4218 		for (i = last_idx;;) {
4219 			if (skip_first) {
4220 				err = 0;
4221 				skip_first = false;
4222 			} else {
4223 				hist = get_jmp_hist_entry(st, history, i);
4224 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4225 			}
4226 			if (err == -ENOTSUPP) {
4227 				mark_all_scalars_precise(env, env->cur_state);
4228 				bt_reset(bt);
4229 				return 0;
4230 			} else if (err) {
4231 				return err;
4232 			}
4233 			if (bt_empty(bt))
4234 				/* Found assignment(s) into tracked register in this state.
4235 				 * Since this state is already marked, just return.
4236 				 * Nothing to be tracked further in the parent state.
4237 				 */
4238 				return 0;
4239 			subseq_idx = i;
4240 			i = get_prev_insn_idx(st, i, &history);
4241 			if (i == -ENOENT)
4242 				break;
4243 			if (i >= env->prog->len) {
4244 				/* This can happen if backtracking reached insn 0
4245 				 * and there are still reg_mask or stack_mask
4246 				 * to backtrack.
4247 				 * It means the backtracking missed the spot where
4248 				 * particular register was initialized with a constant.
4249 				 */
4250 				verbose(env, "BUG backtracking idx %d\n", i);
4251 				WARN_ONCE(1, "verifier backtracking bug");
4252 				return -EFAULT;
4253 			}
4254 		}
4255 		st = st->parent;
4256 		if (!st)
4257 			break;
4258 
4259 		for (fr = bt->frame; fr >= 0; fr--) {
4260 			func = st->frame[fr];
4261 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4262 			for_each_set_bit(i, mask, 32) {
4263 				reg = &func->regs[i];
4264 				if (reg->type != SCALAR_VALUE) {
4265 					bt_clear_frame_reg(bt, fr, i);
4266 					continue;
4267 				}
4268 				if (reg->precise)
4269 					bt_clear_frame_reg(bt, fr, i);
4270 				else
4271 					reg->precise = true;
4272 			}
4273 
4274 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4275 			for_each_set_bit(i, mask, 64) {
4276 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4277 					verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n",
4278 						i, func->allocated_stack / BPF_REG_SIZE);
4279 					WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)");
4280 					return -EFAULT;
4281 				}
4282 
4283 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4284 					bt_clear_frame_slot(bt, fr, i);
4285 					continue;
4286 				}
4287 				reg = &func->stack[i].spilled_ptr;
4288 				if (reg->precise)
4289 					bt_clear_frame_slot(bt, fr, i);
4290 				else
4291 					reg->precise = true;
4292 			}
4293 			if (env->log.level & BPF_LOG_LEVEL2) {
4294 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4295 					     bt_frame_reg_mask(bt, fr));
4296 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4297 					fr, env->tmp_str_buf);
4298 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4299 					       bt_frame_stack_mask(bt, fr));
4300 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4301 				print_verifier_state(env, func, true);
4302 			}
4303 		}
4304 
4305 		if (bt_empty(bt))
4306 			return 0;
4307 
4308 		subseq_idx = first_idx;
4309 		last_idx = st->last_insn_idx;
4310 		first_idx = st->first_insn_idx;
4311 	}
4312 
4313 	/* if we still have requested precise regs or slots, we missed
4314 	 * something (e.g., stack access through non-r10 register), so
4315 	 * fallback to marking all precise
4316 	 */
4317 	if (!bt_empty(bt)) {
4318 		mark_all_scalars_precise(env, env->cur_state);
4319 		bt_reset(bt);
4320 	}
4321 
4322 	return 0;
4323 }
4324 
4325 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4326 {
4327 	return __mark_chain_precision(env, regno);
4328 }
4329 
4330 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4331  * desired reg and stack masks across all relevant frames
4332  */
4333 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4334 {
4335 	return __mark_chain_precision(env, -1);
4336 }
4337 
4338 static bool is_spillable_regtype(enum bpf_reg_type type)
4339 {
4340 	switch (base_type(type)) {
4341 	case PTR_TO_MAP_VALUE:
4342 	case PTR_TO_STACK:
4343 	case PTR_TO_CTX:
4344 	case PTR_TO_PACKET:
4345 	case PTR_TO_PACKET_META:
4346 	case PTR_TO_PACKET_END:
4347 	case PTR_TO_FLOW_KEYS:
4348 	case CONST_PTR_TO_MAP:
4349 	case PTR_TO_SOCKET:
4350 	case PTR_TO_SOCK_COMMON:
4351 	case PTR_TO_TCP_SOCK:
4352 	case PTR_TO_XDP_SOCK:
4353 	case PTR_TO_BTF_ID:
4354 	case PTR_TO_BUF:
4355 	case PTR_TO_MEM:
4356 	case PTR_TO_FUNC:
4357 	case PTR_TO_MAP_KEY:
4358 		return true;
4359 	default:
4360 		return false;
4361 	}
4362 }
4363 
4364 /* Does this register contain a constant zero? */
4365 static bool register_is_null(struct bpf_reg_state *reg)
4366 {
4367 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4368 }
4369 
4370 /* check if register is a constant scalar value */
4371 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4372 {
4373 	return reg->type == SCALAR_VALUE &&
4374 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4375 }
4376 
4377 /* assuming is_reg_const() is true, return constant value of a register */
4378 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4379 {
4380 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4381 }
4382 
4383 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4384 {
4385 	return tnum_is_unknown(reg->var_off) &&
4386 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4387 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4388 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4389 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4390 }
4391 
4392 static bool register_is_bounded(struct bpf_reg_state *reg)
4393 {
4394 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4395 }
4396 
4397 static bool __is_pointer_value(bool allow_ptr_leaks,
4398 			       const struct bpf_reg_state *reg)
4399 {
4400 	if (allow_ptr_leaks)
4401 		return false;
4402 
4403 	return reg->type != SCALAR_VALUE;
4404 }
4405 
4406 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4407 					struct bpf_reg_state *src_reg)
4408 {
4409 	if (src_reg->type == SCALAR_VALUE && !src_reg->id &&
4410 	    !tnum_is_const(src_reg->var_off))
4411 		/* Ensure that src_reg has a valid ID that will be copied to
4412 		 * dst_reg and then will be used by find_equal_scalars() to
4413 		 * propagate min/max range.
4414 		 */
4415 		src_reg->id = ++env->id_gen;
4416 }
4417 
4418 /* Copy src state preserving dst->parent and dst->live fields */
4419 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4420 {
4421 	struct bpf_reg_state *parent = dst->parent;
4422 	enum bpf_reg_liveness live = dst->live;
4423 
4424 	*dst = *src;
4425 	dst->parent = parent;
4426 	dst->live = live;
4427 }
4428 
4429 static void save_register_state(struct bpf_verifier_env *env,
4430 				struct bpf_func_state *state,
4431 				int spi, struct bpf_reg_state *reg,
4432 				int size)
4433 {
4434 	int i;
4435 
4436 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4437 	if (size == BPF_REG_SIZE)
4438 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4439 
4440 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4441 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4442 
4443 	/* size < 8 bytes spill */
4444 	for (; i; i--)
4445 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4446 }
4447 
4448 static bool is_bpf_st_mem(struct bpf_insn *insn)
4449 {
4450 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4451 }
4452 
4453 static int get_reg_width(struct bpf_reg_state *reg)
4454 {
4455 	return fls64(reg->umax_value);
4456 }
4457 
4458 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4459  * stack boundary and alignment are checked in check_mem_access()
4460  */
4461 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4462 				       /* stack frame we're writing to */
4463 				       struct bpf_func_state *state,
4464 				       int off, int size, int value_regno,
4465 				       int insn_idx)
4466 {
4467 	struct bpf_func_state *cur; /* state of the current function */
4468 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4469 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4470 	struct bpf_reg_state *reg = NULL;
4471 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
4472 
4473 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4474 	 * so it's aligned access and [off, off + size) are within stack limits
4475 	 */
4476 	if (!env->allow_ptr_leaks &&
4477 	    is_spilled_reg(&state->stack[spi]) &&
4478 	    size != BPF_REG_SIZE) {
4479 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4480 		return -EACCES;
4481 	}
4482 
4483 	cur = env->cur_state->frame[env->cur_state->curframe];
4484 	if (value_regno >= 0)
4485 		reg = &cur->regs[value_regno];
4486 	if (!env->bypass_spec_v4) {
4487 		bool sanitize = reg && is_spillable_regtype(reg->type);
4488 
4489 		for (i = 0; i < size; i++) {
4490 			u8 type = state->stack[spi].slot_type[i];
4491 
4492 			if (type != STACK_MISC && type != STACK_ZERO) {
4493 				sanitize = true;
4494 				break;
4495 			}
4496 		}
4497 
4498 		if (sanitize)
4499 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4500 	}
4501 
4502 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4503 	if (err)
4504 		return err;
4505 
4506 	mark_stack_slot_scratched(env, spi);
4507 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && env->bpf_capable) {
4508 		bool reg_value_fits;
4509 
4510 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
4511 		/* Make sure that reg had an ID to build a relation on spill. */
4512 		if (reg_value_fits)
4513 			assign_scalar_id_before_mov(env, reg);
4514 		save_register_state(env, state, spi, reg, size);
4515 		/* Break the relation on a narrowing spill. */
4516 		if (!reg_value_fits)
4517 			state->stack[spi].spilled_ptr.id = 0;
4518 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4519 		   env->bpf_capable) {
4520 		struct bpf_reg_state fake_reg = {};
4521 
4522 		__mark_reg_known(&fake_reg, insn->imm);
4523 		fake_reg.type = SCALAR_VALUE;
4524 		save_register_state(env, state, spi, &fake_reg, size);
4525 	} else if (reg && is_spillable_regtype(reg->type)) {
4526 		/* register containing pointer is being spilled into stack */
4527 		if (size != BPF_REG_SIZE) {
4528 			verbose_linfo(env, insn_idx, "; ");
4529 			verbose(env, "invalid size of register spill\n");
4530 			return -EACCES;
4531 		}
4532 		if (state != cur && reg->type == PTR_TO_STACK) {
4533 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4534 			return -EINVAL;
4535 		}
4536 		save_register_state(env, state, spi, reg, size);
4537 	} else {
4538 		u8 type = STACK_MISC;
4539 
4540 		/* regular write of data into stack destroys any spilled ptr */
4541 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4542 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4543 		if (is_stack_slot_special(&state->stack[spi]))
4544 			for (i = 0; i < BPF_REG_SIZE; i++)
4545 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4546 
4547 		/* only mark the slot as written if all 8 bytes were written
4548 		 * otherwise read propagation may incorrectly stop too soon
4549 		 * when stack slots are partially written.
4550 		 * This heuristic means that read propagation will be
4551 		 * conservative, since it will add reg_live_read marks
4552 		 * to stack slots all the way to first state when programs
4553 		 * writes+reads less than 8 bytes
4554 		 */
4555 		if (size == BPF_REG_SIZE)
4556 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4557 
4558 		/* when we zero initialize stack slots mark them as such */
4559 		if ((reg && register_is_null(reg)) ||
4560 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4561 			/* STACK_ZERO case happened because register spill
4562 			 * wasn't properly aligned at the stack slot boundary,
4563 			 * so it's not a register spill anymore; force
4564 			 * originating register to be precise to make
4565 			 * STACK_ZERO correct for subsequent states
4566 			 */
4567 			err = mark_chain_precision(env, value_regno);
4568 			if (err)
4569 				return err;
4570 			type = STACK_ZERO;
4571 		}
4572 
4573 		/* Mark slots affected by this stack write. */
4574 		for (i = 0; i < size; i++)
4575 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
4576 		insn_flags = 0; /* not a register spill */
4577 	}
4578 
4579 	if (insn_flags)
4580 		return push_jmp_history(env, env->cur_state, insn_flags);
4581 	return 0;
4582 }
4583 
4584 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4585  * known to contain a variable offset.
4586  * This function checks whether the write is permitted and conservatively
4587  * tracks the effects of the write, considering that each stack slot in the
4588  * dynamic range is potentially written to.
4589  *
4590  * 'off' includes 'regno->off'.
4591  * 'value_regno' can be -1, meaning that an unknown value is being written to
4592  * the stack.
4593  *
4594  * Spilled pointers in range are not marked as written because we don't know
4595  * what's going to be actually written. This means that read propagation for
4596  * future reads cannot be terminated by this write.
4597  *
4598  * For privileged programs, uninitialized stack slots are considered
4599  * initialized by this write (even though we don't know exactly what offsets
4600  * are going to be written to). The idea is that we don't want the verifier to
4601  * reject future reads that access slots written to through variable offsets.
4602  */
4603 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4604 				     /* func where register points to */
4605 				     struct bpf_func_state *state,
4606 				     int ptr_regno, int off, int size,
4607 				     int value_regno, int insn_idx)
4608 {
4609 	struct bpf_func_state *cur; /* state of the current function */
4610 	int min_off, max_off;
4611 	int i, err;
4612 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4613 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4614 	bool writing_zero = false;
4615 	/* set if the fact that we're writing a zero is used to let any
4616 	 * stack slots remain STACK_ZERO
4617 	 */
4618 	bool zero_used = false;
4619 
4620 	cur = env->cur_state->frame[env->cur_state->curframe];
4621 	ptr_reg = &cur->regs[ptr_regno];
4622 	min_off = ptr_reg->smin_value + off;
4623 	max_off = ptr_reg->smax_value + off + size;
4624 	if (value_regno >= 0)
4625 		value_reg = &cur->regs[value_regno];
4626 	if ((value_reg && register_is_null(value_reg)) ||
4627 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4628 		writing_zero = true;
4629 
4630 	for (i = min_off; i < max_off; i++) {
4631 		int spi;
4632 
4633 		spi = __get_spi(i);
4634 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4635 		if (err)
4636 			return err;
4637 	}
4638 
4639 	/* Variable offset writes destroy any spilled pointers in range. */
4640 	for (i = min_off; i < max_off; i++) {
4641 		u8 new_type, *stype;
4642 		int slot, spi;
4643 
4644 		slot = -i - 1;
4645 		spi = slot / BPF_REG_SIZE;
4646 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4647 		mark_stack_slot_scratched(env, spi);
4648 
4649 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4650 			/* Reject the write if range we may write to has not
4651 			 * been initialized beforehand. If we didn't reject
4652 			 * here, the ptr status would be erased below (even
4653 			 * though not all slots are actually overwritten),
4654 			 * possibly opening the door to leaks.
4655 			 *
4656 			 * We do however catch STACK_INVALID case below, and
4657 			 * only allow reading possibly uninitialized memory
4658 			 * later for CAP_PERFMON, as the write may not happen to
4659 			 * that slot.
4660 			 */
4661 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4662 				insn_idx, i);
4663 			return -EINVAL;
4664 		}
4665 
4666 		/* If writing_zero and the spi slot contains a spill of value 0,
4667 		 * maintain the spill type.
4668 		 */
4669 		if (writing_zero && *stype == STACK_SPILL &&
4670 		    is_spilled_scalar_reg(&state->stack[spi])) {
4671 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
4672 
4673 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
4674 				zero_used = true;
4675 				continue;
4676 			}
4677 		}
4678 
4679 		/* Erase all other spilled pointers. */
4680 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4681 
4682 		/* Update the slot type. */
4683 		new_type = STACK_MISC;
4684 		if (writing_zero && *stype == STACK_ZERO) {
4685 			new_type = STACK_ZERO;
4686 			zero_used = true;
4687 		}
4688 		/* If the slot is STACK_INVALID, we check whether it's OK to
4689 		 * pretend that it will be initialized by this write. The slot
4690 		 * might not actually be written to, and so if we mark it as
4691 		 * initialized future reads might leak uninitialized memory.
4692 		 * For privileged programs, we will accept such reads to slots
4693 		 * that may or may not be written because, if we're reject
4694 		 * them, the error would be too confusing.
4695 		 */
4696 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4697 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4698 					insn_idx, i);
4699 			return -EINVAL;
4700 		}
4701 		*stype = new_type;
4702 	}
4703 	if (zero_used) {
4704 		/* backtracking doesn't work for STACK_ZERO yet. */
4705 		err = mark_chain_precision(env, value_regno);
4706 		if (err)
4707 			return err;
4708 	}
4709 	return 0;
4710 }
4711 
4712 /* When register 'dst_regno' is assigned some values from stack[min_off,
4713  * max_off), we set the register's type according to the types of the
4714  * respective stack slots. If all the stack values are known to be zeros, then
4715  * so is the destination reg. Otherwise, the register is considered to be
4716  * SCALAR. This function does not deal with register filling; the caller must
4717  * ensure that all spilled registers in the stack range have been marked as
4718  * read.
4719  */
4720 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4721 				/* func where src register points to */
4722 				struct bpf_func_state *ptr_state,
4723 				int min_off, int max_off, int dst_regno)
4724 {
4725 	struct bpf_verifier_state *vstate = env->cur_state;
4726 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4727 	int i, slot, spi;
4728 	u8 *stype;
4729 	int zeros = 0;
4730 
4731 	for (i = min_off; i < max_off; i++) {
4732 		slot = -i - 1;
4733 		spi = slot / BPF_REG_SIZE;
4734 		mark_stack_slot_scratched(env, spi);
4735 		stype = ptr_state->stack[spi].slot_type;
4736 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4737 			break;
4738 		zeros++;
4739 	}
4740 	if (zeros == max_off - min_off) {
4741 		/* Any access_size read into register is zero extended,
4742 		 * so the whole register == const_zero.
4743 		 */
4744 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
4745 	} else {
4746 		/* have read misc data from the stack */
4747 		mark_reg_unknown(env, state->regs, dst_regno);
4748 	}
4749 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4750 }
4751 
4752 /* Read the stack at 'off' and put the results into the register indicated by
4753  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4754  * spilled reg.
4755  *
4756  * 'dst_regno' can be -1, meaning that the read value is not going to a
4757  * register.
4758  *
4759  * The access is assumed to be within the current stack bounds.
4760  */
4761 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4762 				      /* func where src register points to */
4763 				      struct bpf_func_state *reg_state,
4764 				      int off, int size, int dst_regno)
4765 {
4766 	struct bpf_verifier_state *vstate = env->cur_state;
4767 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4768 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4769 	struct bpf_reg_state *reg;
4770 	u8 *stype, type;
4771 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
4772 
4773 	stype = reg_state->stack[spi].slot_type;
4774 	reg = &reg_state->stack[spi].spilled_ptr;
4775 
4776 	mark_stack_slot_scratched(env, spi);
4777 
4778 	if (is_spilled_reg(&reg_state->stack[spi])) {
4779 		u8 spill_size = 1;
4780 
4781 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4782 			spill_size++;
4783 
4784 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4785 			if (reg->type != SCALAR_VALUE) {
4786 				verbose_linfo(env, env->insn_idx, "; ");
4787 				verbose(env, "invalid size of register fill\n");
4788 				return -EACCES;
4789 			}
4790 
4791 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4792 			if (dst_regno < 0)
4793 				return 0;
4794 
4795 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4796 				/* The earlier check_reg_arg() has decided the
4797 				 * subreg_def for this insn.  Save it first.
4798 				 */
4799 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4800 
4801 				copy_register_state(&state->regs[dst_regno], reg);
4802 				state->regs[dst_regno].subreg_def = subreg_def;
4803 			} else {
4804 				int spill_cnt = 0, zero_cnt = 0;
4805 
4806 				for (i = 0; i < size; i++) {
4807 					type = stype[(slot - i) % BPF_REG_SIZE];
4808 					if (type == STACK_SPILL) {
4809 						spill_cnt++;
4810 						continue;
4811 					}
4812 					if (type == STACK_MISC)
4813 						continue;
4814 					if (type == STACK_ZERO) {
4815 						zero_cnt++;
4816 						continue;
4817 					}
4818 					if (type == STACK_INVALID && env->allow_uninit_stack)
4819 						continue;
4820 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4821 						off, i, size);
4822 					return -EACCES;
4823 				}
4824 
4825 				if (spill_cnt == size &&
4826 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
4827 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4828 					/* this IS register fill, so keep insn_flags */
4829 				} else if (zero_cnt == size) {
4830 					/* similarly to mark_reg_stack_read(), preserve zeroes */
4831 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4832 					insn_flags = 0; /* not restoring original register state */
4833 				} else {
4834 					mark_reg_unknown(env, state->regs, dst_regno);
4835 					insn_flags = 0; /* not restoring original register state */
4836 				}
4837 			}
4838 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4839 		} else if (dst_regno >= 0) {
4840 			/* restore register state from stack */
4841 			copy_register_state(&state->regs[dst_regno], reg);
4842 			/* mark reg as written since spilled pointer state likely
4843 			 * has its liveness marks cleared by is_state_visited()
4844 			 * which resets stack/reg liveness for state transitions
4845 			 */
4846 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4847 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4848 			/* If dst_regno==-1, the caller is asking us whether
4849 			 * it is acceptable to use this value as a SCALAR_VALUE
4850 			 * (e.g. for XADD).
4851 			 * We must not allow unprivileged callers to do that
4852 			 * with spilled pointers.
4853 			 */
4854 			verbose(env, "leaking pointer from stack off %d\n",
4855 				off);
4856 			return -EACCES;
4857 		}
4858 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4859 	} else {
4860 		for (i = 0; i < size; i++) {
4861 			type = stype[(slot - i) % BPF_REG_SIZE];
4862 			if (type == STACK_MISC)
4863 				continue;
4864 			if (type == STACK_ZERO)
4865 				continue;
4866 			if (type == STACK_INVALID && env->allow_uninit_stack)
4867 				continue;
4868 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4869 				off, i, size);
4870 			return -EACCES;
4871 		}
4872 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4873 		if (dst_regno >= 0)
4874 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4875 		insn_flags = 0; /* we are not restoring spilled register */
4876 	}
4877 	if (insn_flags)
4878 		return push_jmp_history(env, env->cur_state, insn_flags);
4879 	return 0;
4880 }
4881 
4882 enum bpf_access_src {
4883 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4884 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4885 };
4886 
4887 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4888 					 int regno, int off, int access_size,
4889 					 bool zero_size_allowed,
4890 					 enum bpf_access_src type,
4891 					 struct bpf_call_arg_meta *meta);
4892 
4893 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4894 {
4895 	return cur_regs(env) + regno;
4896 }
4897 
4898 /* Read the stack at 'ptr_regno + off' and put the result into the register
4899  * 'dst_regno'.
4900  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4901  * but not its variable offset.
4902  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4903  *
4904  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4905  * filling registers (i.e. reads of spilled register cannot be detected when
4906  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4907  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4908  * offset; for a fixed offset check_stack_read_fixed_off should be used
4909  * instead.
4910  */
4911 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4912 				    int ptr_regno, int off, int size, int dst_regno)
4913 {
4914 	/* The state of the source register. */
4915 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4916 	struct bpf_func_state *ptr_state = func(env, reg);
4917 	int err;
4918 	int min_off, max_off;
4919 
4920 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4921 	 */
4922 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4923 					    false, ACCESS_DIRECT, NULL);
4924 	if (err)
4925 		return err;
4926 
4927 	min_off = reg->smin_value + off;
4928 	max_off = reg->smax_value + off;
4929 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4930 	return 0;
4931 }
4932 
4933 /* check_stack_read dispatches to check_stack_read_fixed_off or
4934  * check_stack_read_var_off.
4935  *
4936  * The caller must ensure that the offset falls within the allocated stack
4937  * bounds.
4938  *
4939  * 'dst_regno' is a register which will receive the value from the stack. It
4940  * can be -1, meaning that the read value is not going to a register.
4941  */
4942 static int check_stack_read(struct bpf_verifier_env *env,
4943 			    int ptr_regno, int off, int size,
4944 			    int dst_regno)
4945 {
4946 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4947 	struct bpf_func_state *state = func(env, reg);
4948 	int err;
4949 	/* Some accesses are only permitted with a static offset. */
4950 	bool var_off = !tnum_is_const(reg->var_off);
4951 
4952 	/* The offset is required to be static when reads don't go to a
4953 	 * register, in order to not leak pointers (see
4954 	 * check_stack_read_fixed_off).
4955 	 */
4956 	if (dst_regno < 0 && var_off) {
4957 		char tn_buf[48];
4958 
4959 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4960 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4961 			tn_buf, off, size);
4962 		return -EACCES;
4963 	}
4964 	/* Variable offset is prohibited for unprivileged mode for simplicity
4965 	 * since it requires corresponding support in Spectre masking for stack
4966 	 * ALU. See also retrieve_ptr_limit(). The check in
4967 	 * check_stack_access_for_ptr_arithmetic() called by
4968 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4969 	 * with variable offsets, therefore no check is required here. Further,
4970 	 * just checking it here would be insufficient as speculative stack
4971 	 * writes could still lead to unsafe speculative behaviour.
4972 	 */
4973 	if (!var_off) {
4974 		off += reg->var_off.value;
4975 		err = check_stack_read_fixed_off(env, state, off, size,
4976 						 dst_regno);
4977 	} else {
4978 		/* Variable offset stack reads need more conservative handling
4979 		 * than fixed offset ones. Note that dst_regno >= 0 on this
4980 		 * branch.
4981 		 */
4982 		err = check_stack_read_var_off(env, ptr_regno, off, size,
4983 					       dst_regno);
4984 	}
4985 	return err;
4986 }
4987 
4988 
4989 /* check_stack_write dispatches to check_stack_write_fixed_off or
4990  * check_stack_write_var_off.
4991  *
4992  * 'ptr_regno' is the register used as a pointer into the stack.
4993  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4994  * 'value_regno' is the register whose value we're writing to the stack. It can
4995  * be -1, meaning that we're not writing from a register.
4996  *
4997  * The caller must ensure that the offset falls within the maximum stack size.
4998  */
4999 static int check_stack_write(struct bpf_verifier_env *env,
5000 			     int ptr_regno, int off, int size,
5001 			     int value_regno, int insn_idx)
5002 {
5003 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5004 	struct bpf_func_state *state = func(env, reg);
5005 	int err;
5006 
5007 	if (tnum_is_const(reg->var_off)) {
5008 		off += reg->var_off.value;
5009 		err = check_stack_write_fixed_off(env, state, off, size,
5010 						  value_regno, insn_idx);
5011 	} else {
5012 		/* Variable offset stack reads need more conservative handling
5013 		 * than fixed offset ones.
5014 		 */
5015 		err = check_stack_write_var_off(env, state,
5016 						ptr_regno, off, size,
5017 						value_regno, insn_idx);
5018 	}
5019 	return err;
5020 }
5021 
5022 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5023 				 int off, int size, enum bpf_access_type type)
5024 {
5025 	struct bpf_reg_state *regs = cur_regs(env);
5026 	struct bpf_map *map = regs[regno].map_ptr;
5027 	u32 cap = bpf_map_flags_to_cap(map);
5028 
5029 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5030 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5031 			map->value_size, off, size);
5032 		return -EACCES;
5033 	}
5034 
5035 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5036 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5037 			map->value_size, off, size);
5038 		return -EACCES;
5039 	}
5040 
5041 	return 0;
5042 }
5043 
5044 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5045 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5046 			      int off, int size, u32 mem_size,
5047 			      bool zero_size_allowed)
5048 {
5049 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5050 	struct bpf_reg_state *reg;
5051 
5052 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5053 		return 0;
5054 
5055 	reg = &cur_regs(env)[regno];
5056 	switch (reg->type) {
5057 	case PTR_TO_MAP_KEY:
5058 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5059 			mem_size, off, size);
5060 		break;
5061 	case PTR_TO_MAP_VALUE:
5062 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5063 			mem_size, off, size);
5064 		break;
5065 	case PTR_TO_PACKET:
5066 	case PTR_TO_PACKET_META:
5067 	case PTR_TO_PACKET_END:
5068 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5069 			off, size, regno, reg->id, off, mem_size);
5070 		break;
5071 	case PTR_TO_MEM:
5072 	default:
5073 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5074 			mem_size, off, size);
5075 	}
5076 
5077 	return -EACCES;
5078 }
5079 
5080 /* check read/write into a memory region with possible variable offset */
5081 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5082 				   int off, int size, u32 mem_size,
5083 				   bool zero_size_allowed)
5084 {
5085 	struct bpf_verifier_state *vstate = env->cur_state;
5086 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5087 	struct bpf_reg_state *reg = &state->regs[regno];
5088 	int err;
5089 
5090 	/* We may have adjusted the register pointing to memory region, so we
5091 	 * need to try adding each of min_value and max_value to off
5092 	 * to make sure our theoretical access will be safe.
5093 	 *
5094 	 * The minimum value is only important with signed
5095 	 * comparisons where we can't assume the floor of a
5096 	 * value is 0.  If we are using signed variables for our
5097 	 * index'es we need to make sure that whatever we use
5098 	 * will have a set floor within our range.
5099 	 */
5100 	if (reg->smin_value < 0 &&
5101 	    (reg->smin_value == S64_MIN ||
5102 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5103 	      reg->smin_value + off < 0)) {
5104 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5105 			regno);
5106 		return -EACCES;
5107 	}
5108 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5109 				 mem_size, zero_size_allowed);
5110 	if (err) {
5111 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5112 			regno);
5113 		return err;
5114 	}
5115 
5116 	/* If we haven't set a max value then we need to bail since we can't be
5117 	 * sure we won't do bad things.
5118 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5119 	 */
5120 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5121 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5122 			regno);
5123 		return -EACCES;
5124 	}
5125 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5126 				 mem_size, zero_size_allowed);
5127 	if (err) {
5128 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5129 			regno);
5130 		return err;
5131 	}
5132 
5133 	return 0;
5134 }
5135 
5136 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5137 			       const struct bpf_reg_state *reg, int regno,
5138 			       bool fixed_off_ok)
5139 {
5140 	/* Access to this pointer-typed register or passing it to a helper
5141 	 * is only allowed in its original, unmodified form.
5142 	 */
5143 
5144 	if (reg->off < 0) {
5145 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5146 			reg_type_str(env, reg->type), regno, reg->off);
5147 		return -EACCES;
5148 	}
5149 
5150 	if (!fixed_off_ok && reg->off) {
5151 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5152 			reg_type_str(env, reg->type), regno, reg->off);
5153 		return -EACCES;
5154 	}
5155 
5156 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5157 		char tn_buf[48];
5158 
5159 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5160 		verbose(env, "variable %s access var_off=%s disallowed\n",
5161 			reg_type_str(env, reg->type), tn_buf);
5162 		return -EACCES;
5163 	}
5164 
5165 	return 0;
5166 }
5167 
5168 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5169 		             const struct bpf_reg_state *reg, int regno)
5170 {
5171 	return __check_ptr_off_reg(env, reg, regno, false);
5172 }
5173 
5174 static int map_kptr_match_type(struct bpf_verifier_env *env,
5175 			       struct btf_field *kptr_field,
5176 			       struct bpf_reg_state *reg, u32 regno)
5177 {
5178 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5179 	int perm_flags;
5180 	const char *reg_name = "";
5181 
5182 	if (btf_is_kernel(reg->btf)) {
5183 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5184 
5185 		/* Only unreferenced case accepts untrusted pointers */
5186 		if (kptr_field->type == BPF_KPTR_UNREF)
5187 			perm_flags |= PTR_UNTRUSTED;
5188 	} else {
5189 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5190 		if (kptr_field->type == BPF_KPTR_PERCPU)
5191 			perm_flags |= MEM_PERCPU;
5192 	}
5193 
5194 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5195 		goto bad_type;
5196 
5197 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5198 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5199 
5200 	/* For ref_ptr case, release function check should ensure we get one
5201 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5202 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5203 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5204 	 * reg->off and reg->ref_obj_id are not needed here.
5205 	 */
5206 	if (__check_ptr_off_reg(env, reg, regno, true))
5207 		return -EACCES;
5208 
5209 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5210 	 * we also need to take into account the reg->off.
5211 	 *
5212 	 * We want to support cases like:
5213 	 *
5214 	 * struct foo {
5215 	 *         struct bar br;
5216 	 *         struct baz bz;
5217 	 * };
5218 	 *
5219 	 * struct foo *v;
5220 	 * v = func();	      // PTR_TO_BTF_ID
5221 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5222 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5223 	 *                    // first member type of struct after comparison fails
5224 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5225 	 *                    // to match type
5226 	 *
5227 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5228 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5229 	 * the struct to match type against first member of struct, i.e. reject
5230 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5231 	 * strict mode to true for type match.
5232 	 */
5233 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5234 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5235 				  kptr_field->type != BPF_KPTR_UNREF))
5236 		goto bad_type;
5237 	return 0;
5238 bad_type:
5239 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5240 		reg_type_str(env, reg->type), reg_name);
5241 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5242 	if (kptr_field->type == BPF_KPTR_UNREF)
5243 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5244 			targ_name);
5245 	else
5246 		verbose(env, "\n");
5247 	return -EINVAL;
5248 }
5249 
5250 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5251  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5252  */
5253 static bool in_rcu_cs(struct bpf_verifier_env *env)
5254 {
5255 	return env->cur_state->active_rcu_lock ||
5256 	       env->cur_state->active_lock.ptr ||
5257 	       !env->prog->aux->sleepable;
5258 }
5259 
5260 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5261 BTF_SET_START(rcu_protected_types)
5262 BTF_ID(struct, prog_test_ref_kfunc)
5263 #ifdef CONFIG_CGROUPS
5264 BTF_ID(struct, cgroup)
5265 #endif
5266 #ifdef CONFIG_BPF_JIT
5267 BTF_ID(struct, bpf_cpumask)
5268 #endif
5269 BTF_ID(struct, task_struct)
5270 BTF_SET_END(rcu_protected_types)
5271 
5272 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5273 {
5274 	if (!btf_is_kernel(btf))
5275 		return true;
5276 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5277 }
5278 
5279 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5280 {
5281 	struct btf_struct_meta *meta;
5282 
5283 	if (btf_is_kernel(kptr_field->kptr.btf))
5284 		return NULL;
5285 
5286 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5287 				    kptr_field->kptr.btf_id);
5288 
5289 	return meta ? meta->record : NULL;
5290 }
5291 
5292 static bool rcu_safe_kptr(const struct btf_field *field)
5293 {
5294 	const struct btf_field_kptr *kptr = &field->kptr;
5295 
5296 	return field->type == BPF_KPTR_PERCPU ||
5297 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5298 }
5299 
5300 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5301 {
5302 	struct btf_record *rec;
5303 	u32 ret;
5304 
5305 	ret = PTR_MAYBE_NULL;
5306 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5307 		ret |= MEM_RCU;
5308 		if (kptr_field->type == BPF_KPTR_PERCPU)
5309 			ret |= MEM_PERCPU;
5310 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5311 			ret |= MEM_ALLOC;
5312 
5313 		rec = kptr_pointee_btf_record(kptr_field);
5314 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5315 			ret |= NON_OWN_REF;
5316 	} else {
5317 		ret |= PTR_UNTRUSTED;
5318 	}
5319 
5320 	return ret;
5321 }
5322 
5323 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5324 				 int value_regno, int insn_idx,
5325 				 struct btf_field *kptr_field)
5326 {
5327 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5328 	int class = BPF_CLASS(insn->code);
5329 	struct bpf_reg_state *val_reg;
5330 
5331 	/* Things we already checked for in check_map_access and caller:
5332 	 *  - Reject cases where variable offset may touch kptr
5333 	 *  - size of access (must be BPF_DW)
5334 	 *  - tnum_is_const(reg->var_off)
5335 	 *  - kptr_field->offset == off + reg->var_off.value
5336 	 */
5337 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5338 	if (BPF_MODE(insn->code) != BPF_MEM) {
5339 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5340 		return -EACCES;
5341 	}
5342 
5343 	/* We only allow loading referenced kptr, since it will be marked as
5344 	 * untrusted, similar to unreferenced kptr.
5345 	 */
5346 	if (class != BPF_LDX &&
5347 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5348 		verbose(env, "store to referenced kptr disallowed\n");
5349 		return -EACCES;
5350 	}
5351 
5352 	if (class == BPF_LDX) {
5353 		val_reg = reg_state(env, value_regno);
5354 		/* We can simply mark the value_regno receiving the pointer
5355 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5356 		 */
5357 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5358 				kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5359 		/* For mark_ptr_or_null_reg */
5360 		val_reg->id = ++env->id_gen;
5361 	} else if (class == BPF_STX) {
5362 		val_reg = reg_state(env, value_regno);
5363 		if (!register_is_null(val_reg) &&
5364 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5365 			return -EACCES;
5366 	} else if (class == BPF_ST) {
5367 		if (insn->imm) {
5368 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5369 				kptr_field->offset);
5370 			return -EACCES;
5371 		}
5372 	} else {
5373 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5374 		return -EACCES;
5375 	}
5376 	return 0;
5377 }
5378 
5379 /* check read/write into a map element with possible variable offset */
5380 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5381 			    int off, int size, bool zero_size_allowed,
5382 			    enum bpf_access_src src)
5383 {
5384 	struct bpf_verifier_state *vstate = env->cur_state;
5385 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5386 	struct bpf_reg_state *reg = &state->regs[regno];
5387 	struct bpf_map *map = reg->map_ptr;
5388 	struct btf_record *rec;
5389 	int err, i;
5390 
5391 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5392 				      zero_size_allowed);
5393 	if (err)
5394 		return err;
5395 
5396 	if (IS_ERR_OR_NULL(map->record))
5397 		return 0;
5398 	rec = map->record;
5399 	for (i = 0; i < rec->cnt; i++) {
5400 		struct btf_field *field = &rec->fields[i];
5401 		u32 p = field->offset;
5402 
5403 		/* If any part of a field  can be touched by load/store, reject
5404 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5405 		 * it is sufficient to check x1 < y2 && y1 < x2.
5406 		 */
5407 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5408 		    p < reg->umax_value + off + size) {
5409 			switch (field->type) {
5410 			case BPF_KPTR_UNREF:
5411 			case BPF_KPTR_REF:
5412 			case BPF_KPTR_PERCPU:
5413 				if (src != ACCESS_DIRECT) {
5414 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5415 					return -EACCES;
5416 				}
5417 				if (!tnum_is_const(reg->var_off)) {
5418 					verbose(env, "kptr access cannot have variable offset\n");
5419 					return -EACCES;
5420 				}
5421 				if (p != off + reg->var_off.value) {
5422 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5423 						p, off + reg->var_off.value);
5424 					return -EACCES;
5425 				}
5426 				if (size != bpf_size_to_bytes(BPF_DW)) {
5427 					verbose(env, "kptr access size must be BPF_DW\n");
5428 					return -EACCES;
5429 				}
5430 				break;
5431 			default:
5432 				verbose(env, "%s cannot be accessed directly by load/store\n",
5433 					btf_field_type_name(field->type));
5434 				return -EACCES;
5435 			}
5436 		}
5437 	}
5438 	return 0;
5439 }
5440 
5441 #define MAX_PACKET_OFF 0xffff
5442 
5443 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5444 				       const struct bpf_call_arg_meta *meta,
5445 				       enum bpf_access_type t)
5446 {
5447 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5448 
5449 	switch (prog_type) {
5450 	/* Program types only with direct read access go here! */
5451 	case BPF_PROG_TYPE_LWT_IN:
5452 	case BPF_PROG_TYPE_LWT_OUT:
5453 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5454 	case BPF_PROG_TYPE_SK_REUSEPORT:
5455 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5456 	case BPF_PROG_TYPE_CGROUP_SKB:
5457 		if (t == BPF_WRITE)
5458 			return false;
5459 		fallthrough;
5460 
5461 	/* Program types with direct read + write access go here! */
5462 	case BPF_PROG_TYPE_SCHED_CLS:
5463 	case BPF_PROG_TYPE_SCHED_ACT:
5464 	case BPF_PROG_TYPE_XDP:
5465 	case BPF_PROG_TYPE_LWT_XMIT:
5466 	case BPF_PROG_TYPE_SK_SKB:
5467 	case BPF_PROG_TYPE_SK_MSG:
5468 		if (meta)
5469 			return meta->pkt_access;
5470 
5471 		env->seen_direct_write = true;
5472 		return true;
5473 
5474 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5475 		if (t == BPF_WRITE)
5476 			env->seen_direct_write = true;
5477 
5478 		return true;
5479 
5480 	default:
5481 		return false;
5482 	}
5483 }
5484 
5485 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5486 			       int size, bool zero_size_allowed)
5487 {
5488 	struct bpf_reg_state *regs = cur_regs(env);
5489 	struct bpf_reg_state *reg = &regs[regno];
5490 	int err;
5491 
5492 	/* We may have added a variable offset to the packet pointer; but any
5493 	 * reg->range we have comes after that.  We are only checking the fixed
5494 	 * offset.
5495 	 */
5496 
5497 	/* We don't allow negative numbers, because we aren't tracking enough
5498 	 * detail to prove they're safe.
5499 	 */
5500 	if (reg->smin_value < 0) {
5501 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5502 			regno);
5503 		return -EACCES;
5504 	}
5505 
5506 	err = reg->range < 0 ? -EINVAL :
5507 	      __check_mem_access(env, regno, off, size, reg->range,
5508 				 zero_size_allowed);
5509 	if (err) {
5510 		verbose(env, "R%d offset is outside of the packet\n", regno);
5511 		return err;
5512 	}
5513 
5514 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5515 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5516 	 * otherwise find_good_pkt_pointers would have refused to set range info
5517 	 * that __check_mem_access would have rejected this pkt access.
5518 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5519 	 */
5520 	env->prog->aux->max_pkt_offset =
5521 		max_t(u32, env->prog->aux->max_pkt_offset,
5522 		      off + reg->umax_value + size - 1);
5523 
5524 	return err;
5525 }
5526 
5527 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5528 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5529 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5530 			    struct btf **btf, u32 *btf_id)
5531 {
5532 	struct bpf_insn_access_aux info = {
5533 		.reg_type = *reg_type,
5534 		.log = &env->log,
5535 	};
5536 
5537 	if (env->ops->is_valid_access &&
5538 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5539 		/* A non zero info.ctx_field_size indicates that this field is a
5540 		 * candidate for later verifier transformation to load the whole
5541 		 * field and then apply a mask when accessed with a narrower
5542 		 * access than actual ctx access size. A zero info.ctx_field_size
5543 		 * will only allow for whole field access and rejects any other
5544 		 * type of narrower access.
5545 		 */
5546 		*reg_type = info.reg_type;
5547 
5548 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5549 			*btf = info.btf;
5550 			*btf_id = info.btf_id;
5551 		} else {
5552 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5553 		}
5554 		/* remember the offset of last byte accessed in ctx */
5555 		if (env->prog->aux->max_ctx_offset < off + size)
5556 			env->prog->aux->max_ctx_offset = off + size;
5557 		return 0;
5558 	}
5559 
5560 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5561 	return -EACCES;
5562 }
5563 
5564 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5565 				  int size)
5566 {
5567 	if (size < 0 || off < 0 ||
5568 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5569 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5570 			off, size);
5571 		return -EACCES;
5572 	}
5573 	return 0;
5574 }
5575 
5576 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5577 			     u32 regno, int off, int size,
5578 			     enum bpf_access_type t)
5579 {
5580 	struct bpf_reg_state *regs = cur_regs(env);
5581 	struct bpf_reg_state *reg = &regs[regno];
5582 	struct bpf_insn_access_aux info = {};
5583 	bool valid;
5584 
5585 	if (reg->smin_value < 0) {
5586 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5587 			regno);
5588 		return -EACCES;
5589 	}
5590 
5591 	switch (reg->type) {
5592 	case PTR_TO_SOCK_COMMON:
5593 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5594 		break;
5595 	case PTR_TO_SOCKET:
5596 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5597 		break;
5598 	case PTR_TO_TCP_SOCK:
5599 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5600 		break;
5601 	case PTR_TO_XDP_SOCK:
5602 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5603 		break;
5604 	default:
5605 		valid = false;
5606 	}
5607 
5608 
5609 	if (valid) {
5610 		env->insn_aux_data[insn_idx].ctx_field_size =
5611 			info.ctx_field_size;
5612 		return 0;
5613 	}
5614 
5615 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5616 		regno, reg_type_str(env, reg->type), off, size);
5617 
5618 	return -EACCES;
5619 }
5620 
5621 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5622 {
5623 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5624 }
5625 
5626 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5627 {
5628 	const struct bpf_reg_state *reg = reg_state(env, regno);
5629 
5630 	return reg->type == PTR_TO_CTX;
5631 }
5632 
5633 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5634 {
5635 	const struct bpf_reg_state *reg = reg_state(env, regno);
5636 
5637 	return type_is_sk_pointer(reg->type);
5638 }
5639 
5640 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5641 {
5642 	const struct bpf_reg_state *reg = reg_state(env, regno);
5643 
5644 	return type_is_pkt_pointer(reg->type);
5645 }
5646 
5647 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5648 {
5649 	const struct bpf_reg_state *reg = reg_state(env, regno);
5650 
5651 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5652 	return reg->type == PTR_TO_FLOW_KEYS;
5653 }
5654 
5655 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5656 #ifdef CONFIG_NET
5657 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5658 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5659 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5660 #endif
5661 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5662 };
5663 
5664 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5665 {
5666 	/* A referenced register is always trusted. */
5667 	if (reg->ref_obj_id)
5668 		return true;
5669 
5670 	/* Types listed in the reg2btf_ids are always trusted */
5671 	if (reg2btf_ids[base_type(reg->type)])
5672 		return true;
5673 
5674 	/* If a register is not referenced, it is trusted if it has the
5675 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5676 	 * other type modifiers may be safe, but we elect to take an opt-in
5677 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5678 	 * not.
5679 	 *
5680 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5681 	 * for whether a register is trusted.
5682 	 */
5683 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5684 	       !bpf_type_has_unsafe_modifiers(reg->type);
5685 }
5686 
5687 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5688 {
5689 	return reg->type & MEM_RCU;
5690 }
5691 
5692 static void clear_trusted_flags(enum bpf_type_flag *flag)
5693 {
5694 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5695 }
5696 
5697 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5698 				   const struct bpf_reg_state *reg,
5699 				   int off, int size, bool strict)
5700 {
5701 	struct tnum reg_off;
5702 	int ip_align;
5703 
5704 	/* Byte size accesses are always allowed. */
5705 	if (!strict || size == 1)
5706 		return 0;
5707 
5708 	/* For platforms that do not have a Kconfig enabling
5709 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5710 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5711 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5712 	 * to this code only in strict mode where we want to emulate
5713 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5714 	 * unconditional IP align value of '2'.
5715 	 */
5716 	ip_align = 2;
5717 
5718 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5719 	if (!tnum_is_aligned(reg_off, size)) {
5720 		char tn_buf[48];
5721 
5722 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5723 		verbose(env,
5724 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5725 			ip_align, tn_buf, reg->off, off, size);
5726 		return -EACCES;
5727 	}
5728 
5729 	return 0;
5730 }
5731 
5732 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5733 				       const struct bpf_reg_state *reg,
5734 				       const char *pointer_desc,
5735 				       int off, int size, bool strict)
5736 {
5737 	struct tnum reg_off;
5738 
5739 	/* Byte size accesses are always allowed. */
5740 	if (!strict || size == 1)
5741 		return 0;
5742 
5743 	reg_off = tnum_add(reg->var_off, tnum_const(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, "misaligned %saccess off %s+%d+%d size %d\n",
5749 			pointer_desc, tn_buf, reg->off, off, size);
5750 		return -EACCES;
5751 	}
5752 
5753 	return 0;
5754 }
5755 
5756 static int check_ptr_alignment(struct bpf_verifier_env *env,
5757 			       const struct bpf_reg_state *reg, int off,
5758 			       int size, bool strict_alignment_once)
5759 {
5760 	bool strict = env->strict_alignment || strict_alignment_once;
5761 	const char *pointer_desc = "";
5762 
5763 	switch (reg->type) {
5764 	case PTR_TO_PACKET:
5765 	case PTR_TO_PACKET_META:
5766 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5767 		 * right in front, treat it the very same way.
5768 		 */
5769 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5770 	case PTR_TO_FLOW_KEYS:
5771 		pointer_desc = "flow keys ";
5772 		break;
5773 	case PTR_TO_MAP_KEY:
5774 		pointer_desc = "key ";
5775 		break;
5776 	case PTR_TO_MAP_VALUE:
5777 		pointer_desc = "value ";
5778 		break;
5779 	case PTR_TO_CTX:
5780 		pointer_desc = "context ";
5781 		break;
5782 	case PTR_TO_STACK:
5783 		pointer_desc = "stack ";
5784 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5785 		 * and check_stack_read_fixed_off() relies on stack accesses being
5786 		 * aligned.
5787 		 */
5788 		strict = true;
5789 		break;
5790 	case PTR_TO_SOCKET:
5791 		pointer_desc = "sock ";
5792 		break;
5793 	case PTR_TO_SOCK_COMMON:
5794 		pointer_desc = "sock_common ";
5795 		break;
5796 	case PTR_TO_TCP_SOCK:
5797 		pointer_desc = "tcp_sock ";
5798 		break;
5799 	case PTR_TO_XDP_SOCK:
5800 		pointer_desc = "xdp_sock ";
5801 		break;
5802 	default:
5803 		break;
5804 	}
5805 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5806 					   strict);
5807 }
5808 
5809 /* starting from main bpf function walk all instructions of the function
5810  * and recursively walk all callees that given function can call.
5811  * Ignore jump and exit insns.
5812  * Since recursion is prevented by check_cfg() this algorithm
5813  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5814  */
5815 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5816 {
5817 	struct bpf_subprog_info *subprog = env->subprog_info;
5818 	struct bpf_insn *insn = env->prog->insnsi;
5819 	int depth = 0, frame = 0, i, subprog_end;
5820 	bool tail_call_reachable = false;
5821 	int ret_insn[MAX_CALL_FRAMES];
5822 	int ret_prog[MAX_CALL_FRAMES];
5823 	int j;
5824 
5825 	i = subprog[idx].start;
5826 process_func:
5827 	/* protect against potential stack overflow that might happen when
5828 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5829 	 * depth for such case down to 256 so that the worst case scenario
5830 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5831 	 * 8k).
5832 	 *
5833 	 * To get the idea what might happen, see an example:
5834 	 * func1 -> sub rsp, 128
5835 	 *  subfunc1 -> sub rsp, 256
5836 	 *  tailcall1 -> add rsp, 256
5837 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5838 	 *   subfunc2 -> sub rsp, 64
5839 	 *   subfunc22 -> sub rsp, 128
5840 	 *   tailcall2 -> add rsp, 128
5841 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5842 	 *
5843 	 * tailcall will unwind the current stack frame but it will not get rid
5844 	 * of caller's stack as shown on the example above.
5845 	 */
5846 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5847 		verbose(env,
5848 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5849 			depth);
5850 		return -EACCES;
5851 	}
5852 	/* round up to 32-bytes, since this is granularity
5853 	 * of interpreter stack size
5854 	 */
5855 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5856 	if (depth > MAX_BPF_STACK) {
5857 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5858 			frame + 1, depth);
5859 		return -EACCES;
5860 	}
5861 continue_func:
5862 	subprog_end = subprog[idx + 1].start;
5863 	for (; i < subprog_end; i++) {
5864 		int next_insn, sidx;
5865 
5866 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
5867 			bool err = false;
5868 
5869 			if (!is_bpf_throw_kfunc(insn + i))
5870 				continue;
5871 			if (subprog[idx].is_cb)
5872 				err = true;
5873 			for (int c = 0; c < frame && !err; c++) {
5874 				if (subprog[ret_prog[c]].is_cb) {
5875 					err = true;
5876 					break;
5877 				}
5878 			}
5879 			if (!err)
5880 				continue;
5881 			verbose(env,
5882 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5883 				i, idx);
5884 			return -EINVAL;
5885 		}
5886 
5887 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5888 			continue;
5889 		/* remember insn and function to return to */
5890 		ret_insn[frame] = i + 1;
5891 		ret_prog[frame] = idx;
5892 
5893 		/* find the callee */
5894 		next_insn = i + insn[i].imm + 1;
5895 		sidx = find_subprog(env, next_insn);
5896 		if (sidx < 0) {
5897 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5898 				  next_insn);
5899 			return -EFAULT;
5900 		}
5901 		if (subprog[sidx].is_async_cb) {
5902 			if (subprog[sidx].has_tail_call) {
5903 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5904 				return -EFAULT;
5905 			}
5906 			/* async callbacks don't increase bpf prog stack size unless called directly */
5907 			if (!bpf_pseudo_call(insn + i))
5908 				continue;
5909 			if (subprog[sidx].is_exception_cb) {
5910 				verbose(env, "insn %d cannot call exception cb directly\n", i);
5911 				return -EINVAL;
5912 			}
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 			if (subprog[ret_prog[j]].is_exception_cb) {
5936 				verbose(env, "cannot tail call within exception cb\n");
5937 				return -EINVAL;
5938 			}
5939 			subprog[ret_prog[j]].tail_call_reachable = true;
5940 		}
5941 	if (subprog[0].tail_call_reachable)
5942 		env->prog->aux->tail_call_reachable = true;
5943 
5944 	/* end of for() loop means the last insn of the 'subprog'
5945 	 * was reached. Doesn't matter whether it was JA or EXIT
5946 	 */
5947 	if (frame == 0)
5948 		return 0;
5949 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5950 	frame--;
5951 	i = ret_insn[frame];
5952 	idx = ret_prog[frame];
5953 	goto continue_func;
5954 }
5955 
5956 static int check_max_stack_depth(struct bpf_verifier_env *env)
5957 {
5958 	struct bpf_subprog_info *si = env->subprog_info;
5959 	int ret;
5960 
5961 	for (int i = 0; i < env->subprog_cnt; i++) {
5962 		if (!i || si[i].is_async_cb) {
5963 			ret = check_max_stack_depth_subprog(env, i);
5964 			if (ret < 0)
5965 				return ret;
5966 		}
5967 		continue;
5968 	}
5969 	return 0;
5970 }
5971 
5972 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5973 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5974 				  const struct bpf_insn *insn, int idx)
5975 {
5976 	int start = idx + insn->imm + 1, subprog;
5977 
5978 	subprog = find_subprog(env, start);
5979 	if (subprog < 0) {
5980 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5981 			  start);
5982 		return -EFAULT;
5983 	}
5984 	return env->subprog_info[subprog].stack_depth;
5985 }
5986 #endif
5987 
5988 static int __check_buffer_access(struct bpf_verifier_env *env,
5989 				 const char *buf_info,
5990 				 const struct bpf_reg_state *reg,
5991 				 int regno, int off, int size)
5992 {
5993 	if (off < 0) {
5994 		verbose(env,
5995 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5996 			regno, buf_info, off, size);
5997 		return -EACCES;
5998 	}
5999 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6000 		char tn_buf[48];
6001 
6002 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6003 		verbose(env,
6004 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6005 			regno, off, tn_buf);
6006 		return -EACCES;
6007 	}
6008 
6009 	return 0;
6010 }
6011 
6012 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6013 				  const struct bpf_reg_state *reg,
6014 				  int regno, int off, int size)
6015 {
6016 	int err;
6017 
6018 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6019 	if (err)
6020 		return err;
6021 
6022 	if (off + size > env->prog->aux->max_tp_access)
6023 		env->prog->aux->max_tp_access = off + size;
6024 
6025 	return 0;
6026 }
6027 
6028 static int check_buffer_access(struct bpf_verifier_env *env,
6029 			       const struct bpf_reg_state *reg,
6030 			       int regno, int off, int size,
6031 			       bool zero_size_allowed,
6032 			       u32 *max_access)
6033 {
6034 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6035 	int err;
6036 
6037 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6038 	if (err)
6039 		return err;
6040 
6041 	if (off + size > *max_access)
6042 		*max_access = off + size;
6043 
6044 	return 0;
6045 }
6046 
6047 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6048 static void zext_32_to_64(struct bpf_reg_state *reg)
6049 {
6050 	reg->var_off = tnum_subreg(reg->var_off);
6051 	__reg_assign_32_into_64(reg);
6052 }
6053 
6054 /* truncate register to smaller size (in bytes)
6055  * must be called with size < BPF_REG_SIZE
6056  */
6057 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6058 {
6059 	u64 mask;
6060 
6061 	/* clear high bits in bit representation */
6062 	reg->var_off = tnum_cast(reg->var_off, size);
6063 
6064 	/* fix arithmetic bounds */
6065 	mask = ((u64)1 << (size * 8)) - 1;
6066 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6067 		reg->umin_value &= mask;
6068 		reg->umax_value &= mask;
6069 	} else {
6070 		reg->umin_value = 0;
6071 		reg->umax_value = mask;
6072 	}
6073 	reg->smin_value = reg->umin_value;
6074 	reg->smax_value = reg->umax_value;
6075 
6076 	/* If size is smaller than 32bit register the 32bit register
6077 	 * values are also truncated so we push 64-bit bounds into
6078 	 * 32-bit bounds. Above were truncated < 32-bits already.
6079 	 */
6080 	if (size < 4) {
6081 		__mark_reg32_unbounded(reg);
6082 		reg_bounds_sync(reg);
6083 	}
6084 }
6085 
6086 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6087 {
6088 	if (size == 1) {
6089 		reg->smin_value = reg->s32_min_value = S8_MIN;
6090 		reg->smax_value = reg->s32_max_value = S8_MAX;
6091 	} else if (size == 2) {
6092 		reg->smin_value = reg->s32_min_value = S16_MIN;
6093 		reg->smax_value = reg->s32_max_value = S16_MAX;
6094 	} else {
6095 		/* size == 4 */
6096 		reg->smin_value = reg->s32_min_value = S32_MIN;
6097 		reg->smax_value = reg->s32_max_value = S32_MAX;
6098 	}
6099 	reg->umin_value = reg->u32_min_value = 0;
6100 	reg->umax_value = U64_MAX;
6101 	reg->u32_max_value = U32_MAX;
6102 	reg->var_off = tnum_unknown;
6103 }
6104 
6105 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6106 {
6107 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6108 	u64 top_smax_value, top_smin_value;
6109 	u64 num_bits = size * 8;
6110 
6111 	if (tnum_is_const(reg->var_off)) {
6112 		u64_cval = reg->var_off.value;
6113 		if (size == 1)
6114 			reg->var_off = tnum_const((s8)u64_cval);
6115 		else if (size == 2)
6116 			reg->var_off = tnum_const((s16)u64_cval);
6117 		else
6118 			/* size == 4 */
6119 			reg->var_off = tnum_const((s32)u64_cval);
6120 
6121 		u64_cval = reg->var_off.value;
6122 		reg->smax_value = reg->smin_value = u64_cval;
6123 		reg->umax_value = reg->umin_value = u64_cval;
6124 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6125 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6126 		return;
6127 	}
6128 
6129 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6130 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6131 
6132 	if (top_smax_value != top_smin_value)
6133 		goto out;
6134 
6135 	/* find the s64_min and s64_min after sign extension */
6136 	if (size == 1) {
6137 		init_s64_max = (s8)reg->smax_value;
6138 		init_s64_min = (s8)reg->smin_value;
6139 	} else if (size == 2) {
6140 		init_s64_max = (s16)reg->smax_value;
6141 		init_s64_min = (s16)reg->smin_value;
6142 	} else {
6143 		init_s64_max = (s32)reg->smax_value;
6144 		init_s64_min = (s32)reg->smin_value;
6145 	}
6146 
6147 	s64_max = max(init_s64_max, init_s64_min);
6148 	s64_min = min(init_s64_max, init_s64_min);
6149 
6150 	/* both of s64_max/s64_min positive or negative */
6151 	if ((s64_max >= 0) == (s64_min >= 0)) {
6152 		reg->smin_value = reg->s32_min_value = s64_min;
6153 		reg->smax_value = reg->s32_max_value = s64_max;
6154 		reg->umin_value = reg->u32_min_value = s64_min;
6155 		reg->umax_value = reg->u32_max_value = s64_max;
6156 		reg->var_off = tnum_range(s64_min, s64_max);
6157 		return;
6158 	}
6159 
6160 out:
6161 	set_sext64_default_val(reg, size);
6162 }
6163 
6164 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6165 {
6166 	if (size == 1) {
6167 		reg->s32_min_value = S8_MIN;
6168 		reg->s32_max_value = S8_MAX;
6169 	} else {
6170 		/* size == 2 */
6171 		reg->s32_min_value = S16_MIN;
6172 		reg->s32_max_value = S16_MAX;
6173 	}
6174 	reg->u32_min_value = 0;
6175 	reg->u32_max_value = U32_MAX;
6176 }
6177 
6178 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6179 {
6180 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6181 	u32 top_smax_value, top_smin_value;
6182 	u32 num_bits = size * 8;
6183 
6184 	if (tnum_is_const(reg->var_off)) {
6185 		u32_val = reg->var_off.value;
6186 		if (size == 1)
6187 			reg->var_off = tnum_const((s8)u32_val);
6188 		else
6189 			reg->var_off = tnum_const((s16)u32_val);
6190 
6191 		u32_val = reg->var_off.value;
6192 		reg->s32_min_value = reg->s32_max_value = u32_val;
6193 		reg->u32_min_value = reg->u32_max_value = u32_val;
6194 		return;
6195 	}
6196 
6197 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6198 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6199 
6200 	if (top_smax_value != top_smin_value)
6201 		goto out;
6202 
6203 	/* find the s32_min and s32_min after sign extension */
6204 	if (size == 1) {
6205 		init_s32_max = (s8)reg->s32_max_value;
6206 		init_s32_min = (s8)reg->s32_min_value;
6207 	} else {
6208 		/* size == 2 */
6209 		init_s32_max = (s16)reg->s32_max_value;
6210 		init_s32_min = (s16)reg->s32_min_value;
6211 	}
6212 	s32_max = max(init_s32_max, init_s32_min);
6213 	s32_min = min(init_s32_max, init_s32_min);
6214 
6215 	if ((s32_min >= 0) == (s32_max >= 0)) {
6216 		reg->s32_min_value = s32_min;
6217 		reg->s32_max_value = s32_max;
6218 		reg->u32_min_value = (u32)s32_min;
6219 		reg->u32_max_value = (u32)s32_max;
6220 		return;
6221 	}
6222 
6223 out:
6224 	set_sext32_default_val(reg, size);
6225 }
6226 
6227 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6228 {
6229 	/* A map is considered read-only if the following condition are true:
6230 	 *
6231 	 * 1) BPF program side cannot change any of the map content. The
6232 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6233 	 *    and was set at map creation time.
6234 	 * 2) The map value(s) have been initialized from user space by a
6235 	 *    loader and then "frozen", such that no new map update/delete
6236 	 *    operations from syscall side are possible for the rest of
6237 	 *    the map's lifetime from that point onwards.
6238 	 * 3) Any parallel/pending map update/delete operations from syscall
6239 	 *    side have been completed. Only after that point, it's safe to
6240 	 *    assume that map value(s) are immutable.
6241 	 */
6242 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6243 	       READ_ONCE(map->frozen) &&
6244 	       !bpf_map_write_active(map);
6245 }
6246 
6247 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6248 			       bool is_ldsx)
6249 {
6250 	void *ptr;
6251 	u64 addr;
6252 	int err;
6253 
6254 	err = map->ops->map_direct_value_addr(map, &addr, off);
6255 	if (err)
6256 		return err;
6257 	ptr = (void *)(long)addr + off;
6258 
6259 	switch (size) {
6260 	case sizeof(u8):
6261 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6262 		break;
6263 	case sizeof(u16):
6264 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6265 		break;
6266 	case sizeof(u32):
6267 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6268 		break;
6269 	case sizeof(u64):
6270 		*val = *(u64 *)ptr;
6271 		break;
6272 	default:
6273 		return -EINVAL;
6274 	}
6275 	return 0;
6276 }
6277 
6278 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6279 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6280 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6281 
6282 /*
6283  * Allow list few fields as RCU trusted or full trusted.
6284  * This logic doesn't allow mix tagging and will be removed once GCC supports
6285  * btf_type_tag.
6286  */
6287 
6288 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6289 BTF_TYPE_SAFE_RCU(struct task_struct) {
6290 	const cpumask_t *cpus_ptr;
6291 	struct css_set __rcu *cgroups;
6292 	struct task_struct __rcu *real_parent;
6293 	struct task_struct *group_leader;
6294 };
6295 
6296 BTF_TYPE_SAFE_RCU(struct cgroup) {
6297 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6298 	struct kernfs_node *kn;
6299 };
6300 
6301 BTF_TYPE_SAFE_RCU(struct css_set) {
6302 	struct cgroup *dfl_cgrp;
6303 };
6304 
6305 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6306 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6307 	struct file __rcu *exe_file;
6308 };
6309 
6310 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6311  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6312  */
6313 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6314 	struct sock *sk;
6315 };
6316 
6317 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6318 	struct sock *sk;
6319 };
6320 
6321 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6322 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6323 	struct seq_file *seq;
6324 };
6325 
6326 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6327 	struct bpf_iter_meta *meta;
6328 	struct task_struct *task;
6329 };
6330 
6331 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6332 	struct file *file;
6333 };
6334 
6335 BTF_TYPE_SAFE_TRUSTED(struct file) {
6336 	struct inode *f_inode;
6337 };
6338 
6339 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6340 	/* no negative dentry-s in places where bpf can see it */
6341 	struct inode *d_inode;
6342 };
6343 
6344 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6345 	struct sock *sk;
6346 };
6347 
6348 static bool type_is_rcu(struct bpf_verifier_env *env,
6349 			struct bpf_reg_state *reg,
6350 			const char *field_name, u32 btf_id)
6351 {
6352 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6353 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6354 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6355 
6356 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6357 }
6358 
6359 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6360 				struct bpf_reg_state *reg,
6361 				const char *field_name, u32 btf_id)
6362 {
6363 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6364 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6365 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6366 
6367 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6368 }
6369 
6370 static bool type_is_trusted(struct bpf_verifier_env *env,
6371 			    struct bpf_reg_state *reg,
6372 			    const char *field_name, u32 btf_id)
6373 {
6374 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6375 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6376 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6377 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6378 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6379 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6380 
6381 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6382 }
6383 
6384 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6385 				   struct bpf_reg_state *regs,
6386 				   int regno, int off, int size,
6387 				   enum bpf_access_type atype,
6388 				   int value_regno)
6389 {
6390 	struct bpf_reg_state *reg = regs + regno;
6391 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6392 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6393 	const char *field_name = NULL;
6394 	enum bpf_type_flag flag = 0;
6395 	u32 btf_id = 0;
6396 	int ret;
6397 
6398 	if (!env->allow_ptr_leaks) {
6399 		verbose(env,
6400 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6401 			tname);
6402 		return -EPERM;
6403 	}
6404 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6405 		verbose(env,
6406 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6407 			tname);
6408 		return -EINVAL;
6409 	}
6410 	if (off < 0) {
6411 		verbose(env,
6412 			"R%d is ptr_%s invalid negative access: off=%d\n",
6413 			regno, tname, off);
6414 		return -EACCES;
6415 	}
6416 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6417 		char tn_buf[48];
6418 
6419 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6420 		verbose(env,
6421 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6422 			regno, tname, off, tn_buf);
6423 		return -EACCES;
6424 	}
6425 
6426 	if (reg->type & MEM_USER) {
6427 		verbose(env,
6428 			"R%d is ptr_%s access user memory: off=%d\n",
6429 			regno, tname, off);
6430 		return -EACCES;
6431 	}
6432 
6433 	if (reg->type & MEM_PERCPU) {
6434 		verbose(env,
6435 			"R%d is ptr_%s access percpu memory: off=%d\n",
6436 			regno, tname, off);
6437 		return -EACCES;
6438 	}
6439 
6440 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6441 		if (!btf_is_kernel(reg->btf)) {
6442 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6443 			return -EFAULT;
6444 		}
6445 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6446 	} else {
6447 		/* Writes are permitted with default btf_struct_access for
6448 		 * program allocated objects (which always have ref_obj_id > 0),
6449 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6450 		 */
6451 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6452 			verbose(env, "only read is supported\n");
6453 			return -EACCES;
6454 		}
6455 
6456 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6457 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
6458 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6459 			return -EFAULT;
6460 		}
6461 
6462 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6463 	}
6464 
6465 	if (ret < 0)
6466 		return ret;
6467 
6468 	if (ret != PTR_TO_BTF_ID) {
6469 		/* just mark; */
6470 
6471 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6472 		/* If this is an untrusted pointer, all pointers formed by walking it
6473 		 * also inherit the untrusted flag.
6474 		 */
6475 		flag = PTR_UNTRUSTED;
6476 
6477 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6478 		/* By default any pointer obtained from walking a trusted pointer is no
6479 		 * longer trusted, unless the field being accessed has explicitly been
6480 		 * marked as inheriting its parent's state of trust (either full or RCU).
6481 		 * For example:
6482 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6483 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6484 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6485 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6486 		 *
6487 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6488 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6489 		 */
6490 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6491 			flag |= PTR_TRUSTED;
6492 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6493 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6494 				/* ignore __rcu tag and mark it MEM_RCU */
6495 				flag |= MEM_RCU;
6496 			} else if (flag & MEM_RCU ||
6497 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6498 				/* __rcu tagged pointers can be NULL */
6499 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6500 
6501 				/* We always trust them */
6502 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6503 				    flag & PTR_UNTRUSTED)
6504 					flag &= ~PTR_UNTRUSTED;
6505 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6506 				/* keep as-is */
6507 			} else {
6508 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6509 				clear_trusted_flags(&flag);
6510 			}
6511 		} else {
6512 			/*
6513 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6514 			 * aggressively mark as untrusted otherwise such
6515 			 * pointers will be plain PTR_TO_BTF_ID without flags
6516 			 * and will be allowed to be passed into helpers for
6517 			 * compat reasons.
6518 			 */
6519 			flag = PTR_UNTRUSTED;
6520 		}
6521 	} else {
6522 		/* Old compat. Deprecated */
6523 		clear_trusted_flags(&flag);
6524 	}
6525 
6526 	if (atype == BPF_READ && value_regno >= 0)
6527 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6528 
6529 	return 0;
6530 }
6531 
6532 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6533 				   struct bpf_reg_state *regs,
6534 				   int regno, int off, int size,
6535 				   enum bpf_access_type atype,
6536 				   int value_regno)
6537 {
6538 	struct bpf_reg_state *reg = regs + regno;
6539 	struct bpf_map *map = reg->map_ptr;
6540 	struct bpf_reg_state map_reg;
6541 	enum bpf_type_flag flag = 0;
6542 	const struct btf_type *t;
6543 	const char *tname;
6544 	u32 btf_id;
6545 	int ret;
6546 
6547 	if (!btf_vmlinux) {
6548 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6549 		return -ENOTSUPP;
6550 	}
6551 
6552 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6553 		verbose(env, "map_ptr access not supported for map type %d\n",
6554 			map->map_type);
6555 		return -ENOTSUPP;
6556 	}
6557 
6558 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6559 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6560 
6561 	if (!env->allow_ptr_leaks) {
6562 		verbose(env,
6563 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6564 			tname);
6565 		return -EPERM;
6566 	}
6567 
6568 	if (off < 0) {
6569 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6570 			regno, tname, off);
6571 		return -EACCES;
6572 	}
6573 
6574 	if (atype != BPF_READ) {
6575 		verbose(env, "only read from %s is supported\n", tname);
6576 		return -EACCES;
6577 	}
6578 
6579 	/* Simulate access to a PTR_TO_BTF_ID */
6580 	memset(&map_reg, 0, sizeof(map_reg));
6581 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6582 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6583 	if (ret < 0)
6584 		return ret;
6585 
6586 	if (value_regno >= 0)
6587 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6588 
6589 	return 0;
6590 }
6591 
6592 /* Check that the stack access at the given offset is within bounds. The
6593  * maximum valid offset is -1.
6594  *
6595  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6596  * -state->allocated_stack for reads.
6597  */
6598 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6599                                           s64 off,
6600                                           struct bpf_func_state *state,
6601                                           enum bpf_access_type t)
6602 {
6603 	int min_valid_off;
6604 
6605 	if (t == BPF_WRITE || env->allow_uninit_stack)
6606 		min_valid_off = -MAX_BPF_STACK;
6607 	else
6608 		min_valid_off = -state->allocated_stack;
6609 
6610 	if (off < min_valid_off || off > -1)
6611 		return -EACCES;
6612 	return 0;
6613 }
6614 
6615 /* Check that the stack access at 'regno + off' falls within the maximum stack
6616  * bounds.
6617  *
6618  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6619  */
6620 static int check_stack_access_within_bounds(
6621 		struct bpf_verifier_env *env,
6622 		int regno, int off, int access_size,
6623 		enum bpf_access_src src, enum bpf_access_type type)
6624 {
6625 	struct bpf_reg_state *regs = cur_regs(env);
6626 	struct bpf_reg_state *reg = regs + regno;
6627 	struct bpf_func_state *state = func(env, reg);
6628 	s64 min_off, max_off;
6629 	int err;
6630 	char *err_extra;
6631 
6632 	if (src == ACCESS_HELPER)
6633 		/* We don't know if helpers are reading or writing (or both). */
6634 		err_extra = " indirect access to";
6635 	else if (type == BPF_READ)
6636 		err_extra = " read from";
6637 	else
6638 		err_extra = " write to";
6639 
6640 	if (tnum_is_const(reg->var_off)) {
6641 		min_off = (s64)reg->var_off.value + off;
6642 		max_off = min_off + access_size;
6643 	} else {
6644 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6645 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6646 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6647 				err_extra, regno);
6648 			return -EACCES;
6649 		}
6650 		min_off = reg->smin_value + off;
6651 		max_off = reg->smax_value + off + access_size;
6652 	}
6653 
6654 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6655 	if (!err && max_off > 0)
6656 		err = -EINVAL; /* out of stack access into non-negative offsets */
6657 
6658 	if (err) {
6659 		if (tnum_is_const(reg->var_off)) {
6660 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6661 				err_extra, regno, off, access_size);
6662 		} else {
6663 			char tn_buf[48];
6664 
6665 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6666 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
6667 				err_extra, regno, tn_buf, off, access_size);
6668 		}
6669 		return err;
6670 	}
6671 
6672 	/* Note that there is no stack access with offset zero, so the needed stack
6673 	 * size is -min_off, not -min_off+1.
6674 	 */
6675 	return grow_stack_state(env, state, -min_off /* size */);
6676 }
6677 
6678 /* check whether memory at (regno + off) is accessible for t = (read | write)
6679  * if t==write, value_regno is a register which value is stored into memory
6680  * if t==read, value_regno is a register which will receive the value from memory
6681  * if t==write && value_regno==-1, some unknown value is stored into memory
6682  * if t==read && value_regno==-1, don't care what we read from memory
6683  */
6684 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6685 			    int off, int bpf_size, enum bpf_access_type t,
6686 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6687 {
6688 	struct bpf_reg_state *regs = cur_regs(env);
6689 	struct bpf_reg_state *reg = regs + regno;
6690 	int size, err = 0;
6691 
6692 	size = bpf_size_to_bytes(bpf_size);
6693 	if (size < 0)
6694 		return size;
6695 
6696 	/* alignment checks will add in reg->off themselves */
6697 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6698 	if (err)
6699 		return err;
6700 
6701 	/* for access checks, reg->off is just part of off */
6702 	off += reg->off;
6703 
6704 	if (reg->type == PTR_TO_MAP_KEY) {
6705 		if (t == BPF_WRITE) {
6706 			verbose(env, "write to change key R%d not allowed\n", regno);
6707 			return -EACCES;
6708 		}
6709 
6710 		err = check_mem_region_access(env, regno, off, size,
6711 					      reg->map_ptr->key_size, false);
6712 		if (err)
6713 			return err;
6714 		if (value_regno >= 0)
6715 			mark_reg_unknown(env, regs, value_regno);
6716 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6717 		struct btf_field *kptr_field = NULL;
6718 
6719 		if (t == BPF_WRITE && value_regno >= 0 &&
6720 		    is_pointer_value(env, value_regno)) {
6721 			verbose(env, "R%d leaks addr into map\n", value_regno);
6722 			return -EACCES;
6723 		}
6724 		err = check_map_access_type(env, regno, off, size, t);
6725 		if (err)
6726 			return err;
6727 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6728 		if (err)
6729 			return err;
6730 		if (tnum_is_const(reg->var_off))
6731 			kptr_field = btf_record_find(reg->map_ptr->record,
6732 						     off + reg->var_off.value, BPF_KPTR);
6733 		if (kptr_field) {
6734 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6735 		} else if (t == BPF_READ && value_regno >= 0) {
6736 			struct bpf_map *map = reg->map_ptr;
6737 
6738 			/* if map is read-only, track its contents as scalars */
6739 			if (tnum_is_const(reg->var_off) &&
6740 			    bpf_map_is_rdonly(map) &&
6741 			    map->ops->map_direct_value_addr) {
6742 				int map_off = off + reg->var_off.value;
6743 				u64 val = 0;
6744 
6745 				err = bpf_map_direct_read(map, map_off, size,
6746 							  &val, is_ldsx);
6747 				if (err)
6748 					return err;
6749 
6750 				regs[value_regno].type = SCALAR_VALUE;
6751 				__mark_reg_known(&regs[value_regno], val);
6752 			} else {
6753 				mark_reg_unknown(env, regs, value_regno);
6754 			}
6755 		}
6756 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6757 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6758 
6759 		if (type_may_be_null(reg->type)) {
6760 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6761 				reg_type_str(env, reg->type));
6762 			return -EACCES;
6763 		}
6764 
6765 		if (t == BPF_WRITE && rdonly_mem) {
6766 			verbose(env, "R%d cannot write into %s\n",
6767 				regno, reg_type_str(env, reg->type));
6768 			return -EACCES;
6769 		}
6770 
6771 		if (t == BPF_WRITE && value_regno >= 0 &&
6772 		    is_pointer_value(env, value_regno)) {
6773 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6774 			return -EACCES;
6775 		}
6776 
6777 		err = check_mem_region_access(env, regno, off, size,
6778 					      reg->mem_size, false);
6779 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6780 			mark_reg_unknown(env, regs, value_regno);
6781 	} else if (reg->type == PTR_TO_CTX) {
6782 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6783 		struct btf *btf = NULL;
6784 		u32 btf_id = 0;
6785 
6786 		if (t == BPF_WRITE && value_regno >= 0 &&
6787 		    is_pointer_value(env, value_regno)) {
6788 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6789 			return -EACCES;
6790 		}
6791 
6792 		err = check_ptr_off_reg(env, reg, regno);
6793 		if (err < 0)
6794 			return err;
6795 
6796 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6797 				       &btf_id);
6798 		if (err)
6799 			verbose_linfo(env, insn_idx, "; ");
6800 		if (!err && t == BPF_READ && value_regno >= 0) {
6801 			/* ctx access returns either a scalar, or a
6802 			 * PTR_TO_PACKET[_META,_END]. In the latter
6803 			 * case, we know the offset is zero.
6804 			 */
6805 			if (reg_type == SCALAR_VALUE) {
6806 				mark_reg_unknown(env, regs, value_regno);
6807 			} else {
6808 				mark_reg_known_zero(env, regs,
6809 						    value_regno);
6810 				if (type_may_be_null(reg_type))
6811 					regs[value_regno].id = ++env->id_gen;
6812 				/* A load of ctx field could have different
6813 				 * actual load size with the one encoded in the
6814 				 * insn. When the dst is PTR, it is for sure not
6815 				 * a sub-register.
6816 				 */
6817 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6818 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6819 					regs[value_regno].btf = btf;
6820 					regs[value_regno].btf_id = btf_id;
6821 				}
6822 			}
6823 			regs[value_regno].type = reg_type;
6824 		}
6825 
6826 	} else if (reg->type == PTR_TO_STACK) {
6827 		/* Basic bounds checks. */
6828 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6829 		if (err)
6830 			return err;
6831 
6832 		if (t == BPF_READ)
6833 			err = check_stack_read(env, regno, off, size,
6834 					       value_regno);
6835 		else
6836 			err = check_stack_write(env, regno, off, size,
6837 						value_regno, insn_idx);
6838 	} else if (reg_is_pkt_pointer(reg)) {
6839 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6840 			verbose(env, "cannot write into packet\n");
6841 			return -EACCES;
6842 		}
6843 		if (t == BPF_WRITE && value_regno >= 0 &&
6844 		    is_pointer_value(env, value_regno)) {
6845 			verbose(env, "R%d leaks addr into packet\n",
6846 				value_regno);
6847 			return -EACCES;
6848 		}
6849 		err = check_packet_access(env, regno, off, size, false);
6850 		if (!err && t == BPF_READ && value_regno >= 0)
6851 			mark_reg_unknown(env, regs, value_regno);
6852 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6853 		if (t == BPF_WRITE && value_regno >= 0 &&
6854 		    is_pointer_value(env, value_regno)) {
6855 			verbose(env, "R%d leaks addr into flow keys\n",
6856 				value_regno);
6857 			return -EACCES;
6858 		}
6859 
6860 		err = check_flow_keys_access(env, off, size);
6861 		if (!err && t == BPF_READ && value_regno >= 0)
6862 			mark_reg_unknown(env, regs, value_regno);
6863 	} else if (type_is_sk_pointer(reg->type)) {
6864 		if (t == BPF_WRITE) {
6865 			verbose(env, "R%d cannot write into %s\n",
6866 				regno, reg_type_str(env, reg->type));
6867 			return -EACCES;
6868 		}
6869 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6870 		if (!err && value_regno >= 0)
6871 			mark_reg_unknown(env, regs, value_regno);
6872 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6873 		err = check_tp_buffer_access(env, reg, regno, off, size);
6874 		if (!err && t == BPF_READ && value_regno >= 0)
6875 			mark_reg_unknown(env, regs, value_regno);
6876 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6877 		   !type_may_be_null(reg->type)) {
6878 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6879 					      value_regno);
6880 	} else if (reg->type == CONST_PTR_TO_MAP) {
6881 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6882 					      value_regno);
6883 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6884 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6885 		u32 *max_access;
6886 
6887 		if (rdonly_mem) {
6888 			if (t == BPF_WRITE) {
6889 				verbose(env, "R%d cannot write into %s\n",
6890 					regno, reg_type_str(env, reg->type));
6891 				return -EACCES;
6892 			}
6893 			max_access = &env->prog->aux->max_rdonly_access;
6894 		} else {
6895 			max_access = &env->prog->aux->max_rdwr_access;
6896 		}
6897 
6898 		err = check_buffer_access(env, reg, regno, off, size, false,
6899 					  max_access);
6900 
6901 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6902 			mark_reg_unknown(env, regs, value_regno);
6903 	} else {
6904 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6905 			reg_type_str(env, reg->type));
6906 		return -EACCES;
6907 	}
6908 
6909 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6910 	    regs[value_regno].type == SCALAR_VALUE) {
6911 		if (!is_ldsx)
6912 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6913 			coerce_reg_to_size(&regs[value_regno], size);
6914 		else
6915 			coerce_reg_to_size_sx(&regs[value_regno], size);
6916 	}
6917 	return err;
6918 }
6919 
6920 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6921 {
6922 	int load_reg;
6923 	int err;
6924 
6925 	switch (insn->imm) {
6926 	case BPF_ADD:
6927 	case BPF_ADD | BPF_FETCH:
6928 	case BPF_AND:
6929 	case BPF_AND | BPF_FETCH:
6930 	case BPF_OR:
6931 	case BPF_OR | BPF_FETCH:
6932 	case BPF_XOR:
6933 	case BPF_XOR | BPF_FETCH:
6934 	case BPF_XCHG:
6935 	case BPF_CMPXCHG:
6936 		break;
6937 	default:
6938 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6939 		return -EINVAL;
6940 	}
6941 
6942 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6943 		verbose(env, "invalid atomic operand size\n");
6944 		return -EINVAL;
6945 	}
6946 
6947 	/* check src1 operand */
6948 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6949 	if (err)
6950 		return err;
6951 
6952 	/* check src2 operand */
6953 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6954 	if (err)
6955 		return err;
6956 
6957 	if (insn->imm == BPF_CMPXCHG) {
6958 		/* Check comparison of R0 with memory location */
6959 		const u32 aux_reg = BPF_REG_0;
6960 
6961 		err = check_reg_arg(env, aux_reg, SRC_OP);
6962 		if (err)
6963 			return err;
6964 
6965 		if (is_pointer_value(env, aux_reg)) {
6966 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6967 			return -EACCES;
6968 		}
6969 	}
6970 
6971 	if (is_pointer_value(env, insn->src_reg)) {
6972 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6973 		return -EACCES;
6974 	}
6975 
6976 	if (is_ctx_reg(env, insn->dst_reg) ||
6977 	    is_pkt_reg(env, insn->dst_reg) ||
6978 	    is_flow_key_reg(env, insn->dst_reg) ||
6979 	    is_sk_reg(env, insn->dst_reg)) {
6980 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6981 			insn->dst_reg,
6982 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6983 		return -EACCES;
6984 	}
6985 
6986 	if (insn->imm & BPF_FETCH) {
6987 		if (insn->imm == BPF_CMPXCHG)
6988 			load_reg = BPF_REG_0;
6989 		else
6990 			load_reg = insn->src_reg;
6991 
6992 		/* check and record load of old value */
6993 		err = check_reg_arg(env, load_reg, DST_OP);
6994 		if (err)
6995 			return err;
6996 	} else {
6997 		/* This instruction accesses a memory location but doesn't
6998 		 * actually load it into a register.
6999 		 */
7000 		load_reg = -1;
7001 	}
7002 
7003 	/* Check whether we can read the memory, with second call for fetch
7004 	 * case to simulate the register fill.
7005 	 */
7006 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7007 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7008 	if (!err && load_reg >= 0)
7009 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7010 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
7011 				       true, false);
7012 	if (err)
7013 		return err;
7014 
7015 	/* Check whether we can write into the same memory. */
7016 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7017 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7018 	if (err)
7019 		return err;
7020 	return 0;
7021 }
7022 
7023 /* When register 'regno' is used to read the stack (either directly or through
7024  * a helper function) make sure that it's within stack boundary and, depending
7025  * on the access type and privileges, that all elements of the stack are
7026  * initialized.
7027  *
7028  * 'off' includes 'regno->off', but not its dynamic part (if any).
7029  *
7030  * All registers that have been spilled on the stack in the slots within the
7031  * read offsets are marked as read.
7032  */
7033 static int check_stack_range_initialized(
7034 		struct bpf_verifier_env *env, int regno, int off,
7035 		int access_size, bool zero_size_allowed,
7036 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7037 {
7038 	struct bpf_reg_state *reg = reg_state(env, regno);
7039 	struct bpf_func_state *state = func(env, reg);
7040 	int err, min_off, max_off, i, j, slot, spi;
7041 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7042 	enum bpf_access_type bounds_check_type;
7043 	/* Some accesses can write anything into the stack, others are
7044 	 * read-only.
7045 	 */
7046 	bool clobber = false;
7047 
7048 	if (access_size == 0 && !zero_size_allowed) {
7049 		verbose(env, "invalid zero-sized read\n");
7050 		return -EACCES;
7051 	}
7052 
7053 	if (type == ACCESS_HELPER) {
7054 		/* The bounds checks for writes are more permissive than for
7055 		 * reads. However, if raw_mode is not set, we'll do extra
7056 		 * checks below.
7057 		 */
7058 		bounds_check_type = BPF_WRITE;
7059 		clobber = true;
7060 	} else {
7061 		bounds_check_type = BPF_READ;
7062 	}
7063 	err = check_stack_access_within_bounds(env, regno, off, access_size,
7064 					       type, bounds_check_type);
7065 	if (err)
7066 		return err;
7067 
7068 
7069 	if (tnum_is_const(reg->var_off)) {
7070 		min_off = max_off = reg->var_off.value + off;
7071 	} else {
7072 		/* Variable offset is prohibited for unprivileged mode for
7073 		 * simplicity since it requires corresponding support in
7074 		 * Spectre masking for stack ALU.
7075 		 * See also retrieve_ptr_limit().
7076 		 */
7077 		if (!env->bypass_spec_v1) {
7078 			char tn_buf[48];
7079 
7080 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7081 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7082 				regno, err_extra, tn_buf);
7083 			return -EACCES;
7084 		}
7085 		/* Only initialized buffer on stack is allowed to be accessed
7086 		 * with variable offset. With uninitialized buffer it's hard to
7087 		 * guarantee that whole memory is marked as initialized on
7088 		 * helper return since specific bounds are unknown what may
7089 		 * cause uninitialized stack leaking.
7090 		 */
7091 		if (meta && meta->raw_mode)
7092 			meta = NULL;
7093 
7094 		min_off = reg->smin_value + off;
7095 		max_off = reg->smax_value + off;
7096 	}
7097 
7098 	if (meta && meta->raw_mode) {
7099 		/* Ensure we won't be overwriting dynptrs when simulating byte
7100 		 * by byte access in check_helper_call using meta.access_size.
7101 		 * This would be a problem if we have a helper in the future
7102 		 * which takes:
7103 		 *
7104 		 *	helper(uninit_mem, len, dynptr)
7105 		 *
7106 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7107 		 * may end up writing to dynptr itself when touching memory from
7108 		 * arg 1. This can be relaxed on a case by case basis for known
7109 		 * safe cases, but reject due to the possibilitiy of aliasing by
7110 		 * default.
7111 		 */
7112 		for (i = min_off; i < max_off + access_size; i++) {
7113 			int stack_off = -i - 1;
7114 
7115 			spi = __get_spi(i);
7116 			/* raw_mode may write past allocated_stack */
7117 			if (state->allocated_stack <= stack_off)
7118 				continue;
7119 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7120 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7121 				return -EACCES;
7122 			}
7123 		}
7124 		meta->access_size = access_size;
7125 		meta->regno = regno;
7126 		return 0;
7127 	}
7128 
7129 	for (i = min_off; i < max_off + access_size; i++) {
7130 		u8 *stype;
7131 
7132 		slot = -i - 1;
7133 		spi = slot / BPF_REG_SIZE;
7134 		if (state->allocated_stack <= slot) {
7135 			verbose(env, "verifier bug: allocated_stack too small");
7136 			return -EFAULT;
7137 		}
7138 
7139 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7140 		if (*stype == STACK_MISC)
7141 			goto mark;
7142 		if ((*stype == STACK_ZERO) ||
7143 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7144 			if (clobber) {
7145 				/* helper can write anything into the stack */
7146 				*stype = STACK_MISC;
7147 			}
7148 			goto mark;
7149 		}
7150 
7151 		if (is_spilled_reg(&state->stack[spi]) &&
7152 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7153 		     env->allow_ptr_leaks)) {
7154 			if (clobber) {
7155 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7156 				for (j = 0; j < BPF_REG_SIZE; j++)
7157 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7158 			}
7159 			goto mark;
7160 		}
7161 
7162 		if (tnum_is_const(reg->var_off)) {
7163 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7164 				err_extra, regno, min_off, i - min_off, access_size);
7165 		} else {
7166 			char tn_buf[48];
7167 
7168 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7169 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7170 				err_extra, regno, tn_buf, i - min_off, access_size);
7171 		}
7172 		return -EACCES;
7173 mark:
7174 		/* reading any byte out of 8-byte 'spill_slot' will cause
7175 		 * the whole slot to be marked as 'read'
7176 		 */
7177 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7178 			      state->stack[spi].spilled_ptr.parent,
7179 			      REG_LIVE_READ64);
7180 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7181 		 * be sure that whether stack slot is written to or not. Hence,
7182 		 * we must still conservatively propagate reads upwards even if
7183 		 * helper may write to the entire memory range.
7184 		 */
7185 	}
7186 	return 0;
7187 }
7188 
7189 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7190 				   int access_size, bool zero_size_allowed,
7191 				   struct bpf_call_arg_meta *meta)
7192 {
7193 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7194 	u32 *max_access;
7195 
7196 	switch (base_type(reg->type)) {
7197 	case PTR_TO_PACKET:
7198 	case PTR_TO_PACKET_META:
7199 		return check_packet_access(env, regno, reg->off, access_size,
7200 					   zero_size_allowed);
7201 	case PTR_TO_MAP_KEY:
7202 		if (meta && meta->raw_mode) {
7203 			verbose(env, "R%d cannot write into %s\n", regno,
7204 				reg_type_str(env, reg->type));
7205 			return -EACCES;
7206 		}
7207 		return check_mem_region_access(env, regno, reg->off, access_size,
7208 					       reg->map_ptr->key_size, false);
7209 	case PTR_TO_MAP_VALUE:
7210 		if (check_map_access_type(env, regno, reg->off, access_size,
7211 					  meta && meta->raw_mode ? BPF_WRITE :
7212 					  BPF_READ))
7213 			return -EACCES;
7214 		return check_map_access(env, regno, reg->off, access_size,
7215 					zero_size_allowed, ACCESS_HELPER);
7216 	case PTR_TO_MEM:
7217 		if (type_is_rdonly_mem(reg->type)) {
7218 			if (meta && meta->raw_mode) {
7219 				verbose(env, "R%d cannot write into %s\n", regno,
7220 					reg_type_str(env, reg->type));
7221 				return -EACCES;
7222 			}
7223 		}
7224 		return check_mem_region_access(env, regno, reg->off,
7225 					       access_size, reg->mem_size,
7226 					       zero_size_allowed);
7227 	case PTR_TO_BUF:
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 			max_access = &env->prog->aux->max_rdonly_access;
7236 		} else {
7237 			max_access = &env->prog->aux->max_rdwr_access;
7238 		}
7239 		return check_buffer_access(env, reg, regno, reg->off,
7240 					   access_size, zero_size_allowed,
7241 					   max_access);
7242 	case PTR_TO_STACK:
7243 		return check_stack_range_initialized(
7244 				env,
7245 				regno, reg->off, access_size,
7246 				zero_size_allowed, ACCESS_HELPER, meta);
7247 	case PTR_TO_BTF_ID:
7248 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7249 					       access_size, BPF_READ, -1);
7250 	case PTR_TO_CTX:
7251 		/* in case the function doesn't know how to access the context,
7252 		 * (because we are in a program of type SYSCALL for example), we
7253 		 * can not statically check its size.
7254 		 * Dynamically check it now.
7255 		 */
7256 		if (!env->ops->convert_ctx_access) {
7257 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7258 			int offset = access_size - 1;
7259 
7260 			/* Allow zero-byte read from PTR_TO_CTX */
7261 			if (access_size == 0)
7262 				return zero_size_allowed ? 0 : -EACCES;
7263 
7264 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7265 						atype, -1, false, false);
7266 		}
7267 
7268 		fallthrough;
7269 	default: /* scalar_value or invalid ptr */
7270 		/* Allow zero-byte read from NULL, regardless of pointer type */
7271 		if (zero_size_allowed && access_size == 0 &&
7272 		    register_is_null(reg))
7273 			return 0;
7274 
7275 		verbose(env, "R%d type=%s ", regno,
7276 			reg_type_str(env, reg->type));
7277 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7278 		return -EACCES;
7279 	}
7280 }
7281 
7282 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7283  * size.
7284  *
7285  * @regno is the register containing the access size. regno-1 is the register
7286  * containing the pointer.
7287  */
7288 static int check_mem_size_reg(struct bpf_verifier_env *env,
7289 			      struct bpf_reg_state *reg, u32 regno,
7290 			      bool zero_size_allowed,
7291 			      struct bpf_call_arg_meta *meta)
7292 {
7293 	int err;
7294 
7295 	/* This is used to refine r0 return value bounds for helpers
7296 	 * that enforce this value as an upper bound on return values.
7297 	 * See do_refine_retval_range() for helpers that can refine
7298 	 * the return value. C type of helper is u32 so we pull register
7299 	 * bound from umax_value however, if negative verifier errors
7300 	 * out. Only upper bounds can be learned because retval is an
7301 	 * int type and negative retvals are allowed.
7302 	 */
7303 	meta->msize_max_value = reg->umax_value;
7304 
7305 	/* The register is SCALAR_VALUE; the access check
7306 	 * happens using its boundaries.
7307 	 */
7308 	if (!tnum_is_const(reg->var_off))
7309 		/* For unprivileged variable accesses, disable raw
7310 		 * mode so that the program is required to
7311 		 * initialize all the memory that the helper could
7312 		 * just partially fill up.
7313 		 */
7314 		meta = NULL;
7315 
7316 	if (reg->smin_value < 0) {
7317 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7318 			regno);
7319 		return -EACCES;
7320 	}
7321 
7322 	if (reg->umin_value == 0 && !zero_size_allowed) {
7323 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7324 			regno, reg->umin_value, reg->umax_value);
7325 		return -EACCES;
7326 	}
7327 
7328 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7329 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7330 			regno);
7331 		return -EACCES;
7332 	}
7333 	err = check_helper_mem_access(env, regno - 1,
7334 				      reg->umax_value,
7335 				      zero_size_allowed, meta);
7336 	if (!err)
7337 		err = mark_chain_precision(env, regno);
7338 	return err;
7339 }
7340 
7341 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7342 			 u32 regno, u32 mem_size)
7343 {
7344 	bool may_be_null = type_may_be_null(reg->type);
7345 	struct bpf_reg_state saved_reg;
7346 	struct bpf_call_arg_meta meta;
7347 	int err;
7348 
7349 	if (register_is_null(reg))
7350 		return 0;
7351 
7352 	memset(&meta, 0, sizeof(meta));
7353 	/* Assuming that the register contains a value check if the memory
7354 	 * access is safe. Temporarily save and restore the register's state as
7355 	 * the conversion shouldn't be visible to a caller.
7356 	 */
7357 	if (may_be_null) {
7358 		saved_reg = *reg;
7359 		mark_ptr_not_null_reg(reg);
7360 	}
7361 
7362 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7363 	/* Check access for BPF_WRITE */
7364 	meta.raw_mode = true;
7365 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7366 
7367 	if (may_be_null)
7368 		*reg = saved_reg;
7369 
7370 	return err;
7371 }
7372 
7373 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7374 				    u32 regno)
7375 {
7376 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7377 	bool may_be_null = type_may_be_null(mem_reg->type);
7378 	struct bpf_reg_state saved_reg;
7379 	struct bpf_call_arg_meta meta;
7380 	int err;
7381 
7382 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7383 
7384 	memset(&meta, 0, sizeof(meta));
7385 
7386 	if (may_be_null) {
7387 		saved_reg = *mem_reg;
7388 		mark_ptr_not_null_reg(mem_reg);
7389 	}
7390 
7391 	err = check_mem_size_reg(env, reg, regno, true, &meta);
7392 	/* Check access for BPF_WRITE */
7393 	meta.raw_mode = true;
7394 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7395 
7396 	if (may_be_null)
7397 		*mem_reg = saved_reg;
7398 	return err;
7399 }
7400 
7401 /* Implementation details:
7402  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7403  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7404  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7405  * Two separate bpf_obj_new will also have different reg->id.
7406  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7407  * clears reg->id after value_or_null->value transition, since the verifier only
7408  * cares about the range of access to valid map value pointer and doesn't care
7409  * about actual address of the map element.
7410  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7411  * reg->id > 0 after value_or_null->value transition. By doing so
7412  * two bpf_map_lookups will be considered two different pointers that
7413  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7414  * returned from bpf_obj_new.
7415  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7416  * dead-locks.
7417  * Since only one bpf_spin_lock is allowed the checks are simpler than
7418  * reg_is_refcounted() logic. The verifier needs to remember only
7419  * one spin_lock instead of array of acquired_refs.
7420  * cur_state->active_lock remembers which map value element or allocated
7421  * object got locked and clears it after bpf_spin_unlock.
7422  */
7423 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7424 			     bool is_lock)
7425 {
7426 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7427 	struct bpf_verifier_state *cur = env->cur_state;
7428 	bool is_const = tnum_is_const(reg->var_off);
7429 	u64 val = reg->var_off.value;
7430 	struct bpf_map *map = NULL;
7431 	struct btf *btf = NULL;
7432 	struct btf_record *rec;
7433 
7434 	if (!is_const) {
7435 		verbose(env,
7436 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7437 			regno);
7438 		return -EINVAL;
7439 	}
7440 	if (reg->type == PTR_TO_MAP_VALUE) {
7441 		map = reg->map_ptr;
7442 		if (!map->btf) {
7443 			verbose(env,
7444 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7445 				map->name);
7446 			return -EINVAL;
7447 		}
7448 	} else {
7449 		btf = reg->btf;
7450 	}
7451 
7452 	rec = reg_btf_record(reg);
7453 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7454 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7455 			map ? map->name : "kptr");
7456 		return -EINVAL;
7457 	}
7458 	if (rec->spin_lock_off != val + reg->off) {
7459 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7460 			val + reg->off, rec->spin_lock_off);
7461 		return -EINVAL;
7462 	}
7463 	if (is_lock) {
7464 		if (cur->active_lock.ptr) {
7465 			verbose(env,
7466 				"Locking two bpf_spin_locks are not allowed\n");
7467 			return -EINVAL;
7468 		}
7469 		if (map)
7470 			cur->active_lock.ptr = map;
7471 		else
7472 			cur->active_lock.ptr = btf;
7473 		cur->active_lock.id = reg->id;
7474 	} else {
7475 		void *ptr;
7476 
7477 		if (map)
7478 			ptr = map;
7479 		else
7480 			ptr = btf;
7481 
7482 		if (!cur->active_lock.ptr) {
7483 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7484 			return -EINVAL;
7485 		}
7486 		if (cur->active_lock.ptr != ptr ||
7487 		    cur->active_lock.id != reg->id) {
7488 			verbose(env, "bpf_spin_unlock of different lock\n");
7489 			return -EINVAL;
7490 		}
7491 
7492 		invalidate_non_owning_refs(env);
7493 
7494 		cur->active_lock.ptr = NULL;
7495 		cur->active_lock.id = 0;
7496 	}
7497 	return 0;
7498 }
7499 
7500 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7501 			      struct bpf_call_arg_meta *meta)
7502 {
7503 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7504 	bool is_const = tnum_is_const(reg->var_off);
7505 	struct bpf_map *map = reg->map_ptr;
7506 	u64 val = reg->var_off.value;
7507 
7508 	if (!is_const) {
7509 		verbose(env,
7510 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7511 			regno);
7512 		return -EINVAL;
7513 	}
7514 	if (!map->btf) {
7515 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7516 			map->name);
7517 		return -EINVAL;
7518 	}
7519 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7520 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7521 		return -EINVAL;
7522 	}
7523 	if (map->record->timer_off != val + reg->off) {
7524 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7525 			val + reg->off, map->record->timer_off);
7526 		return -EINVAL;
7527 	}
7528 	if (meta->map_ptr) {
7529 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7530 		return -EFAULT;
7531 	}
7532 	meta->map_uid = reg->map_uid;
7533 	meta->map_ptr = map;
7534 	return 0;
7535 }
7536 
7537 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7538 			     struct bpf_call_arg_meta *meta)
7539 {
7540 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7541 	struct bpf_map *map_ptr = reg->map_ptr;
7542 	struct btf_field *kptr_field;
7543 	u32 kptr_off;
7544 
7545 	if (!tnum_is_const(reg->var_off)) {
7546 		verbose(env,
7547 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7548 			regno);
7549 		return -EINVAL;
7550 	}
7551 	if (!map_ptr->btf) {
7552 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7553 			map_ptr->name);
7554 		return -EINVAL;
7555 	}
7556 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7557 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7558 		return -EINVAL;
7559 	}
7560 
7561 	meta->map_ptr = map_ptr;
7562 	kptr_off = reg->off + reg->var_off.value;
7563 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7564 	if (!kptr_field) {
7565 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7566 		return -EACCES;
7567 	}
7568 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7569 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7570 		return -EACCES;
7571 	}
7572 	meta->kptr_field = kptr_field;
7573 	return 0;
7574 }
7575 
7576 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7577  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7578  *
7579  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7580  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7581  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7582  *
7583  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7584  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7585  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7586  * mutate the view of the dynptr and also possibly destroy it. In the latter
7587  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7588  * memory that dynptr points to.
7589  *
7590  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7591  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7592  * readonly dynptr view yet, hence only the first case is tracked and checked.
7593  *
7594  * This is consistent with how C applies the const modifier to a struct object,
7595  * where the pointer itself inside bpf_dynptr becomes const but not what it
7596  * points to.
7597  *
7598  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7599  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7600  */
7601 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7602 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7603 {
7604 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7605 	int err;
7606 
7607 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7608 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7609 	 */
7610 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7611 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7612 		return -EFAULT;
7613 	}
7614 
7615 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7616 	 *		 constructing a mutable bpf_dynptr object.
7617 	 *
7618 	 *		 Currently, this is only possible with PTR_TO_STACK
7619 	 *		 pointing to a region of at least 16 bytes which doesn't
7620 	 *		 contain an existing bpf_dynptr.
7621 	 *
7622 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7623 	 *		 mutated or destroyed. However, the memory it points to
7624 	 *		 may be mutated.
7625 	 *
7626 	 *  None       - Points to a initialized dynptr that can be mutated and
7627 	 *		 destroyed, including mutation of the memory it points
7628 	 *		 to.
7629 	 */
7630 	if (arg_type & MEM_UNINIT) {
7631 		int i;
7632 
7633 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7634 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7635 			return -EINVAL;
7636 		}
7637 
7638 		/* we write BPF_DW bits (8 bytes) at a time */
7639 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7640 			err = check_mem_access(env, insn_idx, regno,
7641 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7642 			if (err)
7643 				return err;
7644 		}
7645 
7646 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7647 	} else /* MEM_RDONLY and None case from above */ {
7648 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7649 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7650 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7651 			return -EINVAL;
7652 		}
7653 
7654 		if (!is_dynptr_reg_valid_init(env, reg)) {
7655 			verbose(env,
7656 				"Expected an initialized dynptr as arg #%d\n",
7657 				regno);
7658 			return -EINVAL;
7659 		}
7660 
7661 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7662 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7663 			verbose(env,
7664 				"Expected a dynptr of type %s as arg #%d\n",
7665 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7666 			return -EINVAL;
7667 		}
7668 
7669 		err = mark_dynptr_read(env, reg);
7670 	}
7671 	return err;
7672 }
7673 
7674 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7675 {
7676 	struct bpf_func_state *state = func(env, reg);
7677 
7678 	return state->stack[spi].spilled_ptr.ref_obj_id;
7679 }
7680 
7681 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7682 {
7683 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7684 }
7685 
7686 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7687 {
7688 	return meta->kfunc_flags & KF_ITER_NEW;
7689 }
7690 
7691 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7692 {
7693 	return meta->kfunc_flags & KF_ITER_NEXT;
7694 }
7695 
7696 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7697 {
7698 	return meta->kfunc_flags & KF_ITER_DESTROY;
7699 }
7700 
7701 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7702 {
7703 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7704 	 * kfunc is iter state pointer
7705 	 */
7706 	return arg == 0 && is_iter_kfunc(meta);
7707 }
7708 
7709 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7710 			    struct bpf_kfunc_call_arg_meta *meta)
7711 {
7712 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7713 	const struct btf_type *t;
7714 	const struct btf_param *arg;
7715 	int spi, err, i, nr_slots;
7716 	u32 btf_id;
7717 
7718 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7719 	arg = &btf_params(meta->func_proto)[0];
7720 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7721 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7722 	nr_slots = t->size / BPF_REG_SIZE;
7723 
7724 	if (is_iter_new_kfunc(meta)) {
7725 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7726 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7727 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7728 				iter_type_str(meta->btf, btf_id), regno);
7729 			return -EINVAL;
7730 		}
7731 
7732 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7733 			err = check_mem_access(env, insn_idx, regno,
7734 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7735 			if (err)
7736 				return err;
7737 		}
7738 
7739 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
7740 		if (err)
7741 			return err;
7742 	} else {
7743 		/* iter_next() or iter_destroy() expect initialized iter state*/
7744 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
7745 		switch (err) {
7746 		case 0:
7747 			break;
7748 		case -EINVAL:
7749 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7750 				iter_type_str(meta->btf, btf_id), regno);
7751 			return err;
7752 		case -EPROTO:
7753 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
7754 			return err;
7755 		default:
7756 			return err;
7757 		}
7758 
7759 		spi = iter_get_spi(env, reg, nr_slots);
7760 		if (spi < 0)
7761 			return spi;
7762 
7763 		err = mark_iter_read(env, reg, spi, nr_slots);
7764 		if (err)
7765 			return err;
7766 
7767 		/* remember meta->iter info for process_iter_next_call() */
7768 		meta->iter.spi = spi;
7769 		meta->iter.frameno = reg->frameno;
7770 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7771 
7772 		if (is_iter_destroy_kfunc(meta)) {
7773 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7774 			if (err)
7775 				return err;
7776 		}
7777 	}
7778 
7779 	return 0;
7780 }
7781 
7782 /* Look for a previous loop entry at insn_idx: nearest parent state
7783  * stopped at insn_idx with callsites matching those in cur->frame.
7784  */
7785 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7786 						  struct bpf_verifier_state *cur,
7787 						  int insn_idx)
7788 {
7789 	struct bpf_verifier_state_list *sl;
7790 	struct bpf_verifier_state *st;
7791 
7792 	/* Explored states are pushed in stack order, most recent states come first */
7793 	sl = *explored_state(env, insn_idx);
7794 	for (; sl; sl = sl->next) {
7795 		/* If st->branches != 0 state is a part of current DFS verification path,
7796 		 * hence cur & st for a loop.
7797 		 */
7798 		st = &sl->state;
7799 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7800 		    st->dfs_depth < cur->dfs_depth)
7801 			return st;
7802 	}
7803 
7804 	return NULL;
7805 }
7806 
7807 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7808 static bool regs_exact(const struct bpf_reg_state *rold,
7809 		       const struct bpf_reg_state *rcur,
7810 		       struct bpf_idmap *idmap);
7811 
7812 static void maybe_widen_reg(struct bpf_verifier_env *env,
7813 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7814 			    struct bpf_idmap *idmap)
7815 {
7816 	if (rold->type != SCALAR_VALUE)
7817 		return;
7818 	if (rold->type != rcur->type)
7819 		return;
7820 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7821 		return;
7822 	__mark_reg_unknown(env, rcur);
7823 }
7824 
7825 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7826 				   struct bpf_verifier_state *old,
7827 				   struct bpf_verifier_state *cur)
7828 {
7829 	struct bpf_func_state *fold, *fcur;
7830 	int i, fr;
7831 
7832 	reset_idmap_scratch(env);
7833 	for (fr = old->curframe; fr >= 0; fr--) {
7834 		fold = old->frame[fr];
7835 		fcur = cur->frame[fr];
7836 
7837 		for (i = 0; i < MAX_BPF_REG; i++)
7838 			maybe_widen_reg(env,
7839 					&fold->regs[i],
7840 					&fcur->regs[i],
7841 					&env->idmap_scratch);
7842 
7843 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7844 			if (!is_spilled_reg(&fold->stack[i]) ||
7845 			    !is_spilled_reg(&fcur->stack[i]))
7846 				continue;
7847 
7848 			maybe_widen_reg(env,
7849 					&fold->stack[i].spilled_ptr,
7850 					&fcur->stack[i].spilled_ptr,
7851 					&env->idmap_scratch);
7852 		}
7853 	}
7854 	return 0;
7855 }
7856 
7857 /* process_iter_next_call() is called when verifier gets to iterator's next
7858  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7859  * to it as just "iter_next()" in comments below.
7860  *
7861  * BPF verifier relies on a crucial contract for any iter_next()
7862  * implementation: it should *eventually* return NULL, and once that happens
7863  * it should keep returning NULL. That is, once iterator exhausts elements to
7864  * iterate, it should never reset or spuriously return new elements.
7865  *
7866  * With the assumption of such contract, process_iter_next_call() simulates
7867  * a fork in the verifier state to validate loop logic correctness and safety
7868  * without having to simulate infinite amount of iterations.
7869  *
7870  * In current state, we first assume that iter_next() returned NULL and
7871  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7872  * conditions we should not form an infinite loop and should eventually reach
7873  * exit.
7874  *
7875  * Besides that, we also fork current state and enqueue it for later
7876  * verification. In a forked state we keep iterator state as ACTIVE
7877  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7878  * also bump iteration depth to prevent erroneous infinite loop detection
7879  * later on (see iter_active_depths_differ() comment for details). In this
7880  * state we assume that we'll eventually loop back to another iter_next()
7881  * calls (it could be in exactly same location or in some other instruction,
7882  * it doesn't matter, we don't make any unnecessary assumptions about this,
7883  * everything revolves around iterator state in a stack slot, not which
7884  * instruction is calling iter_next()). When that happens, we either will come
7885  * to iter_next() with equivalent state and can conclude that next iteration
7886  * will proceed in exactly the same way as we just verified, so it's safe to
7887  * assume that loop converges. If not, we'll go on another iteration
7888  * simulation with a different input state, until all possible starting states
7889  * are validated or we reach maximum number of instructions limit.
7890  *
7891  * This way, we will either exhaustively discover all possible input states
7892  * that iterator loop can start with and eventually will converge, or we'll
7893  * effectively regress into bounded loop simulation logic and either reach
7894  * maximum number of instructions if loop is not provably convergent, or there
7895  * is some statically known limit on number of iterations (e.g., if there is
7896  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7897  *
7898  * Iteration convergence logic in is_state_visited() relies on exact
7899  * states comparison, which ignores read and precision marks.
7900  * This is necessary because read and precision marks are not finalized
7901  * while in the loop. Exact comparison might preclude convergence for
7902  * simple programs like below:
7903  *
7904  *     i = 0;
7905  *     while(iter_next(&it))
7906  *       i++;
7907  *
7908  * At each iteration step i++ would produce a new distinct state and
7909  * eventually instruction processing limit would be reached.
7910  *
7911  * To avoid such behavior speculatively forget (widen) range for
7912  * imprecise scalar registers, if those registers were not precise at the
7913  * end of the previous iteration and do not match exactly.
7914  *
7915  * This is a conservative heuristic that allows to verify wide range of programs,
7916  * however it precludes verification of programs that conjure an
7917  * imprecise value on the first loop iteration and use it as precise on a second.
7918  * For example, the following safe program would fail to verify:
7919  *
7920  *     struct bpf_num_iter it;
7921  *     int arr[10];
7922  *     int i = 0, a = 0;
7923  *     bpf_iter_num_new(&it, 0, 10);
7924  *     while (bpf_iter_num_next(&it)) {
7925  *       if (a == 0) {
7926  *         a = 1;
7927  *         i = 7; // Because i changed verifier would forget
7928  *                // it's range on second loop entry.
7929  *       } else {
7930  *         arr[i] = 42; // This would fail to verify.
7931  *       }
7932  *     }
7933  *     bpf_iter_num_destroy(&it);
7934  */
7935 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7936 				  struct bpf_kfunc_call_arg_meta *meta)
7937 {
7938 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7939 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7940 	struct bpf_reg_state *cur_iter, *queued_iter;
7941 	int iter_frameno = meta->iter.frameno;
7942 	int iter_spi = meta->iter.spi;
7943 
7944 	BTF_TYPE_EMIT(struct bpf_iter);
7945 
7946 	cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7947 
7948 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7949 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7950 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7951 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7952 		return -EFAULT;
7953 	}
7954 
7955 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7956 		/* Because iter_next() call is a checkpoint is_state_visitied()
7957 		 * should guarantee parent state with same call sites and insn_idx.
7958 		 */
7959 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7960 		    !same_callsites(cur_st->parent, cur_st)) {
7961 			verbose(env, "bug: bad parent state for iter next call");
7962 			return -EFAULT;
7963 		}
7964 		/* Note cur_st->parent in the call below, it is necessary to skip
7965 		 * checkpoint created for cur_st by is_state_visited()
7966 		 * right at this instruction.
7967 		 */
7968 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7969 		/* branch out active iter state */
7970 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7971 		if (!queued_st)
7972 			return -ENOMEM;
7973 
7974 		queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7975 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7976 		queued_iter->iter.depth++;
7977 		if (prev_st)
7978 			widen_imprecise_scalars(env, prev_st, queued_st);
7979 
7980 		queued_fr = queued_st->frame[queued_st->curframe];
7981 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7982 	}
7983 
7984 	/* switch to DRAINED state, but keep the depth unchanged */
7985 	/* mark current iter state as drained and assume returned NULL */
7986 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7987 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
7988 
7989 	return 0;
7990 }
7991 
7992 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7993 {
7994 	return type == ARG_CONST_SIZE ||
7995 	       type == ARG_CONST_SIZE_OR_ZERO;
7996 }
7997 
7998 static bool arg_type_is_release(enum bpf_arg_type type)
7999 {
8000 	return type & OBJ_RELEASE;
8001 }
8002 
8003 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8004 {
8005 	return base_type(type) == ARG_PTR_TO_DYNPTR;
8006 }
8007 
8008 static int int_ptr_type_to_size(enum bpf_arg_type type)
8009 {
8010 	if (type == ARG_PTR_TO_INT)
8011 		return sizeof(u32);
8012 	else if (type == ARG_PTR_TO_LONG)
8013 		return sizeof(u64);
8014 
8015 	return -EINVAL;
8016 }
8017 
8018 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8019 				 const struct bpf_call_arg_meta *meta,
8020 				 enum bpf_arg_type *arg_type)
8021 {
8022 	if (!meta->map_ptr) {
8023 		/* kernel subsystem misconfigured verifier */
8024 		verbose(env, "invalid map_ptr to access map->type\n");
8025 		return -EACCES;
8026 	}
8027 
8028 	switch (meta->map_ptr->map_type) {
8029 	case BPF_MAP_TYPE_SOCKMAP:
8030 	case BPF_MAP_TYPE_SOCKHASH:
8031 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8032 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8033 		} else {
8034 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8035 			return -EINVAL;
8036 		}
8037 		break;
8038 	case BPF_MAP_TYPE_BLOOM_FILTER:
8039 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8040 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8041 		break;
8042 	default:
8043 		break;
8044 	}
8045 	return 0;
8046 }
8047 
8048 struct bpf_reg_types {
8049 	const enum bpf_reg_type types[10];
8050 	u32 *btf_id;
8051 };
8052 
8053 static const struct bpf_reg_types sock_types = {
8054 	.types = {
8055 		PTR_TO_SOCK_COMMON,
8056 		PTR_TO_SOCKET,
8057 		PTR_TO_TCP_SOCK,
8058 		PTR_TO_XDP_SOCK,
8059 	},
8060 };
8061 
8062 #ifdef CONFIG_NET
8063 static const struct bpf_reg_types btf_id_sock_common_types = {
8064 	.types = {
8065 		PTR_TO_SOCK_COMMON,
8066 		PTR_TO_SOCKET,
8067 		PTR_TO_TCP_SOCK,
8068 		PTR_TO_XDP_SOCK,
8069 		PTR_TO_BTF_ID,
8070 		PTR_TO_BTF_ID | PTR_TRUSTED,
8071 	},
8072 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8073 };
8074 #endif
8075 
8076 static const struct bpf_reg_types mem_types = {
8077 	.types = {
8078 		PTR_TO_STACK,
8079 		PTR_TO_PACKET,
8080 		PTR_TO_PACKET_META,
8081 		PTR_TO_MAP_KEY,
8082 		PTR_TO_MAP_VALUE,
8083 		PTR_TO_MEM,
8084 		PTR_TO_MEM | MEM_RINGBUF,
8085 		PTR_TO_BUF,
8086 		PTR_TO_BTF_ID | PTR_TRUSTED,
8087 	},
8088 };
8089 
8090 static const struct bpf_reg_types int_ptr_types = {
8091 	.types = {
8092 		PTR_TO_STACK,
8093 		PTR_TO_PACKET,
8094 		PTR_TO_PACKET_META,
8095 		PTR_TO_MAP_KEY,
8096 		PTR_TO_MAP_VALUE,
8097 	},
8098 };
8099 
8100 static const struct bpf_reg_types spin_lock_types = {
8101 	.types = {
8102 		PTR_TO_MAP_VALUE,
8103 		PTR_TO_BTF_ID | MEM_ALLOC,
8104 	}
8105 };
8106 
8107 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8108 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8109 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8110 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8111 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8112 static const struct bpf_reg_types btf_ptr_types = {
8113 	.types = {
8114 		PTR_TO_BTF_ID,
8115 		PTR_TO_BTF_ID | PTR_TRUSTED,
8116 		PTR_TO_BTF_ID | MEM_RCU,
8117 	},
8118 };
8119 static const struct bpf_reg_types percpu_btf_ptr_types = {
8120 	.types = {
8121 		PTR_TO_BTF_ID | MEM_PERCPU,
8122 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8123 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8124 	}
8125 };
8126 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8127 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8128 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8129 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8130 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8131 static const struct bpf_reg_types dynptr_types = {
8132 	.types = {
8133 		PTR_TO_STACK,
8134 		CONST_PTR_TO_DYNPTR,
8135 	}
8136 };
8137 
8138 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8139 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8140 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8141 	[ARG_CONST_SIZE]		= &scalar_types,
8142 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8143 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8144 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8145 	[ARG_PTR_TO_CTX]		= &context_types,
8146 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8147 #ifdef CONFIG_NET
8148 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8149 #endif
8150 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8151 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8152 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8153 	[ARG_PTR_TO_MEM]		= &mem_types,
8154 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8155 	[ARG_PTR_TO_INT]		= &int_ptr_types,
8156 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
8157 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8158 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8159 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8160 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8161 	[ARG_PTR_TO_TIMER]		= &timer_types,
8162 	[ARG_PTR_TO_KPTR]		= &kptr_types,
8163 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8164 };
8165 
8166 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8167 			  enum bpf_arg_type arg_type,
8168 			  const u32 *arg_btf_id,
8169 			  struct bpf_call_arg_meta *meta)
8170 {
8171 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8172 	enum bpf_reg_type expected, type = reg->type;
8173 	const struct bpf_reg_types *compatible;
8174 	int i, j;
8175 
8176 	compatible = compatible_reg_types[base_type(arg_type)];
8177 	if (!compatible) {
8178 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8179 		return -EFAULT;
8180 	}
8181 
8182 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8183 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8184 	 *
8185 	 * Same for MAYBE_NULL:
8186 	 *
8187 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8188 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8189 	 *
8190 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8191 	 *
8192 	 * Therefore we fold these flags depending on the arg_type before comparison.
8193 	 */
8194 	if (arg_type & MEM_RDONLY)
8195 		type &= ~MEM_RDONLY;
8196 	if (arg_type & PTR_MAYBE_NULL)
8197 		type &= ~PTR_MAYBE_NULL;
8198 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8199 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8200 
8201 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) {
8202 		type &= ~MEM_ALLOC;
8203 		type &= ~MEM_PERCPU;
8204 	}
8205 
8206 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8207 		expected = compatible->types[i];
8208 		if (expected == NOT_INIT)
8209 			break;
8210 
8211 		if (type == expected)
8212 			goto found;
8213 	}
8214 
8215 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8216 	for (j = 0; j + 1 < i; j++)
8217 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8218 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8219 	return -EACCES;
8220 
8221 found:
8222 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8223 		return 0;
8224 
8225 	if (compatible == &mem_types) {
8226 		if (!(arg_type & MEM_RDONLY)) {
8227 			verbose(env,
8228 				"%s() may write into memory pointed by R%d type=%s\n",
8229 				func_id_name(meta->func_id),
8230 				regno, reg_type_str(env, reg->type));
8231 			return -EACCES;
8232 		}
8233 		return 0;
8234 	}
8235 
8236 	switch ((int)reg->type) {
8237 	case PTR_TO_BTF_ID:
8238 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8239 	case PTR_TO_BTF_ID | MEM_RCU:
8240 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8241 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8242 	{
8243 		/* For bpf_sk_release, it needs to match against first member
8244 		 * 'struct sock_common', hence make an exception for it. This
8245 		 * allows bpf_sk_release to work for multiple socket types.
8246 		 */
8247 		bool strict_type_match = arg_type_is_release(arg_type) &&
8248 					 meta->func_id != BPF_FUNC_sk_release;
8249 
8250 		if (type_may_be_null(reg->type) &&
8251 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8252 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8253 			return -EACCES;
8254 		}
8255 
8256 		if (!arg_btf_id) {
8257 			if (!compatible->btf_id) {
8258 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8259 				return -EFAULT;
8260 			}
8261 			arg_btf_id = compatible->btf_id;
8262 		}
8263 
8264 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8265 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8266 				return -EACCES;
8267 		} else {
8268 			if (arg_btf_id == BPF_PTR_POISON) {
8269 				verbose(env, "verifier internal error:");
8270 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8271 					regno);
8272 				return -EACCES;
8273 			}
8274 
8275 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8276 						  btf_vmlinux, *arg_btf_id,
8277 						  strict_type_match)) {
8278 				verbose(env, "R%d is of type %s but %s is expected\n",
8279 					regno, btf_type_name(reg->btf, reg->btf_id),
8280 					btf_type_name(btf_vmlinux, *arg_btf_id));
8281 				return -EACCES;
8282 			}
8283 		}
8284 		break;
8285 	}
8286 	case PTR_TO_BTF_ID | MEM_ALLOC:
8287 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8288 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8289 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8290 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8291 			return -EFAULT;
8292 		}
8293 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8294 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8295 				return -EACCES;
8296 		}
8297 		break;
8298 	case PTR_TO_BTF_ID | MEM_PERCPU:
8299 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8300 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8301 		/* Handled by helper specific checks */
8302 		break;
8303 	default:
8304 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8305 		return -EFAULT;
8306 	}
8307 	return 0;
8308 }
8309 
8310 static struct btf_field *
8311 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8312 {
8313 	struct btf_field *field;
8314 	struct btf_record *rec;
8315 
8316 	rec = reg_btf_record(reg);
8317 	if (!rec)
8318 		return NULL;
8319 
8320 	field = btf_record_find(rec, off, fields);
8321 	if (!field)
8322 		return NULL;
8323 
8324 	return field;
8325 }
8326 
8327 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8328 				  const struct bpf_reg_state *reg, int regno,
8329 				  enum bpf_arg_type arg_type)
8330 {
8331 	u32 type = reg->type;
8332 
8333 	/* When referenced register is passed to release function, its fixed
8334 	 * offset must be 0.
8335 	 *
8336 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8337 	 * meta->release_regno.
8338 	 */
8339 	if (arg_type_is_release(arg_type)) {
8340 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8341 		 * may not directly point to the object being released, but to
8342 		 * dynptr pointing to such object, which might be at some offset
8343 		 * on the stack. In that case, we simply to fallback to the
8344 		 * default handling.
8345 		 */
8346 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8347 			return 0;
8348 
8349 		/* Doing check_ptr_off_reg check for the offset will catch this
8350 		 * because fixed_off_ok is false, but checking here allows us
8351 		 * to give the user a better error message.
8352 		 */
8353 		if (reg->off) {
8354 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8355 				regno);
8356 			return -EINVAL;
8357 		}
8358 		return __check_ptr_off_reg(env, reg, regno, false);
8359 	}
8360 
8361 	switch (type) {
8362 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8363 	case PTR_TO_STACK:
8364 	case PTR_TO_PACKET:
8365 	case PTR_TO_PACKET_META:
8366 	case PTR_TO_MAP_KEY:
8367 	case PTR_TO_MAP_VALUE:
8368 	case PTR_TO_MEM:
8369 	case PTR_TO_MEM | MEM_RDONLY:
8370 	case PTR_TO_MEM | MEM_RINGBUF:
8371 	case PTR_TO_BUF:
8372 	case PTR_TO_BUF | MEM_RDONLY:
8373 	case SCALAR_VALUE:
8374 		return 0;
8375 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8376 	 * fixed offset.
8377 	 */
8378 	case PTR_TO_BTF_ID:
8379 	case PTR_TO_BTF_ID | MEM_ALLOC:
8380 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8381 	case PTR_TO_BTF_ID | MEM_RCU:
8382 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8383 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8384 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8385 		 * its fixed offset must be 0. In the other cases, fixed offset
8386 		 * can be non-zero. This was already checked above. So pass
8387 		 * fixed_off_ok as true to allow fixed offset for all other
8388 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8389 		 * still need to do checks instead of returning.
8390 		 */
8391 		return __check_ptr_off_reg(env, reg, regno, true);
8392 	default:
8393 		return __check_ptr_off_reg(env, reg, regno, false);
8394 	}
8395 }
8396 
8397 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8398 						const struct bpf_func_proto *fn,
8399 						struct bpf_reg_state *regs)
8400 {
8401 	struct bpf_reg_state *state = NULL;
8402 	int i;
8403 
8404 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8405 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8406 			if (state) {
8407 				verbose(env, "verifier internal error: multiple dynptr args\n");
8408 				return NULL;
8409 			}
8410 			state = &regs[BPF_REG_1 + i];
8411 		}
8412 
8413 	if (!state)
8414 		verbose(env, "verifier internal error: no dynptr arg found\n");
8415 
8416 	return state;
8417 }
8418 
8419 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8420 {
8421 	struct bpf_func_state *state = func(env, reg);
8422 	int spi;
8423 
8424 	if (reg->type == CONST_PTR_TO_DYNPTR)
8425 		return reg->id;
8426 	spi = dynptr_get_spi(env, reg);
8427 	if (spi < 0)
8428 		return spi;
8429 	return state->stack[spi].spilled_ptr.id;
8430 }
8431 
8432 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8433 {
8434 	struct bpf_func_state *state = func(env, reg);
8435 	int spi;
8436 
8437 	if (reg->type == CONST_PTR_TO_DYNPTR)
8438 		return reg->ref_obj_id;
8439 	spi = dynptr_get_spi(env, reg);
8440 	if (spi < 0)
8441 		return spi;
8442 	return state->stack[spi].spilled_ptr.ref_obj_id;
8443 }
8444 
8445 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8446 					    struct bpf_reg_state *reg)
8447 {
8448 	struct bpf_func_state *state = func(env, reg);
8449 	int spi;
8450 
8451 	if (reg->type == CONST_PTR_TO_DYNPTR)
8452 		return reg->dynptr.type;
8453 
8454 	spi = __get_spi(reg->off);
8455 	if (spi < 0) {
8456 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8457 		return BPF_DYNPTR_TYPE_INVALID;
8458 	}
8459 
8460 	return state->stack[spi].spilled_ptr.dynptr.type;
8461 }
8462 
8463 static int check_reg_const_str(struct bpf_verifier_env *env,
8464 			       struct bpf_reg_state *reg, u32 regno)
8465 {
8466 	struct bpf_map *map = reg->map_ptr;
8467 	int err;
8468 	int map_off;
8469 	u64 map_addr;
8470 	char *str_ptr;
8471 
8472 	if (reg->type != PTR_TO_MAP_VALUE)
8473 		return -EINVAL;
8474 
8475 	if (!bpf_map_is_rdonly(map)) {
8476 		verbose(env, "R%d does not point to a readonly map'\n", regno);
8477 		return -EACCES;
8478 	}
8479 
8480 	if (!tnum_is_const(reg->var_off)) {
8481 		verbose(env, "R%d is not a constant address'\n", regno);
8482 		return -EACCES;
8483 	}
8484 
8485 	if (!map->ops->map_direct_value_addr) {
8486 		verbose(env, "no direct value access support for this map type\n");
8487 		return -EACCES;
8488 	}
8489 
8490 	err = check_map_access(env, regno, reg->off,
8491 			       map->value_size - reg->off, false,
8492 			       ACCESS_HELPER);
8493 	if (err)
8494 		return err;
8495 
8496 	map_off = reg->off + reg->var_off.value;
8497 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8498 	if (err) {
8499 		verbose(env, "direct value access on string failed\n");
8500 		return err;
8501 	}
8502 
8503 	str_ptr = (char *)(long)(map_addr);
8504 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8505 		verbose(env, "string is not zero-terminated\n");
8506 		return -EINVAL;
8507 	}
8508 	return 0;
8509 }
8510 
8511 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8512 			  struct bpf_call_arg_meta *meta,
8513 			  const struct bpf_func_proto *fn,
8514 			  int insn_idx)
8515 {
8516 	u32 regno = BPF_REG_1 + arg;
8517 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8518 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8519 	enum bpf_reg_type type = reg->type;
8520 	u32 *arg_btf_id = NULL;
8521 	int err = 0;
8522 
8523 	if (arg_type == ARG_DONTCARE)
8524 		return 0;
8525 
8526 	err = check_reg_arg(env, regno, SRC_OP);
8527 	if (err)
8528 		return err;
8529 
8530 	if (arg_type == ARG_ANYTHING) {
8531 		if (is_pointer_value(env, regno)) {
8532 			verbose(env, "R%d leaks addr into helper function\n",
8533 				regno);
8534 			return -EACCES;
8535 		}
8536 		return 0;
8537 	}
8538 
8539 	if (type_is_pkt_pointer(type) &&
8540 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8541 		verbose(env, "helper access to the packet is not allowed\n");
8542 		return -EACCES;
8543 	}
8544 
8545 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8546 		err = resolve_map_arg_type(env, meta, &arg_type);
8547 		if (err)
8548 			return err;
8549 	}
8550 
8551 	if (register_is_null(reg) && type_may_be_null(arg_type))
8552 		/* A NULL register has a SCALAR_VALUE type, so skip
8553 		 * type checking.
8554 		 */
8555 		goto skip_type_check;
8556 
8557 	/* arg_btf_id and arg_size are in a union. */
8558 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8559 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8560 		arg_btf_id = fn->arg_btf_id[arg];
8561 
8562 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8563 	if (err)
8564 		return err;
8565 
8566 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8567 	if (err)
8568 		return err;
8569 
8570 skip_type_check:
8571 	if (arg_type_is_release(arg_type)) {
8572 		if (arg_type_is_dynptr(arg_type)) {
8573 			struct bpf_func_state *state = func(env, reg);
8574 			int spi;
8575 
8576 			/* Only dynptr created on stack can be released, thus
8577 			 * the get_spi and stack state checks for spilled_ptr
8578 			 * should only be done before process_dynptr_func for
8579 			 * PTR_TO_STACK.
8580 			 */
8581 			if (reg->type == PTR_TO_STACK) {
8582 				spi = dynptr_get_spi(env, reg);
8583 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8584 					verbose(env, "arg %d is an unacquired reference\n", regno);
8585 					return -EINVAL;
8586 				}
8587 			} else {
8588 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8589 				return -EINVAL;
8590 			}
8591 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8592 			verbose(env, "R%d must be referenced when passed to release function\n",
8593 				regno);
8594 			return -EINVAL;
8595 		}
8596 		if (meta->release_regno) {
8597 			verbose(env, "verifier internal error: more than one release argument\n");
8598 			return -EFAULT;
8599 		}
8600 		meta->release_regno = regno;
8601 	}
8602 
8603 	if (reg->ref_obj_id) {
8604 		if (meta->ref_obj_id) {
8605 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8606 				regno, reg->ref_obj_id,
8607 				meta->ref_obj_id);
8608 			return -EFAULT;
8609 		}
8610 		meta->ref_obj_id = reg->ref_obj_id;
8611 	}
8612 
8613 	switch (base_type(arg_type)) {
8614 	case ARG_CONST_MAP_PTR:
8615 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8616 		if (meta->map_ptr) {
8617 			/* Use map_uid (which is unique id of inner map) to reject:
8618 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8619 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8620 			 * if (inner_map1 && inner_map2) {
8621 			 *     timer = bpf_map_lookup_elem(inner_map1);
8622 			 *     if (timer)
8623 			 *         // mismatch would have been allowed
8624 			 *         bpf_timer_init(timer, inner_map2);
8625 			 * }
8626 			 *
8627 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8628 			 */
8629 			if (meta->map_ptr != reg->map_ptr ||
8630 			    meta->map_uid != reg->map_uid) {
8631 				verbose(env,
8632 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8633 					meta->map_uid, reg->map_uid);
8634 				return -EINVAL;
8635 			}
8636 		}
8637 		meta->map_ptr = reg->map_ptr;
8638 		meta->map_uid = reg->map_uid;
8639 		break;
8640 	case ARG_PTR_TO_MAP_KEY:
8641 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8642 		 * check that [key, key + map->key_size) are within
8643 		 * stack limits and initialized
8644 		 */
8645 		if (!meta->map_ptr) {
8646 			/* in function declaration map_ptr must come before
8647 			 * map_key, so that it's verified and known before
8648 			 * we have to check map_key here. Otherwise it means
8649 			 * that kernel subsystem misconfigured verifier
8650 			 */
8651 			verbose(env, "invalid map_ptr to access map->key\n");
8652 			return -EACCES;
8653 		}
8654 		err = check_helper_mem_access(env, regno,
8655 					      meta->map_ptr->key_size, false,
8656 					      NULL);
8657 		break;
8658 	case ARG_PTR_TO_MAP_VALUE:
8659 		if (type_may_be_null(arg_type) && register_is_null(reg))
8660 			return 0;
8661 
8662 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8663 		 * check [value, value + map->value_size) validity
8664 		 */
8665 		if (!meta->map_ptr) {
8666 			/* kernel subsystem misconfigured verifier */
8667 			verbose(env, "invalid map_ptr to access map->value\n");
8668 			return -EACCES;
8669 		}
8670 		meta->raw_mode = arg_type & MEM_UNINIT;
8671 		err = check_helper_mem_access(env, regno,
8672 					      meta->map_ptr->value_size, false,
8673 					      meta);
8674 		break;
8675 	case ARG_PTR_TO_PERCPU_BTF_ID:
8676 		if (!reg->btf_id) {
8677 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8678 			return -EACCES;
8679 		}
8680 		meta->ret_btf = reg->btf;
8681 		meta->ret_btf_id = reg->btf_id;
8682 		break;
8683 	case ARG_PTR_TO_SPIN_LOCK:
8684 		if (in_rbtree_lock_required_cb(env)) {
8685 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8686 			return -EACCES;
8687 		}
8688 		if (meta->func_id == BPF_FUNC_spin_lock) {
8689 			err = process_spin_lock(env, regno, true);
8690 			if (err)
8691 				return err;
8692 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8693 			err = process_spin_lock(env, regno, false);
8694 			if (err)
8695 				return err;
8696 		} else {
8697 			verbose(env, "verifier internal error\n");
8698 			return -EFAULT;
8699 		}
8700 		break;
8701 	case ARG_PTR_TO_TIMER:
8702 		err = process_timer_func(env, regno, meta);
8703 		if (err)
8704 			return err;
8705 		break;
8706 	case ARG_PTR_TO_FUNC:
8707 		meta->subprogno = reg->subprogno;
8708 		break;
8709 	case ARG_PTR_TO_MEM:
8710 		/* The access to this pointer is only checked when we hit the
8711 		 * next is_mem_size argument below.
8712 		 */
8713 		meta->raw_mode = arg_type & MEM_UNINIT;
8714 		if (arg_type & MEM_FIXED_SIZE) {
8715 			err = check_helper_mem_access(env, regno,
8716 						      fn->arg_size[arg], false,
8717 						      meta);
8718 		}
8719 		break;
8720 	case ARG_CONST_SIZE:
8721 		err = check_mem_size_reg(env, reg, regno, false, meta);
8722 		break;
8723 	case ARG_CONST_SIZE_OR_ZERO:
8724 		err = check_mem_size_reg(env, reg, regno, true, meta);
8725 		break;
8726 	case ARG_PTR_TO_DYNPTR:
8727 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8728 		if (err)
8729 			return err;
8730 		break;
8731 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8732 		if (!tnum_is_const(reg->var_off)) {
8733 			verbose(env, "R%d is not a known constant'\n",
8734 				regno);
8735 			return -EACCES;
8736 		}
8737 		meta->mem_size = reg->var_off.value;
8738 		err = mark_chain_precision(env, regno);
8739 		if (err)
8740 			return err;
8741 		break;
8742 	case ARG_PTR_TO_INT:
8743 	case ARG_PTR_TO_LONG:
8744 	{
8745 		int size = int_ptr_type_to_size(arg_type);
8746 
8747 		err = check_helper_mem_access(env, regno, size, false, meta);
8748 		if (err)
8749 			return err;
8750 		err = check_ptr_alignment(env, reg, 0, size, true);
8751 		break;
8752 	}
8753 	case ARG_PTR_TO_CONST_STR:
8754 	{
8755 		err = check_reg_const_str(env, reg, regno);
8756 		if (err)
8757 			return err;
8758 		break;
8759 	}
8760 	case ARG_PTR_TO_KPTR:
8761 		err = process_kptr_func(env, regno, meta);
8762 		if (err)
8763 			return err;
8764 		break;
8765 	}
8766 
8767 	return err;
8768 }
8769 
8770 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8771 {
8772 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8773 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8774 
8775 	if (func_id != BPF_FUNC_map_update_elem)
8776 		return false;
8777 
8778 	/* It's not possible to get access to a locked struct sock in these
8779 	 * contexts, so updating is safe.
8780 	 */
8781 	switch (type) {
8782 	case BPF_PROG_TYPE_TRACING:
8783 		if (eatype == BPF_TRACE_ITER)
8784 			return true;
8785 		break;
8786 	case BPF_PROG_TYPE_SOCKET_FILTER:
8787 	case BPF_PROG_TYPE_SCHED_CLS:
8788 	case BPF_PROG_TYPE_SCHED_ACT:
8789 	case BPF_PROG_TYPE_XDP:
8790 	case BPF_PROG_TYPE_SK_REUSEPORT:
8791 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8792 	case BPF_PROG_TYPE_SK_LOOKUP:
8793 		return true;
8794 	default:
8795 		break;
8796 	}
8797 
8798 	verbose(env, "cannot update sockmap in this context\n");
8799 	return false;
8800 }
8801 
8802 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8803 {
8804 	return env->prog->jit_requested &&
8805 	       bpf_jit_supports_subprog_tailcalls();
8806 }
8807 
8808 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8809 					struct bpf_map *map, int func_id)
8810 {
8811 	if (!map)
8812 		return 0;
8813 
8814 	/* We need a two way check, first is from map perspective ... */
8815 	switch (map->map_type) {
8816 	case BPF_MAP_TYPE_PROG_ARRAY:
8817 		if (func_id != BPF_FUNC_tail_call)
8818 			goto error;
8819 		break;
8820 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8821 		if (func_id != BPF_FUNC_perf_event_read &&
8822 		    func_id != BPF_FUNC_perf_event_output &&
8823 		    func_id != BPF_FUNC_skb_output &&
8824 		    func_id != BPF_FUNC_perf_event_read_value &&
8825 		    func_id != BPF_FUNC_xdp_output)
8826 			goto error;
8827 		break;
8828 	case BPF_MAP_TYPE_RINGBUF:
8829 		if (func_id != BPF_FUNC_ringbuf_output &&
8830 		    func_id != BPF_FUNC_ringbuf_reserve &&
8831 		    func_id != BPF_FUNC_ringbuf_query &&
8832 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8833 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8834 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8835 			goto error;
8836 		break;
8837 	case BPF_MAP_TYPE_USER_RINGBUF:
8838 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8839 			goto error;
8840 		break;
8841 	case BPF_MAP_TYPE_STACK_TRACE:
8842 		if (func_id != BPF_FUNC_get_stackid)
8843 			goto error;
8844 		break;
8845 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8846 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8847 		    func_id != BPF_FUNC_current_task_under_cgroup)
8848 			goto error;
8849 		break;
8850 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8851 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8852 		if (func_id != BPF_FUNC_get_local_storage)
8853 			goto error;
8854 		break;
8855 	case BPF_MAP_TYPE_DEVMAP:
8856 	case BPF_MAP_TYPE_DEVMAP_HASH:
8857 		if (func_id != BPF_FUNC_redirect_map &&
8858 		    func_id != BPF_FUNC_map_lookup_elem)
8859 			goto error;
8860 		break;
8861 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8862 	 * appear.
8863 	 */
8864 	case BPF_MAP_TYPE_CPUMAP:
8865 		if (func_id != BPF_FUNC_redirect_map)
8866 			goto error;
8867 		break;
8868 	case BPF_MAP_TYPE_XSKMAP:
8869 		if (func_id != BPF_FUNC_redirect_map &&
8870 		    func_id != BPF_FUNC_map_lookup_elem)
8871 			goto error;
8872 		break;
8873 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8874 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8875 		if (func_id != BPF_FUNC_map_lookup_elem)
8876 			goto error;
8877 		break;
8878 	case BPF_MAP_TYPE_SOCKMAP:
8879 		if (func_id != BPF_FUNC_sk_redirect_map &&
8880 		    func_id != BPF_FUNC_sock_map_update &&
8881 		    func_id != BPF_FUNC_map_delete_elem &&
8882 		    func_id != BPF_FUNC_msg_redirect_map &&
8883 		    func_id != BPF_FUNC_sk_select_reuseport &&
8884 		    func_id != BPF_FUNC_map_lookup_elem &&
8885 		    !may_update_sockmap(env, func_id))
8886 			goto error;
8887 		break;
8888 	case BPF_MAP_TYPE_SOCKHASH:
8889 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8890 		    func_id != BPF_FUNC_sock_hash_update &&
8891 		    func_id != BPF_FUNC_map_delete_elem &&
8892 		    func_id != BPF_FUNC_msg_redirect_hash &&
8893 		    func_id != BPF_FUNC_sk_select_reuseport &&
8894 		    func_id != BPF_FUNC_map_lookup_elem &&
8895 		    !may_update_sockmap(env, func_id))
8896 			goto error;
8897 		break;
8898 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8899 		if (func_id != BPF_FUNC_sk_select_reuseport)
8900 			goto error;
8901 		break;
8902 	case BPF_MAP_TYPE_QUEUE:
8903 	case BPF_MAP_TYPE_STACK:
8904 		if (func_id != BPF_FUNC_map_peek_elem &&
8905 		    func_id != BPF_FUNC_map_pop_elem &&
8906 		    func_id != BPF_FUNC_map_push_elem)
8907 			goto error;
8908 		break;
8909 	case BPF_MAP_TYPE_SK_STORAGE:
8910 		if (func_id != BPF_FUNC_sk_storage_get &&
8911 		    func_id != BPF_FUNC_sk_storage_delete &&
8912 		    func_id != BPF_FUNC_kptr_xchg)
8913 			goto error;
8914 		break;
8915 	case BPF_MAP_TYPE_INODE_STORAGE:
8916 		if (func_id != BPF_FUNC_inode_storage_get &&
8917 		    func_id != BPF_FUNC_inode_storage_delete &&
8918 		    func_id != BPF_FUNC_kptr_xchg)
8919 			goto error;
8920 		break;
8921 	case BPF_MAP_TYPE_TASK_STORAGE:
8922 		if (func_id != BPF_FUNC_task_storage_get &&
8923 		    func_id != BPF_FUNC_task_storage_delete &&
8924 		    func_id != BPF_FUNC_kptr_xchg)
8925 			goto error;
8926 		break;
8927 	case BPF_MAP_TYPE_CGRP_STORAGE:
8928 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8929 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8930 		    func_id != BPF_FUNC_kptr_xchg)
8931 			goto error;
8932 		break;
8933 	case BPF_MAP_TYPE_BLOOM_FILTER:
8934 		if (func_id != BPF_FUNC_map_peek_elem &&
8935 		    func_id != BPF_FUNC_map_push_elem)
8936 			goto error;
8937 		break;
8938 	default:
8939 		break;
8940 	}
8941 
8942 	/* ... and second from the function itself. */
8943 	switch (func_id) {
8944 	case BPF_FUNC_tail_call:
8945 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8946 			goto error;
8947 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8948 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8949 			return -EINVAL;
8950 		}
8951 		break;
8952 	case BPF_FUNC_perf_event_read:
8953 	case BPF_FUNC_perf_event_output:
8954 	case BPF_FUNC_perf_event_read_value:
8955 	case BPF_FUNC_skb_output:
8956 	case BPF_FUNC_xdp_output:
8957 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8958 			goto error;
8959 		break;
8960 	case BPF_FUNC_ringbuf_output:
8961 	case BPF_FUNC_ringbuf_reserve:
8962 	case BPF_FUNC_ringbuf_query:
8963 	case BPF_FUNC_ringbuf_reserve_dynptr:
8964 	case BPF_FUNC_ringbuf_submit_dynptr:
8965 	case BPF_FUNC_ringbuf_discard_dynptr:
8966 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8967 			goto error;
8968 		break;
8969 	case BPF_FUNC_user_ringbuf_drain:
8970 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8971 			goto error;
8972 		break;
8973 	case BPF_FUNC_get_stackid:
8974 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8975 			goto error;
8976 		break;
8977 	case BPF_FUNC_current_task_under_cgroup:
8978 	case BPF_FUNC_skb_under_cgroup:
8979 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8980 			goto error;
8981 		break;
8982 	case BPF_FUNC_redirect_map:
8983 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8984 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8985 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8986 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8987 			goto error;
8988 		break;
8989 	case BPF_FUNC_sk_redirect_map:
8990 	case BPF_FUNC_msg_redirect_map:
8991 	case BPF_FUNC_sock_map_update:
8992 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8993 			goto error;
8994 		break;
8995 	case BPF_FUNC_sk_redirect_hash:
8996 	case BPF_FUNC_msg_redirect_hash:
8997 	case BPF_FUNC_sock_hash_update:
8998 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8999 			goto error;
9000 		break;
9001 	case BPF_FUNC_get_local_storage:
9002 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
9003 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
9004 			goto error;
9005 		break;
9006 	case BPF_FUNC_sk_select_reuseport:
9007 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
9008 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
9009 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
9010 			goto error;
9011 		break;
9012 	case BPF_FUNC_map_pop_elem:
9013 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9014 		    map->map_type != BPF_MAP_TYPE_STACK)
9015 			goto error;
9016 		break;
9017 	case BPF_FUNC_map_peek_elem:
9018 	case BPF_FUNC_map_push_elem:
9019 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9020 		    map->map_type != BPF_MAP_TYPE_STACK &&
9021 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9022 			goto error;
9023 		break;
9024 	case BPF_FUNC_map_lookup_percpu_elem:
9025 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9026 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9027 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9028 			goto error;
9029 		break;
9030 	case BPF_FUNC_sk_storage_get:
9031 	case BPF_FUNC_sk_storage_delete:
9032 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9033 			goto error;
9034 		break;
9035 	case BPF_FUNC_inode_storage_get:
9036 	case BPF_FUNC_inode_storage_delete:
9037 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9038 			goto error;
9039 		break;
9040 	case BPF_FUNC_task_storage_get:
9041 	case BPF_FUNC_task_storage_delete:
9042 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9043 			goto error;
9044 		break;
9045 	case BPF_FUNC_cgrp_storage_get:
9046 	case BPF_FUNC_cgrp_storage_delete:
9047 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9048 			goto error;
9049 		break;
9050 	default:
9051 		break;
9052 	}
9053 
9054 	return 0;
9055 error:
9056 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9057 		map->map_type, func_id_name(func_id), func_id);
9058 	return -EINVAL;
9059 }
9060 
9061 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9062 {
9063 	int count = 0;
9064 
9065 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
9066 		count++;
9067 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
9068 		count++;
9069 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
9070 		count++;
9071 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
9072 		count++;
9073 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9074 		count++;
9075 
9076 	/* We only support one arg being in raw mode at the moment,
9077 	 * which is sufficient for the helper functions we have
9078 	 * right now.
9079 	 */
9080 	return count <= 1;
9081 }
9082 
9083 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9084 {
9085 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9086 	bool has_size = fn->arg_size[arg] != 0;
9087 	bool is_next_size = false;
9088 
9089 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9090 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9091 
9092 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9093 		return is_next_size;
9094 
9095 	return has_size == is_next_size || is_next_size == is_fixed;
9096 }
9097 
9098 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9099 {
9100 	/* bpf_xxx(..., buf, len) call will access 'len'
9101 	 * bytes from memory 'buf'. Both arg types need
9102 	 * to be paired, so make sure there's no buggy
9103 	 * helper function specification.
9104 	 */
9105 	if (arg_type_is_mem_size(fn->arg1_type) ||
9106 	    check_args_pair_invalid(fn, 0) ||
9107 	    check_args_pair_invalid(fn, 1) ||
9108 	    check_args_pair_invalid(fn, 2) ||
9109 	    check_args_pair_invalid(fn, 3) ||
9110 	    check_args_pair_invalid(fn, 4))
9111 		return false;
9112 
9113 	return true;
9114 }
9115 
9116 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9117 {
9118 	int i;
9119 
9120 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9121 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9122 			return !!fn->arg_btf_id[i];
9123 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9124 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9125 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9126 		    /* arg_btf_id and arg_size are in a union. */
9127 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9128 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9129 			return false;
9130 	}
9131 
9132 	return true;
9133 }
9134 
9135 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9136 {
9137 	return check_raw_mode_ok(fn) &&
9138 	       check_arg_pair_ok(fn) &&
9139 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9140 }
9141 
9142 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9143  * are now invalid, so turn them into unknown SCALAR_VALUE.
9144  *
9145  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9146  * since these slices point to packet data.
9147  */
9148 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9149 {
9150 	struct bpf_func_state *state;
9151 	struct bpf_reg_state *reg;
9152 
9153 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9154 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9155 			mark_reg_invalid(env, reg);
9156 	}));
9157 }
9158 
9159 enum {
9160 	AT_PKT_END = -1,
9161 	BEYOND_PKT_END = -2,
9162 };
9163 
9164 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9165 {
9166 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9167 	struct bpf_reg_state *reg = &state->regs[regn];
9168 
9169 	if (reg->type != PTR_TO_PACKET)
9170 		/* PTR_TO_PACKET_META is not supported yet */
9171 		return;
9172 
9173 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9174 	 * How far beyond pkt_end it goes is unknown.
9175 	 * if (!range_open) it's the case of pkt >= pkt_end
9176 	 * if (range_open) it's the case of pkt > pkt_end
9177 	 * hence this pointer is at least 1 byte bigger than pkt_end
9178 	 */
9179 	if (range_open)
9180 		reg->range = BEYOND_PKT_END;
9181 	else
9182 		reg->range = AT_PKT_END;
9183 }
9184 
9185 /* The pointer with the specified id has released its reference to kernel
9186  * resources. Identify all copies of the same pointer and clear the reference.
9187  */
9188 static int release_reference(struct bpf_verifier_env *env,
9189 			     int ref_obj_id)
9190 {
9191 	struct bpf_func_state *state;
9192 	struct bpf_reg_state *reg;
9193 	int err;
9194 
9195 	err = release_reference_state(cur_func(env), ref_obj_id);
9196 	if (err)
9197 		return err;
9198 
9199 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9200 		if (reg->ref_obj_id == ref_obj_id)
9201 			mark_reg_invalid(env, reg);
9202 	}));
9203 
9204 	return 0;
9205 }
9206 
9207 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9208 {
9209 	struct bpf_func_state *unused;
9210 	struct bpf_reg_state *reg;
9211 
9212 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9213 		if (type_is_non_owning_ref(reg->type))
9214 			mark_reg_invalid(env, reg);
9215 	}));
9216 }
9217 
9218 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9219 				    struct bpf_reg_state *regs)
9220 {
9221 	int i;
9222 
9223 	/* after the call registers r0 - r5 were scratched */
9224 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9225 		mark_reg_not_init(env, regs, caller_saved[i]);
9226 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9227 	}
9228 }
9229 
9230 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9231 				   struct bpf_func_state *caller,
9232 				   struct bpf_func_state *callee,
9233 				   int insn_idx);
9234 
9235 static int set_callee_state(struct bpf_verifier_env *env,
9236 			    struct bpf_func_state *caller,
9237 			    struct bpf_func_state *callee, int insn_idx);
9238 
9239 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9240 			    set_callee_state_fn set_callee_state_cb,
9241 			    struct bpf_verifier_state *state)
9242 {
9243 	struct bpf_func_state *caller, *callee;
9244 	int err;
9245 
9246 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9247 		verbose(env, "the call stack of %d frames is too deep\n",
9248 			state->curframe + 2);
9249 		return -E2BIG;
9250 	}
9251 
9252 	if (state->frame[state->curframe + 1]) {
9253 		verbose(env, "verifier bug. Frame %d already allocated\n",
9254 			state->curframe + 1);
9255 		return -EFAULT;
9256 	}
9257 
9258 	caller = state->frame[state->curframe];
9259 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9260 	if (!callee)
9261 		return -ENOMEM;
9262 	state->frame[state->curframe + 1] = callee;
9263 
9264 	/* callee cannot access r0, r6 - r9 for reading and has to write
9265 	 * into its own stack before reading from it.
9266 	 * callee can read/write into caller's stack
9267 	 */
9268 	init_func_state(env, callee,
9269 			/* remember the callsite, it will be used by bpf_exit */
9270 			callsite,
9271 			state->curframe + 1 /* frameno within this callchain */,
9272 			subprog /* subprog number within this prog */);
9273 	/* Transfer references to the callee */
9274 	err = copy_reference_state(callee, caller);
9275 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9276 	if (err)
9277 		goto err_out;
9278 
9279 	/* only increment it after check_reg_arg() finished */
9280 	state->curframe++;
9281 
9282 	return 0;
9283 
9284 err_out:
9285 	free_func_state(callee);
9286 	state->frame[state->curframe + 1] = NULL;
9287 	return err;
9288 }
9289 
9290 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
9291 				    const struct btf *btf,
9292 				    struct bpf_reg_state *regs)
9293 {
9294 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
9295 	struct bpf_verifier_log *log = &env->log;
9296 	u32 i;
9297 	int ret;
9298 
9299 	ret = btf_prepare_func_args(env, subprog);
9300 	if (ret)
9301 		return ret;
9302 
9303 	/* check that BTF function arguments match actual types that the
9304 	 * verifier sees.
9305 	 */
9306 	for (i = 0; i < sub->arg_cnt; i++) {
9307 		u32 regno = i + 1;
9308 		struct bpf_reg_state *reg = &regs[regno];
9309 		struct bpf_subprog_arg_info *arg = &sub->args[i];
9310 
9311 		if (arg->arg_type == ARG_ANYTHING) {
9312 			if (reg->type != SCALAR_VALUE) {
9313 				bpf_log(log, "R%d is not a scalar\n", regno);
9314 				return -EINVAL;
9315 			}
9316 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
9317 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9318 			if (ret < 0)
9319 				return ret;
9320 			/* If function expects ctx type in BTF check that caller
9321 			 * is passing PTR_TO_CTX.
9322 			 */
9323 			if (reg->type != PTR_TO_CTX) {
9324 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
9325 				return -EINVAL;
9326 			}
9327 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
9328 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9329 			if (ret < 0)
9330 				return ret;
9331 			if (check_mem_reg(env, reg, regno, arg->mem_size))
9332 				return -EINVAL;
9333 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
9334 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
9335 				return -EINVAL;
9336 			}
9337 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
9338 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
9339 			if (ret)
9340 				return ret;
9341 		} else {
9342 			bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n",
9343 				i, arg->arg_type);
9344 			return -EFAULT;
9345 		}
9346 	}
9347 
9348 	return 0;
9349 }
9350 
9351 /* Compare BTF of a function call with given bpf_reg_state.
9352  * Returns:
9353  * EFAULT - there is a verifier bug. Abort verification.
9354  * EINVAL - there is a type mismatch or BTF is not available.
9355  * 0 - BTF matches with what bpf_reg_state expects.
9356  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
9357  */
9358 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
9359 				  struct bpf_reg_state *regs)
9360 {
9361 	struct bpf_prog *prog = env->prog;
9362 	struct btf *btf = prog->aux->btf;
9363 	u32 btf_id;
9364 	int err;
9365 
9366 	if (!prog->aux->func_info)
9367 		return -EINVAL;
9368 
9369 	btf_id = prog->aux->func_info[subprog].type_id;
9370 	if (!btf_id)
9371 		return -EFAULT;
9372 
9373 	if (prog->aux->func_info_aux[subprog].unreliable)
9374 		return -EINVAL;
9375 
9376 	err = btf_check_func_arg_match(env, subprog, btf, regs);
9377 	/* Compiler optimizations can remove arguments from static functions
9378 	 * or mismatched type can be passed into a global function.
9379 	 * In such cases mark the function as unreliable from BTF point of view.
9380 	 */
9381 	if (err)
9382 		prog->aux->func_info_aux[subprog].unreliable = true;
9383 	return err;
9384 }
9385 
9386 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9387 			      int insn_idx, int subprog,
9388 			      set_callee_state_fn set_callee_state_cb)
9389 {
9390 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9391 	struct bpf_func_state *caller, *callee;
9392 	int err;
9393 
9394 	caller = state->frame[state->curframe];
9395 	err = btf_check_subprog_call(env, subprog, caller->regs);
9396 	if (err == -EFAULT)
9397 		return err;
9398 
9399 	/* set_callee_state is used for direct subprog calls, but we are
9400 	 * interested in validating only BPF helpers that can call subprogs as
9401 	 * callbacks
9402 	 */
9403 	env->subprog_info[subprog].is_cb = true;
9404 	if (bpf_pseudo_kfunc_call(insn) &&
9405 	    !is_sync_callback_calling_kfunc(insn->imm)) {
9406 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9407 			func_id_name(insn->imm), insn->imm);
9408 		return -EFAULT;
9409 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9410 		   !is_callback_calling_function(insn->imm)) { /* helper */
9411 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9412 			func_id_name(insn->imm), insn->imm);
9413 		return -EFAULT;
9414 	}
9415 
9416 	if (insn->code == (BPF_JMP | BPF_CALL) &&
9417 	    insn->src_reg == 0 &&
9418 	    insn->imm == BPF_FUNC_timer_set_callback) {
9419 		struct bpf_verifier_state *async_cb;
9420 
9421 		/* there is no real recursion here. timer callbacks are async */
9422 		env->subprog_info[subprog].is_async_cb = true;
9423 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9424 					 insn_idx, subprog);
9425 		if (!async_cb)
9426 			return -EFAULT;
9427 		callee = async_cb->frame[0];
9428 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9429 
9430 		/* Convert bpf_timer_set_callback() args into timer callback args */
9431 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9432 		if (err)
9433 			return err;
9434 
9435 		return 0;
9436 	}
9437 
9438 	/* for callback functions enqueue entry to callback and
9439 	 * proceed with next instruction within current frame.
9440 	 */
9441 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9442 	if (!callback_state)
9443 		return -ENOMEM;
9444 
9445 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9446 			       callback_state);
9447 	if (err)
9448 		return err;
9449 
9450 	callback_state->callback_unroll_depth++;
9451 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9452 	caller->callback_depth = 0;
9453 	return 0;
9454 }
9455 
9456 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9457 			   int *insn_idx)
9458 {
9459 	struct bpf_verifier_state *state = env->cur_state;
9460 	struct bpf_func_state *caller;
9461 	int err, subprog, target_insn;
9462 
9463 	target_insn = *insn_idx + insn->imm + 1;
9464 	subprog = find_subprog(env, target_insn);
9465 	if (subprog < 0) {
9466 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9467 		return -EFAULT;
9468 	}
9469 
9470 	caller = state->frame[state->curframe];
9471 	err = btf_check_subprog_call(env, subprog, caller->regs);
9472 	if (err == -EFAULT)
9473 		return err;
9474 	if (subprog_is_global(env, subprog)) {
9475 		const char *sub_name = subprog_name(env, subprog);
9476 
9477 		if (err) {
9478 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
9479 				subprog, sub_name);
9480 			return err;
9481 		}
9482 
9483 		verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
9484 			subprog, sub_name);
9485 		/* mark global subprog for verifying after main prog */
9486 		subprog_aux(env, subprog)->called = true;
9487 		clear_caller_saved_regs(env, caller->regs);
9488 
9489 		/* All global functions return a 64-bit SCALAR_VALUE */
9490 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9491 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9492 
9493 		/* continue with next insn after call */
9494 		return 0;
9495 	}
9496 
9497 	/* for regular function entry setup new frame and continue
9498 	 * from that frame.
9499 	 */
9500 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9501 	if (err)
9502 		return err;
9503 
9504 	clear_caller_saved_regs(env, caller->regs);
9505 
9506 	/* and go analyze first insn of the callee */
9507 	*insn_idx = env->subprog_info[subprog].start - 1;
9508 
9509 	if (env->log.level & BPF_LOG_LEVEL) {
9510 		verbose(env, "caller:\n");
9511 		print_verifier_state(env, caller, true);
9512 		verbose(env, "callee:\n");
9513 		print_verifier_state(env, state->frame[state->curframe], true);
9514 	}
9515 
9516 	return 0;
9517 }
9518 
9519 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9520 				   struct bpf_func_state *caller,
9521 				   struct bpf_func_state *callee)
9522 {
9523 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9524 	 *      void *callback_ctx, u64 flags);
9525 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9526 	 *      void *callback_ctx);
9527 	 */
9528 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9529 
9530 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9531 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9532 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9533 
9534 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9535 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9536 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9537 
9538 	/* pointer to stack or null */
9539 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9540 
9541 	/* unused */
9542 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9543 	return 0;
9544 }
9545 
9546 static int set_callee_state(struct bpf_verifier_env *env,
9547 			    struct bpf_func_state *caller,
9548 			    struct bpf_func_state *callee, int insn_idx)
9549 {
9550 	int i;
9551 
9552 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9553 	 * pointers, which connects us up to the liveness chain
9554 	 */
9555 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9556 		callee->regs[i] = caller->regs[i];
9557 	return 0;
9558 }
9559 
9560 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9561 				       struct bpf_func_state *caller,
9562 				       struct bpf_func_state *callee,
9563 				       int insn_idx)
9564 {
9565 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9566 	struct bpf_map *map;
9567 	int err;
9568 
9569 	if (bpf_map_ptr_poisoned(insn_aux)) {
9570 		verbose(env, "tail_call abusing map_ptr\n");
9571 		return -EINVAL;
9572 	}
9573 
9574 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9575 	if (!map->ops->map_set_for_each_callback_args ||
9576 	    !map->ops->map_for_each_callback) {
9577 		verbose(env, "callback function not allowed for map\n");
9578 		return -ENOTSUPP;
9579 	}
9580 
9581 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9582 	if (err)
9583 		return err;
9584 
9585 	callee->in_callback_fn = true;
9586 	callee->callback_ret_range = retval_range(0, 1);
9587 	return 0;
9588 }
9589 
9590 static int set_loop_callback_state(struct bpf_verifier_env *env,
9591 				   struct bpf_func_state *caller,
9592 				   struct bpf_func_state *callee,
9593 				   int insn_idx)
9594 {
9595 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9596 	 *	    u64 flags);
9597 	 * callback_fn(u32 index, void *callback_ctx);
9598 	 */
9599 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9600 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9601 
9602 	/* unused */
9603 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9604 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9605 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9606 
9607 	callee->in_callback_fn = true;
9608 	callee->callback_ret_range = retval_range(0, 1);
9609 	return 0;
9610 }
9611 
9612 static int set_timer_callback_state(struct bpf_verifier_env *env,
9613 				    struct bpf_func_state *caller,
9614 				    struct bpf_func_state *callee,
9615 				    int insn_idx)
9616 {
9617 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9618 
9619 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9620 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9621 	 */
9622 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9623 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9624 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9625 
9626 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9627 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9628 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9629 
9630 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9631 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9632 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9633 
9634 	/* unused */
9635 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9636 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9637 	callee->in_async_callback_fn = true;
9638 	callee->callback_ret_range = retval_range(0, 1);
9639 	return 0;
9640 }
9641 
9642 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9643 				       struct bpf_func_state *caller,
9644 				       struct bpf_func_state *callee,
9645 				       int insn_idx)
9646 {
9647 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9648 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9649 	 * (callback_fn)(struct task_struct *task,
9650 	 *               struct vm_area_struct *vma, void *callback_ctx);
9651 	 */
9652 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9653 
9654 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9655 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9656 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9657 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
9658 
9659 	/* pointer to stack or null */
9660 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9661 
9662 	/* unused */
9663 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9664 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9665 	callee->in_callback_fn = true;
9666 	callee->callback_ret_range = retval_range(0, 1);
9667 	return 0;
9668 }
9669 
9670 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9671 					   struct bpf_func_state *caller,
9672 					   struct bpf_func_state *callee,
9673 					   int insn_idx)
9674 {
9675 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9676 	 *			  callback_ctx, u64 flags);
9677 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9678 	 */
9679 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9680 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9681 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9682 
9683 	/* unused */
9684 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9685 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9686 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9687 
9688 	callee->in_callback_fn = true;
9689 	callee->callback_ret_range = retval_range(0, 1);
9690 	return 0;
9691 }
9692 
9693 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9694 					 struct bpf_func_state *caller,
9695 					 struct bpf_func_state *callee,
9696 					 int insn_idx)
9697 {
9698 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9699 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9700 	 *
9701 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9702 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9703 	 * by this point, so look at 'root'
9704 	 */
9705 	struct btf_field *field;
9706 
9707 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9708 				      BPF_RB_ROOT);
9709 	if (!field || !field->graph_root.value_btf_id)
9710 		return -EFAULT;
9711 
9712 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9713 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9714 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9715 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9716 
9717 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9718 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9719 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9720 	callee->in_callback_fn = true;
9721 	callee->callback_ret_range = retval_range(0, 1);
9722 	return 0;
9723 }
9724 
9725 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9726 
9727 /* Are we currently verifying the callback for a rbtree helper that must
9728  * be called with lock held? If so, no need to complain about unreleased
9729  * lock
9730  */
9731 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9732 {
9733 	struct bpf_verifier_state *state = env->cur_state;
9734 	struct bpf_insn *insn = env->prog->insnsi;
9735 	struct bpf_func_state *callee;
9736 	int kfunc_btf_id;
9737 
9738 	if (!state->curframe)
9739 		return false;
9740 
9741 	callee = state->frame[state->curframe];
9742 
9743 	if (!callee->in_callback_fn)
9744 		return false;
9745 
9746 	kfunc_btf_id = insn[callee->callsite].imm;
9747 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9748 }
9749 
9750 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg)
9751 {
9752 	return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
9753 }
9754 
9755 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9756 {
9757 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9758 	struct bpf_func_state *caller, *callee;
9759 	struct bpf_reg_state *r0;
9760 	bool in_callback_fn;
9761 	int err;
9762 
9763 	callee = state->frame[state->curframe];
9764 	r0 = &callee->regs[BPF_REG_0];
9765 	if (r0->type == PTR_TO_STACK) {
9766 		/* technically it's ok to return caller's stack pointer
9767 		 * (or caller's caller's pointer) back to the caller,
9768 		 * since these pointers are valid. Only current stack
9769 		 * pointer will be invalid as soon as function exits,
9770 		 * but let's be conservative
9771 		 */
9772 		verbose(env, "cannot return stack pointer to the caller\n");
9773 		return -EINVAL;
9774 	}
9775 
9776 	caller = state->frame[state->curframe - 1];
9777 	if (callee->in_callback_fn) {
9778 		if (r0->type != SCALAR_VALUE) {
9779 			verbose(env, "R0 not a scalar value\n");
9780 			return -EACCES;
9781 		}
9782 
9783 		/* we are going to rely on register's precise value */
9784 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9785 		err = err ?: mark_chain_precision(env, BPF_REG_0);
9786 		if (err)
9787 			return err;
9788 
9789 		/* enforce R0 return value range */
9790 		if (!retval_range_within(callee->callback_ret_range, r0)) {
9791 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
9792 					       "At callback return", "R0");
9793 			return -EINVAL;
9794 		}
9795 		if (!calls_callback(env, callee->callsite)) {
9796 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9797 				*insn_idx, callee->callsite);
9798 			return -EFAULT;
9799 		}
9800 	} else {
9801 		/* return to the caller whatever r0 had in the callee */
9802 		caller->regs[BPF_REG_0] = *r0;
9803 	}
9804 
9805 	/* callback_fn frame should have released its own additions to parent's
9806 	 * reference state at this point, or check_reference_leak would
9807 	 * complain, hence it must be the same as the caller. There is no need
9808 	 * to copy it back.
9809 	 */
9810 	if (!callee->in_callback_fn) {
9811 		/* Transfer references to the caller */
9812 		err = copy_reference_state(caller, callee);
9813 		if (err)
9814 			return err;
9815 	}
9816 
9817 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9818 	 * there function call logic would reschedule callback visit. If iteration
9819 	 * converges is_state_visited() would prune that visit eventually.
9820 	 */
9821 	in_callback_fn = callee->in_callback_fn;
9822 	if (in_callback_fn)
9823 		*insn_idx = callee->callsite;
9824 	else
9825 		*insn_idx = callee->callsite + 1;
9826 
9827 	if (env->log.level & BPF_LOG_LEVEL) {
9828 		verbose(env, "returning from callee:\n");
9829 		print_verifier_state(env, callee, true);
9830 		verbose(env, "to caller at %d:\n", *insn_idx);
9831 		print_verifier_state(env, caller, true);
9832 	}
9833 	/* clear everything in the callee. In case of exceptional exits using
9834 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
9835 	free_func_state(callee);
9836 	state->frame[state->curframe--] = NULL;
9837 
9838 	/* for callbacks widen imprecise scalars to make programs like below verify:
9839 	 *
9840 	 *   struct ctx { int i; }
9841 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9842 	 *   ...
9843 	 *   struct ctx = { .i = 0; }
9844 	 *   bpf_loop(100, cb, &ctx, 0);
9845 	 *
9846 	 * This is similar to what is done in process_iter_next_call() for open
9847 	 * coded iterators.
9848 	 */
9849 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9850 	if (prev_st) {
9851 		err = widen_imprecise_scalars(env, prev_st, state);
9852 		if (err)
9853 			return err;
9854 	}
9855 	return 0;
9856 }
9857 
9858 static int do_refine_retval_range(struct bpf_verifier_env *env,
9859 				  struct bpf_reg_state *regs, int ret_type,
9860 				  int func_id,
9861 				  struct bpf_call_arg_meta *meta)
9862 {
9863 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9864 
9865 	if (ret_type != RET_INTEGER)
9866 		return 0;
9867 
9868 	switch (func_id) {
9869 	case BPF_FUNC_get_stack:
9870 	case BPF_FUNC_get_task_stack:
9871 	case BPF_FUNC_probe_read_str:
9872 	case BPF_FUNC_probe_read_kernel_str:
9873 	case BPF_FUNC_probe_read_user_str:
9874 		ret_reg->smax_value = meta->msize_max_value;
9875 		ret_reg->s32_max_value = meta->msize_max_value;
9876 		ret_reg->smin_value = -MAX_ERRNO;
9877 		ret_reg->s32_min_value = -MAX_ERRNO;
9878 		reg_bounds_sync(ret_reg);
9879 		break;
9880 	case BPF_FUNC_get_smp_processor_id:
9881 		ret_reg->umax_value = nr_cpu_ids - 1;
9882 		ret_reg->u32_max_value = nr_cpu_ids - 1;
9883 		ret_reg->smax_value = nr_cpu_ids - 1;
9884 		ret_reg->s32_max_value = nr_cpu_ids - 1;
9885 		ret_reg->umin_value = 0;
9886 		ret_reg->u32_min_value = 0;
9887 		ret_reg->smin_value = 0;
9888 		ret_reg->s32_min_value = 0;
9889 		reg_bounds_sync(ret_reg);
9890 		break;
9891 	}
9892 
9893 	return reg_bounds_sanity_check(env, ret_reg, "retval");
9894 }
9895 
9896 static int
9897 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9898 		int func_id, int insn_idx)
9899 {
9900 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9901 	struct bpf_map *map = meta->map_ptr;
9902 
9903 	if (func_id != BPF_FUNC_tail_call &&
9904 	    func_id != BPF_FUNC_map_lookup_elem &&
9905 	    func_id != BPF_FUNC_map_update_elem &&
9906 	    func_id != BPF_FUNC_map_delete_elem &&
9907 	    func_id != BPF_FUNC_map_push_elem &&
9908 	    func_id != BPF_FUNC_map_pop_elem &&
9909 	    func_id != BPF_FUNC_map_peek_elem &&
9910 	    func_id != BPF_FUNC_for_each_map_elem &&
9911 	    func_id != BPF_FUNC_redirect_map &&
9912 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9913 		return 0;
9914 
9915 	if (map == NULL) {
9916 		verbose(env, "kernel subsystem misconfigured verifier\n");
9917 		return -EINVAL;
9918 	}
9919 
9920 	/* In case of read-only, some additional restrictions
9921 	 * need to be applied in order to prevent altering the
9922 	 * state of the map from program side.
9923 	 */
9924 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9925 	    (func_id == BPF_FUNC_map_delete_elem ||
9926 	     func_id == BPF_FUNC_map_update_elem ||
9927 	     func_id == BPF_FUNC_map_push_elem ||
9928 	     func_id == BPF_FUNC_map_pop_elem)) {
9929 		verbose(env, "write into map forbidden\n");
9930 		return -EACCES;
9931 	}
9932 
9933 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9934 		bpf_map_ptr_store(aux, meta->map_ptr,
9935 				  !meta->map_ptr->bypass_spec_v1);
9936 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9937 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9938 				  !meta->map_ptr->bypass_spec_v1);
9939 	return 0;
9940 }
9941 
9942 static int
9943 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9944 		int func_id, int insn_idx)
9945 {
9946 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9947 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9948 	struct bpf_map *map = meta->map_ptr;
9949 	u64 val, max;
9950 	int err;
9951 
9952 	if (func_id != BPF_FUNC_tail_call)
9953 		return 0;
9954 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9955 		verbose(env, "kernel subsystem misconfigured verifier\n");
9956 		return -EINVAL;
9957 	}
9958 
9959 	reg = &regs[BPF_REG_3];
9960 	val = reg->var_off.value;
9961 	max = map->max_entries;
9962 
9963 	if (!(is_reg_const(reg, false) && val < max)) {
9964 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9965 		return 0;
9966 	}
9967 
9968 	err = mark_chain_precision(env, BPF_REG_3);
9969 	if (err)
9970 		return err;
9971 	if (bpf_map_key_unseen(aux))
9972 		bpf_map_key_store(aux, val);
9973 	else if (!bpf_map_key_poisoned(aux) &&
9974 		  bpf_map_key_immediate(aux) != val)
9975 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9976 	return 0;
9977 }
9978 
9979 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
9980 {
9981 	struct bpf_func_state *state = cur_func(env);
9982 	bool refs_lingering = false;
9983 	int i;
9984 
9985 	if (!exception_exit && state->frameno && !state->in_callback_fn)
9986 		return 0;
9987 
9988 	for (i = 0; i < state->acquired_refs; i++) {
9989 		if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9990 			continue;
9991 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9992 			state->refs[i].id, state->refs[i].insn_idx);
9993 		refs_lingering = true;
9994 	}
9995 	return refs_lingering ? -EINVAL : 0;
9996 }
9997 
9998 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9999 				   struct bpf_reg_state *regs)
10000 {
10001 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
10002 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
10003 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
10004 	struct bpf_bprintf_data data = {};
10005 	int err, fmt_map_off, num_args;
10006 	u64 fmt_addr;
10007 	char *fmt;
10008 
10009 	/* data must be an array of u64 */
10010 	if (data_len_reg->var_off.value % 8)
10011 		return -EINVAL;
10012 	num_args = data_len_reg->var_off.value / 8;
10013 
10014 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
10015 	 * and map_direct_value_addr is set.
10016 	 */
10017 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
10018 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
10019 						  fmt_map_off);
10020 	if (err) {
10021 		verbose(env, "verifier bug\n");
10022 		return -EFAULT;
10023 	}
10024 	fmt = (char *)(long)fmt_addr + fmt_map_off;
10025 
10026 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
10027 	 * can focus on validating the format specifiers.
10028 	 */
10029 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
10030 	if (err < 0)
10031 		verbose(env, "Invalid format string\n");
10032 
10033 	return err;
10034 }
10035 
10036 static int check_get_func_ip(struct bpf_verifier_env *env)
10037 {
10038 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10039 	int func_id = BPF_FUNC_get_func_ip;
10040 
10041 	if (type == BPF_PROG_TYPE_TRACING) {
10042 		if (!bpf_prog_has_trampoline(env->prog)) {
10043 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
10044 				func_id_name(func_id), func_id);
10045 			return -ENOTSUPP;
10046 		}
10047 		return 0;
10048 	} else if (type == BPF_PROG_TYPE_KPROBE) {
10049 		return 0;
10050 	}
10051 
10052 	verbose(env, "func %s#%d not supported for program type %d\n",
10053 		func_id_name(func_id), func_id, type);
10054 	return -ENOTSUPP;
10055 }
10056 
10057 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
10058 {
10059 	return &env->insn_aux_data[env->insn_idx];
10060 }
10061 
10062 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10063 {
10064 	struct bpf_reg_state *regs = cur_regs(env);
10065 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
10066 	bool reg_is_null = register_is_null(reg);
10067 
10068 	if (reg_is_null)
10069 		mark_chain_precision(env, BPF_REG_4);
10070 
10071 	return reg_is_null;
10072 }
10073 
10074 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10075 {
10076 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10077 
10078 	if (!state->initialized) {
10079 		state->initialized = 1;
10080 		state->fit_for_inline = loop_flag_is_zero(env);
10081 		state->callback_subprogno = subprogno;
10082 		return;
10083 	}
10084 
10085 	if (!state->fit_for_inline)
10086 		return;
10087 
10088 	state->fit_for_inline = (loop_flag_is_zero(env) &&
10089 				 state->callback_subprogno == subprogno);
10090 }
10091 
10092 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10093 			     int *insn_idx_p)
10094 {
10095 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10096 	bool returns_cpu_specific_alloc_ptr = false;
10097 	const struct bpf_func_proto *fn = NULL;
10098 	enum bpf_return_type ret_type;
10099 	enum bpf_type_flag ret_flag;
10100 	struct bpf_reg_state *regs;
10101 	struct bpf_call_arg_meta meta;
10102 	int insn_idx = *insn_idx_p;
10103 	bool changes_data;
10104 	int i, err, func_id;
10105 
10106 	/* find function prototype */
10107 	func_id = insn->imm;
10108 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
10109 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
10110 			func_id);
10111 		return -EINVAL;
10112 	}
10113 
10114 	if (env->ops->get_func_proto)
10115 		fn = env->ops->get_func_proto(func_id, env->prog);
10116 	if (!fn) {
10117 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
10118 			func_id);
10119 		return -EINVAL;
10120 	}
10121 
10122 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
10123 	if (!env->prog->gpl_compatible && fn->gpl_only) {
10124 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10125 		return -EINVAL;
10126 	}
10127 
10128 	if (fn->allowed && !fn->allowed(env->prog)) {
10129 		verbose(env, "helper call is not allowed in probe\n");
10130 		return -EINVAL;
10131 	}
10132 
10133 	if (!env->prog->aux->sleepable && fn->might_sleep) {
10134 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
10135 		return -EINVAL;
10136 	}
10137 
10138 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
10139 	changes_data = bpf_helper_changes_pkt_data(fn->func);
10140 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10141 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10142 			func_id_name(func_id), func_id);
10143 		return -EINVAL;
10144 	}
10145 
10146 	memset(&meta, 0, sizeof(meta));
10147 	meta.pkt_access = fn->pkt_access;
10148 
10149 	err = check_func_proto(fn, func_id);
10150 	if (err) {
10151 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10152 			func_id_name(func_id), func_id);
10153 		return err;
10154 	}
10155 
10156 	if (env->cur_state->active_rcu_lock) {
10157 		if (fn->might_sleep) {
10158 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10159 				func_id_name(func_id), func_id);
10160 			return -EINVAL;
10161 		}
10162 
10163 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10164 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10165 	}
10166 
10167 	meta.func_id = func_id;
10168 	/* check args */
10169 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10170 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10171 		if (err)
10172 			return err;
10173 	}
10174 
10175 	err = record_func_map(env, &meta, func_id, insn_idx);
10176 	if (err)
10177 		return err;
10178 
10179 	err = record_func_key(env, &meta, func_id, insn_idx);
10180 	if (err)
10181 		return err;
10182 
10183 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10184 	 * is inferred from register state.
10185 	 */
10186 	for (i = 0; i < meta.access_size; i++) {
10187 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10188 				       BPF_WRITE, -1, false, false);
10189 		if (err)
10190 			return err;
10191 	}
10192 
10193 	regs = cur_regs(env);
10194 
10195 	if (meta.release_regno) {
10196 		err = -EINVAL;
10197 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10198 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10199 		 * is safe to do directly.
10200 		 */
10201 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10202 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10203 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10204 				return -EFAULT;
10205 			}
10206 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10207 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10208 			u32 ref_obj_id = meta.ref_obj_id;
10209 			bool in_rcu = in_rcu_cs(env);
10210 			struct bpf_func_state *state;
10211 			struct bpf_reg_state *reg;
10212 
10213 			err = release_reference_state(cur_func(env), ref_obj_id);
10214 			if (!err) {
10215 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10216 					if (reg->ref_obj_id == ref_obj_id) {
10217 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10218 							reg->ref_obj_id = 0;
10219 							reg->type &= ~MEM_ALLOC;
10220 							reg->type |= MEM_RCU;
10221 						} else {
10222 							mark_reg_invalid(env, reg);
10223 						}
10224 					}
10225 				}));
10226 			}
10227 		} else if (meta.ref_obj_id) {
10228 			err = release_reference(env, meta.ref_obj_id);
10229 		} else if (register_is_null(&regs[meta.release_regno])) {
10230 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10231 			 * released is NULL, which must be > R0.
10232 			 */
10233 			err = 0;
10234 		}
10235 		if (err) {
10236 			verbose(env, "func %s#%d reference has not been acquired before\n",
10237 				func_id_name(func_id), func_id);
10238 			return err;
10239 		}
10240 	}
10241 
10242 	switch (func_id) {
10243 	case BPF_FUNC_tail_call:
10244 		err = check_reference_leak(env, false);
10245 		if (err) {
10246 			verbose(env, "tail_call would lead to reference leak\n");
10247 			return err;
10248 		}
10249 		break;
10250 	case BPF_FUNC_get_local_storage:
10251 		/* check that flags argument in get_local_storage(map, flags) is 0,
10252 		 * this is required because get_local_storage() can't return an error.
10253 		 */
10254 		if (!register_is_null(&regs[BPF_REG_2])) {
10255 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10256 			return -EINVAL;
10257 		}
10258 		break;
10259 	case BPF_FUNC_for_each_map_elem:
10260 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10261 					 set_map_elem_callback_state);
10262 		break;
10263 	case BPF_FUNC_timer_set_callback:
10264 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10265 					 set_timer_callback_state);
10266 		break;
10267 	case BPF_FUNC_find_vma:
10268 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10269 					 set_find_vma_callback_state);
10270 		break;
10271 	case BPF_FUNC_snprintf:
10272 		err = check_bpf_snprintf_call(env, regs);
10273 		break;
10274 	case BPF_FUNC_loop:
10275 		update_loop_inline_state(env, meta.subprogno);
10276 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10277 		 * is finished, thus mark it precise.
10278 		 */
10279 		err = mark_chain_precision(env, BPF_REG_1);
10280 		if (err)
10281 			return err;
10282 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10283 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10284 						 set_loop_callback_state);
10285 		} else {
10286 			cur_func(env)->callback_depth = 0;
10287 			if (env->log.level & BPF_LOG_LEVEL2)
10288 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10289 					env->cur_state->curframe);
10290 		}
10291 		break;
10292 	case BPF_FUNC_dynptr_from_mem:
10293 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10294 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10295 				reg_type_str(env, regs[BPF_REG_1].type));
10296 			return -EACCES;
10297 		}
10298 		break;
10299 	case BPF_FUNC_set_retval:
10300 		if (prog_type == BPF_PROG_TYPE_LSM &&
10301 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10302 			if (!env->prog->aux->attach_func_proto->type) {
10303 				/* Make sure programs that attach to void
10304 				 * hooks don't try to modify return value.
10305 				 */
10306 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10307 				return -EINVAL;
10308 			}
10309 		}
10310 		break;
10311 	case BPF_FUNC_dynptr_data:
10312 	{
10313 		struct bpf_reg_state *reg;
10314 		int id, ref_obj_id;
10315 
10316 		reg = get_dynptr_arg_reg(env, fn, regs);
10317 		if (!reg)
10318 			return -EFAULT;
10319 
10320 
10321 		if (meta.dynptr_id) {
10322 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10323 			return -EFAULT;
10324 		}
10325 		if (meta.ref_obj_id) {
10326 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10327 			return -EFAULT;
10328 		}
10329 
10330 		id = dynptr_id(env, reg);
10331 		if (id < 0) {
10332 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10333 			return id;
10334 		}
10335 
10336 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10337 		if (ref_obj_id < 0) {
10338 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10339 			return ref_obj_id;
10340 		}
10341 
10342 		meta.dynptr_id = id;
10343 		meta.ref_obj_id = ref_obj_id;
10344 
10345 		break;
10346 	}
10347 	case BPF_FUNC_dynptr_write:
10348 	{
10349 		enum bpf_dynptr_type dynptr_type;
10350 		struct bpf_reg_state *reg;
10351 
10352 		reg = get_dynptr_arg_reg(env, fn, regs);
10353 		if (!reg)
10354 			return -EFAULT;
10355 
10356 		dynptr_type = dynptr_get_type(env, reg);
10357 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10358 			return -EFAULT;
10359 
10360 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10361 			/* this will trigger clear_all_pkt_pointers(), which will
10362 			 * invalidate all dynptr slices associated with the skb
10363 			 */
10364 			changes_data = true;
10365 
10366 		break;
10367 	}
10368 	case BPF_FUNC_per_cpu_ptr:
10369 	case BPF_FUNC_this_cpu_ptr:
10370 	{
10371 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
10372 		const struct btf_type *type;
10373 
10374 		if (reg->type & MEM_RCU) {
10375 			type = btf_type_by_id(reg->btf, reg->btf_id);
10376 			if (!type || !btf_type_is_struct(type)) {
10377 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
10378 				return -EFAULT;
10379 			}
10380 			returns_cpu_specific_alloc_ptr = true;
10381 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10382 		}
10383 		break;
10384 	}
10385 	case BPF_FUNC_user_ringbuf_drain:
10386 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10387 					 set_user_ringbuf_callback_state);
10388 		break;
10389 	}
10390 
10391 	if (err)
10392 		return err;
10393 
10394 	/* reset caller saved regs */
10395 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10396 		mark_reg_not_init(env, regs, caller_saved[i]);
10397 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10398 	}
10399 
10400 	/* helper call returns 64-bit value. */
10401 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10402 
10403 	/* update return register (already marked as written above) */
10404 	ret_type = fn->ret_type;
10405 	ret_flag = type_flag(ret_type);
10406 
10407 	switch (base_type(ret_type)) {
10408 	case RET_INTEGER:
10409 		/* sets type to SCALAR_VALUE */
10410 		mark_reg_unknown(env, regs, BPF_REG_0);
10411 		break;
10412 	case RET_VOID:
10413 		regs[BPF_REG_0].type = NOT_INIT;
10414 		break;
10415 	case RET_PTR_TO_MAP_VALUE:
10416 		/* There is no offset yet applied, variable or fixed */
10417 		mark_reg_known_zero(env, regs, BPF_REG_0);
10418 		/* remember map_ptr, so that check_map_access()
10419 		 * can check 'value_size' boundary of memory access
10420 		 * to map element returned from bpf_map_lookup_elem()
10421 		 */
10422 		if (meta.map_ptr == NULL) {
10423 			verbose(env,
10424 				"kernel subsystem misconfigured verifier\n");
10425 			return -EINVAL;
10426 		}
10427 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10428 		regs[BPF_REG_0].map_uid = meta.map_uid;
10429 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10430 		if (!type_may_be_null(ret_type) &&
10431 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10432 			regs[BPF_REG_0].id = ++env->id_gen;
10433 		}
10434 		break;
10435 	case RET_PTR_TO_SOCKET:
10436 		mark_reg_known_zero(env, regs, BPF_REG_0);
10437 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10438 		break;
10439 	case RET_PTR_TO_SOCK_COMMON:
10440 		mark_reg_known_zero(env, regs, BPF_REG_0);
10441 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10442 		break;
10443 	case RET_PTR_TO_TCP_SOCK:
10444 		mark_reg_known_zero(env, regs, BPF_REG_0);
10445 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10446 		break;
10447 	case RET_PTR_TO_MEM:
10448 		mark_reg_known_zero(env, regs, BPF_REG_0);
10449 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10450 		regs[BPF_REG_0].mem_size = meta.mem_size;
10451 		break;
10452 	case RET_PTR_TO_MEM_OR_BTF_ID:
10453 	{
10454 		const struct btf_type *t;
10455 
10456 		mark_reg_known_zero(env, regs, BPF_REG_0);
10457 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10458 		if (!btf_type_is_struct(t)) {
10459 			u32 tsize;
10460 			const struct btf_type *ret;
10461 			const char *tname;
10462 
10463 			/* resolve the type size of ksym. */
10464 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10465 			if (IS_ERR(ret)) {
10466 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10467 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10468 					tname, PTR_ERR(ret));
10469 				return -EINVAL;
10470 			}
10471 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10472 			regs[BPF_REG_0].mem_size = tsize;
10473 		} else {
10474 			if (returns_cpu_specific_alloc_ptr) {
10475 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10476 			} else {
10477 				/* MEM_RDONLY may be carried from ret_flag, but it
10478 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10479 				 * it will confuse the check of PTR_TO_BTF_ID in
10480 				 * check_mem_access().
10481 				 */
10482 				ret_flag &= ~MEM_RDONLY;
10483 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10484 			}
10485 
10486 			regs[BPF_REG_0].btf = meta.ret_btf;
10487 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10488 		}
10489 		break;
10490 	}
10491 	case RET_PTR_TO_BTF_ID:
10492 	{
10493 		struct btf *ret_btf;
10494 		int ret_btf_id;
10495 
10496 		mark_reg_known_zero(env, regs, BPF_REG_0);
10497 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10498 		if (func_id == BPF_FUNC_kptr_xchg) {
10499 			ret_btf = meta.kptr_field->kptr.btf;
10500 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10501 			if (!btf_is_kernel(ret_btf)) {
10502 				regs[BPF_REG_0].type |= MEM_ALLOC;
10503 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10504 					regs[BPF_REG_0].type |= MEM_PERCPU;
10505 			}
10506 		} else {
10507 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10508 				verbose(env, "verifier internal error:");
10509 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10510 					func_id_name(func_id));
10511 				return -EINVAL;
10512 			}
10513 			ret_btf = btf_vmlinux;
10514 			ret_btf_id = *fn->ret_btf_id;
10515 		}
10516 		if (ret_btf_id == 0) {
10517 			verbose(env, "invalid return type %u of func %s#%d\n",
10518 				base_type(ret_type), func_id_name(func_id),
10519 				func_id);
10520 			return -EINVAL;
10521 		}
10522 		regs[BPF_REG_0].btf = ret_btf;
10523 		regs[BPF_REG_0].btf_id = ret_btf_id;
10524 		break;
10525 	}
10526 	default:
10527 		verbose(env, "unknown return type %u of func %s#%d\n",
10528 			base_type(ret_type), func_id_name(func_id), func_id);
10529 		return -EINVAL;
10530 	}
10531 
10532 	if (type_may_be_null(regs[BPF_REG_0].type))
10533 		regs[BPF_REG_0].id = ++env->id_gen;
10534 
10535 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10536 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10537 			func_id_name(func_id), func_id);
10538 		return -EFAULT;
10539 	}
10540 
10541 	if (is_dynptr_ref_function(func_id))
10542 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10543 
10544 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10545 		/* For release_reference() */
10546 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10547 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10548 		int id = acquire_reference_state(env, insn_idx);
10549 
10550 		if (id < 0)
10551 			return id;
10552 		/* For mark_ptr_or_null_reg() */
10553 		regs[BPF_REG_0].id = id;
10554 		/* For release_reference() */
10555 		regs[BPF_REG_0].ref_obj_id = id;
10556 	}
10557 
10558 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
10559 	if (err)
10560 		return err;
10561 
10562 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10563 	if (err)
10564 		return err;
10565 
10566 	if ((func_id == BPF_FUNC_get_stack ||
10567 	     func_id == BPF_FUNC_get_task_stack) &&
10568 	    !env->prog->has_callchain_buf) {
10569 		const char *err_str;
10570 
10571 #ifdef CONFIG_PERF_EVENTS
10572 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10573 		err_str = "cannot get callchain buffer for func %s#%d\n";
10574 #else
10575 		err = -ENOTSUPP;
10576 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10577 #endif
10578 		if (err) {
10579 			verbose(env, err_str, func_id_name(func_id), func_id);
10580 			return err;
10581 		}
10582 
10583 		env->prog->has_callchain_buf = true;
10584 	}
10585 
10586 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10587 		env->prog->call_get_stack = true;
10588 
10589 	if (func_id == BPF_FUNC_get_func_ip) {
10590 		if (check_get_func_ip(env))
10591 			return -ENOTSUPP;
10592 		env->prog->call_get_func_ip = true;
10593 	}
10594 
10595 	if (changes_data)
10596 		clear_all_pkt_pointers(env);
10597 	return 0;
10598 }
10599 
10600 /* mark_btf_func_reg_size() is used when the reg size is determined by
10601  * the BTF func_proto's return value size and argument.
10602  */
10603 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10604 				   size_t reg_size)
10605 {
10606 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10607 
10608 	if (regno == BPF_REG_0) {
10609 		/* Function return value */
10610 		reg->live |= REG_LIVE_WRITTEN;
10611 		reg->subreg_def = reg_size == sizeof(u64) ?
10612 			DEF_NOT_SUBREG : env->insn_idx + 1;
10613 	} else {
10614 		/* Function argument */
10615 		if (reg_size == sizeof(u64)) {
10616 			mark_insn_zext(env, reg);
10617 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10618 		} else {
10619 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10620 		}
10621 	}
10622 }
10623 
10624 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10625 {
10626 	return meta->kfunc_flags & KF_ACQUIRE;
10627 }
10628 
10629 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10630 {
10631 	return meta->kfunc_flags & KF_RELEASE;
10632 }
10633 
10634 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10635 {
10636 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10637 }
10638 
10639 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10640 {
10641 	return meta->kfunc_flags & KF_SLEEPABLE;
10642 }
10643 
10644 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10645 {
10646 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10647 }
10648 
10649 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10650 {
10651 	return meta->kfunc_flags & KF_RCU;
10652 }
10653 
10654 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
10655 {
10656 	return meta->kfunc_flags & KF_RCU_PROTECTED;
10657 }
10658 
10659 static bool __kfunc_param_match_suffix(const struct btf *btf,
10660 				       const struct btf_param *arg,
10661 				       const char *suffix)
10662 {
10663 	int suffix_len = strlen(suffix), len;
10664 	const char *param_name;
10665 
10666 	/* In the future, this can be ported to use BTF tagging */
10667 	param_name = btf_name_by_offset(btf, arg->name_off);
10668 	if (str_is_empty(param_name))
10669 		return false;
10670 	len = strlen(param_name);
10671 	if (len < suffix_len)
10672 		return false;
10673 	param_name += len - suffix_len;
10674 	return !strncmp(param_name, suffix, suffix_len);
10675 }
10676 
10677 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10678 				  const struct btf_param *arg,
10679 				  const struct bpf_reg_state *reg)
10680 {
10681 	const struct btf_type *t;
10682 
10683 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10684 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10685 		return false;
10686 
10687 	return __kfunc_param_match_suffix(btf, arg, "__sz");
10688 }
10689 
10690 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10691 					const struct btf_param *arg,
10692 					const struct bpf_reg_state *reg)
10693 {
10694 	const struct btf_type *t;
10695 
10696 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10697 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10698 		return false;
10699 
10700 	return __kfunc_param_match_suffix(btf, arg, "__szk");
10701 }
10702 
10703 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10704 {
10705 	return __kfunc_param_match_suffix(btf, arg, "__opt");
10706 }
10707 
10708 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10709 {
10710 	return __kfunc_param_match_suffix(btf, arg, "__k");
10711 }
10712 
10713 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10714 {
10715 	return __kfunc_param_match_suffix(btf, arg, "__ign");
10716 }
10717 
10718 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10719 {
10720 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
10721 }
10722 
10723 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10724 {
10725 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
10726 }
10727 
10728 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10729 {
10730 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10731 }
10732 
10733 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
10734 {
10735 	return __kfunc_param_match_suffix(btf, arg, "__nullable");
10736 }
10737 
10738 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
10739 {
10740 	return __kfunc_param_match_suffix(btf, arg, "__str");
10741 }
10742 
10743 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10744 					  const struct btf_param *arg,
10745 					  const char *name)
10746 {
10747 	int len, target_len = strlen(name);
10748 	const char *param_name;
10749 
10750 	param_name = btf_name_by_offset(btf, arg->name_off);
10751 	if (str_is_empty(param_name))
10752 		return false;
10753 	len = strlen(param_name);
10754 	if (len != target_len)
10755 		return false;
10756 	if (strcmp(param_name, name))
10757 		return false;
10758 
10759 	return true;
10760 }
10761 
10762 enum {
10763 	KF_ARG_DYNPTR_ID,
10764 	KF_ARG_LIST_HEAD_ID,
10765 	KF_ARG_LIST_NODE_ID,
10766 	KF_ARG_RB_ROOT_ID,
10767 	KF_ARG_RB_NODE_ID,
10768 };
10769 
10770 BTF_ID_LIST(kf_arg_btf_ids)
10771 BTF_ID(struct, bpf_dynptr_kern)
10772 BTF_ID(struct, bpf_list_head)
10773 BTF_ID(struct, bpf_list_node)
10774 BTF_ID(struct, bpf_rb_root)
10775 BTF_ID(struct, bpf_rb_node)
10776 
10777 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10778 				    const struct btf_param *arg, int type)
10779 {
10780 	const struct btf_type *t;
10781 	u32 res_id;
10782 
10783 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10784 	if (!t)
10785 		return false;
10786 	if (!btf_type_is_ptr(t))
10787 		return false;
10788 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10789 	if (!t)
10790 		return false;
10791 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10792 }
10793 
10794 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10795 {
10796 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10797 }
10798 
10799 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10800 {
10801 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10802 }
10803 
10804 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10805 {
10806 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10807 }
10808 
10809 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10810 {
10811 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10812 }
10813 
10814 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10815 {
10816 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10817 }
10818 
10819 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10820 				  const struct btf_param *arg)
10821 {
10822 	const struct btf_type *t;
10823 
10824 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10825 	if (!t)
10826 		return false;
10827 
10828 	return true;
10829 }
10830 
10831 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10832 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10833 					const struct btf *btf,
10834 					const struct btf_type *t, int rec)
10835 {
10836 	const struct btf_type *member_type;
10837 	const struct btf_member *member;
10838 	u32 i;
10839 
10840 	if (!btf_type_is_struct(t))
10841 		return false;
10842 
10843 	for_each_member(i, t, member) {
10844 		const struct btf_array *array;
10845 
10846 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10847 		if (btf_type_is_struct(member_type)) {
10848 			if (rec >= 3) {
10849 				verbose(env, "max struct nesting depth exceeded\n");
10850 				return false;
10851 			}
10852 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10853 				return false;
10854 			continue;
10855 		}
10856 		if (btf_type_is_array(member_type)) {
10857 			array = btf_array(member_type);
10858 			if (!array->nelems)
10859 				return false;
10860 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10861 			if (!btf_type_is_scalar(member_type))
10862 				return false;
10863 			continue;
10864 		}
10865 		if (!btf_type_is_scalar(member_type))
10866 			return false;
10867 	}
10868 	return true;
10869 }
10870 
10871 enum kfunc_ptr_arg_type {
10872 	KF_ARG_PTR_TO_CTX,
10873 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10874 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10875 	KF_ARG_PTR_TO_DYNPTR,
10876 	KF_ARG_PTR_TO_ITER,
10877 	KF_ARG_PTR_TO_LIST_HEAD,
10878 	KF_ARG_PTR_TO_LIST_NODE,
10879 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10880 	KF_ARG_PTR_TO_MEM,
10881 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10882 	KF_ARG_PTR_TO_CALLBACK,
10883 	KF_ARG_PTR_TO_RB_ROOT,
10884 	KF_ARG_PTR_TO_RB_NODE,
10885 	KF_ARG_PTR_TO_NULL,
10886 	KF_ARG_PTR_TO_CONST_STR,
10887 };
10888 
10889 enum special_kfunc_type {
10890 	KF_bpf_obj_new_impl,
10891 	KF_bpf_obj_drop_impl,
10892 	KF_bpf_refcount_acquire_impl,
10893 	KF_bpf_list_push_front_impl,
10894 	KF_bpf_list_push_back_impl,
10895 	KF_bpf_list_pop_front,
10896 	KF_bpf_list_pop_back,
10897 	KF_bpf_cast_to_kern_ctx,
10898 	KF_bpf_rdonly_cast,
10899 	KF_bpf_rcu_read_lock,
10900 	KF_bpf_rcu_read_unlock,
10901 	KF_bpf_rbtree_remove,
10902 	KF_bpf_rbtree_add_impl,
10903 	KF_bpf_rbtree_first,
10904 	KF_bpf_dynptr_from_skb,
10905 	KF_bpf_dynptr_from_xdp,
10906 	KF_bpf_dynptr_slice,
10907 	KF_bpf_dynptr_slice_rdwr,
10908 	KF_bpf_dynptr_clone,
10909 	KF_bpf_percpu_obj_new_impl,
10910 	KF_bpf_percpu_obj_drop_impl,
10911 	KF_bpf_throw,
10912 	KF_bpf_iter_css_task_new,
10913 };
10914 
10915 BTF_SET_START(special_kfunc_set)
10916 BTF_ID(func, bpf_obj_new_impl)
10917 BTF_ID(func, bpf_obj_drop_impl)
10918 BTF_ID(func, bpf_refcount_acquire_impl)
10919 BTF_ID(func, bpf_list_push_front_impl)
10920 BTF_ID(func, bpf_list_push_back_impl)
10921 BTF_ID(func, bpf_list_pop_front)
10922 BTF_ID(func, bpf_list_pop_back)
10923 BTF_ID(func, bpf_cast_to_kern_ctx)
10924 BTF_ID(func, bpf_rdonly_cast)
10925 BTF_ID(func, bpf_rbtree_remove)
10926 BTF_ID(func, bpf_rbtree_add_impl)
10927 BTF_ID(func, bpf_rbtree_first)
10928 BTF_ID(func, bpf_dynptr_from_skb)
10929 BTF_ID(func, bpf_dynptr_from_xdp)
10930 BTF_ID(func, bpf_dynptr_slice)
10931 BTF_ID(func, bpf_dynptr_slice_rdwr)
10932 BTF_ID(func, bpf_dynptr_clone)
10933 BTF_ID(func, bpf_percpu_obj_new_impl)
10934 BTF_ID(func, bpf_percpu_obj_drop_impl)
10935 BTF_ID(func, bpf_throw)
10936 #ifdef CONFIG_CGROUPS
10937 BTF_ID(func, bpf_iter_css_task_new)
10938 #endif
10939 BTF_SET_END(special_kfunc_set)
10940 
10941 BTF_ID_LIST(special_kfunc_list)
10942 BTF_ID(func, bpf_obj_new_impl)
10943 BTF_ID(func, bpf_obj_drop_impl)
10944 BTF_ID(func, bpf_refcount_acquire_impl)
10945 BTF_ID(func, bpf_list_push_front_impl)
10946 BTF_ID(func, bpf_list_push_back_impl)
10947 BTF_ID(func, bpf_list_pop_front)
10948 BTF_ID(func, bpf_list_pop_back)
10949 BTF_ID(func, bpf_cast_to_kern_ctx)
10950 BTF_ID(func, bpf_rdonly_cast)
10951 BTF_ID(func, bpf_rcu_read_lock)
10952 BTF_ID(func, bpf_rcu_read_unlock)
10953 BTF_ID(func, bpf_rbtree_remove)
10954 BTF_ID(func, bpf_rbtree_add_impl)
10955 BTF_ID(func, bpf_rbtree_first)
10956 BTF_ID(func, bpf_dynptr_from_skb)
10957 BTF_ID(func, bpf_dynptr_from_xdp)
10958 BTF_ID(func, bpf_dynptr_slice)
10959 BTF_ID(func, bpf_dynptr_slice_rdwr)
10960 BTF_ID(func, bpf_dynptr_clone)
10961 BTF_ID(func, bpf_percpu_obj_new_impl)
10962 BTF_ID(func, bpf_percpu_obj_drop_impl)
10963 BTF_ID(func, bpf_throw)
10964 #ifdef CONFIG_CGROUPS
10965 BTF_ID(func, bpf_iter_css_task_new)
10966 #else
10967 BTF_ID_UNUSED
10968 #endif
10969 
10970 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10971 {
10972 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10973 	    meta->arg_owning_ref) {
10974 		return false;
10975 	}
10976 
10977 	return meta->kfunc_flags & KF_RET_NULL;
10978 }
10979 
10980 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10981 {
10982 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10983 }
10984 
10985 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10986 {
10987 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10988 }
10989 
10990 static enum kfunc_ptr_arg_type
10991 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10992 		       struct bpf_kfunc_call_arg_meta *meta,
10993 		       const struct btf_type *t, const struct btf_type *ref_t,
10994 		       const char *ref_tname, const struct btf_param *args,
10995 		       int argno, int nargs)
10996 {
10997 	u32 regno = argno + 1;
10998 	struct bpf_reg_state *regs = cur_regs(env);
10999 	struct bpf_reg_state *reg = &regs[regno];
11000 	bool arg_mem_size = false;
11001 
11002 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
11003 		return KF_ARG_PTR_TO_CTX;
11004 
11005 	/* In this function, we verify the kfunc's BTF as per the argument type,
11006 	 * leaving the rest of the verification with respect to the register
11007 	 * type to our caller. When a set of conditions hold in the BTF type of
11008 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
11009 	 */
11010 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
11011 		return KF_ARG_PTR_TO_CTX;
11012 
11013 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
11014 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
11015 
11016 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
11017 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
11018 
11019 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
11020 		return KF_ARG_PTR_TO_DYNPTR;
11021 
11022 	if (is_kfunc_arg_iter(meta, argno))
11023 		return KF_ARG_PTR_TO_ITER;
11024 
11025 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
11026 		return KF_ARG_PTR_TO_LIST_HEAD;
11027 
11028 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
11029 		return KF_ARG_PTR_TO_LIST_NODE;
11030 
11031 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
11032 		return KF_ARG_PTR_TO_RB_ROOT;
11033 
11034 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
11035 		return KF_ARG_PTR_TO_RB_NODE;
11036 
11037 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
11038 		return KF_ARG_PTR_TO_CONST_STR;
11039 
11040 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11041 		if (!btf_type_is_struct(ref_t)) {
11042 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
11043 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
11044 			return -EINVAL;
11045 		}
11046 		return KF_ARG_PTR_TO_BTF_ID;
11047 	}
11048 
11049 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
11050 		return KF_ARG_PTR_TO_CALLBACK;
11051 
11052 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
11053 		return KF_ARG_PTR_TO_NULL;
11054 
11055 	if (argno + 1 < nargs &&
11056 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
11057 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
11058 		arg_mem_size = true;
11059 
11060 	/* This is the catch all argument type of register types supported by
11061 	 * check_helper_mem_access. However, we only allow when argument type is
11062 	 * pointer to scalar, or struct composed (recursively) of scalars. When
11063 	 * arg_mem_size is true, the pointer can be void *.
11064 	 */
11065 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11066 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11067 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
11068 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11069 		return -EINVAL;
11070 	}
11071 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11072 }
11073 
11074 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11075 					struct bpf_reg_state *reg,
11076 					const struct btf_type *ref_t,
11077 					const char *ref_tname, u32 ref_id,
11078 					struct bpf_kfunc_call_arg_meta *meta,
11079 					int argno)
11080 {
11081 	const struct btf_type *reg_ref_t;
11082 	bool strict_type_match = false;
11083 	const struct btf *reg_btf;
11084 	const char *reg_ref_tname;
11085 	u32 reg_ref_id;
11086 
11087 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
11088 		reg_btf = reg->btf;
11089 		reg_ref_id = reg->btf_id;
11090 	} else {
11091 		reg_btf = btf_vmlinux;
11092 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11093 	}
11094 
11095 	/* Enforce strict type matching for calls to kfuncs that are acquiring
11096 	 * or releasing a reference, or are no-cast aliases. We do _not_
11097 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
11098 	 * as we want to enable BPF programs to pass types that are bitwise
11099 	 * equivalent without forcing them to explicitly cast with something
11100 	 * like bpf_cast_to_kern_ctx().
11101 	 *
11102 	 * For example, say we had a type like the following:
11103 	 *
11104 	 * struct bpf_cpumask {
11105 	 *	cpumask_t cpumask;
11106 	 *	refcount_t usage;
11107 	 * };
11108 	 *
11109 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11110 	 * to a struct cpumask, so it would be safe to pass a struct
11111 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11112 	 *
11113 	 * The philosophy here is similar to how we allow scalars of different
11114 	 * types to be passed to kfuncs as long as the size is the same. The
11115 	 * only difference here is that we're simply allowing
11116 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
11117 	 * resolve types.
11118 	 */
11119 	if (is_kfunc_acquire(meta) ||
11120 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
11121 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11122 		strict_type_match = true;
11123 
11124 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
11125 
11126 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
11127 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11128 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
11129 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
11130 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
11131 			btf_type_str(reg_ref_t), reg_ref_tname);
11132 		return -EINVAL;
11133 	}
11134 	return 0;
11135 }
11136 
11137 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11138 {
11139 	struct bpf_verifier_state *state = env->cur_state;
11140 	struct btf_record *rec = reg_btf_record(reg);
11141 
11142 	if (!state->active_lock.ptr) {
11143 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
11144 		return -EFAULT;
11145 	}
11146 
11147 	if (type_flag(reg->type) & NON_OWN_REF) {
11148 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
11149 		return -EFAULT;
11150 	}
11151 
11152 	reg->type |= NON_OWN_REF;
11153 	if (rec->refcount_off >= 0)
11154 		reg->type |= MEM_RCU;
11155 
11156 	return 0;
11157 }
11158 
11159 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
11160 {
11161 	struct bpf_func_state *state, *unused;
11162 	struct bpf_reg_state *reg;
11163 	int i;
11164 
11165 	state = cur_func(env);
11166 
11167 	if (!ref_obj_id) {
11168 		verbose(env, "verifier internal error: ref_obj_id is zero for "
11169 			     "owning -> non-owning conversion\n");
11170 		return -EFAULT;
11171 	}
11172 
11173 	for (i = 0; i < state->acquired_refs; i++) {
11174 		if (state->refs[i].id != ref_obj_id)
11175 			continue;
11176 
11177 		/* Clear ref_obj_id here so release_reference doesn't clobber
11178 		 * the whole reg
11179 		 */
11180 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11181 			if (reg->ref_obj_id == ref_obj_id) {
11182 				reg->ref_obj_id = 0;
11183 				ref_set_non_owning(env, reg);
11184 			}
11185 		}));
11186 		return 0;
11187 	}
11188 
11189 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
11190 	return -EFAULT;
11191 }
11192 
11193 /* Implementation details:
11194  *
11195  * Each register points to some region of memory, which we define as an
11196  * allocation. Each allocation may embed a bpf_spin_lock which protects any
11197  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11198  * allocation. The lock and the data it protects are colocated in the same
11199  * memory region.
11200  *
11201  * Hence, everytime a register holds a pointer value pointing to such
11202  * allocation, the verifier preserves a unique reg->id for it.
11203  *
11204  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11205  * bpf_spin_lock is called.
11206  *
11207  * To enable this, lock state in the verifier captures two values:
11208  *	active_lock.ptr = Register's type specific pointer
11209  *	active_lock.id  = A unique ID for each register pointer value
11210  *
11211  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11212  * supported register types.
11213  *
11214  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11215  * allocated objects is the reg->btf pointer.
11216  *
11217  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11218  * can establish the provenance of the map value statically for each distinct
11219  * lookup into such maps. They always contain a single map value hence unique
11220  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11221  *
11222  * So, in case of global variables, they use array maps with max_entries = 1,
11223  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11224  * into the same map value as max_entries is 1, as described above).
11225  *
11226  * In case of inner map lookups, the inner map pointer has same map_ptr as the
11227  * outer map pointer (in verifier context), but each lookup into an inner map
11228  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11229  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11230  * will get different reg->id assigned to each lookup, hence different
11231  * active_lock.id.
11232  *
11233  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11234  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11235  * returned from bpf_obj_new. Each allocation receives a new reg->id.
11236  */
11237 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11238 {
11239 	void *ptr;
11240 	u32 id;
11241 
11242 	switch ((int)reg->type) {
11243 	case PTR_TO_MAP_VALUE:
11244 		ptr = reg->map_ptr;
11245 		break;
11246 	case PTR_TO_BTF_ID | MEM_ALLOC:
11247 		ptr = reg->btf;
11248 		break;
11249 	default:
11250 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11251 		return -EFAULT;
11252 	}
11253 	id = reg->id;
11254 
11255 	if (!env->cur_state->active_lock.ptr)
11256 		return -EINVAL;
11257 	if (env->cur_state->active_lock.ptr != ptr ||
11258 	    env->cur_state->active_lock.id != id) {
11259 		verbose(env, "held lock and object are not in the same allocation\n");
11260 		return -EINVAL;
11261 	}
11262 	return 0;
11263 }
11264 
11265 static bool is_bpf_list_api_kfunc(u32 btf_id)
11266 {
11267 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11268 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11269 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11270 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11271 }
11272 
11273 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11274 {
11275 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11276 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11277 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11278 }
11279 
11280 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11281 {
11282 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11283 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11284 }
11285 
11286 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11287 {
11288 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11289 }
11290 
11291 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
11292 {
11293 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11294 	       insn->imm == special_kfunc_list[KF_bpf_throw];
11295 }
11296 
11297 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11298 {
11299 	return is_bpf_rbtree_api_kfunc(btf_id);
11300 }
11301 
11302 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11303 					  enum btf_field_type head_field_type,
11304 					  u32 kfunc_btf_id)
11305 {
11306 	bool ret;
11307 
11308 	switch (head_field_type) {
11309 	case BPF_LIST_HEAD:
11310 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11311 		break;
11312 	case BPF_RB_ROOT:
11313 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11314 		break;
11315 	default:
11316 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11317 			btf_field_type_name(head_field_type));
11318 		return false;
11319 	}
11320 
11321 	if (!ret)
11322 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11323 			btf_field_type_name(head_field_type));
11324 	return ret;
11325 }
11326 
11327 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11328 					  enum btf_field_type node_field_type,
11329 					  u32 kfunc_btf_id)
11330 {
11331 	bool ret;
11332 
11333 	switch (node_field_type) {
11334 	case BPF_LIST_NODE:
11335 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11336 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11337 		break;
11338 	case BPF_RB_NODE:
11339 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11340 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11341 		break;
11342 	default:
11343 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11344 			btf_field_type_name(node_field_type));
11345 		return false;
11346 	}
11347 
11348 	if (!ret)
11349 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11350 			btf_field_type_name(node_field_type));
11351 	return ret;
11352 }
11353 
11354 static int
11355 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11356 				   struct bpf_reg_state *reg, u32 regno,
11357 				   struct bpf_kfunc_call_arg_meta *meta,
11358 				   enum btf_field_type head_field_type,
11359 				   struct btf_field **head_field)
11360 {
11361 	const char *head_type_name;
11362 	struct btf_field *field;
11363 	struct btf_record *rec;
11364 	u32 head_off;
11365 
11366 	if (meta->btf != btf_vmlinux) {
11367 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11368 		return -EFAULT;
11369 	}
11370 
11371 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11372 		return -EFAULT;
11373 
11374 	head_type_name = btf_field_type_name(head_field_type);
11375 	if (!tnum_is_const(reg->var_off)) {
11376 		verbose(env,
11377 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11378 			regno, head_type_name);
11379 		return -EINVAL;
11380 	}
11381 
11382 	rec = reg_btf_record(reg);
11383 	head_off = reg->off + reg->var_off.value;
11384 	field = btf_record_find(rec, head_off, head_field_type);
11385 	if (!field) {
11386 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11387 		return -EINVAL;
11388 	}
11389 
11390 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11391 	if (check_reg_allocation_locked(env, reg)) {
11392 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11393 			rec->spin_lock_off, head_type_name);
11394 		return -EINVAL;
11395 	}
11396 
11397 	if (*head_field) {
11398 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11399 		return -EFAULT;
11400 	}
11401 	*head_field = field;
11402 	return 0;
11403 }
11404 
11405 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11406 					   struct bpf_reg_state *reg, u32 regno,
11407 					   struct bpf_kfunc_call_arg_meta *meta)
11408 {
11409 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11410 							  &meta->arg_list_head.field);
11411 }
11412 
11413 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11414 					     struct bpf_reg_state *reg, u32 regno,
11415 					     struct bpf_kfunc_call_arg_meta *meta)
11416 {
11417 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11418 							  &meta->arg_rbtree_root.field);
11419 }
11420 
11421 static int
11422 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11423 				   struct bpf_reg_state *reg, u32 regno,
11424 				   struct bpf_kfunc_call_arg_meta *meta,
11425 				   enum btf_field_type head_field_type,
11426 				   enum btf_field_type node_field_type,
11427 				   struct btf_field **node_field)
11428 {
11429 	const char *node_type_name;
11430 	const struct btf_type *et, *t;
11431 	struct btf_field *field;
11432 	u32 node_off;
11433 
11434 	if (meta->btf != btf_vmlinux) {
11435 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11436 		return -EFAULT;
11437 	}
11438 
11439 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11440 		return -EFAULT;
11441 
11442 	node_type_name = btf_field_type_name(node_field_type);
11443 	if (!tnum_is_const(reg->var_off)) {
11444 		verbose(env,
11445 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11446 			regno, node_type_name);
11447 		return -EINVAL;
11448 	}
11449 
11450 	node_off = reg->off + reg->var_off.value;
11451 	field = reg_find_field_offset(reg, node_off, node_field_type);
11452 	if (!field || field->offset != node_off) {
11453 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11454 		return -EINVAL;
11455 	}
11456 
11457 	field = *node_field;
11458 
11459 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11460 	t = btf_type_by_id(reg->btf, reg->btf_id);
11461 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11462 				  field->graph_root.value_btf_id, true)) {
11463 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11464 			"in struct %s, but arg is at offset=%d in struct %s\n",
11465 			btf_field_type_name(head_field_type),
11466 			btf_field_type_name(node_field_type),
11467 			field->graph_root.node_offset,
11468 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11469 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11470 		return -EINVAL;
11471 	}
11472 	meta->arg_btf = reg->btf;
11473 	meta->arg_btf_id = reg->btf_id;
11474 
11475 	if (node_off != field->graph_root.node_offset) {
11476 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11477 			node_off, btf_field_type_name(node_field_type),
11478 			field->graph_root.node_offset,
11479 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11480 		return -EINVAL;
11481 	}
11482 
11483 	return 0;
11484 }
11485 
11486 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11487 					   struct bpf_reg_state *reg, u32 regno,
11488 					   struct bpf_kfunc_call_arg_meta *meta)
11489 {
11490 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11491 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11492 						  &meta->arg_list_head.field);
11493 }
11494 
11495 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11496 					     struct bpf_reg_state *reg, u32 regno,
11497 					     struct bpf_kfunc_call_arg_meta *meta)
11498 {
11499 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11500 						  BPF_RB_ROOT, BPF_RB_NODE,
11501 						  &meta->arg_rbtree_root.field);
11502 }
11503 
11504 /*
11505  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
11506  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
11507  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
11508  * them can only be attached to some specific hook points.
11509  */
11510 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11511 {
11512 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11513 
11514 	switch (prog_type) {
11515 	case BPF_PROG_TYPE_LSM:
11516 		return true;
11517 	case BPF_PROG_TYPE_TRACING:
11518 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
11519 			return true;
11520 		fallthrough;
11521 	default:
11522 		return env->prog->aux->sleepable;
11523 	}
11524 }
11525 
11526 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11527 			    int insn_idx)
11528 {
11529 	const char *func_name = meta->func_name, *ref_tname;
11530 	const struct btf *btf = meta->btf;
11531 	const struct btf_param *args;
11532 	struct btf_record *rec;
11533 	u32 i, nargs;
11534 	int ret;
11535 
11536 	args = (const struct btf_param *)(meta->func_proto + 1);
11537 	nargs = btf_type_vlen(meta->func_proto);
11538 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11539 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11540 			MAX_BPF_FUNC_REG_ARGS);
11541 		return -EINVAL;
11542 	}
11543 
11544 	/* Check that BTF function arguments match actual types that the
11545 	 * verifier sees.
11546 	 */
11547 	for (i = 0; i < nargs; i++) {
11548 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11549 		const struct btf_type *t, *ref_t, *resolve_ret;
11550 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11551 		u32 regno = i + 1, ref_id, type_size;
11552 		bool is_ret_buf_sz = false;
11553 		int kf_arg_type;
11554 
11555 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11556 
11557 		if (is_kfunc_arg_ignore(btf, &args[i]))
11558 			continue;
11559 
11560 		if (btf_type_is_scalar(t)) {
11561 			if (reg->type != SCALAR_VALUE) {
11562 				verbose(env, "R%d is not a scalar\n", regno);
11563 				return -EINVAL;
11564 			}
11565 
11566 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11567 				if (meta->arg_constant.found) {
11568 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11569 					return -EFAULT;
11570 				}
11571 				if (!tnum_is_const(reg->var_off)) {
11572 					verbose(env, "R%d must be a known constant\n", regno);
11573 					return -EINVAL;
11574 				}
11575 				ret = mark_chain_precision(env, regno);
11576 				if (ret < 0)
11577 					return ret;
11578 				meta->arg_constant.found = true;
11579 				meta->arg_constant.value = reg->var_off.value;
11580 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11581 				meta->r0_rdonly = true;
11582 				is_ret_buf_sz = true;
11583 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11584 				is_ret_buf_sz = true;
11585 			}
11586 
11587 			if (is_ret_buf_sz) {
11588 				if (meta->r0_size) {
11589 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11590 					return -EINVAL;
11591 				}
11592 
11593 				if (!tnum_is_const(reg->var_off)) {
11594 					verbose(env, "R%d is not a const\n", regno);
11595 					return -EINVAL;
11596 				}
11597 
11598 				meta->r0_size = reg->var_off.value;
11599 				ret = mark_chain_precision(env, regno);
11600 				if (ret)
11601 					return ret;
11602 			}
11603 			continue;
11604 		}
11605 
11606 		if (!btf_type_is_ptr(t)) {
11607 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11608 			return -EINVAL;
11609 		}
11610 
11611 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11612 		    (register_is_null(reg) || type_may_be_null(reg->type)) &&
11613 			!is_kfunc_arg_nullable(meta->btf, &args[i])) {
11614 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11615 			return -EACCES;
11616 		}
11617 
11618 		if (reg->ref_obj_id) {
11619 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
11620 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11621 					regno, reg->ref_obj_id,
11622 					meta->ref_obj_id);
11623 				return -EFAULT;
11624 			}
11625 			meta->ref_obj_id = reg->ref_obj_id;
11626 			if (is_kfunc_release(meta))
11627 				meta->release_regno = regno;
11628 		}
11629 
11630 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11631 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11632 
11633 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11634 		if (kf_arg_type < 0)
11635 			return kf_arg_type;
11636 
11637 		switch (kf_arg_type) {
11638 		case KF_ARG_PTR_TO_NULL:
11639 			continue;
11640 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11641 		case KF_ARG_PTR_TO_BTF_ID:
11642 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11643 				break;
11644 
11645 			if (!is_trusted_reg(reg)) {
11646 				if (!is_kfunc_rcu(meta)) {
11647 					verbose(env, "R%d must be referenced or trusted\n", regno);
11648 					return -EINVAL;
11649 				}
11650 				if (!is_rcu_reg(reg)) {
11651 					verbose(env, "R%d must be a rcu pointer\n", regno);
11652 					return -EINVAL;
11653 				}
11654 			}
11655 
11656 			fallthrough;
11657 		case KF_ARG_PTR_TO_CTX:
11658 			/* Trusted arguments have the same offset checks as release arguments */
11659 			arg_type |= OBJ_RELEASE;
11660 			break;
11661 		case KF_ARG_PTR_TO_DYNPTR:
11662 		case KF_ARG_PTR_TO_ITER:
11663 		case KF_ARG_PTR_TO_LIST_HEAD:
11664 		case KF_ARG_PTR_TO_LIST_NODE:
11665 		case KF_ARG_PTR_TO_RB_ROOT:
11666 		case KF_ARG_PTR_TO_RB_NODE:
11667 		case KF_ARG_PTR_TO_MEM:
11668 		case KF_ARG_PTR_TO_MEM_SIZE:
11669 		case KF_ARG_PTR_TO_CALLBACK:
11670 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11671 		case KF_ARG_PTR_TO_CONST_STR:
11672 			/* Trusted by default */
11673 			break;
11674 		default:
11675 			WARN_ON_ONCE(1);
11676 			return -EFAULT;
11677 		}
11678 
11679 		if (is_kfunc_release(meta) && reg->ref_obj_id)
11680 			arg_type |= OBJ_RELEASE;
11681 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11682 		if (ret < 0)
11683 			return ret;
11684 
11685 		switch (kf_arg_type) {
11686 		case KF_ARG_PTR_TO_CTX:
11687 			if (reg->type != PTR_TO_CTX) {
11688 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11689 				return -EINVAL;
11690 			}
11691 
11692 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11693 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11694 				if (ret < 0)
11695 					return -EINVAL;
11696 				meta->ret_btf_id  = ret;
11697 			}
11698 			break;
11699 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11700 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
11701 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
11702 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
11703 					return -EINVAL;
11704 				}
11705 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
11706 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
11707 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
11708 					return -EINVAL;
11709 				}
11710 			} else {
11711 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11712 				return -EINVAL;
11713 			}
11714 			if (!reg->ref_obj_id) {
11715 				verbose(env, "allocated object must be referenced\n");
11716 				return -EINVAL;
11717 			}
11718 			if (meta->btf == btf_vmlinux) {
11719 				meta->arg_btf = reg->btf;
11720 				meta->arg_btf_id = reg->btf_id;
11721 			}
11722 			break;
11723 		case KF_ARG_PTR_TO_DYNPTR:
11724 		{
11725 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11726 			int clone_ref_obj_id = 0;
11727 
11728 			if (reg->type != PTR_TO_STACK &&
11729 			    reg->type != CONST_PTR_TO_DYNPTR) {
11730 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11731 				return -EINVAL;
11732 			}
11733 
11734 			if (reg->type == CONST_PTR_TO_DYNPTR)
11735 				dynptr_arg_type |= MEM_RDONLY;
11736 
11737 			if (is_kfunc_arg_uninit(btf, &args[i]))
11738 				dynptr_arg_type |= MEM_UNINIT;
11739 
11740 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11741 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11742 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11743 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
11744 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11745 				   (dynptr_arg_type & MEM_UNINIT)) {
11746 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11747 
11748 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11749 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11750 					return -EFAULT;
11751 				}
11752 
11753 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11754 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11755 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11756 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11757 					return -EFAULT;
11758 				}
11759 			}
11760 
11761 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11762 			if (ret < 0)
11763 				return ret;
11764 
11765 			if (!(dynptr_arg_type & MEM_UNINIT)) {
11766 				int id = dynptr_id(env, reg);
11767 
11768 				if (id < 0) {
11769 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11770 					return id;
11771 				}
11772 				meta->initialized_dynptr.id = id;
11773 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11774 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11775 			}
11776 
11777 			break;
11778 		}
11779 		case KF_ARG_PTR_TO_ITER:
11780 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
11781 				if (!check_css_task_iter_allowlist(env)) {
11782 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
11783 					return -EINVAL;
11784 				}
11785 			}
11786 			ret = process_iter_arg(env, regno, insn_idx, meta);
11787 			if (ret < 0)
11788 				return ret;
11789 			break;
11790 		case KF_ARG_PTR_TO_LIST_HEAD:
11791 			if (reg->type != PTR_TO_MAP_VALUE &&
11792 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11793 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11794 				return -EINVAL;
11795 			}
11796 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11797 				verbose(env, "allocated object must be referenced\n");
11798 				return -EINVAL;
11799 			}
11800 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11801 			if (ret < 0)
11802 				return ret;
11803 			break;
11804 		case KF_ARG_PTR_TO_RB_ROOT:
11805 			if (reg->type != PTR_TO_MAP_VALUE &&
11806 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11807 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11808 				return -EINVAL;
11809 			}
11810 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11811 				verbose(env, "allocated object must be referenced\n");
11812 				return -EINVAL;
11813 			}
11814 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11815 			if (ret < 0)
11816 				return ret;
11817 			break;
11818 		case KF_ARG_PTR_TO_LIST_NODE:
11819 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11820 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11821 				return -EINVAL;
11822 			}
11823 			if (!reg->ref_obj_id) {
11824 				verbose(env, "allocated object must be referenced\n");
11825 				return -EINVAL;
11826 			}
11827 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11828 			if (ret < 0)
11829 				return ret;
11830 			break;
11831 		case KF_ARG_PTR_TO_RB_NODE:
11832 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11833 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11834 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
11835 					return -EINVAL;
11836 				}
11837 				if (in_rbtree_lock_required_cb(env)) {
11838 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11839 					return -EINVAL;
11840 				}
11841 			} else {
11842 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11843 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
11844 					return -EINVAL;
11845 				}
11846 				if (!reg->ref_obj_id) {
11847 					verbose(env, "allocated object must be referenced\n");
11848 					return -EINVAL;
11849 				}
11850 			}
11851 
11852 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11853 			if (ret < 0)
11854 				return ret;
11855 			break;
11856 		case KF_ARG_PTR_TO_BTF_ID:
11857 			/* Only base_type is checked, further checks are done here */
11858 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11859 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11860 			    !reg2btf_ids[base_type(reg->type)]) {
11861 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11862 				verbose(env, "expected %s or socket\n",
11863 					reg_type_str(env, base_type(reg->type) |
11864 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11865 				return -EINVAL;
11866 			}
11867 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11868 			if (ret < 0)
11869 				return ret;
11870 			break;
11871 		case KF_ARG_PTR_TO_MEM:
11872 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11873 			if (IS_ERR(resolve_ret)) {
11874 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11875 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11876 				return -EINVAL;
11877 			}
11878 			ret = check_mem_reg(env, reg, regno, type_size);
11879 			if (ret < 0)
11880 				return ret;
11881 			break;
11882 		case KF_ARG_PTR_TO_MEM_SIZE:
11883 		{
11884 			struct bpf_reg_state *buff_reg = &regs[regno];
11885 			const struct btf_param *buff_arg = &args[i];
11886 			struct bpf_reg_state *size_reg = &regs[regno + 1];
11887 			const struct btf_param *size_arg = &args[i + 1];
11888 
11889 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11890 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11891 				if (ret < 0) {
11892 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11893 					return ret;
11894 				}
11895 			}
11896 
11897 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11898 				if (meta->arg_constant.found) {
11899 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11900 					return -EFAULT;
11901 				}
11902 				if (!tnum_is_const(size_reg->var_off)) {
11903 					verbose(env, "R%d must be a known constant\n", regno + 1);
11904 					return -EINVAL;
11905 				}
11906 				meta->arg_constant.found = true;
11907 				meta->arg_constant.value = size_reg->var_off.value;
11908 			}
11909 
11910 			/* Skip next '__sz' or '__szk' argument */
11911 			i++;
11912 			break;
11913 		}
11914 		case KF_ARG_PTR_TO_CALLBACK:
11915 			if (reg->type != PTR_TO_FUNC) {
11916 				verbose(env, "arg%d expected pointer to func\n", i);
11917 				return -EINVAL;
11918 			}
11919 			meta->subprogno = reg->subprogno;
11920 			break;
11921 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11922 			if (!type_is_ptr_alloc_obj(reg->type)) {
11923 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11924 				return -EINVAL;
11925 			}
11926 			if (!type_is_non_owning_ref(reg->type))
11927 				meta->arg_owning_ref = true;
11928 
11929 			rec = reg_btf_record(reg);
11930 			if (!rec) {
11931 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
11932 				return -EFAULT;
11933 			}
11934 
11935 			if (rec->refcount_off < 0) {
11936 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11937 				return -EINVAL;
11938 			}
11939 
11940 			meta->arg_btf = reg->btf;
11941 			meta->arg_btf_id = reg->btf_id;
11942 			break;
11943 		case KF_ARG_PTR_TO_CONST_STR:
11944 			if (reg->type != PTR_TO_MAP_VALUE) {
11945 				verbose(env, "arg#%d doesn't point to a const string\n", i);
11946 				return -EINVAL;
11947 			}
11948 			ret = check_reg_const_str(env, reg, regno);
11949 			if (ret)
11950 				return ret;
11951 			break;
11952 		}
11953 	}
11954 
11955 	if (is_kfunc_release(meta) && !meta->release_regno) {
11956 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11957 			func_name);
11958 		return -EINVAL;
11959 	}
11960 
11961 	return 0;
11962 }
11963 
11964 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11965 			    struct bpf_insn *insn,
11966 			    struct bpf_kfunc_call_arg_meta *meta,
11967 			    const char **kfunc_name)
11968 {
11969 	const struct btf_type *func, *func_proto;
11970 	u32 func_id, *kfunc_flags;
11971 	const char *func_name;
11972 	struct btf *desc_btf;
11973 
11974 	if (kfunc_name)
11975 		*kfunc_name = NULL;
11976 
11977 	if (!insn->imm)
11978 		return -EINVAL;
11979 
11980 	desc_btf = find_kfunc_desc_btf(env, insn->off);
11981 	if (IS_ERR(desc_btf))
11982 		return PTR_ERR(desc_btf);
11983 
11984 	func_id = insn->imm;
11985 	func = btf_type_by_id(desc_btf, func_id);
11986 	func_name = btf_name_by_offset(desc_btf, func->name_off);
11987 	if (kfunc_name)
11988 		*kfunc_name = func_name;
11989 	func_proto = btf_type_by_id(desc_btf, func->type);
11990 
11991 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11992 	if (!kfunc_flags) {
11993 		return -EACCES;
11994 	}
11995 
11996 	memset(meta, 0, sizeof(*meta));
11997 	meta->btf = desc_btf;
11998 	meta->func_id = func_id;
11999 	meta->kfunc_flags = *kfunc_flags;
12000 	meta->func_proto = func_proto;
12001 	meta->func_name = func_name;
12002 
12003 	return 0;
12004 }
12005 
12006 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
12007 
12008 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12009 			    int *insn_idx_p)
12010 {
12011 	const struct btf_type *t, *ptr_type;
12012 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
12013 	struct bpf_reg_state *regs = cur_regs(env);
12014 	const char *func_name, *ptr_type_name;
12015 	bool sleepable, rcu_lock, rcu_unlock;
12016 	struct bpf_kfunc_call_arg_meta meta;
12017 	struct bpf_insn_aux_data *insn_aux;
12018 	int err, insn_idx = *insn_idx_p;
12019 	const struct btf_param *args;
12020 	const struct btf_type *ret_t;
12021 	struct btf *desc_btf;
12022 
12023 	/* skip for now, but return error when we find this in fixup_kfunc_call */
12024 	if (!insn->imm)
12025 		return 0;
12026 
12027 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
12028 	if (err == -EACCES && func_name)
12029 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
12030 	if (err)
12031 		return err;
12032 	desc_btf = meta.btf;
12033 	insn_aux = &env->insn_aux_data[insn_idx];
12034 
12035 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
12036 
12037 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
12038 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
12039 		return -EACCES;
12040 	}
12041 
12042 	sleepable = is_kfunc_sleepable(&meta);
12043 	if (sleepable && !env->prog->aux->sleepable) {
12044 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
12045 		return -EACCES;
12046 	}
12047 
12048 	/* Check the arguments */
12049 	err = check_kfunc_args(env, &meta, insn_idx);
12050 	if (err < 0)
12051 		return err;
12052 
12053 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12054 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12055 					 set_rbtree_add_callback_state);
12056 		if (err) {
12057 			verbose(env, "kfunc %s#%d failed callback verification\n",
12058 				func_name, meta.func_id);
12059 			return err;
12060 		}
12061 	}
12062 
12063 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
12064 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
12065 
12066 	if (env->cur_state->active_rcu_lock) {
12067 		struct bpf_func_state *state;
12068 		struct bpf_reg_state *reg;
12069 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
12070 
12071 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
12072 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
12073 			return -EACCES;
12074 		}
12075 
12076 		if (rcu_lock) {
12077 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
12078 			return -EINVAL;
12079 		} else if (rcu_unlock) {
12080 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
12081 				if (reg->type & MEM_RCU) {
12082 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
12083 					reg->type |= PTR_UNTRUSTED;
12084 				}
12085 			}));
12086 			env->cur_state->active_rcu_lock = false;
12087 		} else if (sleepable) {
12088 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
12089 			return -EACCES;
12090 		}
12091 	} else if (rcu_lock) {
12092 		env->cur_state->active_rcu_lock = true;
12093 	} else if (rcu_unlock) {
12094 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
12095 		return -EINVAL;
12096 	}
12097 
12098 	/* In case of release function, we get register number of refcounted
12099 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
12100 	 */
12101 	if (meta.release_regno) {
12102 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
12103 		if (err) {
12104 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12105 				func_name, meta.func_id);
12106 			return err;
12107 		}
12108 	}
12109 
12110 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12111 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12112 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12113 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
12114 		insn_aux->insert_off = regs[BPF_REG_2].off;
12115 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
12116 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
12117 		if (err) {
12118 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
12119 				func_name, meta.func_id);
12120 			return err;
12121 		}
12122 
12123 		err = release_reference(env, release_ref_obj_id);
12124 		if (err) {
12125 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12126 				func_name, meta.func_id);
12127 			return err;
12128 		}
12129 	}
12130 
12131 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
12132 		if (!bpf_jit_supports_exceptions()) {
12133 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
12134 				func_name, meta.func_id);
12135 			return -ENOTSUPP;
12136 		}
12137 		env->seen_exception = true;
12138 
12139 		/* In the case of the default callback, the cookie value passed
12140 		 * to bpf_throw becomes the return value of the program.
12141 		 */
12142 		if (!env->exception_callback_subprog) {
12143 			err = check_return_code(env, BPF_REG_1, "R1");
12144 			if (err < 0)
12145 				return err;
12146 		}
12147 	}
12148 
12149 	for (i = 0; i < CALLER_SAVED_REGS; i++)
12150 		mark_reg_not_init(env, regs, caller_saved[i]);
12151 
12152 	/* Check return type */
12153 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
12154 
12155 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
12156 		/* Only exception is bpf_obj_new_impl */
12157 		if (meta.btf != btf_vmlinux ||
12158 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
12159 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
12160 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
12161 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
12162 			return -EINVAL;
12163 		}
12164 	}
12165 
12166 	if (btf_type_is_scalar(t)) {
12167 		mark_reg_unknown(env, regs, BPF_REG_0);
12168 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
12169 	} else if (btf_type_is_ptr(t)) {
12170 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
12171 
12172 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12173 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
12174 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12175 				struct btf_struct_meta *struct_meta;
12176 				struct btf *ret_btf;
12177 				u32 ret_btf_id;
12178 
12179 				if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
12180 					return -ENOMEM;
12181 
12182 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
12183 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12184 					return -EINVAL;
12185 				}
12186 
12187 				ret_btf = env->prog->aux->btf;
12188 				ret_btf_id = meta.arg_constant.value;
12189 
12190 				/* This may be NULL due to user not supplying a BTF */
12191 				if (!ret_btf) {
12192 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12193 					return -EINVAL;
12194 				}
12195 
12196 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12197 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
12198 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12199 					return -EINVAL;
12200 				}
12201 
12202 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12203 					if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
12204 						verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
12205 							ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
12206 						return -EINVAL;
12207 					}
12208 
12209 					if (!bpf_global_percpu_ma_set) {
12210 						mutex_lock(&bpf_percpu_ma_lock);
12211 						if (!bpf_global_percpu_ma_set) {
12212 							/* Charge memory allocated with bpf_global_percpu_ma to
12213 							 * root memcg. The obj_cgroup for root memcg is NULL.
12214 							 */
12215 							err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
12216 							if (!err)
12217 								bpf_global_percpu_ma_set = true;
12218 						}
12219 						mutex_unlock(&bpf_percpu_ma_lock);
12220 						if (err)
12221 							return err;
12222 					}
12223 
12224 					mutex_lock(&bpf_percpu_ma_lock);
12225 					err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
12226 					mutex_unlock(&bpf_percpu_ma_lock);
12227 					if (err)
12228 						return err;
12229 				}
12230 
12231 				struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12232 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12233 					if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12234 						verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12235 						return -EINVAL;
12236 					}
12237 
12238 					if (struct_meta) {
12239 						verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12240 						return -EINVAL;
12241 					}
12242 				}
12243 
12244 				mark_reg_known_zero(env, regs, BPF_REG_0);
12245 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12246 				regs[BPF_REG_0].btf = ret_btf;
12247 				regs[BPF_REG_0].btf_id = ret_btf_id;
12248 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12249 					regs[BPF_REG_0].type |= MEM_PERCPU;
12250 
12251 				insn_aux->obj_new_size = ret_t->size;
12252 				insn_aux->kptr_struct_meta = struct_meta;
12253 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12254 				mark_reg_known_zero(env, regs, BPF_REG_0);
12255 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12256 				regs[BPF_REG_0].btf = meta.arg_btf;
12257 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
12258 
12259 				insn_aux->kptr_struct_meta =
12260 					btf_find_struct_meta(meta.arg_btf,
12261 							     meta.arg_btf_id);
12262 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12263 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12264 				struct btf_field *field = meta.arg_list_head.field;
12265 
12266 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12267 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12268 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12269 				struct btf_field *field = meta.arg_rbtree_root.field;
12270 
12271 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12272 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12273 				mark_reg_known_zero(env, regs, BPF_REG_0);
12274 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12275 				regs[BPF_REG_0].btf = desc_btf;
12276 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12277 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12278 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12279 				if (!ret_t || !btf_type_is_struct(ret_t)) {
12280 					verbose(env,
12281 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
12282 					return -EINVAL;
12283 				}
12284 
12285 				mark_reg_known_zero(env, regs, BPF_REG_0);
12286 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12287 				regs[BPF_REG_0].btf = desc_btf;
12288 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
12289 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12290 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12291 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
12292 
12293 				mark_reg_known_zero(env, regs, BPF_REG_0);
12294 
12295 				if (!meta.arg_constant.found) {
12296 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
12297 					return -EFAULT;
12298 				}
12299 
12300 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
12301 
12302 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12303 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12304 
12305 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12306 					regs[BPF_REG_0].type |= MEM_RDONLY;
12307 				} else {
12308 					/* this will set env->seen_direct_write to true */
12309 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12310 						verbose(env, "the prog does not allow writes to packet data\n");
12311 						return -EINVAL;
12312 					}
12313 				}
12314 
12315 				if (!meta.initialized_dynptr.id) {
12316 					verbose(env, "verifier internal error: no dynptr id\n");
12317 					return -EFAULT;
12318 				}
12319 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
12320 
12321 				/* we don't need to set BPF_REG_0's ref obj id
12322 				 * because packet slices are not refcounted (see
12323 				 * dynptr_type_refcounted)
12324 				 */
12325 			} else {
12326 				verbose(env, "kernel function %s unhandled dynamic return type\n",
12327 					meta.func_name);
12328 				return -EFAULT;
12329 			}
12330 		} else if (!__btf_type_is_struct(ptr_type)) {
12331 			if (!meta.r0_size) {
12332 				__u32 sz;
12333 
12334 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
12335 					meta.r0_size = sz;
12336 					meta.r0_rdonly = true;
12337 				}
12338 			}
12339 			if (!meta.r0_size) {
12340 				ptr_type_name = btf_name_by_offset(desc_btf,
12341 								   ptr_type->name_off);
12342 				verbose(env,
12343 					"kernel function %s returns pointer type %s %s is not supported\n",
12344 					func_name,
12345 					btf_type_str(ptr_type),
12346 					ptr_type_name);
12347 				return -EINVAL;
12348 			}
12349 
12350 			mark_reg_known_zero(env, regs, BPF_REG_0);
12351 			regs[BPF_REG_0].type = PTR_TO_MEM;
12352 			regs[BPF_REG_0].mem_size = meta.r0_size;
12353 
12354 			if (meta.r0_rdonly)
12355 				regs[BPF_REG_0].type |= MEM_RDONLY;
12356 
12357 			/* Ensures we don't access the memory after a release_reference() */
12358 			if (meta.ref_obj_id)
12359 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12360 		} else {
12361 			mark_reg_known_zero(env, regs, BPF_REG_0);
12362 			regs[BPF_REG_0].btf = desc_btf;
12363 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12364 			regs[BPF_REG_0].btf_id = ptr_type_id;
12365 		}
12366 
12367 		if (is_kfunc_ret_null(&meta)) {
12368 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12369 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12370 			regs[BPF_REG_0].id = ++env->id_gen;
12371 		}
12372 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12373 		if (is_kfunc_acquire(&meta)) {
12374 			int id = acquire_reference_state(env, insn_idx);
12375 
12376 			if (id < 0)
12377 				return id;
12378 			if (is_kfunc_ret_null(&meta))
12379 				regs[BPF_REG_0].id = id;
12380 			regs[BPF_REG_0].ref_obj_id = id;
12381 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12382 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12383 		}
12384 
12385 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12386 			regs[BPF_REG_0].id = ++env->id_gen;
12387 	} else if (btf_type_is_void(t)) {
12388 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12389 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
12390 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12391 				insn_aux->kptr_struct_meta =
12392 					btf_find_struct_meta(meta.arg_btf,
12393 							     meta.arg_btf_id);
12394 			}
12395 		}
12396 	}
12397 
12398 	nargs = btf_type_vlen(meta.func_proto);
12399 	args = (const struct btf_param *)(meta.func_proto + 1);
12400 	for (i = 0; i < nargs; i++) {
12401 		u32 regno = i + 1;
12402 
12403 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12404 		if (btf_type_is_ptr(t))
12405 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12406 		else
12407 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12408 			mark_btf_func_reg_size(env, regno, t->size);
12409 	}
12410 
12411 	if (is_iter_next_kfunc(&meta)) {
12412 		err = process_iter_next_call(env, insn_idx, &meta);
12413 		if (err)
12414 			return err;
12415 	}
12416 
12417 	return 0;
12418 }
12419 
12420 static bool signed_add_overflows(s64 a, s64 b)
12421 {
12422 	/* Do the add in u64, where overflow is well-defined */
12423 	s64 res = (s64)((u64)a + (u64)b);
12424 
12425 	if (b < 0)
12426 		return res > a;
12427 	return res < a;
12428 }
12429 
12430 static bool signed_add32_overflows(s32 a, s32 b)
12431 {
12432 	/* Do the add in u32, where overflow is well-defined */
12433 	s32 res = (s32)((u32)a + (u32)b);
12434 
12435 	if (b < 0)
12436 		return res > a;
12437 	return res < a;
12438 }
12439 
12440 static bool signed_sub_overflows(s64 a, s64 b)
12441 {
12442 	/* Do the sub in u64, where overflow is well-defined */
12443 	s64 res = (s64)((u64)a - (u64)b);
12444 
12445 	if (b < 0)
12446 		return res < a;
12447 	return res > a;
12448 }
12449 
12450 static bool signed_sub32_overflows(s32 a, s32 b)
12451 {
12452 	/* Do the sub in u32, where overflow is well-defined */
12453 	s32 res = (s32)((u32)a - (u32)b);
12454 
12455 	if (b < 0)
12456 		return res < a;
12457 	return res > a;
12458 }
12459 
12460 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12461 				  const struct bpf_reg_state *reg,
12462 				  enum bpf_reg_type type)
12463 {
12464 	bool known = tnum_is_const(reg->var_off);
12465 	s64 val = reg->var_off.value;
12466 	s64 smin = reg->smin_value;
12467 
12468 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12469 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12470 			reg_type_str(env, type), val);
12471 		return false;
12472 	}
12473 
12474 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12475 		verbose(env, "%s pointer offset %d is not allowed\n",
12476 			reg_type_str(env, type), reg->off);
12477 		return false;
12478 	}
12479 
12480 	if (smin == S64_MIN) {
12481 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12482 			reg_type_str(env, type));
12483 		return false;
12484 	}
12485 
12486 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12487 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12488 			smin, reg_type_str(env, type));
12489 		return false;
12490 	}
12491 
12492 	return true;
12493 }
12494 
12495 enum {
12496 	REASON_BOUNDS	= -1,
12497 	REASON_TYPE	= -2,
12498 	REASON_PATHS	= -3,
12499 	REASON_LIMIT	= -4,
12500 	REASON_STACK	= -5,
12501 };
12502 
12503 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12504 			      u32 *alu_limit, bool mask_to_left)
12505 {
12506 	u32 max = 0, ptr_limit = 0;
12507 
12508 	switch (ptr_reg->type) {
12509 	case PTR_TO_STACK:
12510 		/* Offset 0 is out-of-bounds, but acceptable start for the
12511 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12512 		 * offset where we would need to deal with min/max bounds is
12513 		 * currently prohibited for unprivileged.
12514 		 */
12515 		max = MAX_BPF_STACK + mask_to_left;
12516 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12517 		break;
12518 	case PTR_TO_MAP_VALUE:
12519 		max = ptr_reg->map_ptr->value_size;
12520 		ptr_limit = (mask_to_left ?
12521 			     ptr_reg->smin_value :
12522 			     ptr_reg->umax_value) + ptr_reg->off;
12523 		break;
12524 	default:
12525 		return REASON_TYPE;
12526 	}
12527 
12528 	if (ptr_limit >= max)
12529 		return REASON_LIMIT;
12530 	*alu_limit = ptr_limit;
12531 	return 0;
12532 }
12533 
12534 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12535 				    const struct bpf_insn *insn)
12536 {
12537 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12538 }
12539 
12540 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12541 				       u32 alu_state, u32 alu_limit)
12542 {
12543 	/* If we arrived here from different branches with different
12544 	 * state or limits to sanitize, then this won't work.
12545 	 */
12546 	if (aux->alu_state &&
12547 	    (aux->alu_state != alu_state ||
12548 	     aux->alu_limit != alu_limit))
12549 		return REASON_PATHS;
12550 
12551 	/* Corresponding fixup done in do_misc_fixups(). */
12552 	aux->alu_state = alu_state;
12553 	aux->alu_limit = alu_limit;
12554 	return 0;
12555 }
12556 
12557 static int sanitize_val_alu(struct bpf_verifier_env *env,
12558 			    struct bpf_insn *insn)
12559 {
12560 	struct bpf_insn_aux_data *aux = cur_aux(env);
12561 
12562 	if (can_skip_alu_sanitation(env, insn))
12563 		return 0;
12564 
12565 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12566 }
12567 
12568 static bool sanitize_needed(u8 opcode)
12569 {
12570 	return opcode == BPF_ADD || opcode == BPF_SUB;
12571 }
12572 
12573 struct bpf_sanitize_info {
12574 	struct bpf_insn_aux_data aux;
12575 	bool mask_to_left;
12576 };
12577 
12578 static struct bpf_verifier_state *
12579 sanitize_speculative_path(struct bpf_verifier_env *env,
12580 			  const struct bpf_insn *insn,
12581 			  u32 next_idx, u32 curr_idx)
12582 {
12583 	struct bpf_verifier_state *branch;
12584 	struct bpf_reg_state *regs;
12585 
12586 	branch = push_stack(env, next_idx, curr_idx, true);
12587 	if (branch && insn) {
12588 		regs = branch->frame[branch->curframe]->regs;
12589 		if (BPF_SRC(insn->code) == BPF_K) {
12590 			mark_reg_unknown(env, regs, insn->dst_reg);
12591 		} else if (BPF_SRC(insn->code) == BPF_X) {
12592 			mark_reg_unknown(env, regs, insn->dst_reg);
12593 			mark_reg_unknown(env, regs, insn->src_reg);
12594 		}
12595 	}
12596 	return branch;
12597 }
12598 
12599 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12600 			    struct bpf_insn *insn,
12601 			    const struct bpf_reg_state *ptr_reg,
12602 			    const struct bpf_reg_state *off_reg,
12603 			    struct bpf_reg_state *dst_reg,
12604 			    struct bpf_sanitize_info *info,
12605 			    const bool commit_window)
12606 {
12607 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12608 	struct bpf_verifier_state *vstate = env->cur_state;
12609 	bool off_is_imm = tnum_is_const(off_reg->var_off);
12610 	bool off_is_neg = off_reg->smin_value < 0;
12611 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12612 	u8 opcode = BPF_OP(insn->code);
12613 	u32 alu_state, alu_limit;
12614 	struct bpf_reg_state tmp;
12615 	bool ret;
12616 	int err;
12617 
12618 	if (can_skip_alu_sanitation(env, insn))
12619 		return 0;
12620 
12621 	/* We already marked aux for masking from non-speculative
12622 	 * paths, thus we got here in the first place. We only care
12623 	 * to explore bad access from here.
12624 	 */
12625 	if (vstate->speculative)
12626 		goto do_sim;
12627 
12628 	if (!commit_window) {
12629 		if (!tnum_is_const(off_reg->var_off) &&
12630 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12631 			return REASON_BOUNDS;
12632 
12633 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12634 				     (opcode == BPF_SUB && !off_is_neg);
12635 	}
12636 
12637 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12638 	if (err < 0)
12639 		return err;
12640 
12641 	if (commit_window) {
12642 		/* In commit phase we narrow the masking window based on
12643 		 * the observed pointer move after the simulated operation.
12644 		 */
12645 		alu_state = info->aux.alu_state;
12646 		alu_limit = abs(info->aux.alu_limit - alu_limit);
12647 	} else {
12648 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12649 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12650 		alu_state |= ptr_is_dst_reg ?
12651 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12652 
12653 		/* Limit pruning on unknown scalars to enable deep search for
12654 		 * potential masking differences from other program paths.
12655 		 */
12656 		if (!off_is_imm)
12657 			env->explore_alu_limits = true;
12658 	}
12659 
12660 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12661 	if (err < 0)
12662 		return err;
12663 do_sim:
12664 	/* If we're in commit phase, we're done here given we already
12665 	 * pushed the truncated dst_reg into the speculative verification
12666 	 * stack.
12667 	 *
12668 	 * Also, when register is a known constant, we rewrite register-based
12669 	 * operation to immediate-based, and thus do not need masking (and as
12670 	 * a consequence, do not need to simulate the zero-truncation either).
12671 	 */
12672 	if (commit_window || off_is_imm)
12673 		return 0;
12674 
12675 	/* Simulate and find potential out-of-bounds access under
12676 	 * speculative execution from truncation as a result of
12677 	 * masking when off was not within expected range. If off
12678 	 * sits in dst, then we temporarily need to move ptr there
12679 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12680 	 * for cases where we use K-based arithmetic in one direction
12681 	 * and truncated reg-based in the other in order to explore
12682 	 * bad access.
12683 	 */
12684 	if (!ptr_is_dst_reg) {
12685 		tmp = *dst_reg;
12686 		copy_register_state(dst_reg, ptr_reg);
12687 	}
12688 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12689 					env->insn_idx);
12690 	if (!ptr_is_dst_reg && ret)
12691 		*dst_reg = tmp;
12692 	return !ret ? REASON_STACK : 0;
12693 }
12694 
12695 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12696 {
12697 	struct bpf_verifier_state *vstate = env->cur_state;
12698 
12699 	/* If we simulate paths under speculation, we don't update the
12700 	 * insn as 'seen' such that when we verify unreachable paths in
12701 	 * the non-speculative domain, sanitize_dead_code() can still
12702 	 * rewrite/sanitize them.
12703 	 */
12704 	if (!vstate->speculative)
12705 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12706 }
12707 
12708 static int sanitize_err(struct bpf_verifier_env *env,
12709 			const struct bpf_insn *insn, int reason,
12710 			const struct bpf_reg_state *off_reg,
12711 			const struct bpf_reg_state *dst_reg)
12712 {
12713 	static const char *err = "pointer arithmetic with it prohibited for !root";
12714 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12715 	u32 dst = insn->dst_reg, src = insn->src_reg;
12716 
12717 	switch (reason) {
12718 	case REASON_BOUNDS:
12719 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12720 			off_reg == dst_reg ? dst : src, err);
12721 		break;
12722 	case REASON_TYPE:
12723 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12724 			off_reg == dst_reg ? src : dst, err);
12725 		break;
12726 	case REASON_PATHS:
12727 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12728 			dst, op, err);
12729 		break;
12730 	case REASON_LIMIT:
12731 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12732 			dst, op, err);
12733 		break;
12734 	case REASON_STACK:
12735 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12736 			dst, err);
12737 		break;
12738 	default:
12739 		verbose(env, "verifier internal error: unknown reason (%d)\n",
12740 			reason);
12741 		break;
12742 	}
12743 
12744 	return -EACCES;
12745 }
12746 
12747 /* check that stack access falls within stack limits and that 'reg' doesn't
12748  * have a variable offset.
12749  *
12750  * Variable offset is prohibited for unprivileged mode for simplicity since it
12751  * requires corresponding support in Spectre masking for stack ALU.  See also
12752  * retrieve_ptr_limit().
12753  *
12754  *
12755  * 'off' includes 'reg->off'.
12756  */
12757 static int check_stack_access_for_ptr_arithmetic(
12758 				struct bpf_verifier_env *env,
12759 				int regno,
12760 				const struct bpf_reg_state *reg,
12761 				int off)
12762 {
12763 	if (!tnum_is_const(reg->var_off)) {
12764 		char tn_buf[48];
12765 
12766 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12767 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12768 			regno, tn_buf, off);
12769 		return -EACCES;
12770 	}
12771 
12772 	if (off >= 0 || off < -MAX_BPF_STACK) {
12773 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
12774 			"prohibited for !root; off=%d\n", regno, off);
12775 		return -EACCES;
12776 	}
12777 
12778 	return 0;
12779 }
12780 
12781 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12782 				 const struct bpf_insn *insn,
12783 				 const struct bpf_reg_state *dst_reg)
12784 {
12785 	u32 dst = insn->dst_reg;
12786 
12787 	/* For unprivileged we require that resulting offset must be in bounds
12788 	 * in order to be able to sanitize access later on.
12789 	 */
12790 	if (env->bypass_spec_v1)
12791 		return 0;
12792 
12793 	switch (dst_reg->type) {
12794 	case PTR_TO_STACK:
12795 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12796 					dst_reg->off + dst_reg->var_off.value))
12797 			return -EACCES;
12798 		break;
12799 	case PTR_TO_MAP_VALUE:
12800 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12801 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12802 				"prohibited for !root\n", dst);
12803 			return -EACCES;
12804 		}
12805 		break;
12806 	default:
12807 		break;
12808 	}
12809 
12810 	return 0;
12811 }
12812 
12813 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12814  * Caller should also handle BPF_MOV case separately.
12815  * If we return -EACCES, caller may want to try again treating pointer as a
12816  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12817  */
12818 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12819 				   struct bpf_insn *insn,
12820 				   const struct bpf_reg_state *ptr_reg,
12821 				   const struct bpf_reg_state *off_reg)
12822 {
12823 	struct bpf_verifier_state *vstate = env->cur_state;
12824 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12825 	struct bpf_reg_state *regs = state->regs, *dst_reg;
12826 	bool known = tnum_is_const(off_reg->var_off);
12827 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12828 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12829 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12830 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12831 	struct bpf_sanitize_info info = {};
12832 	u8 opcode = BPF_OP(insn->code);
12833 	u32 dst = insn->dst_reg;
12834 	int ret;
12835 
12836 	dst_reg = &regs[dst];
12837 
12838 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12839 	    smin_val > smax_val || umin_val > umax_val) {
12840 		/* Taint dst register if offset had invalid bounds derived from
12841 		 * e.g. dead branches.
12842 		 */
12843 		__mark_reg_unknown(env, dst_reg);
12844 		return 0;
12845 	}
12846 
12847 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
12848 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
12849 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12850 			__mark_reg_unknown(env, dst_reg);
12851 			return 0;
12852 		}
12853 
12854 		verbose(env,
12855 			"R%d 32-bit pointer arithmetic prohibited\n",
12856 			dst);
12857 		return -EACCES;
12858 	}
12859 
12860 	if (ptr_reg->type & PTR_MAYBE_NULL) {
12861 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12862 			dst, reg_type_str(env, ptr_reg->type));
12863 		return -EACCES;
12864 	}
12865 
12866 	switch (base_type(ptr_reg->type)) {
12867 	case PTR_TO_CTX:
12868 	case PTR_TO_MAP_VALUE:
12869 	case PTR_TO_MAP_KEY:
12870 	case PTR_TO_STACK:
12871 	case PTR_TO_PACKET_META:
12872 	case PTR_TO_PACKET:
12873 	case PTR_TO_TP_BUFFER:
12874 	case PTR_TO_BTF_ID:
12875 	case PTR_TO_MEM:
12876 	case PTR_TO_BUF:
12877 	case PTR_TO_FUNC:
12878 	case CONST_PTR_TO_DYNPTR:
12879 		break;
12880 	case PTR_TO_FLOW_KEYS:
12881 		if (known)
12882 			break;
12883 		fallthrough;
12884 	case CONST_PTR_TO_MAP:
12885 		/* smin_val represents the known value */
12886 		if (known && smin_val == 0 && opcode == BPF_ADD)
12887 			break;
12888 		fallthrough;
12889 	default:
12890 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12891 			dst, reg_type_str(env, ptr_reg->type));
12892 		return -EACCES;
12893 	}
12894 
12895 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12896 	 * The id may be overwritten later if we create a new variable offset.
12897 	 */
12898 	dst_reg->type = ptr_reg->type;
12899 	dst_reg->id = ptr_reg->id;
12900 
12901 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12902 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12903 		return -EINVAL;
12904 
12905 	/* pointer types do not carry 32-bit bounds at the moment. */
12906 	__mark_reg32_unbounded(dst_reg);
12907 
12908 	if (sanitize_needed(opcode)) {
12909 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12910 				       &info, false);
12911 		if (ret < 0)
12912 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12913 	}
12914 
12915 	switch (opcode) {
12916 	case BPF_ADD:
12917 		/* We can take a fixed offset as long as it doesn't overflow
12918 		 * the s32 'off' field
12919 		 */
12920 		if (known && (ptr_reg->off + smin_val ==
12921 			      (s64)(s32)(ptr_reg->off + smin_val))) {
12922 			/* pointer += K.  Accumulate it into fixed offset */
12923 			dst_reg->smin_value = smin_ptr;
12924 			dst_reg->smax_value = smax_ptr;
12925 			dst_reg->umin_value = umin_ptr;
12926 			dst_reg->umax_value = umax_ptr;
12927 			dst_reg->var_off = ptr_reg->var_off;
12928 			dst_reg->off = ptr_reg->off + smin_val;
12929 			dst_reg->raw = ptr_reg->raw;
12930 			break;
12931 		}
12932 		/* A new variable offset is created.  Note that off_reg->off
12933 		 * == 0, since it's a scalar.
12934 		 * dst_reg gets the pointer type and since some positive
12935 		 * integer value was added to the pointer, give it a new 'id'
12936 		 * if it's a PTR_TO_PACKET.
12937 		 * this creates a new 'base' pointer, off_reg (variable) gets
12938 		 * added into the variable offset, and we copy the fixed offset
12939 		 * from ptr_reg.
12940 		 */
12941 		if (signed_add_overflows(smin_ptr, smin_val) ||
12942 		    signed_add_overflows(smax_ptr, smax_val)) {
12943 			dst_reg->smin_value = S64_MIN;
12944 			dst_reg->smax_value = S64_MAX;
12945 		} else {
12946 			dst_reg->smin_value = smin_ptr + smin_val;
12947 			dst_reg->smax_value = smax_ptr + smax_val;
12948 		}
12949 		if (umin_ptr + umin_val < umin_ptr ||
12950 		    umax_ptr + umax_val < umax_ptr) {
12951 			dst_reg->umin_value = 0;
12952 			dst_reg->umax_value = U64_MAX;
12953 		} else {
12954 			dst_reg->umin_value = umin_ptr + umin_val;
12955 			dst_reg->umax_value = umax_ptr + umax_val;
12956 		}
12957 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12958 		dst_reg->off = ptr_reg->off;
12959 		dst_reg->raw = ptr_reg->raw;
12960 		if (reg_is_pkt_pointer(ptr_reg)) {
12961 			dst_reg->id = ++env->id_gen;
12962 			/* something was added to pkt_ptr, set range to zero */
12963 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12964 		}
12965 		break;
12966 	case BPF_SUB:
12967 		if (dst_reg == off_reg) {
12968 			/* scalar -= pointer.  Creates an unknown scalar */
12969 			verbose(env, "R%d tried to subtract pointer from scalar\n",
12970 				dst);
12971 			return -EACCES;
12972 		}
12973 		/* We don't allow subtraction from FP, because (according to
12974 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
12975 		 * be able to deal with it.
12976 		 */
12977 		if (ptr_reg->type == PTR_TO_STACK) {
12978 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
12979 				dst);
12980 			return -EACCES;
12981 		}
12982 		if (known && (ptr_reg->off - smin_val ==
12983 			      (s64)(s32)(ptr_reg->off - smin_val))) {
12984 			/* pointer -= K.  Subtract it from fixed offset */
12985 			dst_reg->smin_value = smin_ptr;
12986 			dst_reg->smax_value = smax_ptr;
12987 			dst_reg->umin_value = umin_ptr;
12988 			dst_reg->umax_value = umax_ptr;
12989 			dst_reg->var_off = ptr_reg->var_off;
12990 			dst_reg->id = ptr_reg->id;
12991 			dst_reg->off = ptr_reg->off - smin_val;
12992 			dst_reg->raw = ptr_reg->raw;
12993 			break;
12994 		}
12995 		/* A new variable offset is created.  If the subtrahend is known
12996 		 * nonnegative, then any reg->range we had before is still good.
12997 		 */
12998 		if (signed_sub_overflows(smin_ptr, smax_val) ||
12999 		    signed_sub_overflows(smax_ptr, smin_val)) {
13000 			/* Overflow possible, we know nothing */
13001 			dst_reg->smin_value = S64_MIN;
13002 			dst_reg->smax_value = S64_MAX;
13003 		} else {
13004 			dst_reg->smin_value = smin_ptr - smax_val;
13005 			dst_reg->smax_value = smax_ptr - smin_val;
13006 		}
13007 		if (umin_ptr < umax_val) {
13008 			/* Overflow possible, we know nothing */
13009 			dst_reg->umin_value = 0;
13010 			dst_reg->umax_value = U64_MAX;
13011 		} else {
13012 			/* Cannot overflow (as long as bounds are consistent) */
13013 			dst_reg->umin_value = umin_ptr - umax_val;
13014 			dst_reg->umax_value = umax_ptr - umin_val;
13015 		}
13016 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
13017 		dst_reg->off = ptr_reg->off;
13018 		dst_reg->raw = ptr_reg->raw;
13019 		if (reg_is_pkt_pointer(ptr_reg)) {
13020 			dst_reg->id = ++env->id_gen;
13021 			/* something was added to pkt_ptr, set range to zero */
13022 			if (smin_val < 0)
13023 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13024 		}
13025 		break;
13026 	case BPF_AND:
13027 	case BPF_OR:
13028 	case BPF_XOR:
13029 		/* bitwise ops on pointers are troublesome, prohibit. */
13030 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
13031 			dst, bpf_alu_string[opcode >> 4]);
13032 		return -EACCES;
13033 	default:
13034 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
13035 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
13036 			dst, bpf_alu_string[opcode >> 4]);
13037 		return -EACCES;
13038 	}
13039 
13040 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
13041 		return -EINVAL;
13042 	reg_bounds_sync(dst_reg);
13043 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
13044 		return -EACCES;
13045 	if (sanitize_needed(opcode)) {
13046 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
13047 				       &info, true);
13048 		if (ret < 0)
13049 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13050 	}
13051 
13052 	return 0;
13053 }
13054 
13055 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
13056 				 struct bpf_reg_state *src_reg)
13057 {
13058 	s32 smin_val = src_reg->s32_min_value;
13059 	s32 smax_val = src_reg->s32_max_value;
13060 	u32 umin_val = src_reg->u32_min_value;
13061 	u32 umax_val = src_reg->u32_max_value;
13062 
13063 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
13064 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
13065 		dst_reg->s32_min_value = S32_MIN;
13066 		dst_reg->s32_max_value = S32_MAX;
13067 	} else {
13068 		dst_reg->s32_min_value += smin_val;
13069 		dst_reg->s32_max_value += smax_val;
13070 	}
13071 	if (dst_reg->u32_min_value + umin_val < umin_val ||
13072 	    dst_reg->u32_max_value + umax_val < umax_val) {
13073 		dst_reg->u32_min_value = 0;
13074 		dst_reg->u32_max_value = U32_MAX;
13075 	} else {
13076 		dst_reg->u32_min_value += umin_val;
13077 		dst_reg->u32_max_value += umax_val;
13078 	}
13079 }
13080 
13081 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
13082 			       struct bpf_reg_state *src_reg)
13083 {
13084 	s64 smin_val = src_reg->smin_value;
13085 	s64 smax_val = src_reg->smax_value;
13086 	u64 umin_val = src_reg->umin_value;
13087 	u64 umax_val = src_reg->umax_value;
13088 
13089 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
13090 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
13091 		dst_reg->smin_value = S64_MIN;
13092 		dst_reg->smax_value = S64_MAX;
13093 	} else {
13094 		dst_reg->smin_value += smin_val;
13095 		dst_reg->smax_value += smax_val;
13096 	}
13097 	if (dst_reg->umin_value + umin_val < umin_val ||
13098 	    dst_reg->umax_value + umax_val < umax_val) {
13099 		dst_reg->umin_value = 0;
13100 		dst_reg->umax_value = U64_MAX;
13101 	} else {
13102 		dst_reg->umin_value += umin_val;
13103 		dst_reg->umax_value += umax_val;
13104 	}
13105 }
13106 
13107 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
13108 				 struct bpf_reg_state *src_reg)
13109 {
13110 	s32 smin_val = src_reg->s32_min_value;
13111 	s32 smax_val = src_reg->s32_max_value;
13112 	u32 umin_val = src_reg->u32_min_value;
13113 	u32 umax_val = src_reg->u32_max_value;
13114 
13115 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
13116 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
13117 		/* Overflow possible, we know nothing */
13118 		dst_reg->s32_min_value = S32_MIN;
13119 		dst_reg->s32_max_value = S32_MAX;
13120 	} else {
13121 		dst_reg->s32_min_value -= smax_val;
13122 		dst_reg->s32_max_value -= smin_val;
13123 	}
13124 	if (dst_reg->u32_min_value < umax_val) {
13125 		/* Overflow possible, we know nothing */
13126 		dst_reg->u32_min_value = 0;
13127 		dst_reg->u32_max_value = U32_MAX;
13128 	} else {
13129 		/* Cannot overflow (as long as bounds are consistent) */
13130 		dst_reg->u32_min_value -= umax_val;
13131 		dst_reg->u32_max_value -= umin_val;
13132 	}
13133 }
13134 
13135 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
13136 			       struct bpf_reg_state *src_reg)
13137 {
13138 	s64 smin_val = src_reg->smin_value;
13139 	s64 smax_val = src_reg->smax_value;
13140 	u64 umin_val = src_reg->umin_value;
13141 	u64 umax_val = src_reg->umax_value;
13142 
13143 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
13144 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
13145 		/* Overflow possible, we know nothing */
13146 		dst_reg->smin_value = S64_MIN;
13147 		dst_reg->smax_value = S64_MAX;
13148 	} else {
13149 		dst_reg->smin_value -= smax_val;
13150 		dst_reg->smax_value -= smin_val;
13151 	}
13152 	if (dst_reg->umin_value < umax_val) {
13153 		/* Overflow possible, we know nothing */
13154 		dst_reg->umin_value = 0;
13155 		dst_reg->umax_value = U64_MAX;
13156 	} else {
13157 		/* Cannot overflow (as long as bounds are consistent) */
13158 		dst_reg->umin_value -= umax_val;
13159 		dst_reg->umax_value -= umin_val;
13160 	}
13161 }
13162 
13163 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13164 				 struct bpf_reg_state *src_reg)
13165 {
13166 	s32 smin_val = src_reg->s32_min_value;
13167 	u32 umin_val = src_reg->u32_min_value;
13168 	u32 umax_val = src_reg->u32_max_value;
13169 
13170 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
13171 		/* Ain't nobody got time to multiply that sign */
13172 		__mark_reg32_unbounded(dst_reg);
13173 		return;
13174 	}
13175 	/* Both values are positive, so we can work with unsigned and
13176 	 * copy the result to signed (unless it exceeds S32_MAX).
13177 	 */
13178 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
13179 		/* Potential overflow, we know nothing */
13180 		__mark_reg32_unbounded(dst_reg);
13181 		return;
13182 	}
13183 	dst_reg->u32_min_value *= umin_val;
13184 	dst_reg->u32_max_value *= umax_val;
13185 	if (dst_reg->u32_max_value > S32_MAX) {
13186 		/* Overflow possible, we know nothing */
13187 		dst_reg->s32_min_value = S32_MIN;
13188 		dst_reg->s32_max_value = S32_MAX;
13189 	} else {
13190 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13191 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13192 	}
13193 }
13194 
13195 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13196 			       struct bpf_reg_state *src_reg)
13197 {
13198 	s64 smin_val = src_reg->smin_value;
13199 	u64 umin_val = src_reg->umin_value;
13200 	u64 umax_val = src_reg->umax_value;
13201 
13202 	if (smin_val < 0 || dst_reg->smin_value < 0) {
13203 		/* Ain't nobody got time to multiply that sign */
13204 		__mark_reg64_unbounded(dst_reg);
13205 		return;
13206 	}
13207 	/* Both values are positive, so we can work with unsigned and
13208 	 * copy the result to signed (unless it exceeds S64_MAX).
13209 	 */
13210 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
13211 		/* Potential overflow, we know nothing */
13212 		__mark_reg64_unbounded(dst_reg);
13213 		return;
13214 	}
13215 	dst_reg->umin_value *= umin_val;
13216 	dst_reg->umax_value *= umax_val;
13217 	if (dst_reg->umax_value > S64_MAX) {
13218 		/* Overflow possible, we know nothing */
13219 		dst_reg->smin_value = S64_MIN;
13220 		dst_reg->smax_value = S64_MAX;
13221 	} else {
13222 		dst_reg->smin_value = dst_reg->umin_value;
13223 		dst_reg->smax_value = dst_reg->umax_value;
13224 	}
13225 }
13226 
13227 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13228 				 struct bpf_reg_state *src_reg)
13229 {
13230 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13231 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13232 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13233 	s32 smin_val = src_reg->s32_min_value;
13234 	u32 umax_val = src_reg->u32_max_value;
13235 
13236 	if (src_known && dst_known) {
13237 		__mark_reg32_known(dst_reg, var32_off.value);
13238 		return;
13239 	}
13240 
13241 	/* We get our minimum from the var_off, since that's inherently
13242 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13243 	 */
13244 	dst_reg->u32_min_value = var32_off.value;
13245 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13246 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13247 		/* Lose signed bounds when ANDing negative numbers,
13248 		 * ain't nobody got time for that.
13249 		 */
13250 		dst_reg->s32_min_value = S32_MIN;
13251 		dst_reg->s32_max_value = S32_MAX;
13252 	} else {
13253 		/* ANDing two positives gives a positive, so safe to
13254 		 * cast result into s64.
13255 		 */
13256 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13257 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13258 	}
13259 }
13260 
13261 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
13262 			       struct bpf_reg_state *src_reg)
13263 {
13264 	bool src_known = tnum_is_const(src_reg->var_off);
13265 	bool dst_known = tnum_is_const(dst_reg->var_off);
13266 	s64 smin_val = src_reg->smin_value;
13267 	u64 umax_val = src_reg->umax_value;
13268 
13269 	if (src_known && dst_known) {
13270 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13271 		return;
13272 	}
13273 
13274 	/* We get our minimum from the var_off, since that's inherently
13275 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13276 	 */
13277 	dst_reg->umin_value = dst_reg->var_off.value;
13278 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13279 	if (dst_reg->smin_value < 0 || smin_val < 0) {
13280 		/* Lose signed bounds when ANDing negative numbers,
13281 		 * ain't nobody got time for that.
13282 		 */
13283 		dst_reg->smin_value = S64_MIN;
13284 		dst_reg->smax_value = S64_MAX;
13285 	} else {
13286 		/* ANDing two positives gives a positive, so safe to
13287 		 * cast result into s64.
13288 		 */
13289 		dst_reg->smin_value = dst_reg->umin_value;
13290 		dst_reg->smax_value = dst_reg->umax_value;
13291 	}
13292 	/* We may learn something more from the var_off */
13293 	__update_reg_bounds(dst_reg);
13294 }
13295 
13296 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13297 				struct bpf_reg_state *src_reg)
13298 {
13299 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13300 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13301 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13302 	s32 smin_val = src_reg->s32_min_value;
13303 	u32 umin_val = src_reg->u32_min_value;
13304 
13305 	if (src_known && dst_known) {
13306 		__mark_reg32_known(dst_reg, var32_off.value);
13307 		return;
13308 	}
13309 
13310 	/* We get our maximum from the var_off, and our minimum is the
13311 	 * maximum of the operands' minima
13312 	 */
13313 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13314 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13315 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13316 		/* Lose signed bounds when ORing negative numbers,
13317 		 * ain't nobody got time for that.
13318 		 */
13319 		dst_reg->s32_min_value = S32_MIN;
13320 		dst_reg->s32_max_value = S32_MAX;
13321 	} else {
13322 		/* ORing two positives gives a positive, so safe to
13323 		 * cast result into s64.
13324 		 */
13325 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13326 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13327 	}
13328 }
13329 
13330 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13331 			      struct bpf_reg_state *src_reg)
13332 {
13333 	bool src_known = tnum_is_const(src_reg->var_off);
13334 	bool dst_known = tnum_is_const(dst_reg->var_off);
13335 	s64 smin_val = src_reg->smin_value;
13336 	u64 umin_val = src_reg->umin_value;
13337 
13338 	if (src_known && dst_known) {
13339 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13340 		return;
13341 	}
13342 
13343 	/* We get our maximum from the var_off, and our minimum is the
13344 	 * maximum of the operands' minima
13345 	 */
13346 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13347 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13348 	if (dst_reg->smin_value < 0 || smin_val < 0) {
13349 		/* Lose signed bounds when ORing negative numbers,
13350 		 * ain't nobody got time for that.
13351 		 */
13352 		dst_reg->smin_value = S64_MIN;
13353 		dst_reg->smax_value = S64_MAX;
13354 	} else {
13355 		/* ORing two positives gives a positive, so safe to
13356 		 * cast result into s64.
13357 		 */
13358 		dst_reg->smin_value = dst_reg->umin_value;
13359 		dst_reg->smax_value = dst_reg->umax_value;
13360 	}
13361 	/* We may learn something more from the var_off */
13362 	__update_reg_bounds(dst_reg);
13363 }
13364 
13365 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13366 				 struct bpf_reg_state *src_reg)
13367 {
13368 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13369 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13370 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13371 	s32 smin_val = src_reg->s32_min_value;
13372 
13373 	if (src_known && dst_known) {
13374 		__mark_reg32_known(dst_reg, var32_off.value);
13375 		return;
13376 	}
13377 
13378 	/* We get both minimum and maximum from the var32_off. */
13379 	dst_reg->u32_min_value = var32_off.value;
13380 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13381 
13382 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13383 		/* XORing two positive sign numbers gives a positive,
13384 		 * so safe to cast u32 result into s32.
13385 		 */
13386 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13387 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13388 	} else {
13389 		dst_reg->s32_min_value = S32_MIN;
13390 		dst_reg->s32_max_value = S32_MAX;
13391 	}
13392 }
13393 
13394 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13395 			       struct bpf_reg_state *src_reg)
13396 {
13397 	bool src_known = tnum_is_const(src_reg->var_off);
13398 	bool dst_known = tnum_is_const(dst_reg->var_off);
13399 	s64 smin_val = src_reg->smin_value;
13400 
13401 	if (src_known && dst_known) {
13402 		/* dst_reg->var_off.value has been updated earlier */
13403 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13404 		return;
13405 	}
13406 
13407 	/* We get both minimum and maximum from the var_off. */
13408 	dst_reg->umin_value = dst_reg->var_off.value;
13409 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13410 
13411 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13412 		/* XORing two positive sign numbers gives a positive,
13413 		 * so safe to cast u64 result into s64.
13414 		 */
13415 		dst_reg->smin_value = dst_reg->umin_value;
13416 		dst_reg->smax_value = dst_reg->umax_value;
13417 	} else {
13418 		dst_reg->smin_value = S64_MIN;
13419 		dst_reg->smax_value = S64_MAX;
13420 	}
13421 
13422 	__update_reg_bounds(dst_reg);
13423 }
13424 
13425 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13426 				   u64 umin_val, u64 umax_val)
13427 {
13428 	/* We lose all sign bit information (except what we can pick
13429 	 * up from var_off)
13430 	 */
13431 	dst_reg->s32_min_value = S32_MIN;
13432 	dst_reg->s32_max_value = S32_MAX;
13433 	/* If we might shift our top bit out, then we know nothing */
13434 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13435 		dst_reg->u32_min_value = 0;
13436 		dst_reg->u32_max_value = U32_MAX;
13437 	} else {
13438 		dst_reg->u32_min_value <<= umin_val;
13439 		dst_reg->u32_max_value <<= umax_val;
13440 	}
13441 }
13442 
13443 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13444 				 struct bpf_reg_state *src_reg)
13445 {
13446 	u32 umax_val = src_reg->u32_max_value;
13447 	u32 umin_val = src_reg->u32_min_value;
13448 	/* u32 alu operation will zext upper bits */
13449 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13450 
13451 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13452 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13453 	/* Not required but being careful mark reg64 bounds as unknown so
13454 	 * that we are forced to pick them up from tnum and zext later and
13455 	 * if some path skips this step we are still safe.
13456 	 */
13457 	__mark_reg64_unbounded(dst_reg);
13458 	__update_reg32_bounds(dst_reg);
13459 }
13460 
13461 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13462 				   u64 umin_val, u64 umax_val)
13463 {
13464 	/* Special case <<32 because it is a common compiler pattern to sign
13465 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13466 	 * positive we know this shift will also be positive so we can track
13467 	 * bounds correctly. Otherwise we lose all sign bit information except
13468 	 * what we can pick up from var_off. Perhaps we can generalize this
13469 	 * later to shifts of any length.
13470 	 */
13471 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13472 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13473 	else
13474 		dst_reg->smax_value = S64_MAX;
13475 
13476 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13477 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13478 	else
13479 		dst_reg->smin_value = S64_MIN;
13480 
13481 	/* If we might shift our top bit out, then we know nothing */
13482 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13483 		dst_reg->umin_value = 0;
13484 		dst_reg->umax_value = U64_MAX;
13485 	} else {
13486 		dst_reg->umin_value <<= umin_val;
13487 		dst_reg->umax_value <<= umax_val;
13488 	}
13489 }
13490 
13491 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13492 			       struct bpf_reg_state *src_reg)
13493 {
13494 	u64 umax_val = src_reg->umax_value;
13495 	u64 umin_val = src_reg->umin_value;
13496 
13497 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13498 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13499 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13500 
13501 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13502 	/* We may learn something more from the var_off */
13503 	__update_reg_bounds(dst_reg);
13504 }
13505 
13506 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13507 				 struct bpf_reg_state *src_reg)
13508 {
13509 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13510 	u32 umax_val = src_reg->u32_max_value;
13511 	u32 umin_val = src_reg->u32_min_value;
13512 
13513 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13514 	 * be negative, then either:
13515 	 * 1) src_reg might be zero, so the sign bit of the result is
13516 	 *    unknown, so we lose our signed bounds
13517 	 * 2) it's known negative, thus the unsigned bounds capture the
13518 	 *    signed bounds
13519 	 * 3) the signed bounds cross zero, so they tell us nothing
13520 	 *    about the result
13521 	 * If the value in dst_reg is known nonnegative, then again the
13522 	 * unsigned bounds capture the signed bounds.
13523 	 * Thus, in all cases it suffices to blow away our signed bounds
13524 	 * and rely on inferring new ones from the unsigned bounds and
13525 	 * var_off of the result.
13526 	 */
13527 	dst_reg->s32_min_value = S32_MIN;
13528 	dst_reg->s32_max_value = S32_MAX;
13529 
13530 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13531 	dst_reg->u32_min_value >>= umax_val;
13532 	dst_reg->u32_max_value >>= umin_val;
13533 
13534 	__mark_reg64_unbounded(dst_reg);
13535 	__update_reg32_bounds(dst_reg);
13536 }
13537 
13538 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13539 			       struct bpf_reg_state *src_reg)
13540 {
13541 	u64 umax_val = src_reg->umax_value;
13542 	u64 umin_val = src_reg->umin_value;
13543 
13544 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13545 	 * be negative, then either:
13546 	 * 1) src_reg might be zero, so the sign bit of the result is
13547 	 *    unknown, so we lose our signed bounds
13548 	 * 2) it's known negative, thus the unsigned bounds capture the
13549 	 *    signed bounds
13550 	 * 3) the signed bounds cross zero, so they tell us nothing
13551 	 *    about the result
13552 	 * If the value in dst_reg is known nonnegative, then again the
13553 	 * unsigned bounds capture the signed bounds.
13554 	 * Thus, in all cases it suffices to blow away our signed bounds
13555 	 * and rely on inferring new ones from the unsigned bounds and
13556 	 * var_off of the result.
13557 	 */
13558 	dst_reg->smin_value = S64_MIN;
13559 	dst_reg->smax_value = S64_MAX;
13560 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13561 	dst_reg->umin_value >>= umax_val;
13562 	dst_reg->umax_value >>= umin_val;
13563 
13564 	/* Its not easy to operate on alu32 bounds here because it depends
13565 	 * on bits being shifted in. Take easy way out and mark unbounded
13566 	 * so we can recalculate later from tnum.
13567 	 */
13568 	__mark_reg32_unbounded(dst_reg);
13569 	__update_reg_bounds(dst_reg);
13570 }
13571 
13572 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13573 				  struct bpf_reg_state *src_reg)
13574 {
13575 	u64 umin_val = src_reg->u32_min_value;
13576 
13577 	/* Upon reaching here, src_known is true and
13578 	 * umax_val is equal to umin_val.
13579 	 */
13580 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13581 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13582 
13583 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13584 
13585 	/* blow away the dst_reg umin_value/umax_value and rely on
13586 	 * dst_reg var_off to refine the result.
13587 	 */
13588 	dst_reg->u32_min_value = 0;
13589 	dst_reg->u32_max_value = U32_MAX;
13590 
13591 	__mark_reg64_unbounded(dst_reg);
13592 	__update_reg32_bounds(dst_reg);
13593 }
13594 
13595 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13596 				struct bpf_reg_state *src_reg)
13597 {
13598 	u64 umin_val = src_reg->umin_value;
13599 
13600 	/* Upon reaching here, src_known is true and umax_val is equal
13601 	 * to umin_val.
13602 	 */
13603 	dst_reg->smin_value >>= umin_val;
13604 	dst_reg->smax_value >>= umin_val;
13605 
13606 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13607 
13608 	/* blow away the dst_reg umin_value/umax_value and rely on
13609 	 * dst_reg var_off to refine the result.
13610 	 */
13611 	dst_reg->umin_value = 0;
13612 	dst_reg->umax_value = U64_MAX;
13613 
13614 	/* Its not easy to operate on alu32 bounds here because it depends
13615 	 * on bits being shifted in from upper 32-bits. Take easy way out
13616 	 * and mark unbounded so we can recalculate later from tnum.
13617 	 */
13618 	__mark_reg32_unbounded(dst_reg);
13619 	__update_reg_bounds(dst_reg);
13620 }
13621 
13622 /* WARNING: This function does calculations on 64-bit values, but the actual
13623  * execution may occur on 32-bit values. Therefore, things like bitshifts
13624  * need extra checks in the 32-bit case.
13625  */
13626 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13627 				      struct bpf_insn *insn,
13628 				      struct bpf_reg_state *dst_reg,
13629 				      struct bpf_reg_state src_reg)
13630 {
13631 	struct bpf_reg_state *regs = cur_regs(env);
13632 	u8 opcode = BPF_OP(insn->code);
13633 	bool src_known;
13634 	s64 smin_val, smax_val;
13635 	u64 umin_val, umax_val;
13636 	s32 s32_min_val, s32_max_val;
13637 	u32 u32_min_val, u32_max_val;
13638 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13639 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13640 	int ret;
13641 
13642 	smin_val = src_reg.smin_value;
13643 	smax_val = src_reg.smax_value;
13644 	umin_val = src_reg.umin_value;
13645 	umax_val = src_reg.umax_value;
13646 
13647 	s32_min_val = src_reg.s32_min_value;
13648 	s32_max_val = src_reg.s32_max_value;
13649 	u32_min_val = src_reg.u32_min_value;
13650 	u32_max_val = src_reg.u32_max_value;
13651 
13652 	if (alu32) {
13653 		src_known = tnum_subreg_is_const(src_reg.var_off);
13654 		if ((src_known &&
13655 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13656 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13657 			/* Taint dst register if offset had invalid bounds
13658 			 * derived from e.g. dead branches.
13659 			 */
13660 			__mark_reg_unknown(env, dst_reg);
13661 			return 0;
13662 		}
13663 	} else {
13664 		src_known = tnum_is_const(src_reg.var_off);
13665 		if ((src_known &&
13666 		     (smin_val != smax_val || umin_val != umax_val)) ||
13667 		    smin_val > smax_val || umin_val > umax_val) {
13668 			/* Taint dst register if offset had invalid bounds
13669 			 * derived from e.g. dead branches.
13670 			 */
13671 			__mark_reg_unknown(env, dst_reg);
13672 			return 0;
13673 		}
13674 	}
13675 
13676 	if (!src_known &&
13677 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13678 		__mark_reg_unknown(env, dst_reg);
13679 		return 0;
13680 	}
13681 
13682 	if (sanitize_needed(opcode)) {
13683 		ret = sanitize_val_alu(env, insn);
13684 		if (ret < 0)
13685 			return sanitize_err(env, insn, ret, NULL, NULL);
13686 	}
13687 
13688 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13689 	 * There are two classes of instructions: The first class we track both
13690 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13691 	 * greatest amount of precision when alu operations are mixed with jmp32
13692 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13693 	 * and BPF_OR. This is possible because these ops have fairly easy to
13694 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13695 	 * See alu32 verifier tests for examples. The second class of
13696 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13697 	 * with regards to tracking sign/unsigned bounds because the bits may
13698 	 * cross subreg boundaries in the alu64 case. When this happens we mark
13699 	 * the reg unbounded in the subreg bound space and use the resulting
13700 	 * tnum to calculate an approximation of the sign/unsigned bounds.
13701 	 */
13702 	switch (opcode) {
13703 	case BPF_ADD:
13704 		scalar32_min_max_add(dst_reg, &src_reg);
13705 		scalar_min_max_add(dst_reg, &src_reg);
13706 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13707 		break;
13708 	case BPF_SUB:
13709 		scalar32_min_max_sub(dst_reg, &src_reg);
13710 		scalar_min_max_sub(dst_reg, &src_reg);
13711 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13712 		break;
13713 	case BPF_MUL:
13714 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13715 		scalar32_min_max_mul(dst_reg, &src_reg);
13716 		scalar_min_max_mul(dst_reg, &src_reg);
13717 		break;
13718 	case BPF_AND:
13719 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13720 		scalar32_min_max_and(dst_reg, &src_reg);
13721 		scalar_min_max_and(dst_reg, &src_reg);
13722 		break;
13723 	case BPF_OR:
13724 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13725 		scalar32_min_max_or(dst_reg, &src_reg);
13726 		scalar_min_max_or(dst_reg, &src_reg);
13727 		break;
13728 	case BPF_XOR:
13729 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13730 		scalar32_min_max_xor(dst_reg, &src_reg);
13731 		scalar_min_max_xor(dst_reg, &src_reg);
13732 		break;
13733 	case BPF_LSH:
13734 		if (umax_val >= insn_bitness) {
13735 			/* Shifts greater than 31 or 63 are undefined.
13736 			 * This includes shifts by a negative number.
13737 			 */
13738 			mark_reg_unknown(env, regs, insn->dst_reg);
13739 			break;
13740 		}
13741 		if (alu32)
13742 			scalar32_min_max_lsh(dst_reg, &src_reg);
13743 		else
13744 			scalar_min_max_lsh(dst_reg, &src_reg);
13745 		break;
13746 	case BPF_RSH:
13747 		if (umax_val >= insn_bitness) {
13748 			/* Shifts greater than 31 or 63 are undefined.
13749 			 * This includes shifts by a negative number.
13750 			 */
13751 			mark_reg_unknown(env, regs, insn->dst_reg);
13752 			break;
13753 		}
13754 		if (alu32)
13755 			scalar32_min_max_rsh(dst_reg, &src_reg);
13756 		else
13757 			scalar_min_max_rsh(dst_reg, &src_reg);
13758 		break;
13759 	case BPF_ARSH:
13760 		if (umax_val >= insn_bitness) {
13761 			/* Shifts greater than 31 or 63 are undefined.
13762 			 * This includes shifts by a negative number.
13763 			 */
13764 			mark_reg_unknown(env, regs, insn->dst_reg);
13765 			break;
13766 		}
13767 		if (alu32)
13768 			scalar32_min_max_arsh(dst_reg, &src_reg);
13769 		else
13770 			scalar_min_max_arsh(dst_reg, &src_reg);
13771 		break;
13772 	default:
13773 		mark_reg_unknown(env, regs, insn->dst_reg);
13774 		break;
13775 	}
13776 
13777 	/* ALU32 ops are zero extended into 64bit register */
13778 	if (alu32)
13779 		zext_32_to_64(dst_reg);
13780 	reg_bounds_sync(dst_reg);
13781 	return 0;
13782 }
13783 
13784 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13785  * and var_off.
13786  */
13787 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13788 				   struct bpf_insn *insn)
13789 {
13790 	struct bpf_verifier_state *vstate = env->cur_state;
13791 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13792 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13793 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13794 	u8 opcode = BPF_OP(insn->code);
13795 	int err;
13796 
13797 	dst_reg = &regs[insn->dst_reg];
13798 	src_reg = NULL;
13799 	if (dst_reg->type != SCALAR_VALUE)
13800 		ptr_reg = dst_reg;
13801 	else
13802 		/* Make sure ID is cleared otherwise dst_reg min/max could be
13803 		 * incorrectly propagated into other registers by find_equal_scalars()
13804 		 */
13805 		dst_reg->id = 0;
13806 	if (BPF_SRC(insn->code) == BPF_X) {
13807 		src_reg = &regs[insn->src_reg];
13808 		if (src_reg->type != SCALAR_VALUE) {
13809 			if (dst_reg->type != SCALAR_VALUE) {
13810 				/* Combining two pointers by any ALU op yields
13811 				 * an arbitrary scalar. Disallow all math except
13812 				 * pointer subtraction
13813 				 */
13814 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13815 					mark_reg_unknown(env, regs, insn->dst_reg);
13816 					return 0;
13817 				}
13818 				verbose(env, "R%d pointer %s pointer prohibited\n",
13819 					insn->dst_reg,
13820 					bpf_alu_string[opcode >> 4]);
13821 				return -EACCES;
13822 			} else {
13823 				/* scalar += pointer
13824 				 * This is legal, but we have to reverse our
13825 				 * src/dest handling in computing the range
13826 				 */
13827 				err = mark_chain_precision(env, insn->dst_reg);
13828 				if (err)
13829 					return err;
13830 				return adjust_ptr_min_max_vals(env, insn,
13831 							       src_reg, dst_reg);
13832 			}
13833 		} else if (ptr_reg) {
13834 			/* pointer += scalar */
13835 			err = mark_chain_precision(env, insn->src_reg);
13836 			if (err)
13837 				return err;
13838 			return adjust_ptr_min_max_vals(env, insn,
13839 						       dst_reg, src_reg);
13840 		} else if (dst_reg->precise) {
13841 			/* if dst_reg is precise, src_reg should be precise as well */
13842 			err = mark_chain_precision(env, insn->src_reg);
13843 			if (err)
13844 				return err;
13845 		}
13846 	} else {
13847 		/* Pretend the src is a reg with a known value, since we only
13848 		 * need to be able to read from this state.
13849 		 */
13850 		off_reg.type = SCALAR_VALUE;
13851 		__mark_reg_known(&off_reg, insn->imm);
13852 		src_reg = &off_reg;
13853 		if (ptr_reg) /* pointer += K */
13854 			return adjust_ptr_min_max_vals(env, insn,
13855 						       ptr_reg, src_reg);
13856 	}
13857 
13858 	/* Got here implies adding two SCALAR_VALUEs */
13859 	if (WARN_ON_ONCE(ptr_reg)) {
13860 		print_verifier_state(env, state, true);
13861 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
13862 		return -EINVAL;
13863 	}
13864 	if (WARN_ON(!src_reg)) {
13865 		print_verifier_state(env, state, true);
13866 		verbose(env, "verifier internal error: no src_reg\n");
13867 		return -EINVAL;
13868 	}
13869 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13870 }
13871 
13872 /* check validity of 32-bit and 64-bit arithmetic operations */
13873 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13874 {
13875 	struct bpf_reg_state *regs = cur_regs(env);
13876 	u8 opcode = BPF_OP(insn->code);
13877 	int err;
13878 
13879 	if (opcode == BPF_END || opcode == BPF_NEG) {
13880 		if (opcode == BPF_NEG) {
13881 			if (BPF_SRC(insn->code) != BPF_K ||
13882 			    insn->src_reg != BPF_REG_0 ||
13883 			    insn->off != 0 || insn->imm != 0) {
13884 				verbose(env, "BPF_NEG uses reserved fields\n");
13885 				return -EINVAL;
13886 			}
13887 		} else {
13888 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13889 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13890 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
13891 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
13892 				verbose(env, "BPF_END uses reserved fields\n");
13893 				return -EINVAL;
13894 			}
13895 		}
13896 
13897 		/* check src operand */
13898 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13899 		if (err)
13900 			return err;
13901 
13902 		if (is_pointer_value(env, insn->dst_reg)) {
13903 			verbose(env, "R%d pointer arithmetic prohibited\n",
13904 				insn->dst_reg);
13905 			return -EACCES;
13906 		}
13907 
13908 		/* check dest operand */
13909 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
13910 		if (err)
13911 			return err;
13912 
13913 	} else if (opcode == BPF_MOV) {
13914 
13915 		if (BPF_SRC(insn->code) == BPF_X) {
13916 			if (insn->imm != 0) {
13917 				verbose(env, "BPF_MOV uses reserved fields\n");
13918 				return -EINVAL;
13919 			}
13920 
13921 			if (BPF_CLASS(insn->code) == BPF_ALU) {
13922 				if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13923 					verbose(env, "BPF_MOV uses reserved fields\n");
13924 					return -EINVAL;
13925 				}
13926 			} else {
13927 				if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13928 				    insn->off != 32) {
13929 					verbose(env, "BPF_MOV uses reserved fields\n");
13930 					return -EINVAL;
13931 				}
13932 			}
13933 
13934 			/* check src operand */
13935 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13936 			if (err)
13937 				return err;
13938 		} else {
13939 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13940 				verbose(env, "BPF_MOV uses reserved fields\n");
13941 				return -EINVAL;
13942 			}
13943 		}
13944 
13945 		/* check dest operand, mark as required later */
13946 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13947 		if (err)
13948 			return err;
13949 
13950 		if (BPF_SRC(insn->code) == BPF_X) {
13951 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
13952 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13953 
13954 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13955 				if (insn->off == 0) {
13956 					/* case: R1 = R2
13957 					 * copy register state to dest reg
13958 					 */
13959 					assign_scalar_id_before_mov(env, src_reg);
13960 					copy_register_state(dst_reg, src_reg);
13961 					dst_reg->live |= REG_LIVE_WRITTEN;
13962 					dst_reg->subreg_def = DEF_NOT_SUBREG;
13963 				} else {
13964 					/* case: R1 = (s8, s16 s32)R2 */
13965 					if (is_pointer_value(env, insn->src_reg)) {
13966 						verbose(env,
13967 							"R%d sign-extension part of pointer\n",
13968 							insn->src_reg);
13969 						return -EACCES;
13970 					} else if (src_reg->type == SCALAR_VALUE) {
13971 						bool no_sext;
13972 
13973 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13974 						if (no_sext)
13975 							assign_scalar_id_before_mov(env, src_reg);
13976 						copy_register_state(dst_reg, src_reg);
13977 						if (!no_sext)
13978 							dst_reg->id = 0;
13979 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13980 						dst_reg->live |= REG_LIVE_WRITTEN;
13981 						dst_reg->subreg_def = DEF_NOT_SUBREG;
13982 					} else {
13983 						mark_reg_unknown(env, regs, insn->dst_reg);
13984 					}
13985 				}
13986 			} else {
13987 				/* R1 = (u32) R2 */
13988 				if (is_pointer_value(env, insn->src_reg)) {
13989 					verbose(env,
13990 						"R%d partial copy of pointer\n",
13991 						insn->src_reg);
13992 					return -EACCES;
13993 				} else if (src_reg->type == SCALAR_VALUE) {
13994 					if (insn->off == 0) {
13995 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
13996 
13997 						if (is_src_reg_u32)
13998 							assign_scalar_id_before_mov(env, src_reg);
13999 						copy_register_state(dst_reg, src_reg);
14000 						/* Make sure ID is cleared if src_reg is not in u32
14001 						 * range otherwise dst_reg min/max could be incorrectly
14002 						 * propagated into src_reg by find_equal_scalars()
14003 						 */
14004 						if (!is_src_reg_u32)
14005 							dst_reg->id = 0;
14006 						dst_reg->live |= REG_LIVE_WRITTEN;
14007 						dst_reg->subreg_def = env->insn_idx + 1;
14008 					} else {
14009 						/* case: W1 = (s8, s16)W2 */
14010 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14011 
14012 						if (no_sext)
14013 							assign_scalar_id_before_mov(env, src_reg);
14014 						copy_register_state(dst_reg, src_reg);
14015 						if (!no_sext)
14016 							dst_reg->id = 0;
14017 						dst_reg->live |= REG_LIVE_WRITTEN;
14018 						dst_reg->subreg_def = env->insn_idx + 1;
14019 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
14020 					}
14021 				} else {
14022 					mark_reg_unknown(env, regs,
14023 							 insn->dst_reg);
14024 				}
14025 				zext_32_to_64(dst_reg);
14026 				reg_bounds_sync(dst_reg);
14027 			}
14028 		} else {
14029 			/* case: R = imm
14030 			 * remember the value we stored into this reg
14031 			 */
14032 			/* clear any state __mark_reg_known doesn't set */
14033 			mark_reg_unknown(env, regs, insn->dst_reg);
14034 			regs[insn->dst_reg].type = SCALAR_VALUE;
14035 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
14036 				__mark_reg_known(regs + insn->dst_reg,
14037 						 insn->imm);
14038 			} else {
14039 				__mark_reg_known(regs + insn->dst_reg,
14040 						 (u32)insn->imm);
14041 			}
14042 		}
14043 
14044 	} else if (opcode > BPF_END) {
14045 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
14046 		return -EINVAL;
14047 
14048 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
14049 
14050 		if (BPF_SRC(insn->code) == BPF_X) {
14051 			if (insn->imm != 0 || insn->off > 1 ||
14052 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14053 				verbose(env, "BPF_ALU uses reserved fields\n");
14054 				return -EINVAL;
14055 			}
14056 			/* check src1 operand */
14057 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14058 			if (err)
14059 				return err;
14060 		} else {
14061 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
14062 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14063 				verbose(env, "BPF_ALU uses reserved fields\n");
14064 				return -EINVAL;
14065 			}
14066 		}
14067 
14068 		/* check src2 operand */
14069 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14070 		if (err)
14071 			return err;
14072 
14073 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
14074 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
14075 			verbose(env, "div by zero\n");
14076 			return -EINVAL;
14077 		}
14078 
14079 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
14080 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
14081 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
14082 
14083 			if (insn->imm < 0 || insn->imm >= size) {
14084 				verbose(env, "invalid shift %d\n", insn->imm);
14085 				return -EINVAL;
14086 			}
14087 		}
14088 
14089 		/* check dest operand */
14090 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14091 		err = err ?: adjust_reg_min_max_vals(env, insn);
14092 		if (err)
14093 			return err;
14094 	}
14095 
14096 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
14097 }
14098 
14099 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
14100 				   struct bpf_reg_state *dst_reg,
14101 				   enum bpf_reg_type type,
14102 				   bool range_right_open)
14103 {
14104 	struct bpf_func_state *state;
14105 	struct bpf_reg_state *reg;
14106 	int new_range;
14107 
14108 	if (dst_reg->off < 0 ||
14109 	    (dst_reg->off == 0 && range_right_open))
14110 		/* This doesn't give us any range */
14111 		return;
14112 
14113 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
14114 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
14115 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
14116 		 * than pkt_end, but that's because it's also less than pkt.
14117 		 */
14118 		return;
14119 
14120 	new_range = dst_reg->off;
14121 	if (range_right_open)
14122 		new_range++;
14123 
14124 	/* Examples for register markings:
14125 	 *
14126 	 * pkt_data in dst register:
14127 	 *
14128 	 *   r2 = r3;
14129 	 *   r2 += 8;
14130 	 *   if (r2 > pkt_end) goto <handle exception>
14131 	 *   <access okay>
14132 	 *
14133 	 *   r2 = r3;
14134 	 *   r2 += 8;
14135 	 *   if (r2 < pkt_end) goto <access okay>
14136 	 *   <handle exception>
14137 	 *
14138 	 *   Where:
14139 	 *     r2 == dst_reg, pkt_end == src_reg
14140 	 *     r2=pkt(id=n,off=8,r=0)
14141 	 *     r3=pkt(id=n,off=0,r=0)
14142 	 *
14143 	 * pkt_data in src register:
14144 	 *
14145 	 *   r2 = r3;
14146 	 *   r2 += 8;
14147 	 *   if (pkt_end >= r2) goto <access okay>
14148 	 *   <handle exception>
14149 	 *
14150 	 *   r2 = r3;
14151 	 *   r2 += 8;
14152 	 *   if (pkt_end <= r2) goto <handle exception>
14153 	 *   <access okay>
14154 	 *
14155 	 *   Where:
14156 	 *     pkt_end == dst_reg, r2 == src_reg
14157 	 *     r2=pkt(id=n,off=8,r=0)
14158 	 *     r3=pkt(id=n,off=0,r=0)
14159 	 *
14160 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
14161 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
14162 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
14163 	 * the check.
14164 	 */
14165 
14166 	/* If our ids match, then we must have the same max_value.  And we
14167 	 * don't care about the other reg's fixed offset, since if it's too big
14168 	 * the range won't allow anything.
14169 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
14170 	 */
14171 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14172 		if (reg->type == type && reg->id == dst_reg->id)
14173 			/* keep the maximum range already checked */
14174 			reg->range = max(reg->range, new_range);
14175 	}));
14176 }
14177 
14178 /*
14179  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
14180  */
14181 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14182 				  u8 opcode, bool is_jmp32)
14183 {
14184 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
14185 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
14186 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
14187 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
14188 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
14189 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
14190 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
14191 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
14192 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
14193 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
14194 
14195 	switch (opcode) {
14196 	case BPF_JEQ:
14197 		/* constants, umin/umax and smin/smax checks would be
14198 		 * redundant in this case because they all should match
14199 		 */
14200 		if (tnum_is_const(t1) && tnum_is_const(t2))
14201 			return t1.value == t2.value;
14202 		/* non-overlapping ranges */
14203 		if (umin1 > umax2 || umax1 < umin2)
14204 			return 0;
14205 		if (smin1 > smax2 || smax1 < smin2)
14206 			return 0;
14207 		if (!is_jmp32) {
14208 			/* if 64-bit ranges are inconclusive, see if we can
14209 			 * utilize 32-bit subrange knowledge to eliminate
14210 			 * branches that can't be taken a priori
14211 			 */
14212 			if (reg1->u32_min_value > reg2->u32_max_value ||
14213 			    reg1->u32_max_value < reg2->u32_min_value)
14214 				return 0;
14215 			if (reg1->s32_min_value > reg2->s32_max_value ||
14216 			    reg1->s32_max_value < reg2->s32_min_value)
14217 				return 0;
14218 		}
14219 		break;
14220 	case BPF_JNE:
14221 		/* constants, umin/umax and smin/smax checks would be
14222 		 * redundant in this case because they all should match
14223 		 */
14224 		if (tnum_is_const(t1) && tnum_is_const(t2))
14225 			return t1.value != t2.value;
14226 		/* non-overlapping ranges */
14227 		if (umin1 > umax2 || umax1 < umin2)
14228 			return 1;
14229 		if (smin1 > smax2 || smax1 < smin2)
14230 			return 1;
14231 		if (!is_jmp32) {
14232 			/* if 64-bit ranges are inconclusive, see if we can
14233 			 * utilize 32-bit subrange knowledge to eliminate
14234 			 * branches that can't be taken a priori
14235 			 */
14236 			if (reg1->u32_min_value > reg2->u32_max_value ||
14237 			    reg1->u32_max_value < reg2->u32_min_value)
14238 				return 1;
14239 			if (reg1->s32_min_value > reg2->s32_max_value ||
14240 			    reg1->s32_max_value < reg2->s32_min_value)
14241 				return 1;
14242 		}
14243 		break;
14244 	case BPF_JSET:
14245 		if (!is_reg_const(reg2, is_jmp32)) {
14246 			swap(reg1, reg2);
14247 			swap(t1, t2);
14248 		}
14249 		if (!is_reg_const(reg2, is_jmp32))
14250 			return -1;
14251 		if ((~t1.mask & t1.value) & t2.value)
14252 			return 1;
14253 		if (!((t1.mask | t1.value) & t2.value))
14254 			return 0;
14255 		break;
14256 	case BPF_JGT:
14257 		if (umin1 > umax2)
14258 			return 1;
14259 		else if (umax1 <= umin2)
14260 			return 0;
14261 		break;
14262 	case BPF_JSGT:
14263 		if (smin1 > smax2)
14264 			return 1;
14265 		else if (smax1 <= smin2)
14266 			return 0;
14267 		break;
14268 	case BPF_JLT:
14269 		if (umax1 < umin2)
14270 			return 1;
14271 		else if (umin1 >= umax2)
14272 			return 0;
14273 		break;
14274 	case BPF_JSLT:
14275 		if (smax1 < smin2)
14276 			return 1;
14277 		else if (smin1 >= smax2)
14278 			return 0;
14279 		break;
14280 	case BPF_JGE:
14281 		if (umin1 >= umax2)
14282 			return 1;
14283 		else if (umax1 < umin2)
14284 			return 0;
14285 		break;
14286 	case BPF_JSGE:
14287 		if (smin1 >= smax2)
14288 			return 1;
14289 		else if (smax1 < smin2)
14290 			return 0;
14291 		break;
14292 	case BPF_JLE:
14293 		if (umax1 <= umin2)
14294 			return 1;
14295 		else if (umin1 > umax2)
14296 			return 0;
14297 		break;
14298 	case BPF_JSLE:
14299 		if (smax1 <= smin2)
14300 			return 1;
14301 		else if (smin1 > smax2)
14302 			return 0;
14303 		break;
14304 	}
14305 
14306 	return -1;
14307 }
14308 
14309 static int flip_opcode(u32 opcode)
14310 {
14311 	/* How can we transform "a <op> b" into "b <op> a"? */
14312 	static const u8 opcode_flip[16] = {
14313 		/* these stay the same */
14314 		[BPF_JEQ  >> 4] = BPF_JEQ,
14315 		[BPF_JNE  >> 4] = BPF_JNE,
14316 		[BPF_JSET >> 4] = BPF_JSET,
14317 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14318 		[BPF_JGE  >> 4] = BPF_JLE,
14319 		[BPF_JGT  >> 4] = BPF_JLT,
14320 		[BPF_JLE  >> 4] = BPF_JGE,
14321 		[BPF_JLT  >> 4] = BPF_JGT,
14322 		[BPF_JSGE >> 4] = BPF_JSLE,
14323 		[BPF_JSGT >> 4] = BPF_JSLT,
14324 		[BPF_JSLE >> 4] = BPF_JSGE,
14325 		[BPF_JSLT >> 4] = BPF_JSGT
14326 	};
14327 	return opcode_flip[opcode >> 4];
14328 }
14329 
14330 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14331 				   struct bpf_reg_state *src_reg,
14332 				   u8 opcode)
14333 {
14334 	struct bpf_reg_state *pkt;
14335 
14336 	if (src_reg->type == PTR_TO_PACKET_END) {
14337 		pkt = dst_reg;
14338 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14339 		pkt = src_reg;
14340 		opcode = flip_opcode(opcode);
14341 	} else {
14342 		return -1;
14343 	}
14344 
14345 	if (pkt->range >= 0)
14346 		return -1;
14347 
14348 	switch (opcode) {
14349 	case BPF_JLE:
14350 		/* pkt <= pkt_end */
14351 		fallthrough;
14352 	case BPF_JGT:
14353 		/* pkt > pkt_end */
14354 		if (pkt->range == BEYOND_PKT_END)
14355 			/* pkt has at last one extra byte beyond pkt_end */
14356 			return opcode == BPF_JGT;
14357 		break;
14358 	case BPF_JLT:
14359 		/* pkt < pkt_end */
14360 		fallthrough;
14361 	case BPF_JGE:
14362 		/* pkt >= pkt_end */
14363 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14364 			return opcode == BPF_JGE;
14365 		break;
14366 	}
14367 	return -1;
14368 }
14369 
14370 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
14371  * and return:
14372  *  1 - branch will be taken and "goto target" will be executed
14373  *  0 - branch will not be taken and fall-through to next insn
14374  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
14375  *      range [0,10]
14376  */
14377 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14378 			   u8 opcode, bool is_jmp32)
14379 {
14380 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
14381 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
14382 
14383 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
14384 		u64 val;
14385 
14386 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
14387 		if (!is_reg_const(reg2, is_jmp32)) {
14388 			opcode = flip_opcode(opcode);
14389 			swap(reg1, reg2);
14390 		}
14391 		/* and ensure that reg2 is a constant */
14392 		if (!is_reg_const(reg2, is_jmp32))
14393 			return -1;
14394 
14395 		if (!reg_not_null(reg1))
14396 			return -1;
14397 
14398 		/* If pointer is valid tests against zero will fail so we can
14399 		 * use this to direct branch taken.
14400 		 */
14401 		val = reg_const_value(reg2, is_jmp32);
14402 		if (val != 0)
14403 			return -1;
14404 
14405 		switch (opcode) {
14406 		case BPF_JEQ:
14407 			return 0;
14408 		case BPF_JNE:
14409 			return 1;
14410 		default:
14411 			return -1;
14412 		}
14413 	}
14414 
14415 	/* now deal with two scalars, but not necessarily constants */
14416 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
14417 }
14418 
14419 /* Opcode that corresponds to a *false* branch condition.
14420  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
14421  */
14422 static u8 rev_opcode(u8 opcode)
14423 {
14424 	switch (opcode) {
14425 	case BPF_JEQ:		return BPF_JNE;
14426 	case BPF_JNE:		return BPF_JEQ;
14427 	/* JSET doesn't have it's reverse opcode in BPF, so add
14428 	 * BPF_X flag to denote the reverse of that operation
14429 	 */
14430 	case BPF_JSET:		return BPF_JSET | BPF_X;
14431 	case BPF_JSET | BPF_X:	return BPF_JSET;
14432 	case BPF_JGE:		return BPF_JLT;
14433 	case BPF_JGT:		return BPF_JLE;
14434 	case BPF_JLE:		return BPF_JGT;
14435 	case BPF_JLT:		return BPF_JGE;
14436 	case BPF_JSGE:		return BPF_JSLT;
14437 	case BPF_JSGT:		return BPF_JSLE;
14438 	case BPF_JSLE:		return BPF_JSGT;
14439 	case BPF_JSLT:		return BPF_JSGE;
14440 	default:		return 0;
14441 	}
14442 }
14443 
14444 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
14445 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14446 				u8 opcode, bool is_jmp32)
14447 {
14448 	struct tnum t;
14449 	u64 val;
14450 
14451 again:
14452 	switch (opcode) {
14453 	case BPF_JEQ:
14454 		if (is_jmp32) {
14455 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14456 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14457 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14458 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14459 			reg2->u32_min_value = reg1->u32_min_value;
14460 			reg2->u32_max_value = reg1->u32_max_value;
14461 			reg2->s32_min_value = reg1->s32_min_value;
14462 			reg2->s32_max_value = reg1->s32_max_value;
14463 
14464 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
14465 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14466 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
14467 		} else {
14468 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
14469 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14470 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
14471 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14472 			reg2->umin_value = reg1->umin_value;
14473 			reg2->umax_value = reg1->umax_value;
14474 			reg2->smin_value = reg1->smin_value;
14475 			reg2->smax_value = reg1->smax_value;
14476 
14477 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
14478 			reg2->var_off = reg1->var_off;
14479 		}
14480 		break;
14481 	case BPF_JNE:
14482 		if (!is_reg_const(reg2, is_jmp32))
14483 			swap(reg1, reg2);
14484 		if (!is_reg_const(reg2, is_jmp32))
14485 			break;
14486 
14487 		/* try to recompute the bound of reg1 if reg2 is a const and
14488 		 * is exactly the edge of reg1.
14489 		 */
14490 		val = reg_const_value(reg2, is_jmp32);
14491 		if (is_jmp32) {
14492 			/* u32_min_value is not equal to 0xffffffff at this point,
14493 			 * because otherwise u32_max_value is 0xffffffff as well,
14494 			 * in such a case both reg1 and reg2 would be constants,
14495 			 * jump would be predicted and reg_set_min_max() won't
14496 			 * be called.
14497 			 *
14498 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
14499 			 * below.
14500 			 */
14501 			if (reg1->u32_min_value == (u32)val)
14502 				reg1->u32_min_value++;
14503 			if (reg1->u32_max_value == (u32)val)
14504 				reg1->u32_max_value--;
14505 			if (reg1->s32_min_value == (s32)val)
14506 				reg1->s32_min_value++;
14507 			if (reg1->s32_max_value == (s32)val)
14508 				reg1->s32_max_value--;
14509 		} else {
14510 			if (reg1->umin_value == (u64)val)
14511 				reg1->umin_value++;
14512 			if (reg1->umax_value == (u64)val)
14513 				reg1->umax_value--;
14514 			if (reg1->smin_value == (s64)val)
14515 				reg1->smin_value++;
14516 			if (reg1->smax_value == (s64)val)
14517 				reg1->smax_value--;
14518 		}
14519 		break;
14520 	case BPF_JSET:
14521 		if (!is_reg_const(reg2, is_jmp32))
14522 			swap(reg1, reg2);
14523 		if (!is_reg_const(reg2, is_jmp32))
14524 			break;
14525 		val = reg_const_value(reg2, is_jmp32);
14526 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
14527 		 * requires single bit to learn something useful. E.g., if we
14528 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
14529 		 * are actually set? We can learn something definite only if
14530 		 * it's a single-bit value to begin with.
14531 		 *
14532 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
14533 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
14534 		 * bit 1 is set, which we can readily use in adjustments.
14535 		 */
14536 		if (!is_power_of_2(val))
14537 			break;
14538 		if (is_jmp32) {
14539 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
14540 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14541 		} else {
14542 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
14543 		}
14544 		break;
14545 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
14546 		if (!is_reg_const(reg2, is_jmp32))
14547 			swap(reg1, reg2);
14548 		if (!is_reg_const(reg2, is_jmp32))
14549 			break;
14550 		val = reg_const_value(reg2, is_jmp32);
14551 		if (is_jmp32) {
14552 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
14553 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14554 		} else {
14555 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
14556 		}
14557 		break;
14558 	case BPF_JLE:
14559 		if (is_jmp32) {
14560 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14561 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14562 		} else {
14563 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14564 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
14565 		}
14566 		break;
14567 	case BPF_JLT:
14568 		if (is_jmp32) {
14569 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
14570 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
14571 		} else {
14572 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
14573 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
14574 		}
14575 		break;
14576 	case BPF_JSLE:
14577 		if (is_jmp32) {
14578 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14579 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14580 		} else {
14581 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14582 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
14583 		}
14584 		break;
14585 	case BPF_JSLT:
14586 		if (is_jmp32) {
14587 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
14588 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
14589 		} else {
14590 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
14591 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
14592 		}
14593 		break;
14594 	case BPF_JGE:
14595 	case BPF_JGT:
14596 	case BPF_JSGE:
14597 	case BPF_JSGT:
14598 		/* just reuse LE/LT logic above */
14599 		opcode = flip_opcode(opcode);
14600 		swap(reg1, reg2);
14601 		goto again;
14602 	default:
14603 		return;
14604 	}
14605 }
14606 
14607 /* Adjusts the register min/max values in the case that the dst_reg and
14608  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
14609  * check, in which case we havea fake SCALAR_VALUE representing insn->imm).
14610  * Technically we can do similar adjustments for pointers to the same object,
14611  * but we don't support that right now.
14612  */
14613 static int reg_set_min_max(struct bpf_verifier_env *env,
14614 			   struct bpf_reg_state *true_reg1,
14615 			   struct bpf_reg_state *true_reg2,
14616 			   struct bpf_reg_state *false_reg1,
14617 			   struct bpf_reg_state *false_reg2,
14618 			   u8 opcode, bool is_jmp32)
14619 {
14620 	int err;
14621 
14622 	/* If either register is a pointer, we can't learn anything about its
14623 	 * variable offset from the compare (unless they were a pointer into
14624 	 * the same object, but we don't bother with that).
14625 	 */
14626 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
14627 		return 0;
14628 
14629 	/* fallthrough (FALSE) branch */
14630 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
14631 	reg_bounds_sync(false_reg1);
14632 	reg_bounds_sync(false_reg2);
14633 
14634 	/* jump (TRUE) branch */
14635 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
14636 	reg_bounds_sync(true_reg1);
14637 	reg_bounds_sync(true_reg2);
14638 
14639 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
14640 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
14641 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
14642 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
14643 	return err;
14644 }
14645 
14646 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14647 				 struct bpf_reg_state *reg, u32 id,
14648 				 bool is_null)
14649 {
14650 	if (type_may_be_null(reg->type) && reg->id == id &&
14651 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14652 		/* Old offset (both fixed and variable parts) should have been
14653 		 * known-zero, because we don't allow pointer arithmetic on
14654 		 * pointers that might be NULL. If we see this happening, don't
14655 		 * convert the register.
14656 		 *
14657 		 * But in some cases, some helpers that return local kptrs
14658 		 * advance offset for the returned pointer. In those cases, it
14659 		 * is fine to expect to see reg->off.
14660 		 */
14661 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14662 			return;
14663 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14664 		    WARN_ON_ONCE(reg->off))
14665 			return;
14666 
14667 		if (is_null) {
14668 			reg->type = SCALAR_VALUE;
14669 			/* We don't need id and ref_obj_id from this point
14670 			 * onwards anymore, thus we should better reset it,
14671 			 * so that state pruning has chances to take effect.
14672 			 */
14673 			reg->id = 0;
14674 			reg->ref_obj_id = 0;
14675 
14676 			return;
14677 		}
14678 
14679 		mark_ptr_not_null_reg(reg);
14680 
14681 		if (!reg_may_point_to_spin_lock(reg)) {
14682 			/* For not-NULL ptr, reg->ref_obj_id will be reset
14683 			 * in release_reference().
14684 			 *
14685 			 * reg->id is still used by spin_lock ptr. Other
14686 			 * than spin_lock ptr type, reg->id can be reset.
14687 			 */
14688 			reg->id = 0;
14689 		}
14690 	}
14691 }
14692 
14693 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14694  * be folded together at some point.
14695  */
14696 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14697 				  bool is_null)
14698 {
14699 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14700 	struct bpf_reg_state *regs = state->regs, *reg;
14701 	u32 ref_obj_id = regs[regno].ref_obj_id;
14702 	u32 id = regs[regno].id;
14703 
14704 	if (ref_obj_id && ref_obj_id == id && is_null)
14705 		/* regs[regno] is in the " == NULL" branch.
14706 		 * No one could have freed the reference state before
14707 		 * doing the NULL check.
14708 		 */
14709 		WARN_ON_ONCE(release_reference_state(state, id));
14710 
14711 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14712 		mark_ptr_or_null_reg(state, reg, id, is_null);
14713 	}));
14714 }
14715 
14716 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14717 				   struct bpf_reg_state *dst_reg,
14718 				   struct bpf_reg_state *src_reg,
14719 				   struct bpf_verifier_state *this_branch,
14720 				   struct bpf_verifier_state *other_branch)
14721 {
14722 	if (BPF_SRC(insn->code) != BPF_X)
14723 		return false;
14724 
14725 	/* Pointers are always 64-bit. */
14726 	if (BPF_CLASS(insn->code) == BPF_JMP32)
14727 		return false;
14728 
14729 	switch (BPF_OP(insn->code)) {
14730 	case BPF_JGT:
14731 		if ((dst_reg->type == PTR_TO_PACKET &&
14732 		     src_reg->type == PTR_TO_PACKET_END) ||
14733 		    (dst_reg->type == PTR_TO_PACKET_META &&
14734 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14735 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14736 			find_good_pkt_pointers(this_branch, dst_reg,
14737 					       dst_reg->type, false);
14738 			mark_pkt_end(other_branch, insn->dst_reg, true);
14739 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14740 			    src_reg->type == PTR_TO_PACKET) ||
14741 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14742 			    src_reg->type == PTR_TO_PACKET_META)) {
14743 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
14744 			find_good_pkt_pointers(other_branch, src_reg,
14745 					       src_reg->type, true);
14746 			mark_pkt_end(this_branch, insn->src_reg, false);
14747 		} else {
14748 			return false;
14749 		}
14750 		break;
14751 	case BPF_JLT:
14752 		if ((dst_reg->type == PTR_TO_PACKET &&
14753 		     src_reg->type == PTR_TO_PACKET_END) ||
14754 		    (dst_reg->type == PTR_TO_PACKET_META &&
14755 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14756 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14757 			find_good_pkt_pointers(other_branch, dst_reg,
14758 					       dst_reg->type, true);
14759 			mark_pkt_end(this_branch, insn->dst_reg, false);
14760 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14761 			    src_reg->type == PTR_TO_PACKET) ||
14762 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14763 			    src_reg->type == PTR_TO_PACKET_META)) {
14764 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
14765 			find_good_pkt_pointers(this_branch, src_reg,
14766 					       src_reg->type, false);
14767 			mark_pkt_end(other_branch, insn->src_reg, true);
14768 		} else {
14769 			return false;
14770 		}
14771 		break;
14772 	case BPF_JGE:
14773 		if ((dst_reg->type == PTR_TO_PACKET &&
14774 		     src_reg->type == PTR_TO_PACKET_END) ||
14775 		    (dst_reg->type == PTR_TO_PACKET_META &&
14776 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14777 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14778 			find_good_pkt_pointers(this_branch, dst_reg,
14779 					       dst_reg->type, true);
14780 			mark_pkt_end(other_branch, insn->dst_reg, false);
14781 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14782 			    src_reg->type == PTR_TO_PACKET) ||
14783 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14784 			    src_reg->type == PTR_TO_PACKET_META)) {
14785 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14786 			find_good_pkt_pointers(other_branch, src_reg,
14787 					       src_reg->type, false);
14788 			mark_pkt_end(this_branch, insn->src_reg, true);
14789 		} else {
14790 			return false;
14791 		}
14792 		break;
14793 	case BPF_JLE:
14794 		if ((dst_reg->type == PTR_TO_PACKET &&
14795 		     src_reg->type == PTR_TO_PACKET_END) ||
14796 		    (dst_reg->type == PTR_TO_PACKET_META &&
14797 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14798 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14799 			find_good_pkt_pointers(other_branch, dst_reg,
14800 					       dst_reg->type, false);
14801 			mark_pkt_end(this_branch, insn->dst_reg, true);
14802 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14803 			    src_reg->type == PTR_TO_PACKET) ||
14804 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14805 			    src_reg->type == PTR_TO_PACKET_META)) {
14806 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14807 			find_good_pkt_pointers(this_branch, src_reg,
14808 					       src_reg->type, true);
14809 			mark_pkt_end(other_branch, insn->src_reg, false);
14810 		} else {
14811 			return false;
14812 		}
14813 		break;
14814 	default:
14815 		return false;
14816 	}
14817 
14818 	return true;
14819 }
14820 
14821 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14822 			       struct bpf_reg_state *known_reg)
14823 {
14824 	struct bpf_func_state *state;
14825 	struct bpf_reg_state *reg;
14826 
14827 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14828 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14829 			copy_register_state(reg, known_reg);
14830 	}));
14831 }
14832 
14833 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14834 			     struct bpf_insn *insn, int *insn_idx)
14835 {
14836 	struct bpf_verifier_state *this_branch = env->cur_state;
14837 	struct bpf_verifier_state *other_branch;
14838 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14839 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14840 	struct bpf_reg_state *eq_branch_regs;
14841 	struct bpf_reg_state fake_reg = {};
14842 	u8 opcode = BPF_OP(insn->code);
14843 	bool is_jmp32;
14844 	int pred = -1;
14845 	int err;
14846 
14847 	/* Only conditional jumps are expected to reach here. */
14848 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
14849 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14850 		return -EINVAL;
14851 	}
14852 
14853 	/* check src2 operand */
14854 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14855 	if (err)
14856 		return err;
14857 
14858 	dst_reg = &regs[insn->dst_reg];
14859 	if (BPF_SRC(insn->code) == BPF_X) {
14860 		if (insn->imm != 0) {
14861 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14862 			return -EINVAL;
14863 		}
14864 
14865 		/* check src1 operand */
14866 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14867 		if (err)
14868 			return err;
14869 
14870 		src_reg = &regs[insn->src_reg];
14871 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14872 		    is_pointer_value(env, insn->src_reg)) {
14873 			verbose(env, "R%d pointer comparison prohibited\n",
14874 				insn->src_reg);
14875 			return -EACCES;
14876 		}
14877 	} else {
14878 		if (insn->src_reg != BPF_REG_0) {
14879 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14880 			return -EINVAL;
14881 		}
14882 		src_reg = &fake_reg;
14883 		src_reg->type = SCALAR_VALUE;
14884 		__mark_reg_known(src_reg, insn->imm);
14885 	}
14886 
14887 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14888 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
14889 	if (pred >= 0) {
14890 		/* If we get here with a dst_reg pointer type it is because
14891 		 * above is_branch_taken() special cased the 0 comparison.
14892 		 */
14893 		if (!__is_pointer_value(false, dst_reg))
14894 			err = mark_chain_precision(env, insn->dst_reg);
14895 		if (BPF_SRC(insn->code) == BPF_X && !err &&
14896 		    !__is_pointer_value(false, src_reg))
14897 			err = mark_chain_precision(env, insn->src_reg);
14898 		if (err)
14899 			return err;
14900 	}
14901 
14902 	if (pred == 1) {
14903 		/* Only follow the goto, ignore fall-through. If needed, push
14904 		 * the fall-through branch for simulation under speculative
14905 		 * execution.
14906 		 */
14907 		if (!env->bypass_spec_v1 &&
14908 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
14909 					       *insn_idx))
14910 			return -EFAULT;
14911 		if (env->log.level & BPF_LOG_LEVEL)
14912 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14913 		*insn_idx += insn->off;
14914 		return 0;
14915 	} else if (pred == 0) {
14916 		/* Only follow the fall-through branch, since that's where the
14917 		 * program will go. If needed, push the goto branch for
14918 		 * simulation under speculative execution.
14919 		 */
14920 		if (!env->bypass_spec_v1 &&
14921 		    !sanitize_speculative_path(env, insn,
14922 					       *insn_idx + insn->off + 1,
14923 					       *insn_idx))
14924 			return -EFAULT;
14925 		if (env->log.level & BPF_LOG_LEVEL)
14926 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14927 		return 0;
14928 	}
14929 
14930 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14931 				  false);
14932 	if (!other_branch)
14933 		return -EFAULT;
14934 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14935 
14936 	if (BPF_SRC(insn->code) == BPF_X) {
14937 		err = reg_set_min_max(env,
14938 				      &other_branch_regs[insn->dst_reg],
14939 				      &other_branch_regs[insn->src_reg],
14940 				      dst_reg, src_reg, opcode, is_jmp32);
14941 	} else /* BPF_SRC(insn->code) == BPF_K */ {
14942 		err = reg_set_min_max(env,
14943 				      &other_branch_regs[insn->dst_reg],
14944 				      src_reg /* fake one */,
14945 				      dst_reg, src_reg /* same fake one */,
14946 				      opcode, is_jmp32);
14947 	}
14948 	if (err)
14949 		return err;
14950 
14951 	if (BPF_SRC(insn->code) == BPF_X &&
14952 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
14953 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14954 		find_equal_scalars(this_branch, src_reg);
14955 		find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14956 	}
14957 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14958 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14959 		find_equal_scalars(this_branch, dst_reg);
14960 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14961 	}
14962 
14963 	/* if one pointer register is compared to another pointer
14964 	 * register check if PTR_MAYBE_NULL could be lifted.
14965 	 * E.g. register A - maybe null
14966 	 *      register B - not null
14967 	 * for JNE A, B, ... - A is not null in the false branch;
14968 	 * for JEQ A, B, ... - A is not null in the true branch.
14969 	 *
14970 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
14971 	 * not need to be null checked by the BPF program, i.e.,
14972 	 * could be null even without PTR_MAYBE_NULL marking, so
14973 	 * only propagate nullness when neither reg is that type.
14974 	 */
14975 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14976 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14977 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14978 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
14979 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14980 		eq_branch_regs = NULL;
14981 		switch (opcode) {
14982 		case BPF_JEQ:
14983 			eq_branch_regs = other_branch_regs;
14984 			break;
14985 		case BPF_JNE:
14986 			eq_branch_regs = regs;
14987 			break;
14988 		default:
14989 			/* do nothing */
14990 			break;
14991 		}
14992 		if (eq_branch_regs) {
14993 			if (type_may_be_null(src_reg->type))
14994 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14995 			else
14996 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14997 		}
14998 	}
14999 
15000 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
15001 	 * NOTE: these optimizations below are related with pointer comparison
15002 	 *       which will never be JMP32.
15003 	 */
15004 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
15005 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
15006 	    type_may_be_null(dst_reg->type)) {
15007 		/* Mark all identical registers in each branch as either
15008 		 * safe or unknown depending R == 0 or R != 0 conditional.
15009 		 */
15010 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
15011 				      opcode == BPF_JNE);
15012 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
15013 				      opcode == BPF_JEQ);
15014 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
15015 					   this_branch, other_branch) &&
15016 		   is_pointer_value(env, insn->dst_reg)) {
15017 		verbose(env, "R%d pointer comparison prohibited\n",
15018 			insn->dst_reg);
15019 		return -EACCES;
15020 	}
15021 	if (env->log.level & BPF_LOG_LEVEL)
15022 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
15023 	return 0;
15024 }
15025 
15026 /* verify BPF_LD_IMM64 instruction */
15027 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
15028 {
15029 	struct bpf_insn_aux_data *aux = cur_aux(env);
15030 	struct bpf_reg_state *regs = cur_regs(env);
15031 	struct bpf_reg_state *dst_reg;
15032 	struct bpf_map *map;
15033 	int err;
15034 
15035 	if (BPF_SIZE(insn->code) != BPF_DW) {
15036 		verbose(env, "invalid BPF_LD_IMM insn\n");
15037 		return -EINVAL;
15038 	}
15039 	if (insn->off != 0) {
15040 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
15041 		return -EINVAL;
15042 	}
15043 
15044 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
15045 	if (err)
15046 		return err;
15047 
15048 	dst_reg = &regs[insn->dst_reg];
15049 	if (insn->src_reg == 0) {
15050 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
15051 
15052 		dst_reg->type = SCALAR_VALUE;
15053 		__mark_reg_known(&regs[insn->dst_reg], imm);
15054 		return 0;
15055 	}
15056 
15057 	/* All special src_reg cases are listed below. From this point onwards
15058 	 * we either succeed and assign a corresponding dst_reg->type after
15059 	 * zeroing the offset, or fail and reject the program.
15060 	 */
15061 	mark_reg_known_zero(env, regs, insn->dst_reg);
15062 
15063 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
15064 		dst_reg->type = aux->btf_var.reg_type;
15065 		switch (base_type(dst_reg->type)) {
15066 		case PTR_TO_MEM:
15067 			dst_reg->mem_size = aux->btf_var.mem_size;
15068 			break;
15069 		case PTR_TO_BTF_ID:
15070 			dst_reg->btf = aux->btf_var.btf;
15071 			dst_reg->btf_id = aux->btf_var.btf_id;
15072 			break;
15073 		default:
15074 			verbose(env, "bpf verifier is misconfigured\n");
15075 			return -EFAULT;
15076 		}
15077 		return 0;
15078 	}
15079 
15080 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
15081 		struct bpf_prog_aux *aux = env->prog->aux;
15082 		u32 subprogno = find_subprog(env,
15083 					     env->insn_idx + insn->imm + 1);
15084 
15085 		if (!aux->func_info) {
15086 			verbose(env, "missing btf func_info\n");
15087 			return -EINVAL;
15088 		}
15089 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
15090 			verbose(env, "callback function not static\n");
15091 			return -EINVAL;
15092 		}
15093 
15094 		dst_reg->type = PTR_TO_FUNC;
15095 		dst_reg->subprogno = subprogno;
15096 		return 0;
15097 	}
15098 
15099 	map = env->used_maps[aux->map_index];
15100 	dst_reg->map_ptr = map;
15101 
15102 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
15103 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
15104 		dst_reg->type = PTR_TO_MAP_VALUE;
15105 		dst_reg->off = aux->map_off;
15106 		WARN_ON_ONCE(map->max_entries != 1);
15107 		/* We want reg->id to be same (0) as map_value is not distinct */
15108 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
15109 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
15110 		dst_reg->type = CONST_PTR_TO_MAP;
15111 	} else {
15112 		verbose(env, "bpf verifier is misconfigured\n");
15113 		return -EINVAL;
15114 	}
15115 
15116 	return 0;
15117 }
15118 
15119 static bool may_access_skb(enum bpf_prog_type type)
15120 {
15121 	switch (type) {
15122 	case BPF_PROG_TYPE_SOCKET_FILTER:
15123 	case BPF_PROG_TYPE_SCHED_CLS:
15124 	case BPF_PROG_TYPE_SCHED_ACT:
15125 		return true;
15126 	default:
15127 		return false;
15128 	}
15129 }
15130 
15131 /* verify safety of LD_ABS|LD_IND instructions:
15132  * - they can only appear in the programs where ctx == skb
15133  * - since they are wrappers of function calls, they scratch R1-R5 registers,
15134  *   preserve R6-R9, and store return value into R0
15135  *
15136  * Implicit input:
15137  *   ctx == skb == R6 == CTX
15138  *
15139  * Explicit input:
15140  *   SRC == any register
15141  *   IMM == 32-bit immediate
15142  *
15143  * Output:
15144  *   R0 - 8/16/32-bit skb data converted to cpu endianness
15145  */
15146 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
15147 {
15148 	struct bpf_reg_state *regs = cur_regs(env);
15149 	static const int ctx_reg = BPF_REG_6;
15150 	u8 mode = BPF_MODE(insn->code);
15151 	int i, err;
15152 
15153 	if (!may_access_skb(resolve_prog_type(env->prog))) {
15154 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
15155 		return -EINVAL;
15156 	}
15157 
15158 	if (!env->ops->gen_ld_abs) {
15159 		verbose(env, "bpf verifier is misconfigured\n");
15160 		return -EINVAL;
15161 	}
15162 
15163 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
15164 	    BPF_SIZE(insn->code) == BPF_DW ||
15165 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
15166 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
15167 		return -EINVAL;
15168 	}
15169 
15170 	/* check whether implicit source operand (register R6) is readable */
15171 	err = check_reg_arg(env, ctx_reg, SRC_OP);
15172 	if (err)
15173 		return err;
15174 
15175 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
15176 	 * gen_ld_abs() may terminate the program at runtime, leading to
15177 	 * reference leak.
15178 	 */
15179 	err = check_reference_leak(env, false);
15180 	if (err) {
15181 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
15182 		return err;
15183 	}
15184 
15185 	if (env->cur_state->active_lock.ptr) {
15186 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
15187 		return -EINVAL;
15188 	}
15189 
15190 	if (env->cur_state->active_rcu_lock) {
15191 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
15192 		return -EINVAL;
15193 	}
15194 
15195 	if (regs[ctx_reg].type != PTR_TO_CTX) {
15196 		verbose(env,
15197 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
15198 		return -EINVAL;
15199 	}
15200 
15201 	if (mode == BPF_IND) {
15202 		/* check explicit source operand */
15203 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
15204 		if (err)
15205 			return err;
15206 	}
15207 
15208 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
15209 	if (err < 0)
15210 		return err;
15211 
15212 	/* reset caller saved regs to unreadable */
15213 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
15214 		mark_reg_not_init(env, regs, caller_saved[i]);
15215 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
15216 	}
15217 
15218 	/* mark destination R0 register as readable, since it contains
15219 	 * the value fetched from the packet.
15220 	 * Already marked as written above.
15221 	 */
15222 	mark_reg_unknown(env, regs, BPF_REG_0);
15223 	/* ld_abs load up to 32-bit skb data. */
15224 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
15225 	return 0;
15226 }
15227 
15228 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
15229 {
15230 	const char *exit_ctx = "At program exit";
15231 	struct tnum enforce_attach_type_range = tnum_unknown;
15232 	const struct bpf_prog *prog = env->prog;
15233 	struct bpf_reg_state *reg;
15234 	struct bpf_retval_range range = retval_range(0, 1);
15235 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15236 	int err;
15237 	struct bpf_func_state *frame = env->cur_state->frame[0];
15238 	const bool is_subprog = frame->subprogno;
15239 
15240 	/* LSM and struct_ops func-ptr's return type could be "void" */
15241 	if (!is_subprog || frame->in_exception_callback_fn) {
15242 		switch (prog_type) {
15243 		case BPF_PROG_TYPE_LSM:
15244 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
15245 				/* See below, can be 0 or 0-1 depending on hook. */
15246 				break;
15247 			fallthrough;
15248 		case BPF_PROG_TYPE_STRUCT_OPS:
15249 			if (!prog->aux->attach_func_proto->type)
15250 				return 0;
15251 			break;
15252 		default:
15253 			break;
15254 		}
15255 	}
15256 
15257 	/* eBPF calling convention is such that R0 is used
15258 	 * to return the value from eBPF program.
15259 	 * Make sure that it's readable at this time
15260 	 * of bpf_exit, which means that program wrote
15261 	 * something into it earlier
15262 	 */
15263 	err = check_reg_arg(env, regno, SRC_OP);
15264 	if (err)
15265 		return err;
15266 
15267 	if (is_pointer_value(env, regno)) {
15268 		verbose(env, "R%d leaks addr as return value\n", regno);
15269 		return -EACCES;
15270 	}
15271 
15272 	reg = cur_regs(env) + regno;
15273 
15274 	if (frame->in_async_callback_fn) {
15275 		/* enforce return zero from async callbacks like timer */
15276 		exit_ctx = "At async callback return";
15277 		range = retval_range(0, 0);
15278 		goto enforce_retval;
15279 	}
15280 
15281 	if (is_subprog && !frame->in_exception_callback_fn) {
15282 		if (reg->type != SCALAR_VALUE) {
15283 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
15284 				regno, reg_type_str(env, reg->type));
15285 			return -EINVAL;
15286 		}
15287 		return 0;
15288 	}
15289 
15290 	switch (prog_type) {
15291 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15292 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15293 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15294 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
15295 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15296 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15297 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
15298 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15299 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
15300 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
15301 			range = retval_range(1, 1);
15302 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15303 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15304 			range = retval_range(0, 3);
15305 		break;
15306 	case BPF_PROG_TYPE_CGROUP_SKB:
15307 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15308 			range = retval_range(0, 3);
15309 			enforce_attach_type_range = tnum_range(2, 3);
15310 		}
15311 		break;
15312 	case BPF_PROG_TYPE_CGROUP_SOCK:
15313 	case BPF_PROG_TYPE_SOCK_OPS:
15314 	case BPF_PROG_TYPE_CGROUP_DEVICE:
15315 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15316 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15317 		break;
15318 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15319 		if (!env->prog->aux->attach_btf_id)
15320 			return 0;
15321 		range = retval_range(0, 0);
15322 		break;
15323 	case BPF_PROG_TYPE_TRACING:
15324 		switch (env->prog->expected_attach_type) {
15325 		case BPF_TRACE_FENTRY:
15326 		case BPF_TRACE_FEXIT:
15327 			range = retval_range(0, 0);
15328 			break;
15329 		case BPF_TRACE_RAW_TP:
15330 		case BPF_MODIFY_RETURN:
15331 			return 0;
15332 		case BPF_TRACE_ITER:
15333 			break;
15334 		default:
15335 			return -ENOTSUPP;
15336 		}
15337 		break;
15338 	case BPF_PROG_TYPE_SK_LOOKUP:
15339 		range = retval_range(SK_DROP, SK_PASS);
15340 		break;
15341 
15342 	case BPF_PROG_TYPE_LSM:
15343 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15344 			/* Regular BPF_PROG_TYPE_LSM programs can return
15345 			 * any value.
15346 			 */
15347 			return 0;
15348 		}
15349 		if (!env->prog->aux->attach_func_proto->type) {
15350 			/* Make sure programs that attach to void
15351 			 * hooks don't try to modify return value.
15352 			 */
15353 			range = retval_range(1, 1);
15354 		}
15355 		break;
15356 
15357 	case BPF_PROG_TYPE_NETFILTER:
15358 		range = retval_range(NF_DROP, NF_ACCEPT);
15359 		break;
15360 	case BPF_PROG_TYPE_EXT:
15361 		/* freplace program can return anything as its return value
15362 		 * depends on the to-be-replaced kernel func or bpf program.
15363 		 */
15364 	default:
15365 		return 0;
15366 	}
15367 
15368 enforce_retval:
15369 	if (reg->type != SCALAR_VALUE) {
15370 		verbose(env, "%s the register R%d is not a known value (%s)\n",
15371 			exit_ctx, regno, reg_type_str(env, reg->type));
15372 		return -EINVAL;
15373 	}
15374 
15375 	err = mark_chain_precision(env, regno);
15376 	if (err)
15377 		return err;
15378 
15379 	if (!retval_range_within(range, reg)) {
15380 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
15381 		if (!is_subprog &&
15382 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
15383 		    prog_type == BPF_PROG_TYPE_LSM &&
15384 		    !prog->aux->attach_func_proto->type)
15385 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15386 		return -EINVAL;
15387 	}
15388 
15389 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15390 	    tnum_in(enforce_attach_type_range, reg->var_off))
15391 		env->prog->enforce_expected_attach_type = 1;
15392 	return 0;
15393 }
15394 
15395 /* non-recursive DFS pseudo code
15396  * 1  procedure DFS-iterative(G,v):
15397  * 2      label v as discovered
15398  * 3      let S be a stack
15399  * 4      S.push(v)
15400  * 5      while S is not empty
15401  * 6            t <- S.peek()
15402  * 7            if t is what we're looking for:
15403  * 8                return t
15404  * 9            for all edges e in G.adjacentEdges(t) do
15405  * 10               if edge e is already labelled
15406  * 11                   continue with the next edge
15407  * 12               w <- G.adjacentVertex(t,e)
15408  * 13               if vertex w is not discovered and not explored
15409  * 14                   label e as tree-edge
15410  * 15                   label w as discovered
15411  * 16                   S.push(w)
15412  * 17                   continue at 5
15413  * 18               else if vertex w is discovered
15414  * 19                   label e as back-edge
15415  * 20               else
15416  * 21                   // vertex w is explored
15417  * 22                   label e as forward- or cross-edge
15418  * 23           label t as explored
15419  * 24           S.pop()
15420  *
15421  * convention:
15422  * 0x10 - discovered
15423  * 0x11 - discovered and fall-through edge labelled
15424  * 0x12 - discovered and fall-through and branch edges labelled
15425  * 0x20 - explored
15426  */
15427 
15428 enum {
15429 	DISCOVERED = 0x10,
15430 	EXPLORED = 0x20,
15431 	FALLTHROUGH = 1,
15432 	BRANCH = 2,
15433 };
15434 
15435 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15436 {
15437 	env->insn_aux_data[idx].prune_point = true;
15438 }
15439 
15440 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15441 {
15442 	return env->insn_aux_data[insn_idx].prune_point;
15443 }
15444 
15445 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15446 {
15447 	env->insn_aux_data[idx].force_checkpoint = true;
15448 }
15449 
15450 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15451 {
15452 	return env->insn_aux_data[insn_idx].force_checkpoint;
15453 }
15454 
15455 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15456 {
15457 	env->insn_aux_data[idx].calls_callback = true;
15458 }
15459 
15460 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15461 {
15462 	return env->insn_aux_data[insn_idx].calls_callback;
15463 }
15464 
15465 enum {
15466 	DONE_EXPLORING = 0,
15467 	KEEP_EXPLORING = 1,
15468 };
15469 
15470 /* t, w, e - match pseudo-code above:
15471  * t - index of current instruction
15472  * w - next instruction
15473  * e - edge
15474  */
15475 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15476 {
15477 	int *insn_stack = env->cfg.insn_stack;
15478 	int *insn_state = env->cfg.insn_state;
15479 
15480 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15481 		return DONE_EXPLORING;
15482 
15483 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15484 		return DONE_EXPLORING;
15485 
15486 	if (w < 0 || w >= env->prog->len) {
15487 		verbose_linfo(env, t, "%d: ", t);
15488 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15489 		return -EINVAL;
15490 	}
15491 
15492 	if (e == BRANCH) {
15493 		/* mark branch target for state pruning */
15494 		mark_prune_point(env, w);
15495 		mark_jmp_point(env, w);
15496 	}
15497 
15498 	if (insn_state[w] == 0) {
15499 		/* tree-edge */
15500 		insn_state[t] = DISCOVERED | e;
15501 		insn_state[w] = DISCOVERED;
15502 		if (env->cfg.cur_stack >= env->prog->len)
15503 			return -E2BIG;
15504 		insn_stack[env->cfg.cur_stack++] = w;
15505 		return KEEP_EXPLORING;
15506 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15507 		if (env->bpf_capable)
15508 			return DONE_EXPLORING;
15509 		verbose_linfo(env, t, "%d: ", t);
15510 		verbose_linfo(env, w, "%d: ", w);
15511 		verbose(env, "back-edge from insn %d to %d\n", t, w);
15512 		return -EINVAL;
15513 	} else if (insn_state[w] == EXPLORED) {
15514 		/* forward- or cross-edge */
15515 		insn_state[t] = DISCOVERED | e;
15516 	} else {
15517 		verbose(env, "insn state internal bug\n");
15518 		return -EFAULT;
15519 	}
15520 	return DONE_EXPLORING;
15521 }
15522 
15523 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15524 				struct bpf_verifier_env *env,
15525 				bool visit_callee)
15526 {
15527 	int ret, insn_sz;
15528 
15529 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15530 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15531 	if (ret)
15532 		return ret;
15533 
15534 	mark_prune_point(env, t + insn_sz);
15535 	/* when we exit from subprog, we need to record non-linear history */
15536 	mark_jmp_point(env, t + insn_sz);
15537 
15538 	if (visit_callee) {
15539 		mark_prune_point(env, t);
15540 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15541 	}
15542 	return ret;
15543 }
15544 
15545 /* Visits the instruction at index t and returns one of the following:
15546  *  < 0 - an error occurred
15547  *  DONE_EXPLORING - the instruction was fully explored
15548  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15549  */
15550 static int visit_insn(int t, struct bpf_verifier_env *env)
15551 {
15552 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15553 	int ret, off, insn_sz;
15554 
15555 	if (bpf_pseudo_func(insn))
15556 		return visit_func_call_insn(t, insns, env, true);
15557 
15558 	/* All non-branch instructions have a single fall-through edge. */
15559 	if (BPF_CLASS(insn->code) != BPF_JMP &&
15560 	    BPF_CLASS(insn->code) != BPF_JMP32) {
15561 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15562 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15563 	}
15564 
15565 	switch (BPF_OP(insn->code)) {
15566 	case BPF_EXIT:
15567 		return DONE_EXPLORING;
15568 
15569 	case BPF_CALL:
15570 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15571 			/* Mark this call insn as a prune point to trigger
15572 			 * is_state_visited() check before call itself is
15573 			 * processed by __check_func_call(). Otherwise new
15574 			 * async state will be pushed for further exploration.
15575 			 */
15576 			mark_prune_point(env, t);
15577 		/* For functions that invoke callbacks it is not known how many times
15578 		 * callback would be called. Verifier models callback calling functions
15579 		 * by repeatedly visiting callback bodies and returning to origin call
15580 		 * instruction.
15581 		 * In order to stop such iteration verifier needs to identify when a
15582 		 * state identical some state from a previous iteration is reached.
15583 		 * Check below forces creation of checkpoint before callback calling
15584 		 * instruction to allow search for such identical states.
15585 		 */
15586 		if (is_sync_callback_calling_insn(insn)) {
15587 			mark_calls_callback(env, t);
15588 			mark_force_checkpoint(env, t);
15589 			mark_prune_point(env, t);
15590 			mark_jmp_point(env, t);
15591 		}
15592 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15593 			struct bpf_kfunc_call_arg_meta meta;
15594 
15595 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15596 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15597 				mark_prune_point(env, t);
15598 				/* Checking and saving state checkpoints at iter_next() call
15599 				 * is crucial for fast convergence of open-coded iterator loop
15600 				 * logic, so we need to force it. If we don't do that,
15601 				 * is_state_visited() might skip saving a checkpoint, causing
15602 				 * unnecessarily long sequence of not checkpointed
15603 				 * instructions and jumps, leading to exhaustion of jump
15604 				 * history buffer, and potentially other undesired outcomes.
15605 				 * It is expected that with correct open-coded iterators
15606 				 * convergence will happen quickly, so we don't run a risk of
15607 				 * exhausting memory.
15608 				 */
15609 				mark_force_checkpoint(env, t);
15610 			}
15611 		}
15612 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15613 
15614 	case BPF_JA:
15615 		if (BPF_SRC(insn->code) != BPF_K)
15616 			return -EINVAL;
15617 
15618 		if (BPF_CLASS(insn->code) == BPF_JMP)
15619 			off = insn->off;
15620 		else
15621 			off = insn->imm;
15622 
15623 		/* unconditional jump with single edge */
15624 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15625 		if (ret)
15626 			return ret;
15627 
15628 		mark_prune_point(env, t + off + 1);
15629 		mark_jmp_point(env, t + off + 1);
15630 
15631 		return ret;
15632 
15633 	default:
15634 		/* conditional jump with two edges */
15635 		mark_prune_point(env, t);
15636 
15637 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15638 		if (ret)
15639 			return ret;
15640 
15641 		return push_insn(t, t + insn->off + 1, BRANCH, env);
15642 	}
15643 }
15644 
15645 /* non-recursive depth-first-search to detect loops in BPF program
15646  * loop == back-edge in directed graph
15647  */
15648 static int check_cfg(struct bpf_verifier_env *env)
15649 {
15650 	int insn_cnt = env->prog->len;
15651 	int *insn_stack, *insn_state;
15652 	int ex_insn_beg, i, ret = 0;
15653 	bool ex_done = false;
15654 
15655 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15656 	if (!insn_state)
15657 		return -ENOMEM;
15658 
15659 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15660 	if (!insn_stack) {
15661 		kvfree(insn_state);
15662 		return -ENOMEM;
15663 	}
15664 
15665 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15666 	insn_stack[0] = 0; /* 0 is the first instruction */
15667 	env->cfg.cur_stack = 1;
15668 
15669 walk_cfg:
15670 	while (env->cfg.cur_stack > 0) {
15671 		int t = insn_stack[env->cfg.cur_stack - 1];
15672 
15673 		ret = visit_insn(t, env);
15674 		switch (ret) {
15675 		case DONE_EXPLORING:
15676 			insn_state[t] = EXPLORED;
15677 			env->cfg.cur_stack--;
15678 			break;
15679 		case KEEP_EXPLORING:
15680 			break;
15681 		default:
15682 			if (ret > 0) {
15683 				verbose(env, "visit_insn internal bug\n");
15684 				ret = -EFAULT;
15685 			}
15686 			goto err_free;
15687 		}
15688 	}
15689 
15690 	if (env->cfg.cur_stack < 0) {
15691 		verbose(env, "pop stack internal bug\n");
15692 		ret = -EFAULT;
15693 		goto err_free;
15694 	}
15695 
15696 	if (env->exception_callback_subprog && !ex_done) {
15697 		ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
15698 
15699 		insn_state[ex_insn_beg] = DISCOVERED;
15700 		insn_stack[0] = ex_insn_beg;
15701 		env->cfg.cur_stack = 1;
15702 		ex_done = true;
15703 		goto walk_cfg;
15704 	}
15705 
15706 	for (i = 0; i < insn_cnt; i++) {
15707 		struct bpf_insn *insn = &env->prog->insnsi[i];
15708 
15709 		if (insn_state[i] != EXPLORED) {
15710 			verbose(env, "unreachable insn %d\n", i);
15711 			ret = -EINVAL;
15712 			goto err_free;
15713 		}
15714 		if (bpf_is_ldimm64(insn)) {
15715 			if (insn_state[i + 1] != 0) {
15716 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15717 				ret = -EINVAL;
15718 				goto err_free;
15719 			}
15720 			i++; /* skip second half of ldimm64 */
15721 		}
15722 	}
15723 	ret = 0; /* cfg looks good */
15724 
15725 err_free:
15726 	kvfree(insn_state);
15727 	kvfree(insn_stack);
15728 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
15729 	return ret;
15730 }
15731 
15732 static int check_abnormal_return(struct bpf_verifier_env *env)
15733 {
15734 	int i;
15735 
15736 	for (i = 1; i < env->subprog_cnt; i++) {
15737 		if (env->subprog_info[i].has_ld_abs) {
15738 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15739 			return -EINVAL;
15740 		}
15741 		if (env->subprog_info[i].has_tail_call) {
15742 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15743 			return -EINVAL;
15744 		}
15745 	}
15746 	return 0;
15747 }
15748 
15749 /* The minimum supported BTF func info size */
15750 #define MIN_BPF_FUNCINFO_SIZE	8
15751 #define MAX_FUNCINFO_REC_SIZE	252
15752 
15753 static int check_btf_func_early(struct bpf_verifier_env *env,
15754 				const union bpf_attr *attr,
15755 				bpfptr_t uattr)
15756 {
15757 	u32 krec_size = sizeof(struct bpf_func_info);
15758 	const struct btf_type *type, *func_proto;
15759 	u32 i, nfuncs, urec_size, min_size;
15760 	struct bpf_func_info *krecord;
15761 	struct bpf_prog *prog;
15762 	const struct btf *btf;
15763 	u32 prev_offset = 0;
15764 	bpfptr_t urecord;
15765 	int ret = -ENOMEM;
15766 
15767 	nfuncs = attr->func_info_cnt;
15768 	if (!nfuncs) {
15769 		if (check_abnormal_return(env))
15770 			return -EINVAL;
15771 		return 0;
15772 	}
15773 
15774 	urec_size = attr->func_info_rec_size;
15775 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15776 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
15777 	    urec_size % sizeof(u32)) {
15778 		verbose(env, "invalid func info rec size %u\n", urec_size);
15779 		return -EINVAL;
15780 	}
15781 
15782 	prog = env->prog;
15783 	btf = prog->aux->btf;
15784 
15785 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15786 	min_size = min_t(u32, krec_size, urec_size);
15787 
15788 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15789 	if (!krecord)
15790 		return -ENOMEM;
15791 
15792 	for (i = 0; i < nfuncs; i++) {
15793 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15794 		if (ret) {
15795 			if (ret == -E2BIG) {
15796 				verbose(env, "nonzero tailing record in func info");
15797 				/* set the size kernel expects so loader can zero
15798 				 * out the rest of the record.
15799 				 */
15800 				if (copy_to_bpfptr_offset(uattr,
15801 							  offsetof(union bpf_attr, func_info_rec_size),
15802 							  &min_size, sizeof(min_size)))
15803 					ret = -EFAULT;
15804 			}
15805 			goto err_free;
15806 		}
15807 
15808 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15809 			ret = -EFAULT;
15810 			goto err_free;
15811 		}
15812 
15813 		/* check insn_off */
15814 		ret = -EINVAL;
15815 		if (i == 0) {
15816 			if (krecord[i].insn_off) {
15817 				verbose(env,
15818 					"nonzero insn_off %u for the first func info record",
15819 					krecord[i].insn_off);
15820 				goto err_free;
15821 			}
15822 		} else if (krecord[i].insn_off <= prev_offset) {
15823 			verbose(env,
15824 				"same or smaller insn offset (%u) than previous func info record (%u)",
15825 				krecord[i].insn_off, prev_offset);
15826 			goto err_free;
15827 		}
15828 
15829 		/* check type_id */
15830 		type = btf_type_by_id(btf, krecord[i].type_id);
15831 		if (!type || !btf_type_is_func(type)) {
15832 			verbose(env, "invalid type id %d in func info",
15833 				krecord[i].type_id);
15834 			goto err_free;
15835 		}
15836 
15837 		func_proto = btf_type_by_id(btf, type->type);
15838 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15839 			/* btf_func_check() already verified it during BTF load */
15840 			goto err_free;
15841 
15842 		prev_offset = krecord[i].insn_off;
15843 		bpfptr_add(&urecord, urec_size);
15844 	}
15845 
15846 	prog->aux->func_info = krecord;
15847 	prog->aux->func_info_cnt = nfuncs;
15848 	return 0;
15849 
15850 err_free:
15851 	kvfree(krecord);
15852 	return ret;
15853 }
15854 
15855 static int check_btf_func(struct bpf_verifier_env *env,
15856 			  const union bpf_attr *attr,
15857 			  bpfptr_t uattr)
15858 {
15859 	const struct btf_type *type, *func_proto, *ret_type;
15860 	u32 i, nfuncs, urec_size;
15861 	struct bpf_func_info *krecord;
15862 	struct bpf_func_info_aux *info_aux = NULL;
15863 	struct bpf_prog *prog;
15864 	const struct btf *btf;
15865 	bpfptr_t urecord;
15866 	bool scalar_return;
15867 	int ret = -ENOMEM;
15868 
15869 	nfuncs = attr->func_info_cnt;
15870 	if (!nfuncs) {
15871 		if (check_abnormal_return(env))
15872 			return -EINVAL;
15873 		return 0;
15874 	}
15875 	if (nfuncs != env->subprog_cnt) {
15876 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15877 		return -EINVAL;
15878 	}
15879 
15880 	urec_size = attr->func_info_rec_size;
15881 
15882 	prog = env->prog;
15883 	btf = prog->aux->btf;
15884 
15885 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15886 
15887 	krecord = prog->aux->func_info;
15888 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15889 	if (!info_aux)
15890 		return -ENOMEM;
15891 
15892 	for (i = 0; i < nfuncs; i++) {
15893 		/* check insn_off */
15894 		ret = -EINVAL;
15895 
15896 		if (env->subprog_info[i].start != krecord[i].insn_off) {
15897 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15898 			goto err_free;
15899 		}
15900 
15901 		/* Already checked type_id */
15902 		type = btf_type_by_id(btf, krecord[i].type_id);
15903 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15904 		/* Already checked func_proto */
15905 		func_proto = btf_type_by_id(btf, type->type);
15906 
15907 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15908 		scalar_return =
15909 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15910 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15911 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15912 			goto err_free;
15913 		}
15914 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15915 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15916 			goto err_free;
15917 		}
15918 
15919 		bpfptr_add(&urecord, urec_size);
15920 	}
15921 
15922 	prog->aux->func_info_aux = info_aux;
15923 	return 0;
15924 
15925 err_free:
15926 	kfree(info_aux);
15927 	return ret;
15928 }
15929 
15930 static void adjust_btf_func(struct bpf_verifier_env *env)
15931 {
15932 	struct bpf_prog_aux *aux = env->prog->aux;
15933 	int i;
15934 
15935 	if (!aux->func_info)
15936 		return;
15937 
15938 	/* func_info is not available for hidden subprogs */
15939 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
15940 		aux->func_info[i].insn_off = env->subprog_info[i].start;
15941 }
15942 
15943 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
15944 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
15945 
15946 static int check_btf_line(struct bpf_verifier_env *env,
15947 			  const union bpf_attr *attr,
15948 			  bpfptr_t uattr)
15949 {
15950 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15951 	struct bpf_subprog_info *sub;
15952 	struct bpf_line_info *linfo;
15953 	struct bpf_prog *prog;
15954 	const struct btf *btf;
15955 	bpfptr_t ulinfo;
15956 	int err;
15957 
15958 	nr_linfo = attr->line_info_cnt;
15959 	if (!nr_linfo)
15960 		return 0;
15961 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15962 		return -EINVAL;
15963 
15964 	rec_size = attr->line_info_rec_size;
15965 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15966 	    rec_size > MAX_LINEINFO_REC_SIZE ||
15967 	    rec_size & (sizeof(u32) - 1))
15968 		return -EINVAL;
15969 
15970 	/* Need to zero it in case the userspace may
15971 	 * pass in a smaller bpf_line_info object.
15972 	 */
15973 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15974 			 GFP_KERNEL | __GFP_NOWARN);
15975 	if (!linfo)
15976 		return -ENOMEM;
15977 
15978 	prog = env->prog;
15979 	btf = prog->aux->btf;
15980 
15981 	s = 0;
15982 	sub = env->subprog_info;
15983 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15984 	expected_size = sizeof(struct bpf_line_info);
15985 	ncopy = min_t(u32, expected_size, rec_size);
15986 	for (i = 0; i < nr_linfo; i++) {
15987 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15988 		if (err) {
15989 			if (err == -E2BIG) {
15990 				verbose(env, "nonzero tailing record in line_info");
15991 				if (copy_to_bpfptr_offset(uattr,
15992 							  offsetof(union bpf_attr, line_info_rec_size),
15993 							  &expected_size, sizeof(expected_size)))
15994 					err = -EFAULT;
15995 			}
15996 			goto err_free;
15997 		}
15998 
15999 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
16000 			err = -EFAULT;
16001 			goto err_free;
16002 		}
16003 
16004 		/*
16005 		 * Check insn_off to ensure
16006 		 * 1) strictly increasing AND
16007 		 * 2) bounded by prog->len
16008 		 *
16009 		 * The linfo[0].insn_off == 0 check logically falls into
16010 		 * the later "missing bpf_line_info for func..." case
16011 		 * because the first linfo[0].insn_off must be the
16012 		 * first sub also and the first sub must have
16013 		 * subprog_info[0].start == 0.
16014 		 */
16015 		if ((i && linfo[i].insn_off <= prev_offset) ||
16016 		    linfo[i].insn_off >= prog->len) {
16017 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
16018 				i, linfo[i].insn_off, prev_offset,
16019 				prog->len);
16020 			err = -EINVAL;
16021 			goto err_free;
16022 		}
16023 
16024 		if (!prog->insnsi[linfo[i].insn_off].code) {
16025 			verbose(env,
16026 				"Invalid insn code at line_info[%u].insn_off\n",
16027 				i);
16028 			err = -EINVAL;
16029 			goto err_free;
16030 		}
16031 
16032 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
16033 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
16034 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
16035 			err = -EINVAL;
16036 			goto err_free;
16037 		}
16038 
16039 		if (s != env->subprog_cnt) {
16040 			if (linfo[i].insn_off == sub[s].start) {
16041 				sub[s].linfo_idx = i;
16042 				s++;
16043 			} else if (sub[s].start < linfo[i].insn_off) {
16044 				verbose(env, "missing bpf_line_info for func#%u\n", s);
16045 				err = -EINVAL;
16046 				goto err_free;
16047 			}
16048 		}
16049 
16050 		prev_offset = linfo[i].insn_off;
16051 		bpfptr_add(&ulinfo, rec_size);
16052 	}
16053 
16054 	if (s != env->subprog_cnt) {
16055 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
16056 			env->subprog_cnt - s, s);
16057 		err = -EINVAL;
16058 		goto err_free;
16059 	}
16060 
16061 	prog->aux->linfo = linfo;
16062 	prog->aux->nr_linfo = nr_linfo;
16063 
16064 	return 0;
16065 
16066 err_free:
16067 	kvfree(linfo);
16068 	return err;
16069 }
16070 
16071 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
16072 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
16073 
16074 static int check_core_relo(struct bpf_verifier_env *env,
16075 			   const union bpf_attr *attr,
16076 			   bpfptr_t uattr)
16077 {
16078 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
16079 	struct bpf_core_relo core_relo = {};
16080 	struct bpf_prog *prog = env->prog;
16081 	const struct btf *btf = prog->aux->btf;
16082 	struct bpf_core_ctx ctx = {
16083 		.log = &env->log,
16084 		.btf = btf,
16085 	};
16086 	bpfptr_t u_core_relo;
16087 	int err;
16088 
16089 	nr_core_relo = attr->core_relo_cnt;
16090 	if (!nr_core_relo)
16091 		return 0;
16092 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
16093 		return -EINVAL;
16094 
16095 	rec_size = attr->core_relo_rec_size;
16096 	if (rec_size < MIN_CORE_RELO_SIZE ||
16097 	    rec_size > MAX_CORE_RELO_SIZE ||
16098 	    rec_size % sizeof(u32))
16099 		return -EINVAL;
16100 
16101 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
16102 	expected_size = sizeof(struct bpf_core_relo);
16103 	ncopy = min_t(u32, expected_size, rec_size);
16104 
16105 	/* Unlike func_info and line_info, copy and apply each CO-RE
16106 	 * relocation record one at a time.
16107 	 */
16108 	for (i = 0; i < nr_core_relo; i++) {
16109 		/* future proofing when sizeof(bpf_core_relo) changes */
16110 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
16111 		if (err) {
16112 			if (err == -E2BIG) {
16113 				verbose(env, "nonzero tailing record in core_relo");
16114 				if (copy_to_bpfptr_offset(uattr,
16115 							  offsetof(union bpf_attr, core_relo_rec_size),
16116 							  &expected_size, sizeof(expected_size)))
16117 					err = -EFAULT;
16118 			}
16119 			break;
16120 		}
16121 
16122 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
16123 			err = -EFAULT;
16124 			break;
16125 		}
16126 
16127 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
16128 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
16129 				i, core_relo.insn_off, prog->len);
16130 			err = -EINVAL;
16131 			break;
16132 		}
16133 
16134 		err = bpf_core_apply(&ctx, &core_relo, i,
16135 				     &prog->insnsi[core_relo.insn_off / 8]);
16136 		if (err)
16137 			break;
16138 		bpfptr_add(&u_core_relo, rec_size);
16139 	}
16140 	return err;
16141 }
16142 
16143 static int check_btf_info_early(struct bpf_verifier_env *env,
16144 				const union bpf_attr *attr,
16145 				bpfptr_t uattr)
16146 {
16147 	struct btf *btf;
16148 	int err;
16149 
16150 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
16151 		if (check_abnormal_return(env))
16152 			return -EINVAL;
16153 		return 0;
16154 	}
16155 
16156 	btf = btf_get_by_fd(attr->prog_btf_fd);
16157 	if (IS_ERR(btf))
16158 		return PTR_ERR(btf);
16159 	if (btf_is_kernel(btf)) {
16160 		btf_put(btf);
16161 		return -EACCES;
16162 	}
16163 	env->prog->aux->btf = btf;
16164 
16165 	err = check_btf_func_early(env, attr, uattr);
16166 	if (err)
16167 		return err;
16168 	return 0;
16169 }
16170 
16171 static int check_btf_info(struct bpf_verifier_env *env,
16172 			  const union bpf_attr *attr,
16173 			  bpfptr_t uattr)
16174 {
16175 	int err;
16176 
16177 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
16178 		if (check_abnormal_return(env))
16179 			return -EINVAL;
16180 		return 0;
16181 	}
16182 
16183 	err = check_btf_func(env, attr, uattr);
16184 	if (err)
16185 		return err;
16186 
16187 	err = check_btf_line(env, attr, uattr);
16188 	if (err)
16189 		return err;
16190 
16191 	err = check_core_relo(env, attr, uattr);
16192 	if (err)
16193 		return err;
16194 
16195 	return 0;
16196 }
16197 
16198 /* check %cur's range satisfies %old's */
16199 static bool range_within(struct bpf_reg_state *old,
16200 			 struct bpf_reg_state *cur)
16201 {
16202 	return old->umin_value <= cur->umin_value &&
16203 	       old->umax_value >= cur->umax_value &&
16204 	       old->smin_value <= cur->smin_value &&
16205 	       old->smax_value >= cur->smax_value &&
16206 	       old->u32_min_value <= cur->u32_min_value &&
16207 	       old->u32_max_value >= cur->u32_max_value &&
16208 	       old->s32_min_value <= cur->s32_min_value &&
16209 	       old->s32_max_value >= cur->s32_max_value;
16210 }
16211 
16212 /* If in the old state two registers had the same id, then they need to have
16213  * the same id in the new state as well.  But that id could be different from
16214  * the old state, so we need to track the mapping from old to new ids.
16215  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
16216  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
16217  * regs with a different old id could still have new id 9, we don't care about
16218  * that.
16219  * So we look through our idmap to see if this old id has been seen before.  If
16220  * so, we require the new id to match; otherwise, we add the id pair to the map.
16221  */
16222 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16223 {
16224 	struct bpf_id_pair *map = idmap->map;
16225 	unsigned int i;
16226 
16227 	/* either both IDs should be set or both should be zero */
16228 	if (!!old_id != !!cur_id)
16229 		return false;
16230 
16231 	if (old_id == 0) /* cur_id == 0 as well */
16232 		return true;
16233 
16234 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
16235 		if (!map[i].old) {
16236 			/* Reached an empty slot; haven't seen this id before */
16237 			map[i].old = old_id;
16238 			map[i].cur = cur_id;
16239 			return true;
16240 		}
16241 		if (map[i].old == old_id)
16242 			return map[i].cur == cur_id;
16243 		if (map[i].cur == cur_id)
16244 			return false;
16245 	}
16246 	/* We ran out of idmap slots, which should be impossible */
16247 	WARN_ON_ONCE(1);
16248 	return false;
16249 }
16250 
16251 /* Similar to check_ids(), but allocate a unique temporary ID
16252  * for 'old_id' or 'cur_id' of zero.
16253  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
16254  */
16255 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16256 {
16257 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
16258 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
16259 
16260 	return check_ids(old_id, cur_id, idmap);
16261 }
16262 
16263 static void clean_func_state(struct bpf_verifier_env *env,
16264 			     struct bpf_func_state *st)
16265 {
16266 	enum bpf_reg_liveness live;
16267 	int i, j;
16268 
16269 	for (i = 0; i < BPF_REG_FP; i++) {
16270 		live = st->regs[i].live;
16271 		/* liveness must not touch this register anymore */
16272 		st->regs[i].live |= REG_LIVE_DONE;
16273 		if (!(live & REG_LIVE_READ))
16274 			/* since the register is unused, clear its state
16275 			 * to make further comparison simpler
16276 			 */
16277 			__mark_reg_not_init(env, &st->regs[i]);
16278 	}
16279 
16280 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
16281 		live = st->stack[i].spilled_ptr.live;
16282 		/* liveness must not touch this stack slot anymore */
16283 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
16284 		if (!(live & REG_LIVE_READ)) {
16285 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
16286 			for (j = 0; j < BPF_REG_SIZE; j++)
16287 				st->stack[i].slot_type[j] = STACK_INVALID;
16288 		}
16289 	}
16290 }
16291 
16292 static void clean_verifier_state(struct bpf_verifier_env *env,
16293 				 struct bpf_verifier_state *st)
16294 {
16295 	int i;
16296 
16297 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
16298 		/* all regs in this state in all frames were already marked */
16299 		return;
16300 
16301 	for (i = 0; i <= st->curframe; i++)
16302 		clean_func_state(env, st->frame[i]);
16303 }
16304 
16305 /* the parentage chains form a tree.
16306  * the verifier states are added to state lists at given insn and
16307  * pushed into state stack for future exploration.
16308  * when the verifier reaches bpf_exit insn some of the verifer states
16309  * stored in the state lists have their final liveness state already,
16310  * but a lot of states will get revised from liveness point of view when
16311  * the verifier explores other branches.
16312  * Example:
16313  * 1: r0 = 1
16314  * 2: if r1 == 100 goto pc+1
16315  * 3: r0 = 2
16316  * 4: exit
16317  * when the verifier reaches exit insn the register r0 in the state list of
16318  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
16319  * of insn 2 and goes exploring further. At the insn 4 it will walk the
16320  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
16321  *
16322  * Since the verifier pushes the branch states as it sees them while exploring
16323  * the program the condition of walking the branch instruction for the second
16324  * time means that all states below this branch were already explored and
16325  * their final liveness marks are already propagated.
16326  * Hence when the verifier completes the search of state list in is_state_visited()
16327  * we can call this clean_live_states() function to mark all liveness states
16328  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
16329  * will not be used.
16330  * This function also clears the registers and stack for states that !READ
16331  * to simplify state merging.
16332  *
16333  * Important note here that walking the same branch instruction in the callee
16334  * doesn't meant that the states are DONE. The verifier has to compare
16335  * the callsites
16336  */
16337 static void clean_live_states(struct bpf_verifier_env *env, int insn,
16338 			      struct bpf_verifier_state *cur)
16339 {
16340 	struct bpf_verifier_state_list *sl;
16341 
16342 	sl = *explored_state(env, insn);
16343 	while (sl) {
16344 		if (sl->state.branches)
16345 			goto next;
16346 		if (sl->state.insn_idx != insn ||
16347 		    !same_callsites(&sl->state, cur))
16348 			goto next;
16349 		clean_verifier_state(env, &sl->state);
16350 next:
16351 		sl = sl->next;
16352 	}
16353 }
16354 
16355 static bool regs_exact(const struct bpf_reg_state *rold,
16356 		       const struct bpf_reg_state *rcur,
16357 		       struct bpf_idmap *idmap)
16358 {
16359 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16360 	       check_ids(rold->id, rcur->id, idmap) &&
16361 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16362 }
16363 
16364 /* Returns true if (rold safe implies rcur safe) */
16365 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
16366 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
16367 {
16368 	if (exact)
16369 		return regs_exact(rold, rcur, idmap);
16370 
16371 	if (!(rold->live & REG_LIVE_READ))
16372 		/* explored state didn't use this */
16373 		return true;
16374 	if (rold->type == NOT_INIT)
16375 		/* explored state can't have used this */
16376 		return true;
16377 	if (rcur->type == NOT_INIT)
16378 		return false;
16379 
16380 	/* Enforce that register types have to match exactly, including their
16381 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16382 	 * rule.
16383 	 *
16384 	 * One can make a point that using a pointer register as unbounded
16385 	 * SCALAR would be technically acceptable, but this could lead to
16386 	 * pointer leaks because scalars are allowed to leak while pointers
16387 	 * are not. We could make this safe in special cases if root is
16388 	 * calling us, but it's probably not worth the hassle.
16389 	 *
16390 	 * Also, register types that are *not* MAYBE_NULL could technically be
16391 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16392 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16393 	 * to the same map).
16394 	 * However, if the old MAYBE_NULL register then got NULL checked,
16395 	 * doing so could have affected others with the same id, and we can't
16396 	 * check for that because we lost the id when we converted to
16397 	 * a non-MAYBE_NULL variant.
16398 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
16399 	 * non-MAYBE_NULL registers as well.
16400 	 */
16401 	if (rold->type != rcur->type)
16402 		return false;
16403 
16404 	switch (base_type(rold->type)) {
16405 	case SCALAR_VALUE:
16406 		if (env->explore_alu_limits) {
16407 			/* explore_alu_limits disables tnum_in() and range_within()
16408 			 * logic and requires everything to be strict
16409 			 */
16410 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16411 			       check_scalar_ids(rold->id, rcur->id, idmap);
16412 		}
16413 		if (!rold->precise)
16414 			return true;
16415 		/* Why check_ids() for scalar registers?
16416 		 *
16417 		 * Consider the following BPF code:
16418 		 *   1: r6 = ... unbound scalar, ID=a ...
16419 		 *   2: r7 = ... unbound scalar, ID=b ...
16420 		 *   3: if (r6 > r7) goto +1
16421 		 *   4: r6 = r7
16422 		 *   5: if (r6 > X) goto ...
16423 		 *   6: ... memory operation using r7 ...
16424 		 *
16425 		 * First verification path is [1-6]:
16426 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16427 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16428 		 *   r7 <= X, because r6 and r7 share same id.
16429 		 * Next verification path is [1-4, 6].
16430 		 *
16431 		 * Instruction (6) would be reached in two states:
16432 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16433 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16434 		 *
16435 		 * Use check_ids() to distinguish these states.
16436 		 * ---
16437 		 * Also verify that new value satisfies old value range knowledge.
16438 		 */
16439 		return range_within(rold, rcur) &&
16440 		       tnum_in(rold->var_off, rcur->var_off) &&
16441 		       check_scalar_ids(rold->id, rcur->id, idmap);
16442 	case PTR_TO_MAP_KEY:
16443 	case PTR_TO_MAP_VALUE:
16444 	case PTR_TO_MEM:
16445 	case PTR_TO_BUF:
16446 	case PTR_TO_TP_BUFFER:
16447 		/* If the new min/max/var_off satisfy the old ones and
16448 		 * everything else matches, we are OK.
16449 		 */
16450 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16451 		       range_within(rold, rcur) &&
16452 		       tnum_in(rold->var_off, rcur->var_off) &&
16453 		       check_ids(rold->id, rcur->id, idmap) &&
16454 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16455 	case PTR_TO_PACKET_META:
16456 	case PTR_TO_PACKET:
16457 		/* We must have at least as much range as the old ptr
16458 		 * did, so that any accesses which were safe before are
16459 		 * still safe.  This is true even if old range < old off,
16460 		 * since someone could have accessed through (ptr - k), or
16461 		 * even done ptr -= k in a register, to get a safe access.
16462 		 */
16463 		if (rold->range > rcur->range)
16464 			return false;
16465 		/* If the offsets don't match, we can't trust our alignment;
16466 		 * nor can we be sure that we won't fall out of range.
16467 		 */
16468 		if (rold->off != rcur->off)
16469 			return false;
16470 		/* id relations must be preserved */
16471 		if (!check_ids(rold->id, rcur->id, idmap))
16472 			return false;
16473 		/* new val must satisfy old val knowledge */
16474 		return range_within(rold, rcur) &&
16475 		       tnum_in(rold->var_off, rcur->var_off);
16476 	case PTR_TO_STACK:
16477 		/* two stack pointers are equal only if they're pointing to
16478 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16479 		 */
16480 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16481 	default:
16482 		return regs_exact(rold, rcur, idmap);
16483 	}
16484 }
16485 
16486 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16487 		      struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16488 {
16489 	int i, spi;
16490 
16491 	/* walk slots of the explored stack and ignore any additional
16492 	 * slots in the current stack, since explored(safe) state
16493 	 * didn't use them
16494 	 */
16495 	for (i = 0; i < old->allocated_stack; i++) {
16496 		struct bpf_reg_state *old_reg, *cur_reg;
16497 
16498 		spi = i / BPF_REG_SIZE;
16499 
16500 		if (exact &&
16501 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16502 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16503 			return false;
16504 
16505 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16506 			i += BPF_REG_SIZE - 1;
16507 			/* explored state didn't use this */
16508 			continue;
16509 		}
16510 
16511 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16512 			continue;
16513 
16514 		if (env->allow_uninit_stack &&
16515 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16516 			continue;
16517 
16518 		/* explored stack has more populated slots than current stack
16519 		 * and these slots were used
16520 		 */
16521 		if (i >= cur->allocated_stack)
16522 			return false;
16523 
16524 		/* if old state was safe with misc data in the stack
16525 		 * it will be safe with zero-initialized stack.
16526 		 * The opposite is not true
16527 		 */
16528 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16529 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16530 			continue;
16531 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16532 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16533 			/* Ex: old explored (safe) state has STACK_SPILL in
16534 			 * this stack slot, but current has STACK_MISC ->
16535 			 * this verifier states are not equivalent,
16536 			 * return false to continue verification of this path
16537 			 */
16538 			return false;
16539 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16540 			continue;
16541 		/* Both old and cur are having same slot_type */
16542 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16543 		case STACK_SPILL:
16544 			/* when explored and current stack slot are both storing
16545 			 * spilled registers, check that stored pointers types
16546 			 * are the same as well.
16547 			 * Ex: explored safe path could have stored
16548 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16549 			 * but current path has stored:
16550 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16551 			 * such verifier states are not equivalent.
16552 			 * return false to continue verification of this path
16553 			 */
16554 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16555 				     &cur->stack[spi].spilled_ptr, idmap, exact))
16556 				return false;
16557 			break;
16558 		case STACK_DYNPTR:
16559 			old_reg = &old->stack[spi].spilled_ptr;
16560 			cur_reg = &cur->stack[spi].spilled_ptr;
16561 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16562 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16563 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16564 				return false;
16565 			break;
16566 		case STACK_ITER:
16567 			old_reg = &old->stack[spi].spilled_ptr;
16568 			cur_reg = &cur->stack[spi].spilled_ptr;
16569 			/* iter.depth is not compared between states as it
16570 			 * doesn't matter for correctness and would otherwise
16571 			 * prevent convergence; we maintain it only to prevent
16572 			 * infinite loop check triggering, see
16573 			 * iter_active_depths_differ()
16574 			 */
16575 			if (old_reg->iter.btf != cur_reg->iter.btf ||
16576 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16577 			    old_reg->iter.state != cur_reg->iter.state ||
16578 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16579 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16580 				return false;
16581 			break;
16582 		case STACK_MISC:
16583 		case STACK_ZERO:
16584 		case STACK_INVALID:
16585 			continue;
16586 		/* Ensure that new unhandled slot types return false by default */
16587 		default:
16588 			return false;
16589 		}
16590 	}
16591 	return true;
16592 }
16593 
16594 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16595 		    struct bpf_idmap *idmap)
16596 {
16597 	int i;
16598 
16599 	if (old->acquired_refs != cur->acquired_refs)
16600 		return false;
16601 
16602 	for (i = 0; i < old->acquired_refs; i++) {
16603 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16604 			return false;
16605 	}
16606 
16607 	return true;
16608 }
16609 
16610 /* compare two verifier states
16611  *
16612  * all states stored in state_list are known to be valid, since
16613  * verifier reached 'bpf_exit' instruction through them
16614  *
16615  * this function is called when verifier exploring different branches of
16616  * execution popped from the state stack. If it sees an old state that has
16617  * more strict register state and more strict stack state then this execution
16618  * branch doesn't need to be explored further, since verifier already
16619  * concluded that more strict state leads to valid finish.
16620  *
16621  * Therefore two states are equivalent if register state is more conservative
16622  * and explored stack state is more conservative than the current one.
16623  * Example:
16624  *       explored                   current
16625  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16626  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16627  *
16628  * In other words if current stack state (one being explored) has more
16629  * valid slots than old one that already passed validation, it means
16630  * the verifier can stop exploring and conclude that current state is valid too
16631  *
16632  * Similarly with registers. If explored state has register type as invalid
16633  * whereas register type in current state is meaningful, it means that
16634  * the current state will reach 'bpf_exit' instruction safely
16635  */
16636 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16637 			      struct bpf_func_state *cur, bool exact)
16638 {
16639 	int i;
16640 
16641 	for (i = 0; i < MAX_BPF_REG; i++)
16642 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
16643 			     &env->idmap_scratch, exact))
16644 			return false;
16645 
16646 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16647 		return false;
16648 
16649 	if (!refsafe(old, cur, &env->idmap_scratch))
16650 		return false;
16651 
16652 	return true;
16653 }
16654 
16655 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16656 {
16657 	env->idmap_scratch.tmp_id_gen = env->id_gen;
16658 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16659 }
16660 
16661 static bool states_equal(struct bpf_verifier_env *env,
16662 			 struct bpf_verifier_state *old,
16663 			 struct bpf_verifier_state *cur,
16664 			 bool exact)
16665 {
16666 	int i;
16667 
16668 	if (old->curframe != cur->curframe)
16669 		return false;
16670 
16671 	reset_idmap_scratch(env);
16672 
16673 	/* Verification state from speculative execution simulation
16674 	 * must never prune a non-speculative execution one.
16675 	 */
16676 	if (old->speculative && !cur->speculative)
16677 		return false;
16678 
16679 	if (old->active_lock.ptr != cur->active_lock.ptr)
16680 		return false;
16681 
16682 	/* Old and cur active_lock's have to be either both present
16683 	 * or both absent.
16684 	 */
16685 	if (!!old->active_lock.id != !!cur->active_lock.id)
16686 		return false;
16687 
16688 	if (old->active_lock.id &&
16689 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16690 		return false;
16691 
16692 	if (old->active_rcu_lock != cur->active_rcu_lock)
16693 		return false;
16694 
16695 	/* for states to be equal callsites have to be the same
16696 	 * and all frame states need to be equivalent
16697 	 */
16698 	for (i = 0; i <= old->curframe; i++) {
16699 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
16700 			return false;
16701 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16702 			return false;
16703 	}
16704 	return true;
16705 }
16706 
16707 /* Return 0 if no propagation happened. Return negative error code if error
16708  * happened. Otherwise, return the propagated bit.
16709  */
16710 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16711 				  struct bpf_reg_state *reg,
16712 				  struct bpf_reg_state *parent_reg)
16713 {
16714 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16715 	u8 flag = reg->live & REG_LIVE_READ;
16716 	int err;
16717 
16718 	/* When comes here, read flags of PARENT_REG or REG could be any of
16719 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16720 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16721 	 */
16722 	if (parent_flag == REG_LIVE_READ64 ||
16723 	    /* Or if there is no read flag from REG. */
16724 	    !flag ||
16725 	    /* Or if the read flag from REG is the same as PARENT_REG. */
16726 	    parent_flag == flag)
16727 		return 0;
16728 
16729 	err = mark_reg_read(env, reg, parent_reg, flag);
16730 	if (err)
16731 		return err;
16732 
16733 	return flag;
16734 }
16735 
16736 /* A write screens off any subsequent reads; but write marks come from the
16737  * straight-line code between a state and its parent.  When we arrive at an
16738  * equivalent state (jump target or such) we didn't arrive by the straight-line
16739  * code, so read marks in the state must propagate to the parent regardless
16740  * of the state's write marks. That's what 'parent == state->parent' comparison
16741  * in mark_reg_read() is for.
16742  */
16743 static int propagate_liveness(struct bpf_verifier_env *env,
16744 			      const struct bpf_verifier_state *vstate,
16745 			      struct bpf_verifier_state *vparent)
16746 {
16747 	struct bpf_reg_state *state_reg, *parent_reg;
16748 	struct bpf_func_state *state, *parent;
16749 	int i, frame, err = 0;
16750 
16751 	if (vparent->curframe != vstate->curframe) {
16752 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
16753 		     vparent->curframe, vstate->curframe);
16754 		return -EFAULT;
16755 	}
16756 	/* Propagate read liveness of registers... */
16757 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16758 	for (frame = 0; frame <= vstate->curframe; frame++) {
16759 		parent = vparent->frame[frame];
16760 		state = vstate->frame[frame];
16761 		parent_reg = parent->regs;
16762 		state_reg = state->regs;
16763 		/* We don't need to worry about FP liveness, it's read-only */
16764 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16765 			err = propagate_liveness_reg(env, &state_reg[i],
16766 						     &parent_reg[i]);
16767 			if (err < 0)
16768 				return err;
16769 			if (err == REG_LIVE_READ64)
16770 				mark_insn_zext(env, &parent_reg[i]);
16771 		}
16772 
16773 		/* Propagate stack slots. */
16774 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16775 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16776 			parent_reg = &parent->stack[i].spilled_ptr;
16777 			state_reg = &state->stack[i].spilled_ptr;
16778 			err = propagate_liveness_reg(env, state_reg,
16779 						     parent_reg);
16780 			if (err < 0)
16781 				return err;
16782 		}
16783 	}
16784 	return 0;
16785 }
16786 
16787 /* find precise scalars in the previous equivalent state and
16788  * propagate them into the current state
16789  */
16790 static int propagate_precision(struct bpf_verifier_env *env,
16791 			       const struct bpf_verifier_state *old)
16792 {
16793 	struct bpf_reg_state *state_reg;
16794 	struct bpf_func_state *state;
16795 	int i, err = 0, fr;
16796 	bool first;
16797 
16798 	for (fr = old->curframe; fr >= 0; fr--) {
16799 		state = old->frame[fr];
16800 		state_reg = state->regs;
16801 		first = true;
16802 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16803 			if (state_reg->type != SCALAR_VALUE ||
16804 			    !state_reg->precise ||
16805 			    !(state_reg->live & REG_LIVE_READ))
16806 				continue;
16807 			if (env->log.level & BPF_LOG_LEVEL2) {
16808 				if (first)
16809 					verbose(env, "frame %d: propagating r%d", fr, i);
16810 				else
16811 					verbose(env, ",r%d", i);
16812 			}
16813 			bt_set_frame_reg(&env->bt, fr, i);
16814 			first = false;
16815 		}
16816 
16817 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16818 			if (!is_spilled_reg(&state->stack[i]))
16819 				continue;
16820 			state_reg = &state->stack[i].spilled_ptr;
16821 			if (state_reg->type != SCALAR_VALUE ||
16822 			    !state_reg->precise ||
16823 			    !(state_reg->live & REG_LIVE_READ))
16824 				continue;
16825 			if (env->log.level & BPF_LOG_LEVEL2) {
16826 				if (first)
16827 					verbose(env, "frame %d: propagating fp%d",
16828 						fr, (-i - 1) * BPF_REG_SIZE);
16829 				else
16830 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16831 			}
16832 			bt_set_frame_slot(&env->bt, fr, i);
16833 			first = false;
16834 		}
16835 		if (!first)
16836 			verbose(env, "\n");
16837 	}
16838 
16839 	err = mark_chain_precision_batch(env);
16840 	if (err < 0)
16841 		return err;
16842 
16843 	return 0;
16844 }
16845 
16846 static bool states_maybe_looping(struct bpf_verifier_state *old,
16847 				 struct bpf_verifier_state *cur)
16848 {
16849 	struct bpf_func_state *fold, *fcur;
16850 	int i, fr = cur->curframe;
16851 
16852 	if (old->curframe != fr)
16853 		return false;
16854 
16855 	fold = old->frame[fr];
16856 	fcur = cur->frame[fr];
16857 	for (i = 0; i < MAX_BPF_REG; i++)
16858 		if (memcmp(&fold->regs[i], &fcur->regs[i],
16859 			   offsetof(struct bpf_reg_state, parent)))
16860 			return false;
16861 	return true;
16862 }
16863 
16864 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16865 {
16866 	return env->insn_aux_data[insn_idx].is_iter_next;
16867 }
16868 
16869 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16870  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16871  * states to match, which otherwise would look like an infinite loop. So while
16872  * iter_next() calls are taken care of, we still need to be careful and
16873  * prevent erroneous and too eager declaration of "ininite loop", when
16874  * iterators are involved.
16875  *
16876  * Here's a situation in pseudo-BPF assembly form:
16877  *
16878  *   0: again:                          ; set up iter_next() call args
16879  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16880  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16881  *   3:   if r0 == 0 goto done
16882  *   4:   ... something useful here ...
16883  *   5:   goto again                    ; another iteration
16884  *   6: done:
16885  *   7:   r1 = &it
16886  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16887  *   9:   exit
16888  *
16889  * This is a typical loop. Let's assume that we have a prune point at 1:,
16890  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16891  * again`, assuming other heuristics don't get in a way).
16892  *
16893  * When we first time come to 1:, let's say we have some state X. We proceed
16894  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16895  * Now we come back to validate that forked ACTIVE state. We proceed through
16896  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16897  * are converging. But the problem is that we don't know that yet, as this
16898  * convergence has to happen at iter_next() call site only. So if nothing is
16899  * done, at 1: verifier will use bounded loop logic and declare infinite
16900  * looping (and would be *technically* correct, if not for iterator's
16901  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16902  * don't want that. So what we do in process_iter_next_call() when we go on
16903  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16904  * a different iteration. So when we suspect an infinite loop, we additionally
16905  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16906  * pretend we are not looping and wait for next iter_next() call.
16907  *
16908  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16909  * loop, because that would actually mean infinite loop, as DRAINED state is
16910  * "sticky", and so we'll keep returning into the same instruction with the
16911  * same state (at least in one of possible code paths).
16912  *
16913  * This approach allows to keep infinite loop heuristic even in the face of
16914  * active iterator. E.g., C snippet below is and will be detected as
16915  * inifintely looping:
16916  *
16917  *   struct bpf_iter_num it;
16918  *   int *p, x;
16919  *
16920  *   bpf_iter_num_new(&it, 0, 10);
16921  *   while ((p = bpf_iter_num_next(&t))) {
16922  *       x = p;
16923  *       while (x--) {} // <<-- infinite loop here
16924  *   }
16925  *
16926  */
16927 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16928 {
16929 	struct bpf_reg_state *slot, *cur_slot;
16930 	struct bpf_func_state *state;
16931 	int i, fr;
16932 
16933 	for (fr = old->curframe; fr >= 0; fr--) {
16934 		state = old->frame[fr];
16935 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16936 			if (state->stack[i].slot_type[0] != STACK_ITER)
16937 				continue;
16938 
16939 			slot = &state->stack[i].spilled_ptr;
16940 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16941 				continue;
16942 
16943 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16944 			if (cur_slot->iter.depth != slot->iter.depth)
16945 				return true;
16946 		}
16947 	}
16948 	return false;
16949 }
16950 
16951 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16952 {
16953 	struct bpf_verifier_state_list *new_sl;
16954 	struct bpf_verifier_state_list *sl, **pprev;
16955 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16956 	int i, j, n, err, states_cnt = 0;
16957 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16958 	bool add_new_state = force_new_state;
16959 	bool force_exact;
16960 
16961 	/* bpf progs typically have pruning point every 4 instructions
16962 	 * http://vger.kernel.org/bpfconf2019.html#session-1
16963 	 * Do not add new state for future pruning if the verifier hasn't seen
16964 	 * at least 2 jumps and at least 8 instructions.
16965 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16966 	 * In tests that amounts to up to 50% reduction into total verifier
16967 	 * memory consumption and 20% verifier time speedup.
16968 	 */
16969 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16970 	    env->insn_processed - env->prev_insn_processed >= 8)
16971 		add_new_state = true;
16972 
16973 	pprev = explored_state(env, insn_idx);
16974 	sl = *pprev;
16975 
16976 	clean_live_states(env, insn_idx, cur);
16977 
16978 	while (sl) {
16979 		states_cnt++;
16980 		if (sl->state.insn_idx != insn_idx)
16981 			goto next;
16982 
16983 		if (sl->state.branches) {
16984 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16985 
16986 			if (frame->in_async_callback_fn &&
16987 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16988 				/* Different async_entry_cnt means that the verifier is
16989 				 * processing another entry into async callback.
16990 				 * Seeing the same state is not an indication of infinite
16991 				 * loop or infinite recursion.
16992 				 * But finding the same state doesn't mean that it's safe
16993 				 * to stop processing the current state. The previous state
16994 				 * hasn't yet reached bpf_exit, since state.branches > 0.
16995 				 * Checking in_async_callback_fn alone is not enough either.
16996 				 * Since the verifier still needs to catch infinite loops
16997 				 * inside async callbacks.
16998 				 */
16999 				goto skip_inf_loop_check;
17000 			}
17001 			/* BPF open-coded iterators loop detection is special.
17002 			 * states_maybe_looping() logic is too simplistic in detecting
17003 			 * states that *might* be equivalent, because it doesn't know
17004 			 * about ID remapping, so don't even perform it.
17005 			 * See process_iter_next_call() and iter_active_depths_differ()
17006 			 * for overview of the logic. When current and one of parent
17007 			 * states are detected as equivalent, it's a good thing: we prove
17008 			 * convergence and can stop simulating further iterations.
17009 			 * It's safe to assume that iterator loop will finish, taking into
17010 			 * account iter_next() contract of eventually returning
17011 			 * sticky NULL result.
17012 			 *
17013 			 * Note, that states have to be compared exactly in this case because
17014 			 * read and precision marks might not be finalized inside the loop.
17015 			 * E.g. as in the program below:
17016 			 *
17017 			 *     1. r7 = -16
17018 			 *     2. r6 = bpf_get_prandom_u32()
17019 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
17020 			 *     4.   if (r6 != 42) {
17021 			 *     5.     r7 = -32
17022 			 *     6.     r6 = bpf_get_prandom_u32()
17023 			 *     7.     continue
17024 			 *     8.   }
17025 			 *     9.   r0 = r10
17026 			 *    10.   r0 += r7
17027 			 *    11.   r8 = *(u64 *)(r0 + 0)
17028 			 *    12.   r6 = bpf_get_prandom_u32()
17029 			 *    13. }
17030 			 *
17031 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
17032 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
17033 			 * not have read or precision mark for r7 yet, thus inexact states
17034 			 * comparison would discard current state with r7=-32
17035 			 * => unsafe memory access at 11 would not be caught.
17036 			 */
17037 			if (is_iter_next_insn(env, insn_idx)) {
17038 				if (states_equal(env, &sl->state, cur, true)) {
17039 					struct bpf_func_state *cur_frame;
17040 					struct bpf_reg_state *iter_state, *iter_reg;
17041 					int spi;
17042 
17043 					cur_frame = cur->frame[cur->curframe];
17044 					/* btf_check_iter_kfuncs() enforces that
17045 					 * iter state pointer is always the first arg
17046 					 */
17047 					iter_reg = &cur_frame->regs[BPF_REG_1];
17048 					/* current state is valid due to states_equal(),
17049 					 * so we can assume valid iter and reg state,
17050 					 * no need for extra (re-)validations
17051 					 */
17052 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
17053 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
17054 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
17055 						update_loop_entry(cur, &sl->state);
17056 						goto hit;
17057 					}
17058 				}
17059 				goto skip_inf_loop_check;
17060 			}
17061 			if (calls_callback(env, insn_idx)) {
17062 				if (states_equal(env, &sl->state, cur, true))
17063 					goto hit;
17064 				goto skip_inf_loop_check;
17065 			}
17066 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
17067 			if (states_maybe_looping(&sl->state, cur) &&
17068 			    states_equal(env, &sl->state, cur, true) &&
17069 			    !iter_active_depths_differ(&sl->state, cur) &&
17070 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
17071 				verbose_linfo(env, insn_idx, "; ");
17072 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
17073 				verbose(env, "cur state:");
17074 				print_verifier_state(env, cur->frame[cur->curframe], true);
17075 				verbose(env, "old state:");
17076 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
17077 				return -EINVAL;
17078 			}
17079 			/* if the verifier is processing a loop, avoid adding new state
17080 			 * too often, since different loop iterations have distinct
17081 			 * states and may not help future pruning.
17082 			 * This threshold shouldn't be too low to make sure that
17083 			 * a loop with large bound will be rejected quickly.
17084 			 * The most abusive loop will be:
17085 			 * r1 += 1
17086 			 * if r1 < 1000000 goto pc-2
17087 			 * 1M insn_procssed limit / 100 == 10k peak states.
17088 			 * This threshold shouldn't be too high either, since states
17089 			 * at the end of the loop are likely to be useful in pruning.
17090 			 */
17091 skip_inf_loop_check:
17092 			if (!force_new_state &&
17093 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
17094 			    env->insn_processed - env->prev_insn_processed < 100)
17095 				add_new_state = false;
17096 			goto miss;
17097 		}
17098 		/* If sl->state is a part of a loop and this loop's entry is a part of
17099 		 * current verification path then states have to be compared exactly.
17100 		 * 'force_exact' is needed to catch the following case:
17101 		 *
17102 		 *                initial     Here state 'succ' was processed first,
17103 		 *                  |         it was eventually tracked to produce a
17104 		 *                  V         state identical to 'hdr'.
17105 		 *     .---------> hdr        All branches from 'succ' had been explored
17106 		 *     |            |         and thus 'succ' has its .branches == 0.
17107 		 *     |            V
17108 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
17109 		 *     |    |       |         to the same instruction + callsites.
17110 		 *     |    V       V         In such case it is necessary to check
17111 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
17112 		 *     |    |       |         If 'succ' and 'cur' are a part of the
17113 		 *     |    V       V         same loop exact flag has to be set.
17114 		 *     |   succ <- cur        To check if that is the case, verify
17115 		 *     |    |                 if loop entry of 'succ' is in current
17116 		 *     |    V                 DFS path.
17117 		 *     |   ...
17118 		 *     |    |
17119 		 *     '----'
17120 		 *
17121 		 * Additional details are in the comment before get_loop_entry().
17122 		 */
17123 		loop_entry = get_loop_entry(&sl->state);
17124 		force_exact = loop_entry && loop_entry->branches > 0;
17125 		if (states_equal(env, &sl->state, cur, force_exact)) {
17126 			if (force_exact)
17127 				update_loop_entry(cur, loop_entry);
17128 hit:
17129 			sl->hit_cnt++;
17130 			/* reached equivalent register/stack state,
17131 			 * prune the search.
17132 			 * Registers read by the continuation are read by us.
17133 			 * If we have any write marks in env->cur_state, they
17134 			 * will prevent corresponding reads in the continuation
17135 			 * from reaching our parent (an explored_state).  Our
17136 			 * own state will get the read marks recorded, but
17137 			 * they'll be immediately forgotten as we're pruning
17138 			 * this state and will pop a new one.
17139 			 */
17140 			err = propagate_liveness(env, &sl->state, cur);
17141 
17142 			/* if previous state reached the exit with precision and
17143 			 * current state is equivalent to it (except precsion marks)
17144 			 * the precision needs to be propagated back in
17145 			 * the current state.
17146 			 */
17147 			if (is_jmp_point(env, env->insn_idx))
17148 				err = err ? : push_jmp_history(env, cur, 0);
17149 			err = err ? : propagate_precision(env, &sl->state);
17150 			if (err)
17151 				return err;
17152 			return 1;
17153 		}
17154 miss:
17155 		/* when new state is not going to be added do not increase miss count.
17156 		 * Otherwise several loop iterations will remove the state
17157 		 * recorded earlier. The goal of these heuristics is to have
17158 		 * states from some iterations of the loop (some in the beginning
17159 		 * and some at the end) to help pruning.
17160 		 */
17161 		if (add_new_state)
17162 			sl->miss_cnt++;
17163 		/* heuristic to determine whether this state is beneficial
17164 		 * to keep checking from state equivalence point of view.
17165 		 * Higher numbers increase max_states_per_insn and verification time,
17166 		 * but do not meaningfully decrease insn_processed.
17167 		 * 'n' controls how many times state could miss before eviction.
17168 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
17169 		 * too early would hinder iterator convergence.
17170 		 */
17171 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
17172 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
17173 			/* the state is unlikely to be useful. Remove it to
17174 			 * speed up verification
17175 			 */
17176 			*pprev = sl->next;
17177 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
17178 			    !sl->state.used_as_loop_entry) {
17179 				u32 br = sl->state.branches;
17180 
17181 				WARN_ONCE(br,
17182 					  "BUG live_done but branches_to_explore %d\n",
17183 					  br);
17184 				free_verifier_state(&sl->state, false);
17185 				kfree(sl);
17186 				env->peak_states--;
17187 			} else {
17188 				/* cannot free this state, since parentage chain may
17189 				 * walk it later. Add it for free_list instead to
17190 				 * be freed at the end of verification
17191 				 */
17192 				sl->next = env->free_list;
17193 				env->free_list = sl;
17194 			}
17195 			sl = *pprev;
17196 			continue;
17197 		}
17198 next:
17199 		pprev = &sl->next;
17200 		sl = *pprev;
17201 	}
17202 
17203 	if (env->max_states_per_insn < states_cnt)
17204 		env->max_states_per_insn = states_cnt;
17205 
17206 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
17207 		return 0;
17208 
17209 	if (!add_new_state)
17210 		return 0;
17211 
17212 	/* There were no equivalent states, remember the current one.
17213 	 * Technically the current state is not proven to be safe yet,
17214 	 * but it will either reach outer most bpf_exit (which means it's safe)
17215 	 * or it will be rejected. When there are no loops the verifier won't be
17216 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
17217 	 * again on the way to bpf_exit.
17218 	 * When looping the sl->state.branches will be > 0 and this state
17219 	 * will not be considered for equivalence until branches == 0.
17220 	 */
17221 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
17222 	if (!new_sl)
17223 		return -ENOMEM;
17224 	env->total_states++;
17225 	env->peak_states++;
17226 	env->prev_jmps_processed = env->jmps_processed;
17227 	env->prev_insn_processed = env->insn_processed;
17228 
17229 	/* forget precise markings we inherited, see __mark_chain_precision */
17230 	if (env->bpf_capable)
17231 		mark_all_scalars_imprecise(env, cur);
17232 
17233 	/* add new state to the head of linked list */
17234 	new = &new_sl->state;
17235 	err = copy_verifier_state(new, cur);
17236 	if (err) {
17237 		free_verifier_state(new, false);
17238 		kfree(new_sl);
17239 		return err;
17240 	}
17241 	new->insn_idx = insn_idx;
17242 	WARN_ONCE(new->branches != 1,
17243 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
17244 
17245 	cur->parent = new;
17246 	cur->first_insn_idx = insn_idx;
17247 	cur->dfs_depth = new->dfs_depth + 1;
17248 	clear_jmp_history(cur);
17249 	new_sl->next = *explored_state(env, insn_idx);
17250 	*explored_state(env, insn_idx) = new_sl;
17251 	/* connect new state to parentage chain. Current frame needs all
17252 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
17253 	 * to the stack implicitly by JITs) so in callers' frames connect just
17254 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
17255 	 * the state of the call instruction (with WRITTEN set), and r0 comes
17256 	 * from callee with its full parentage chain, anyway.
17257 	 */
17258 	/* clear write marks in current state: the writes we did are not writes
17259 	 * our child did, so they don't screen off its reads from us.
17260 	 * (There are no read marks in current state, because reads always mark
17261 	 * their parent and current state never has children yet.  Only
17262 	 * explored_states can get read marks.)
17263 	 */
17264 	for (j = 0; j <= cur->curframe; j++) {
17265 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
17266 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
17267 		for (i = 0; i < BPF_REG_FP; i++)
17268 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
17269 	}
17270 
17271 	/* all stack frames are accessible from callee, clear them all */
17272 	for (j = 0; j <= cur->curframe; j++) {
17273 		struct bpf_func_state *frame = cur->frame[j];
17274 		struct bpf_func_state *newframe = new->frame[j];
17275 
17276 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
17277 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
17278 			frame->stack[i].spilled_ptr.parent =
17279 						&newframe->stack[i].spilled_ptr;
17280 		}
17281 	}
17282 	return 0;
17283 }
17284 
17285 /* Return true if it's OK to have the same insn return a different type. */
17286 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
17287 {
17288 	switch (base_type(type)) {
17289 	case PTR_TO_CTX:
17290 	case PTR_TO_SOCKET:
17291 	case PTR_TO_SOCK_COMMON:
17292 	case PTR_TO_TCP_SOCK:
17293 	case PTR_TO_XDP_SOCK:
17294 	case PTR_TO_BTF_ID:
17295 		return false;
17296 	default:
17297 		return true;
17298 	}
17299 }
17300 
17301 /* If an instruction was previously used with particular pointer types, then we
17302  * need to be careful to avoid cases such as the below, where it may be ok
17303  * for one branch accessing the pointer, but not ok for the other branch:
17304  *
17305  * R1 = sock_ptr
17306  * goto X;
17307  * ...
17308  * R1 = some_other_valid_ptr;
17309  * goto X;
17310  * ...
17311  * R2 = *(u32 *)(R1 + 0);
17312  */
17313 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17314 {
17315 	return src != prev && (!reg_type_mismatch_ok(src) ||
17316 			       !reg_type_mismatch_ok(prev));
17317 }
17318 
17319 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17320 			     bool allow_trust_missmatch)
17321 {
17322 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17323 
17324 	if (*prev_type == NOT_INIT) {
17325 		/* Saw a valid insn
17326 		 * dst_reg = *(u32 *)(src_reg + off)
17327 		 * save type to validate intersecting paths
17328 		 */
17329 		*prev_type = type;
17330 	} else if (reg_type_mismatch(type, *prev_type)) {
17331 		/* Abuser program is trying to use the same insn
17332 		 * dst_reg = *(u32*) (src_reg + off)
17333 		 * with different pointer types:
17334 		 * src_reg == ctx in one branch and
17335 		 * src_reg == stack|map in some other branch.
17336 		 * Reject it.
17337 		 */
17338 		if (allow_trust_missmatch &&
17339 		    base_type(type) == PTR_TO_BTF_ID &&
17340 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
17341 			/*
17342 			 * Have to support a use case when one path through
17343 			 * the program yields TRUSTED pointer while another
17344 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
17345 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
17346 			 */
17347 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
17348 		} else {
17349 			verbose(env, "same insn cannot be used with different pointers\n");
17350 			return -EINVAL;
17351 		}
17352 	}
17353 
17354 	return 0;
17355 }
17356 
17357 static int do_check(struct bpf_verifier_env *env)
17358 {
17359 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17360 	struct bpf_verifier_state *state = env->cur_state;
17361 	struct bpf_insn *insns = env->prog->insnsi;
17362 	struct bpf_reg_state *regs;
17363 	int insn_cnt = env->prog->len;
17364 	bool do_print_state = false;
17365 	int prev_insn_idx = -1;
17366 
17367 	for (;;) {
17368 		bool exception_exit = false;
17369 		struct bpf_insn *insn;
17370 		u8 class;
17371 		int err;
17372 
17373 		/* reset current history entry on each new instruction */
17374 		env->cur_hist_ent = NULL;
17375 
17376 		env->prev_insn_idx = prev_insn_idx;
17377 		if (env->insn_idx >= insn_cnt) {
17378 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
17379 				env->insn_idx, insn_cnt);
17380 			return -EFAULT;
17381 		}
17382 
17383 		insn = &insns[env->insn_idx];
17384 		class = BPF_CLASS(insn->code);
17385 
17386 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17387 			verbose(env,
17388 				"BPF program is too large. Processed %d insn\n",
17389 				env->insn_processed);
17390 			return -E2BIG;
17391 		}
17392 
17393 		state->last_insn_idx = env->prev_insn_idx;
17394 
17395 		if (is_prune_point(env, env->insn_idx)) {
17396 			err = is_state_visited(env, env->insn_idx);
17397 			if (err < 0)
17398 				return err;
17399 			if (err == 1) {
17400 				/* found equivalent state, can prune the search */
17401 				if (env->log.level & BPF_LOG_LEVEL) {
17402 					if (do_print_state)
17403 						verbose(env, "\nfrom %d to %d%s: safe\n",
17404 							env->prev_insn_idx, env->insn_idx,
17405 							env->cur_state->speculative ?
17406 							" (speculative execution)" : "");
17407 					else
17408 						verbose(env, "%d: safe\n", env->insn_idx);
17409 				}
17410 				goto process_bpf_exit;
17411 			}
17412 		}
17413 
17414 		if (is_jmp_point(env, env->insn_idx)) {
17415 			err = push_jmp_history(env, state, 0);
17416 			if (err)
17417 				return err;
17418 		}
17419 
17420 		if (signal_pending(current))
17421 			return -EAGAIN;
17422 
17423 		if (need_resched())
17424 			cond_resched();
17425 
17426 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17427 			verbose(env, "\nfrom %d to %d%s:",
17428 				env->prev_insn_idx, env->insn_idx,
17429 				env->cur_state->speculative ?
17430 				" (speculative execution)" : "");
17431 			print_verifier_state(env, state->frame[state->curframe], true);
17432 			do_print_state = false;
17433 		}
17434 
17435 		if (env->log.level & BPF_LOG_LEVEL) {
17436 			const struct bpf_insn_cbs cbs = {
17437 				.cb_call	= disasm_kfunc_name,
17438 				.cb_print	= verbose,
17439 				.private_data	= env,
17440 			};
17441 
17442 			if (verifier_state_scratched(env))
17443 				print_insn_state(env, state->frame[state->curframe]);
17444 
17445 			verbose_linfo(env, env->insn_idx, "; ");
17446 			env->prev_log_pos = env->log.end_pos;
17447 			verbose(env, "%d: ", env->insn_idx);
17448 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17449 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17450 			env->prev_log_pos = env->log.end_pos;
17451 		}
17452 
17453 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17454 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17455 							   env->prev_insn_idx);
17456 			if (err)
17457 				return err;
17458 		}
17459 
17460 		regs = cur_regs(env);
17461 		sanitize_mark_insn_seen(env);
17462 		prev_insn_idx = env->insn_idx;
17463 
17464 		if (class == BPF_ALU || class == BPF_ALU64) {
17465 			err = check_alu_op(env, insn);
17466 			if (err)
17467 				return err;
17468 
17469 		} else if (class == BPF_LDX) {
17470 			enum bpf_reg_type src_reg_type;
17471 
17472 			/* check for reserved fields is already done */
17473 
17474 			/* check src operand */
17475 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17476 			if (err)
17477 				return err;
17478 
17479 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17480 			if (err)
17481 				return err;
17482 
17483 			src_reg_type = regs[insn->src_reg].type;
17484 
17485 			/* check that memory (src_reg + off) is readable,
17486 			 * the state of dst_reg will be updated by this func
17487 			 */
17488 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17489 					       insn->off, BPF_SIZE(insn->code),
17490 					       BPF_READ, insn->dst_reg, false,
17491 					       BPF_MODE(insn->code) == BPF_MEMSX);
17492 			err = err ?: save_aux_ptr_type(env, src_reg_type, true);
17493 			err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], "ldx");
17494 			if (err)
17495 				return err;
17496 		} else if (class == BPF_STX) {
17497 			enum bpf_reg_type dst_reg_type;
17498 
17499 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17500 				err = check_atomic(env, env->insn_idx, insn);
17501 				if (err)
17502 					return err;
17503 				env->insn_idx++;
17504 				continue;
17505 			}
17506 
17507 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17508 				verbose(env, "BPF_STX uses reserved fields\n");
17509 				return -EINVAL;
17510 			}
17511 
17512 			/* check src1 operand */
17513 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17514 			if (err)
17515 				return err;
17516 			/* check src2 operand */
17517 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17518 			if (err)
17519 				return err;
17520 
17521 			dst_reg_type = regs[insn->dst_reg].type;
17522 
17523 			/* check that memory (dst_reg + off) is writeable */
17524 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17525 					       insn->off, BPF_SIZE(insn->code),
17526 					       BPF_WRITE, insn->src_reg, false, false);
17527 			if (err)
17528 				return err;
17529 
17530 			err = save_aux_ptr_type(env, dst_reg_type, false);
17531 			if (err)
17532 				return err;
17533 		} else if (class == BPF_ST) {
17534 			enum bpf_reg_type dst_reg_type;
17535 
17536 			if (BPF_MODE(insn->code) != BPF_MEM ||
17537 			    insn->src_reg != BPF_REG_0) {
17538 				verbose(env, "BPF_ST uses reserved fields\n");
17539 				return -EINVAL;
17540 			}
17541 			/* check src operand */
17542 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17543 			if (err)
17544 				return err;
17545 
17546 			dst_reg_type = regs[insn->dst_reg].type;
17547 
17548 			/* check that memory (dst_reg + off) is writeable */
17549 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17550 					       insn->off, BPF_SIZE(insn->code),
17551 					       BPF_WRITE, -1, false, false);
17552 			if (err)
17553 				return err;
17554 
17555 			err = save_aux_ptr_type(env, dst_reg_type, false);
17556 			if (err)
17557 				return err;
17558 		} else if (class == BPF_JMP || class == BPF_JMP32) {
17559 			u8 opcode = BPF_OP(insn->code);
17560 
17561 			env->jmps_processed++;
17562 			if (opcode == BPF_CALL) {
17563 				if (BPF_SRC(insn->code) != BPF_K ||
17564 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17565 				     && insn->off != 0) ||
17566 				    (insn->src_reg != BPF_REG_0 &&
17567 				     insn->src_reg != BPF_PSEUDO_CALL &&
17568 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17569 				    insn->dst_reg != BPF_REG_0 ||
17570 				    class == BPF_JMP32) {
17571 					verbose(env, "BPF_CALL uses reserved fields\n");
17572 					return -EINVAL;
17573 				}
17574 
17575 				if (env->cur_state->active_lock.ptr) {
17576 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17577 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
17578 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17579 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17580 						verbose(env, "function calls are not allowed while holding a lock\n");
17581 						return -EINVAL;
17582 					}
17583 				}
17584 				if (insn->src_reg == BPF_PSEUDO_CALL) {
17585 					err = check_func_call(env, insn, &env->insn_idx);
17586 				} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17587 					err = check_kfunc_call(env, insn, &env->insn_idx);
17588 					if (!err && is_bpf_throw_kfunc(insn)) {
17589 						exception_exit = true;
17590 						goto process_bpf_exit_full;
17591 					}
17592 				} else {
17593 					err = check_helper_call(env, insn, &env->insn_idx);
17594 				}
17595 				if (err)
17596 					return err;
17597 
17598 				mark_reg_scratched(env, BPF_REG_0);
17599 			} else if (opcode == BPF_JA) {
17600 				if (BPF_SRC(insn->code) != BPF_K ||
17601 				    insn->src_reg != BPF_REG_0 ||
17602 				    insn->dst_reg != BPF_REG_0 ||
17603 				    (class == BPF_JMP && insn->imm != 0) ||
17604 				    (class == BPF_JMP32 && insn->off != 0)) {
17605 					verbose(env, "BPF_JA uses reserved fields\n");
17606 					return -EINVAL;
17607 				}
17608 
17609 				if (class == BPF_JMP)
17610 					env->insn_idx += insn->off + 1;
17611 				else
17612 					env->insn_idx += insn->imm + 1;
17613 				continue;
17614 
17615 			} else if (opcode == BPF_EXIT) {
17616 				if (BPF_SRC(insn->code) != BPF_K ||
17617 				    insn->imm != 0 ||
17618 				    insn->src_reg != BPF_REG_0 ||
17619 				    insn->dst_reg != BPF_REG_0 ||
17620 				    class == BPF_JMP32) {
17621 					verbose(env, "BPF_EXIT uses reserved fields\n");
17622 					return -EINVAL;
17623 				}
17624 process_bpf_exit_full:
17625 				if (env->cur_state->active_lock.ptr &&
17626 				    !in_rbtree_lock_required_cb(env)) {
17627 					verbose(env, "bpf_spin_unlock is missing\n");
17628 					return -EINVAL;
17629 				}
17630 
17631 				if (env->cur_state->active_rcu_lock &&
17632 				    !in_rbtree_lock_required_cb(env)) {
17633 					verbose(env, "bpf_rcu_read_unlock is missing\n");
17634 					return -EINVAL;
17635 				}
17636 
17637 				/* We must do check_reference_leak here before
17638 				 * prepare_func_exit to handle the case when
17639 				 * state->curframe > 0, it may be a callback
17640 				 * function, for which reference_state must
17641 				 * match caller reference state when it exits.
17642 				 */
17643 				err = check_reference_leak(env, exception_exit);
17644 				if (err)
17645 					return err;
17646 
17647 				/* The side effect of the prepare_func_exit
17648 				 * which is being skipped is that it frees
17649 				 * bpf_func_state. Typically, process_bpf_exit
17650 				 * will only be hit with outermost exit.
17651 				 * copy_verifier_state in pop_stack will handle
17652 				 * freeing of any extra bpf_func_state left over
17653 				 * from not processing all nested function
17654 				 * exits. We also skip return code checks as
17655 				 * they are not needed for exceptional exits.
17656 				 */
17657 				if (exception_exit)
17658 					goto process_bpf_exit;
17659 
17660 				if (state->curframe) {
17661 					/* exit from nested function */
17662 					err = prepare_func_exit(env, &env->insn_idx);
17663 					if (err)
17664 						return err;
17665 					do_print_state = true;
17666 					continue;
17667 				}
17668 
17669 				err = check_return_code(env, BPF_REG_0, "R0");
17670 				if (err)
17671 					return err;
17672 process_bpf_exit:
17673 				mark_verifier_state_scratched(env);
17674 				update_branch_counts(env, env->cur_state);
17675 				err = pop_stack(env, &prev_insn_idx,
17676 						&env->insn_idx, pop_log);
17677 				if (err < 0) {
17678 					if (err != -ENOENT)
17679 						return err;
17680 					break;
17681 				} else {
17682 					do_print_state = true;
17683 					continue;
17684 				}
17685 			} else {
17686 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
17687 				if (err)
17688 					return err;
17689 			}
17690 		} else if (class == BPF_LD) {
17691 			u8 mode = BPF_MODE(insn->code);
17692 
17693 			if (mode == BPF_ABS || mode == BPF_IND) {
17694 				err = check_ld_abs(env, insn);
17695 				if (err)
17696 					return err;
17697 
17698 			} else if (mode == BPF_IMM) {
17699 				err = check_ld_imm(env, insn);
17700 				if (err)
17701 					return err;
17702 
17703 				env->insn_idx++;
17704 				sanitize_mark_insn_seen(env);
17705 			} else {
17706 				verbose(env, "invalid BPF_LD mode\n");
17707 				return -EINVAL;
17708 			}
17709 		} else {
17710 			verbose(env, "unknown insn class %d\n", class);
17711 			return -EINVAL;
17712 		}
17713 
17714 		env->insn_idx++;
17715 	}
17716 
17717 	return 0;
17718 }
17719 
17720 static int find_btf_percpu_datasec(struct btf *btf)
17721 {
17722 	const struct btf_type *t;
17723 	const char *tname;
17724 	int i, n;
17725 
17726 	/*
17727 	 * Both vmlinux and module each have their own ".data..percpu"
17728 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17729 	 * types to look at only module's own BTF types.
17730 	 */
17731 	n = btf_nr_types(btf);
17732 	if (btf_is_module(btf))
17733 		i = btf_nr_types(btf_vmlinux);
17734 	else
17735 		i = 1;
17736 
17737 	for(; i < n; i++) {
17738 		t = btf_type_by_id(btf, i);
17739 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17740 			continue;
17741 
17742 		tname = btf_name_by_offset(btf, t->name_off);
17743 		if (!strcmp(tname, ".data..percpu"))
17744 			return i;
17745 	}
17746 
17747 	return -ENOENT;
17748 }
17749 
17750 /* replace pseudo btf_id with kernel symbol address */
17751 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17752 			       struct bpf_insn *insn,
17753 			       struct bpf_insn_aux_data *aux)
17754 {
17755 	const struct btf_var_secinfo *vsi;
17756 	const struct btf_type *datasec;
17757 	struct btf_mod_pair *btf_mod;
17758 	const struct btf_type *t;
17759 	const char *sym_name;
17760 	bool percpu = false;
17761 	u32 type, id = insn->imm;
17762 	struct btf *btf;
17763 	s32 datasec_id;
17764 	u64 addr;
17765 	int i, btf_fd, err;
17766 
17767 	btf_fd = insn[1].imm;
17768 	if (btf_fd) {
17769 		btf = btf_get_by_fd(btf_fd);
17770 		if (IS_ERR(btf)) {
17771 			verbose(env, "invalid module BTF object FD specified.\n");
17772 			return -EINVAL;
17773 		}
17774 	} else {
17775 		if (!btf_vmlinux) {
17776 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17777 			return -EINVAL;
17778 		}
17779 		btf = btf_vmlinux;
17780 		btf_get(btf);
17781 	}
17782 
17783 	t = btf_type_by_id(btf, id);
17784 	if (!t) {
17785 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17786 		err = -ENOENT;
17787 		goto err_put;
17788 	}
17789 
17790 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17791 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17792 		err = -EINVAL;
17793 		goto err_put;
17794 	}
17795 
17796 	sym_name = btf_name_by_offset(btf, t->name_off);
17797 	addr = kallsyms_lookup_name(sym_name);
17798 	if (!addr) {
17799 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17800 			sym_name);
17801 		err = -ENOENT;
17802 		goto err_put;
17803 	}
17804 	insn[0].imm = (u32)addr;
17805 	insn[1].imm = addr >> 32;
17806 
17807 	if (btf_type_is_func(t)) {
17808 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17809 		aux->btf_var.mem_size = 0;
17810 		goto check_btf;
17811 	}
17812 
17813 	datasec_id = find_btf_percpu_datasec(btf);
17814 	if (datasec_id > 0) {
17815 		datasec = btf_type_by_id(btf, datasec_id);
17816 		for_each_vsi(i, datasec, vsi) {
17817 			if (vsi->type == id) {
17818 				percpu = true;
17819 				break;
17820 			}
17821 		}
17822 	}
17823 
17824 	type = t->type;
17825 	t = btf_type_skip_modifiers(btf, type, NULL);
17826 	if (percpu) {
17827 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17828 		aux->btf_var.btf = btf;
17829 		aux->btf_var.btf_id = type;
17830 	} else if (!btf_type_is_struct(t)) {
17831 		const struct btf_type *ret;
17832 		const char *tname;
17833 		u32 tsize;
17834 
17835 		/* resolve the type size of ksym. */
17836 		ret = btf_resolve_size(btf, t, &tsize);
17837 		if (IS_ERR(ret)) {
17838 			tname = btf_name_by_offset(btf, t->name_off);
17839 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17840 				tname, PTR_ERR(ret));
17841 			err = -EINVAL;
17842 			goto err_put;
17843 		}
17844 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17845 		aux->btf_var.mem_size = tsize;
17846 	} else {
17847 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
17848 		aux->btf_var.btf = btf;
17849 		aux->btf_var.btf_id = type;
17850 	}
17851 check_btf:
17852 	/* check whether we recorded this BTF (and maybe module) already */
17853 	for (i = 0; i < env->used_btf_cnt; i++) {
17854 		if (env->used_btfs[i].btf == btf) {
17855 			btf_put(btf);
17856 			return 0;
17857 		}
17858 	}
17859 
17860 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
17861 		err = -E2BIG;
17862 		goto err_put;
17863 	}
17864 
17865 	btf_mod = &env->used_btfs[env->used_btf_cnt];
17866 	btf_mod->btf = btf;
17867 	btf_mod->module = NULL;
17868 
17869 	/* if we reference variables from kernel module, bump its refcount */
17870 	if (btf_is_module(btf)) {
17871 		btf_mod->module = btf_try_get_module(btf);
17872 		if (!btf_mod->module) {
17873 			err = -ENXIO;
17874 			goto err_put;
17875 		}
17876 	}
17877 
17878 	env->used_btf_cnt++;
17879 
17880 	return 0;
17881 err_put:
17882 	btf_put(btf);
17883 	return err;
17884 }
17885 
17886 static bool is_tracing_prog_type(enum bpf_prog_type type)
17887 {
17888 	switch (type) {
17889 	case BPF_PROG_TYPE_KPROBE:
17890 	case BPF_PROG_TYPE_TRACEPOINT:
17891 	case BPF_PROG_TYPE_PERF_EVENT:
17892 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17893 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17894 		return true;
17895 	default:
17896 		return false;
17897 	}
17898 }
17899 
17900 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17901 					struct bpf_map *map,
17902 					struct bpf_prog *prog)
17903 
17904 {
17905 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17906 
17907 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17908 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
17909 		if (is_tracing_prog_type(prog_type)) {
17910 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17911 			return -EINVAL;
17912 		}
17913 	}
17914 
17915 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17916 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17917 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17918 			return -EINVAL;
17919 		}
17920 
17921 		if (is_tracing_prog_type(prog_type)) {
17922 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17923 			return -EINVAL;
17924 		}
17925 	}
17926 
17927 	if (btf_record_has_field(map->record, BPF_TIMER)) {
17928 		if (is_tracing_prog_type(prog_type)) {
17929 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
17930 			return -EINVAL;
17931 		}
17932 	}
17933 
17934 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17935 	    !bpf_offload_prog_map_match(prog, map)) {
17936 		verbose(env, "offload device mismatch between prog and map\n");
17937 		return -EINVAL;
17938 	}
17939 
17940 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17941 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17942 		return -EINVAL;
17943 	}
17944 
17945 	if (prog->aux->sleepable)
17946 		switch (map->map_type) {
17947 		case BPF_MAP_TYPE_HASH:
17948 		case BPF_MAP_TYPE_LRU_HASH:
17949 		case BPF_MAP_TYPE_ARRAY:
17950 		case BPF_MAP_TYPE_PERCPU_HASH:
17951 		case BPF_MAP_TYPE_PERCPU_ARRAY:
17952 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17953 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17954 		case BPF_MAP_TYPE_HASH_OF_MAPS:
17955 		case BPF_MAP_TYPE_RINGBUF:
17956 		case BPF_MAP_TYPE_USER_RINGBUF:
17957 		case BPF_MAP_TYPE_INODE_STORAGE:
17958 		case BPF_MAP_TYPE_SK_STORAGE:
17959 		case BPF_MAP_TYPE_TASK_STORAGE:
17960 		case BPF_MAP_TYPE_CGRP_STORAGE:
17961 			break;
17962 		default:
17963 			verbose(env,
17964 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17965 			return -EINVAL;
17966 		}
17967 
17968 	return 0;
17969 }
17970 
17971 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17972 {
17973 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17974 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17975 }
17976 
17977 /* find and rewrite pseudo imm in ld_imm64 instructions:
17978  *
17979  * 1. if it accesses map FD, replace it with actual map pointer.
17980  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17981  *
17982  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17983  */
17984 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17985 {
17986 	struct bpf_insn *insn = env->prog->insnsi;
17987 	int insn_cnt = env->prog->len;
17988 	int i, j, err;
17989 
17990 	err = bpf_prog_calc_tag(env->prog);
17991 	if (err)
17992 		return err;
17993 
17994 	for (i = 0; i < insn_cnt; i++, insn++) {
17995 		if (BPF_CLASS(insn->code) == BPF_LDX &&
17996 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17997 		    insn->imm != 0)) {
17998 			verbose(env, "BPF_LDX uses reserved fields\n");
17999 			return -EINVAL;
18000 		}
18001 
18002 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
18003 			struct bpf_insn_aux_data *aux;
18004 			struct bpf_map *map;
18005 			struct fd f;
18006 			u64 addr;
18007 			u32 fd;
18008 
18009 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
18010 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
18011 			    insn[1].off != 0) {
18012 				verbose(env, "invalid bpf_ld_imm64 insn\n");
18013 				return -EINVAL;
18014 			}
18015 
18016 			if (insn[0].src_reg == 0)
18017 				/* valid generic load 64-bit imm */
18018 				goto next_insn;
18019 
18020 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
18021 				aux = &env->insn_aux_data[i];
18022 				err = check_pseudo_btf_id(env, insn, aux);
18023 				if (err)
18024 					return err;
18025 				goto next_insn;
18026 			}
18027 
18028 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
18029 				aux = &env->insn_aux_data[i];
18030 				aux->ptr_type = PTR_TO_FUNC;
18031 				goto next_insn;
18032 			}
18033 
18034 			/* In final convert_pseudo_ld_imm64() step, this is
18035 			 * converted into regular 64-bit imm load insn.
18036 			 */
18037 			switch (insn[0].src_reg) {
18038 			case BPF_PSEUDO_MAP_VALUE:
18039 			case BPF_PSEUDO_MAP_IDX_VALUE:
18040 				break;
18041 			case BPF_PSEUDO_MAP_FD:
18042 			case BPF_PSEUDO_MAP_IDX:
18043 				if (insn[1].imm == 0)
18044 					break;
18045 				fallthrough;
18046 			default:
18047 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
18048 				return -EINVAL;
18049 			}
18050 
18051 			switch (insn[0].src_reg) {
18052 			case BPF_PSEUDO_MAP_IDX_VALUE:
18053 			case BPF_PSEUDO_MAP_IDX:
18054 				if (bpfptr_is_null(env->fd_array)) {
18055 					verbose(env, "fd_idx without fd_array is invalid\n");
18056 					return -EPROTO;
18057 				}
18058 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
18059 							    insn[0].imm * sizeof(fd),
18060 							    sizeof(fd)))
18061 					return -EFAULT;
18062 				break;
18063 			default:
18064 				fd = insn[0].imm;
18065 				break;
18066 			}
18067 
18068 			f = fdget(fd);
18069 			map = __bpf_map_get(f);
18070 			if (IS_ERR(map)) {
18071 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
18072 					insn[0].imm);
18073 				return PTR_ERR(map);
18074 			}
18075 
18076 			err = check_map_prog_compatibility(env, map, env->prog);
18077 			if (err) {
18078 				fdput(f);
18079 				return err;
18080 			}
18081 
18082 			aux = &env->insn_aux_data[i];
18083 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
18084 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
18085 				addr = (unsigned long)map;
18086 			} else {
18087 				u32 off = insn[1].imm;
18088 
18089 				if (off >= BPF_MAX_VAR_OFF) {
18090 					verbose(env, "direct value offset of %u is not allowed\n", off);
18091 					fdput(f);
18092 					return -EINVAL;
18093 				}
18094 
18095 				if (!map->ops->map_direct_value_addr) {
18096 					verbose(env, "no direct value access support for this map type\n");
18097 					fdput(f);
18098 					return -EINVAL;
18099 				}
18100 
18101 				err = map->ops->map_direct_value_addr(map, &addr, off);
18102 				if (err) {
18103 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
18104 						map->value_size, off);
18105 					fdput(f);
18106 					return err;
18107 				}
18108 
18109 				aux->map_off = off;
18110 				addr += off;
18111 			}
18112 
18113 			insn[0].imm = (u32)addr;
18114 			insn[1].imm = addr >> 32;
18115 
18116 			/* check whether we recorded this map already */
18117 			for (j = 0; j < env->used_map_cnt; j++) {
18118 				if (env->used_maps[j] == map) {
18119 					aux->map_index = j;
18120 					fdput(f);
18121 					goto next_insn;
18122 				}
18123 			}
18124 
18125 			if (env->used_map_cnt >= MAX_USED_MAPS) {
18126 				fdput(f);
18127 				return -E2BIG;
18128 			}
18129 
18130 			if (env->prog->aux->sleepable)
18131 				atomic64_inc(&map->sleepable_refcnt);
18132 			/* hold the map. If the program is rejected by verifier,
18133 			 * the map will be released by release_maps() or it
18134 			 * will be used by the valid program until it's unloaded
18135 			 * and all maps are released in bpf_free_used_maps()
18136 			 */
18137 			bpf_map_inc(map);
18138 
18139 			aux->map_index = env->used_map_cnt;
18140 			env->used_maps[env->used_map_cnt++] = map;
18141 
18142 			if (bpf_map_is_cgroup_storage(map) &&
18143 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
18144 				verbose(env, "only one cgroup storage of each type is allowed\n");
18145 				fdput(f);
18146 				return -EBUSY;
18147 			}
18148 
18149 			fdput(f);
18150 next_insn:
18151 			insn++;
18152 			i++;
18153 			continue;
18154 		}
18155 
18156 		/* Basic sanity check before we invest more work here. */
18157 		if (!bpf_opcode_in_insntable(insn->code)) {
18158 			verbose(env, "unknown opcode %02x\n", insn->code);
18159 			return -EINVAL;
18160 		}
18161 	}
18162 
18163 	/* now all pseudo BPF_LD_IMM64 instructions load valid
18164 	 * 'struct bpf_map *' into a register instead of user map_fd.
18165 	 * These pointers will be used later by verifier to validate map access.
18166 	 */
18167 	return 0;
18168 }
18169 
18170 /* drop refcnt of maps used by the rejected program */
18171 static void release_maps(struct bpf_verifier_env *env)
18172 {
18173 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
18174 			     env->used_map_cnt);
18175 }
18176 
18177 /* drop refcnt of maps used by the rejected program */
18178 static void release_btfs(struct bpf_verifier_env *env)
18179 {
18180 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
18181 			     env->used_btf_cnt);
18182 }
18183 
18184 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
18185 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
18186 {
18187 	struct bpf_insn *insn = env->prog->insnsi;
18188 	int insn_cnt = env->prog->len;
18189 	int i;
18190 
18191 	for (i = 0; i < insn_cnt; i++, insn++) {
18192 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
18193 			continue;
18194 		if (insn->src_reg == BPF_PSEUDO_FUNC)
18195 			continue;
18196 		insn->src_reg = 0;
18197 	}
18198 }
18199 
18200 /* single env->prog->insni[off] instruction was replaced with the range
18201  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
18202  * [0, off) and [off, end) to new locations, so the patched range stays zero
18203  */
18204 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
18205 				 struct bpf_insn_aux_data *new_data,
18206 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
18207 {
18208 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
18209 	struct bpf_insn *insn = new_prog->insnsi;
18210 	u32 old_seen = old_data[off].seen;
18211 	u32 prog_len;
18212 	int i;
18213 
18214 	/* aux info at OFF always needs adjustment, no matter fast path
18215 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
18216 	 * original insn at old prog.
18217 	 */
18218 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
18219 
18220 	if (cnt == 1)
18221 		return;
18222 	prog_len = new_prog->len;
18223 
18224 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
18225 	memcpy(new_data + off + cnt - 1, old_data + off,
18226 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
18227 	for (i = off; i < off + cnt - 1; i++) {
18228 		/* Expand insni[off]'s seen count to the patched range. */
18229 		new_data[i].seen = old_seen;
18230 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
18231 	}
18232 	env->insn_aux_data = new_data;
18233 	vfree(old_data);
18234 }
18235 
18236 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
18237 {
18238 	int i;
18239 
18240 	if (len == 1)
18241 		return;
18242 	/* NOTE: fake 'exit' subprog should be updated as well. */
18243 	for (i = 0; i <= env->subprog_cnt; i++) {
18244 		if (env->subprog_info[i].start <= off)
18245 			continue;
18246 		env->subprog_info[i].start += len - 1;
18247 	}
18248 }
18249 
18250 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
18251 {
18252 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
18253 	int i, sz = prog->aux->size_poke_tab;
18254 	struct bpf_jit_poke_descriptor *desc;
18255 
18256 	for (i = 0; i < sz; i++) {
18257 		desc = &tab[i];
18258 		if (desc->insn_idx <= off)
18259 			continue;
18260 		desc->insn_idx += len - 1;
18261 	}
18262 }
18263 
18264 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
18265 					    const struct bpf_insn *patch, u32 len)
18266 {
18267 	struct bpf_prog *new_prog;
18268 	struct bpf_insn_aux_data *new_data = NULL;
18269 
18270 	if (len > 1) {
18271 		new_data = vzalloc(array_size(env->prog->len + len - 1,
18272 					      sizeof(struct bpf_insn_aux_data)));
18273 		if (!new_data)
18274 			return NULL;
18275 	}
18276 
18277 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
18278 	if (IS_ERR(new_prog)) {
18279 		if (PTR_ERR(new_prog) == -ERANGE)
18280 			verbose(env,
18281 				"insn %d cannot be patched due to 16-bit range\n",
18282 				env->insn_aux_data[off].orig_idx);
18283 		vfree(new_data);
18284 		return NULL;
18285 	}
18286 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
18287 	adjust_subprog_starts(env, off, len);
18288 	adjust_poke_descs(new_prog, off, len);
18289 	return new_prog;
18290 }
18291 
18292 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
18293 					      u32 off, u32 cnt)
18294 {
18295 	int i, j;
18296 
18297 	/* find first prog starting at or after off (first to remove) */
18298 	for (i = 0; i < env->subprog_cnt; i++)
18299 		if (env->subprog_info[i].start >= off)
18300 			break;
18301 	/* find first prog starting at or after off + cnt (first to stay) */
18302 	for (j = i; j < env->subprog_cnt; j++)
18303 		if (env->subprog_info[j].start >= off + cnt)
18304 			break;
18305 	/* if j doesn't start exactly at off + cnt, we are just removing
18306 	 * the front of previous prog
18307 	 */
18308 	if (env->subprog_info[j].start != off + cnt)
18309 		j--;
18310 
18311 	if (j > i) {
18312 		struct bpf_prog_aux *aux = env->prog->aux;
18313 		int move;
18314 
18315 		/* move fake 'exit' subprog as well */
18316 		move = env->subprog_cnt + 1 - j;
18317 
18318 		memmove(env->subprog_info + i,
18319 			env->subprog_info + j,
18320 			sizeof(*env->subprog_info) * move);
18321 		env->subprog_cnt -= j - i;
18322 
18323 		/* remove func_info */
18324 		if (aux->func_info) {
18325 			move = aux->func_info_cnt - j;
18326 
18327 			memmove(aux->func_info + i,
18328 				aux->func_info + j,
18329 				sizeof(*aux->func_info) * move);
18330 			aux->func_info_cnt -= j - i;
18331 			/* func_info->insn_off is set after all code rewrites,
18332 			 * in adjust_btf_func() - no need to adjust
18333 			 */
18334 		}
18335 	} else {
18336 		/* convert i from "first prog to remove" to "first to adjust" */
18337 		if (env->subprog_info[i].start == off)
18338 			i++;
18339 	}
18340 
18341 	/* update fake 'exit' subprog as well */
18342 	for (; i <= env->subprog_cnt; i++)
18343 		env->subprog_info[i].start -= cnt;
18344 
18345 	return 0;
18346 }
18347 
18348 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
18349 				      u32 cnt)
18350 {
18351 	struct bpf_prog *prog = env->prog;
18352 	u32 i, l_off, l_cnt, nr_linfo;
18353 	struct bpf_line_info *linfo;
18354 
18355 	nr_linfo = prog->aux->nr_linfo;
18356 	if (!nr_linfo)
18357 		return 0;
18358 
18359 	linfo = prog->aux->linfo;
18360 
18361 	/* find first line info to remove, count lines to be removed */
18362 	for (i = 0; i < nr_linfo; i++)
18363 		if (linfo[i].insn_off >= off)
18364 			break;
18365 
18366 	l_off = i;
18367 	l_cnt = 0;
18368 	for (; i < nr_linfo; i++)
18369 		if (linfo[i].insn_off < off + cnt)
18370 			l_cnt++;
18371 		else
18372 			break;
18373 
18374 	/* First live insn doesn't match first live linfo, it needs to "inherit"
18375 	 * last removed linfo.  prog is already modified, so prog->len == off
18376 	 * means no live instructions after (tail of the program was removed).
18377 	 */
18378 	if (prog->len != off && l_cnt &&
18379 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
18380 		l_cnt--;
18381 		linfo[--i].insn_off = off + cnt;
18382 	}
18383 
18384 	/* remove the line info which refer to the removed instructions */
18385 	if (l_cnt) {
18386 		memmove(linfo + l_off, linfo + i,
18387 			sizeof(*linfo) * (nr_linfo - i));
18388 
18389 		prog->aux->nr_linfo -= l_cnt;
18390 		nr_linfo = prog->aux->nr_linfo;
18391 	}
18392 
18393 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
18394 	for (i = l_off; i < nr_linfo; i++)
18395 		linfo[i].insn_off -= cnt;
18396 
18397 	/* fix up all subprogs (incl. 'exit') which start >= off */
18398 	for (i = 0; i <= env->subprog_cnt; i++)
18399 		if (env->subprog_info[i].linfo_idx > l_off) {
18400 			/* program may have started in the removed region but
18401 			 * may not be fully removed
18402 			 */
18403 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18404 				env->subprog_info[i].linfo_idx -= l_cnt;
18405 			else
18406 				env->subprog_info[i].linfo_idx = l_off;
18407 		}
18408 
18409 	return 0;
18410 }
18411 
18412 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18413 {
18414 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18415 	unsigned int orig_prog_len = env->prog->len;
18416 	int err;
18417 
18418 	if (bpf_prog_is_offloaded(env->prog->aux))
18419 		bpf_prog_offload_remove_insns(env, off, cnt);
18420 
18421 	err = bpf_remove_insns(env->prog, off, cnt);
18422 	if (err)
18423 		return err;
18424 
18425 	err = adjust_subprog_starts_after_remove(env, off, cnt);
18426 	if (err)
18427 		return err;
18428 
18429 	err = bpf_adj_linfo_after_remove(env, off, cnt);
18430 	if (err)
18431 		return err;
18432 
18433 	memmove(aux_data + off,	aux_data + off + cnt,
18434 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18435 
18436 	return 0;
18437 }
18438 
18439 /* The verifier does more data flow analysis than llvm and will not
18440  * explore branches that are dead at run time. Malicious programs can
18441  * have dead code too. Therefore replace all dead at-run-time code
18442  * with 'ja -1'.
18443  *
18444  * Just nops are not optimal, e.g. if they would sit at the end of the
18445  * program and through another bug we would manage to jump there, then
18446  * we'd execute beyond program memory otherwise. Returning exception
18447  * code also wouldn't work since we can have subprogs where the dead
18448  * code could be located.
18449  */
18450 static void sanitize_dead_code(struct bpf_verifier_env *env)
18451 {
18452 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18453 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18454 	struct bpf_insn *insn = env->prog->insnsi;
18455 	const int insn_cnt = env->prog->len;
18456 	int i;
18457 
18458 	for (i = 0; i < insn_cnt; i++) {
18459 		if (aux_data[i].seen)
18460 			continue;
18461 		memcpy(insn + i, &trap, sizeof(trap));
18462 		aux_data[i].zext_dst = false;
18463 	}
18464 }
18465 
18466 static bool insn_is_cond_jump(u8 code)
18467 {
18468 	u8 op;
18469 
18470 	op = BPF_OP(code);
18471 	if (BPF_CLASS(code) == BPF_JMP32)
18472 		return op != BPF_JA;
18473 
18474 	if (BPF_CLASS(code) != BPF_JMP)
18475 		return false;
18476 
18477 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18478 }
18479 
18480 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18481 {
18482 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18483 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18484 	struct bpf_insn *insn = env->prog->insnsi;
18485 	const int insn_cnt = env->prog->len;
18486 	int i;
18487 
18488 	for (i = 0; i < insn_cnt; i++, insn++) {
18489 		if (!insn_is_cond_jump(insn->code))
18490 			continue;
18491 
18492 		if (!aux_data[i + 1].seen)
18493 			ja.off = insn->off;
18494 		else if (!aux_data[i + 1 + insn->off].seen)
18495 			ja.off = 0;
18496 		else
18497 			continue;
18498 
18499 		if (bpf_prog_is_offloaded(env->prog->aux))
18500 			bpf_prog_offload_replace_insn(env, i, &ja);
18501 
18502 		memcpy(insn, &ja, sizeof(ja));
18503 	}
18504 }
18505 
18506 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18507 {
18508 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18509 	int insn_cnt = env->prog->len;
18510 	int i, err;
18511 
18512 	for (i = 0; i < insn_cnt; i++) {
18513 		int j;
18514 
18515 		j = 0;
18516 		while (i + j < insn_cnt && !aux_data[i + j].seen)
18517 			j++;
18518 		if (!j)
18519 			continue;
18520 
18521 		err = verifier_remove_insns(env, i, j);
18522 		if (err)
18523 			return err;
18524 		insn_cnt = env->prog->len;
18525 	}
18526 
18527 	return 0;
18528 }
18529 
18530 static int opt_remove_nops(struct bpf_verifier_env *env)
18531 {
18532 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18533 	struct bpf_insn *insn = env->prog->insnsi;
18534 	int insn_cnt = env->prog->len;
18535 	int i, err;
18536 
18537 	for (i = 0; i < insn_cnt; i++) {
18538 		if (memcmp(&insn[i], &ja, sizeof(ja)))
18539 			continue;
18540 
18541 		err = verifier_remove_insns(env, i, 1);
18542 		if (err)
18543 			return err;
18544 		insn_cnt--;
18545 		i--;
18546 	}
18547 
18548 	return 0;
18549 }
18550 
18551 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18552 					 const union bpf_attr *attr)
18553 {
18554 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18555 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18556 	int i, patch_len, delta = 0, len = env->prog->len;
18557 	struct bpf_insn *insns = env->prog->insnsi;
18558 	struct bpf_prog *new_prog;
18559 	bool rnd_hi32;
18560 
18561 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18562 	zext_patch[1] = BPF_ZEXT_REG(0);
18563 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18564 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18565 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18566 	for (i = 0; i < len; i++) {
18567 		int adj_idx = i + delta;
18568 		struct bpf_insn insn;
18569 		int load_reg;
18570 
18571 		insn = insns[adj_idx];
18572 		load_reg = insn_def_regno(&insn);
18573 		if (!aux[adj_idx].zext_dst) {
18574 			u8 code, class;
18575 			u32 imm_rnd;
18576 
18577 			if (!rnd_hi32)
18578 				continue;
18579 
18580 			code = insn.code;
18581 			class = BPF_CLASS(code);
18582 			if (load_reg == -1)
18583 				continue;
18584 
18585 			/* NOTE: arg "reg" (the fourth one) is only used for
18586 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
18587 			 *       here.
18588 			 */
18589 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18590 				if (class == BPF_LD &&
18591 				    BPF_MODE(code) == BPF_IMM)
18592 					i++;
18593 				continue;
18594 			}
18595 
18596 			/* ctx load could be transformed into wider load. */
18597 			if (class == BPF_LDX &&
18598 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
18599 				continue;
18600 
18601 			imm_rnd = get_random_u32();
18602 			rnd_hi32_patch[0] = insn;
18603 			rnd_hi32_patch[1].imm = imm_rnd;
18604 			rnd_hi32_patch[3].dst_reg = load_reg;
18605 			patch = rnd_hi32_patch;
18606 			patch_len = 4;
18607 			goto apply_patch_buffer;
18608 		}
18609 
18610 		/* Add in an zero-extend instruction if a) the JIT has requested
18611 		 * it or b) it's a CMPXCHG.
18612 		 *
18613 		 * The latter is because: BPF_CMPXCHG always loads a value into
18614 		 * R0, therefore always zero-extends. However some archs'
18615 		 * equivalent instruction only does this load when the
18616 		 * comparison is successful. This detail of CMPXCHG is
18617 		 * orthogonal to the general zero-extension behaviour of the
18618 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
18619 		 */
18620 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18621 			continue;
18622 
18623 		/* Zero-extension is done by the caller. */
18624 		if (bpf_pseudo_kfunc_call(&insn))
18625 			continue;
18626 
18627 		if (WARN_ON(load_reg == -1)) {
18628 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18629 			return -EFAULT;
18630 		}
18631 
18632 		zext_patch[0] = insn;
18633 		zext_patch[1].dst_reg = load_reg;
18634 		zext_patch[1].src_reg = load_reg;
18635 		patch = zext_patch;
18636 		patch_len = 2;
18637 apply_patch_buffer:
18638 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18639 		if (!new_prog)
18640 			return -ENOMEM;
18641 		env->prog = new_prog;
18642 		insns = new_prog->insnsi;
18643 		aux = env->insn_aux_data;
18644 		delta += patch_len - 1;
18645 	}
18646 
18647 	return 0;
18648 }
18649 
18650 /* convert load instructions that access fields of a context type into a
18651  * sequence of instructions that access fields of the underlying structure:
18652  *     struct __sk_buff    -> struct sk_buff
18653  *     struct bpf_sock_ops -> struct sock
18654  */
18655 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18656 {
18657 	const struct bpf_verifier_ops *ops = env->ops;
18658 	int i, cnt, size, ctx_field_size, delta = 0;
18659 	const int insn_cnt = env->prog->len;
18660 	struct bpf_insn insn_buf[16], *insn;
18661 	u32 target_size, size_default, off;
18662 	struct bpf_prog *new_prog;
18663 	enum bpf_access_type type;
18664 	bool is_narrower_load;
18665 
18666 	if (ops->gen_prologue || env->seen_direct_write) {
18667 		if (!ops->gen_prologue) {
18668 			verbose(env, "bpf verifier is misconfigured\n");
18669 			return -EINVAL;
18670 		}
18671 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18672 					env->prog);
18673 		if (cnt >= ARRAY_SIZE(insn_buf)) {
18674 			verbose(env, "bpf verifier is misconfigured\n");
18675 			return -EINVAL;
18676 		} else if (cnt) {
18677 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18678 			if (!new_prog)
18679 				return -ENOMEM;
18680 
18681 			env->prog = new_prog;
18682 			delta += cnt - 1;
18683 		}
18684 	}
18685 
18686 	if (bpf_prog_is_offloaded(env->prog->aux))
18687 		return 0;
18688 
18689 	insn = env->prog->insnsi + delta;
18690 
18691 	for (i = 0; i < insn_cnt; i++, insn++) {
18692 		bpf_convert_ctx_access_t convert_ctx_access;
18693 		u8 mode;
18694 
18695 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18696 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18697 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18698 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18699 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18700 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18701 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18702 			type = BPF_READ;
18703 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18704 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18705 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18706 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18707 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18708 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18709 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18710 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18711 			type = BPF_WRITE;
18712 		} else {
18713 			continue;
18714 		}
18715 
18716 		if (type == BPF_WRITE &&
18717 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
18718 			struct bpf_insn patch[] = {
18719 				*insn,
18720 				BPF_ST_NOSPEC(),
18721 			};
18722 
18723 			cnt = ARRAY_SIZE(patch);
18724 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18725 			if (!new_prog)
18726 				return -ENOMEM;
18727 
18728 			delta    += cnt - 1;
18729 			env->prog = new_prog;
18730 			insn      = new_prog->insnsi + i + delta;
18731 			continue;
18732 		}
18733 
18734 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18735 		case PTR_TO_CTX:
18736 			if (!ops->convert_ctx_access)
18737 				continue;
18738 			convert_ctx_access = ops->convert_ctx_access;
18739 			break;
18740 		case PTR_TO_SOCKET:
18741 		case PTR_TO_SOCK_COMMON:
18742 			convert_ctx_access = bpf_sock_convert_ctx_access;
18743 			break;
18744 		case PTR_TO_TCP_SOCK:
18745 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18746 			break;
18747 		case PTR_TO_XDP_SOCK:
18748 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18749 			break;
18750 		case PTR_TO_BTF_ID:
18751 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18752 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18753 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18754 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18755 		 * any faults for loads into such types. BPF_WRITE is disallowed
18756 		 * for this case.
18757 		 */
18758 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18759 			if (type == BPF_READ) {
18760 				if (BPF_MODE(insn->code) == BPF_MEM)
18761 					insn->code = BPF_LDX | BPF_PROBE_MEM |
18762 						     BPF_SIZE((insn)->code);
18763 				else
18764 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18765 						     BPF_SIZE((insn)->code);
18766 				env->prog->aux->num_exentries++;
18767 			}
18768 			continue;
18769 		default:
18770 			continue;
18771 		}
18772 
18773 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18774 		size = BPF_LDST_BYTES(insn);
18775 		mode = BPF_MODE(insn->code);
18776 
18777 		/* If the read access is a narrower load of the field,
18778 		 * convert to a 4/8-byte load, to minimum program type specific
18779 		 * convert_ctx_access changes. If conversion is successful,
18780 		 * we will apply proper mask to the result.
18781 		 */
18782 		is_narrower_load = size < ctx_field_size;
18783 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18784 		off = insn->off;
18785 		if (is_narrower_load) {
18786 			u8 size_code;
18787 
18788 			if (type == BPF_WRITE) {
18789 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18790 				return -EINVAL;
18791 			}
18792 
18793 			size_code = BPF_H;
18794 			if (ctx_field_size == 4)
18795 				size_code = BPF_W;
18796 			else if (ctx_field_size == 8)
18797 				size_code = BPF_DW;
18798 
18799 			insn->off = off & ~(size_default - 1);
18800 			insn->code = BPF_LDX | BPF_MEM | size_code;
18801 		}
18802 
18803 		target_size = 0;
18804 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18805 					 &target_size);
18806 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18807 		    (ctx_field_size && !target_size)) {
18808 			verbose(env, "bpf verifier is misconfigured\n");
18809 			return -EINVAL;
18810 		}
18811 
18812 		if (is_narrower_load && size < target_size) {
18813 			u8 shift = bpf_ctx_narrow_access_offset(
18814 				off, size, size_default) * 8;
18815 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18816 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18817 				return -EINVAL;
18818 			}
18819 			if (ctx_field_size <= 4) {
18820 				if (shift)
18821 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18822 									insn->dst_reg,
18823 									shift);
18824 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18825 								(1 << size * 8) - 1);
18826 			} else {
18827 				if (shift)
18828 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18829 									insn->dst_reg,
18830 									shift);
18831 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18832 								(1ULL << size * 8) - 1);
18833 			}
18834 		}
18835 		if (mode == BPF_MEMSX)
18836 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18837 						       insn->dst_reg, insn->dst_reg,
18838 						       size * 8, 0);
18839 
18840 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18841 		if (!new_prog)
18842 			return -ENOMEM;
18843 
18844 		delta += cnt - 1;
18845 
18846 		/* keep walking new program and skip insns we just inserted */
18847 		env->prog = new_prog;
18848 		insn      = new_prog->insnsi + i + delta;
18849 	}
18850 
18851 	return 0;
18852 }
18853 
18854 static int jit_subprogs(struct bpf_verifier_env *env)
18855 {
18856 	struct bpf_prog *prog = env->prog, **func, *tmp;
18857 	int i, j, subprog_start, subprog_end = 0, len, subprog;
18858 	struct bpf_map *map_ptr;
18859 	struct bpf_insn *insn;
18860 	void *old_bpf_func;
18861 	int err, num_exentries;
18862 
18863 	if (env->subprog_cnt <= 1)
18864 		return 0;
18865 
18866 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18867 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18868 			continue;
18869 
18870 		/* Upon error here we cannot fall back to interpreter but
18871 		 * need a hard reject of the program. Thus -EFAULT is
18872 		 * propagated in any case.
18873 		 */
18874 		subprog = find_subprog(env, i + insn->imm + 1);
18875 		if (subprog < 0) {
18876 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18877 				  i + insn->imm + 1);
18878 			return -EFAULT;
18879 		}
18880 		/* temporarily remember subprog id inside insn instead of
18881 		 * aux_data, since next loop will split up all insns into funcs
18882 		 */
18883 		insn->off = subprog;
18884 		/* remember original imm in case JIT fails and fallback
18885 		 * to interpreter will be needed
18886 		 */
18887 		env->insn_aux_data[i].call_imm = insn->imm;
18888 		/* point imm to __bpf_call_base+1 from JITs point of view */
18889 		insn->imm = 1;
18890 		if (bpf_pseudo_func(insn))
18891 			/* jit (e.g. x86_64) may emit fewer instructions
18892 			 * if it learns a u32 imm is the same as a u64 imm.
18893 			 * Force a non zero here.
18894 			 */
18895 			insn[1].imm = 1;
18896 	}
18897 
18898 	err = bpf_prog_alloc_jited_linfo(prog);
18899 	if (err)
18900 		goto out_undo_insn;
18901 
18902 	err = -ENOMEM;
18903 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18904 	if (!func)
18905 		goto out_undo_insn;
18906 
18907 	for (i = 0; i < env->subprog_cnt; i++) {
18908 		subprog_start = subprog_end;
18909 		subprog_end = env->subprog_info[i + 1].start;
18910 
18911 		len = subprog_end - subprog_start;
18912 		/* bpf_prog_run() doesn't call subprogs directly,
18913 		 * hence main prog stats include the runtime of subprogs.
18914 		 * subprogs don't have IDs and not reachable via prog_get_next_id
18915 		 * func[i]->stats will never be accessed and stays NULL
18916 		 */
18917 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18918 		if (!func[i])
18919 			goto out_free;
18920 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18921 		       len * sizeof(struct bpf_insn));
18922 		func[i]->type = prog->type;
18923 		func[i]->len = len;
18924 		if (bpf_prog_calc_tag(func[i]))
18925 			goto out_free;
18926 		func[i]->is_func = 1;
18927 		func[i]->aux->func_idx = i;
18928 		/* Below members will be freed only at prog->aux */
18929 		func[i]->aux->btf = prog->aux->btf;
18930 		func[i]->aux->func_info = prog->aux->func_info;
18931 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18932 		func[i]->aux->poke_tab = prog->aux->poke_tab;
18933 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18934 
18935 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
18936 			struct bpf_jit_poke_descriptor *poke;
18937 
18938 			poke = &prog->aux->poke_tab[j];
18939 			if (poke->insn_idx < subprog_end &&
18940 			    poke->insn_idx >= subprog_start)
18941 				poke->aux = func[i]->aux;
18942 		}
18943 
18944 		func[i]->aux->name[0] = 'F';
18945 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18946 		func[i]->jit_requested = 1;
18947 		func[i]->blinding_requested = prog->blinding_requested;
18948 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18949 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18950 		func[i]->aux->linfo = prog->aux->linfo;
18951 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18952 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18953 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18954 		num_exentries = 0;
18955 		insn = func[i]->insnsi;
18956 		for (j = 0; j < func[i]->len; j++, insn++) {
18957 			if (BPF_CLASS(insn->code) == BPF_LDX &&
18958 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18959 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18960 				num_exentries++;
18961 		}
18962 		func[i]->aux->num_exentries = num_exentries;
18963 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18964 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
18965 		if (!i)
18966 			func[i]->aux->exception_boundary = env->seen_exception;
18967 		func[i] = bpf_int_jit_compile(func[i]);
18968 		if (!func[i]->jited) {
18969 			err = -ENOTSUPP;
18970 			goto out_free;
18971 		}
18972 		cond_resched();
18973 	}
18974 
18975 	/* at this point all bpf functions were successfully JITed
18976 	 * now populate all bpf_calls with correct addresses and
18977 	 * run last pass of JIT
18978 	 */
18979 	for (i = 0; i < env->subprog_cnt; i++) {
18980 		insn = func[i]->insnsi;
18981 		for (j = 0; j < func[i]->len; j++, insn++) {
18982 			if (bpf_pseudo_func(insn)) {
18983 				subprog = insn->off;
18984 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18985 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18986 				continue;
18987 			}
18988 			if (!bpf_pseudo_call(insn))
18989 				continue;
18990 			subprog = insn->off;
18991 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18992 		}
18993 
18994 		/* we use the aux data to keep a list of the start addresses
18995 		 * of the JITed images for each function in the program
18996 		 *
18997 		 * for some architectures, such as powerpc64, the imm field
18998 		 * might not be large enough to hold the offset of the start
18999 		 * address of the callee's JITed image from __bpf_call_base
19000 		 *
19001 		 * in such cases, we can lookup the start address of a callee
19002 		 * by using its subprog id, available from the off field of
19003 		 * the call instruction, as an index for this list
19004 		 */
19005 		func[i]->aux->func = func;
19006 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19007 		func[i]->aux->real_func_cnt = env->subprog_cnt;
19008 	}
19009 	for (i = 0; i < env->subprog_cnt; i++) {
19010 		old_bpf_func = func[i]->bpf_func;
19011 		tmp = bpf_int_jit_compile(func[i]);
19012 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
19013 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
19014 			err = -ENOTSUPP;
19015 			goto out_free;
19016 		}
19017 		cond_resched();
19018 	}
19019 
19020 	/* finally lock prog and jit images for all functions and
19021 	 * populate kallsysm. Begin at the first subprogram, since
19022 	 * bpf_prog_load will add the kallsyms for the main program.
19023 	 */
19024 	for (i = 1; i < env->subprog_cnt; i++) {
19025 		bpf_prog_lock_ro(func[i]);
19026 		bpf_prog_kallsyms_add(func[i]);
19027 	}
19028 
19029 	/* Last step: make now unused interpreter insns from main
19030 	 * prog consistent for later dump requests, so they can
19031 	 * later look the same as if they were interpreted only.
19032 	 */
19033 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19034 		if (bpf_pseudo_func(insn)) {
19035 			insn[0].imm = env->insn_aux_data[i].call_imm;
19036 			insn[1].imm = insn->off;
19037 			insn->off = 0;
19038 			continue;
19039 		}
19040 		if (!bpf_pseudo_call(insn))
19041 			continue;
19042 		insn->off = env->insn_aux_data[i].call_imm;
19043 		subprog = find_subprog(env, i + insn->off + 1);
19044 		insn->imm = subprog;
19045 	}
19046 
19047 	prog->jited = 1;
19048 	prog->bpf_func = func[0]->bpf_func;
19049 	prog->jited_len = func[0]->jited_len;
19050 	prog->aux->extable = func[0]->aux->extable;
19051 	prog->aux->num_exentries = func[0]->aux->num_exentries;
19052 	prog->aux->func = func;
19053 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19054 	prog->aux->real_func_cnt = env->subprog_cnt;
19055 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
19056 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
19057 	bpf_prog_jit_attempt_done(prog);
19058 	return 0;
19059 out_free:
19060 	/* We failed JIT'ing, so at this point we need to unregister poke
19061 	 * descriptors from subprogs, so that kernel is not attempting to
19062 	 * patch it anymore as we're freeing the subprog JIT memory.
19063 	 */
19064 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19065 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19066 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
19067 	}
19068 	/* At this point we're guaranteed that poke descriptors are not
19069 	 * live anymore. We can just unlink its descriptor table as it's
19070 	 * released with the main prog.
19071 	 */
19072 	for (i = 0; i < env->subprog_cnt; i++) {
19073 		if (!func[i])
19074 			continue;
19075 		func[i]->aux->poke_tab = NULL;
19076 		bpf_jit_free(func[i]);
19077 	}
19078 	kfree(func);
19079 out_undo_insn:
19080 	/* cleanup main prog to be interpreted */
19081 	prog->jit_requested = 0;
19082 	prog->blinding_requested = 0;
19083 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19084 		if (!bpf_pseudo_call(insn))
19085 			continue;
19086 		insn->off = 0;
19087 		insn->imm = env->insn_aux_data[i].call_imm;
19088 	}
19089 	bpf_prog_jit_attempt_done(prog);
19090 	return err;
19091 }
19092 
19093 static int fixup_call_args(struct bpf_verifier_env *env)
19094 {
19095 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19096 	struct bpf_prog *prog = env->prog;
19097 	struct bpf_insn *insn = prog->insnsi;
19098 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
19099 	int i, depth;
19100 #endif
19101 	int err = 0;
19102 
19103 	if (env->prog->jit_requested &&
19104 	    !bpf_prog_is_offloaded(env->prog->aux)) {
19105 		err = jit_subprogs(env);
19106 		if (err == 0)
19107 			return 0;
19108 		if (err == -EFAULT)
19109 			return err;
19110 	}
19111 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19112 	if (has_kfunc_call) {
19113 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
19114 		return -EINVAL;
19115 	}
19116 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
19117 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
19118 		 * have to be rejected, since interpreter doesn't support them yet.
19119 		 */
19120 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
19121 		return -EINVAL;
19122 	}
19123 	for (i = 0; i < prog->len; i++, insn++) {
19124 		if (bpf_pseudo_func(insn)) {
19125 			/* When JIT fails the progs with callback calls
19126 			 * have to be rejected, since interpreter doesn't support them yet.
19127 			 */
19128 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
19129 			return -EINVAL;
19130 		}
19131 
19132 		if (!bpf_pseudo_call(insn))
19133 			continue;
19134 		depth = get_callee_stack_depth(env, insn, i);
19135 		if (depth < 0)
19136 			return depth;
19137 		bpf_patch_call_args(insn, depth);
19138 	}
19139 	err = 0;
19140 #endif
19141 	return err;
19142 }
19143 
19144 /* replace a generic kfunc with a specialized version if necessary */
19145 static void specialize_kfunc(struct bpf_verifier_env *env,
19146 			     u32 func_id, u16 offset, unsigned long *addr)
19147 {
19148 	struct bpf_prog *prog = env->prog;
19149 	bool seen_direct_write;
19150 	void *xdp_kfunc;
19151 	bool is_rdonly;
19152 
19153 	if (bpf_dev_bound_kfunc_id(func_id)) {
19154 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
19155 		if (xdp_kfunc) {
19156 			*addr = (unsigned long)xdp_kfunc;
19157 			return;
19158 		}
19159 		/* fallback to default kfunc when not supported by netdev */
19160 	}
19161 
19162 	if (offset)
19163 		return;
19164 
19165 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
19166 		seen_direct_write = env->seen_direct_write;
19167 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
19168 
19169 		if (is_rdonly)
19170 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
19171 
19172 		/* restore env->seen_direct_write to its original value, since
19173 		 * may_access_direct_pkt_data mutates it
19174 		 */
19175 		env->seen_direct_write = seen_direct_write;
19176 	}
19177 }
19178 
19179 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
19180 					    u16 struct_meta_reg,
19181 					    u16 node_offset_reg,
19182 					    struct bpf_insn *insn,
19183 					    struct bpf_insn *insn_buf,
19184 					    int *cnt)
19185 {
19186 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
19187 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
19188 
19189 	insn_buf[0] = addr[0];
19190 	insn_buf[1] = addr[1];
19191 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
19192 	insn_buf[3] = *insn;
19193 	*cnt = 4;
19194 }
19195 
19196 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
19197 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
19198 {
19199 	const struct bpf_kfunc_desc *desc;
19200 
19201 	if (!insn->imm) {
19202 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
19203 		return -EINVAL;
19204 	}
19205 
19206 	*cnt = 0;
19207 
19208 	/* insn->imm has the btf func_id. Replace it with an offset relative to
19209 	 * __bpf_call_base, unless the JIT needs to call functions that are
19210 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
19211 	 */
19212 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
19213 	if (!desc) {
19214 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
19215 			insn->imm);
19216 		return -EFAULT;
19217 	}
19218 
19219 	if (!bpf_jit_supports_far_kfunc_call())
19220 		insn->imm = BPF_CALL_IMM(desc->addr);
19221 	if (insn->off)
19222 		return 0;
19223 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
19224 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
19225 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19226 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19227 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
19228 
19229 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
19230 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19231 				insn_idx);
19232 			return -EFAULT;
19233 		}
19234 
19235 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
19236 		insn_buf[1] = addr[0];
19237 		insn_buf[2] = addr[1];
19238 		insn_buf[3] = *insn;
19239 		*cnt = 4;
19240 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
19241 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
19242 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
19243 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19244 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19245 
19246 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
19247 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19248 				insn_idx);
19249 			return -EFAULT;
19250 		}
19251 
19252 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
19253 		    !kptr_struct_meta) {
19254 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19255 				insn_idx);
19256 			return -EFAULT;
19257 		}
19258 
19259 		insn_buf[0] = addr[0];
19260 		insn_buf[1] = addr[1];
19261 		insn_buf[2] = *insn;
19262 		*cnt = 3;
19263 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
19264 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
19265 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19266 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19267 		int struct_meta_reg = BPF_REG_3;
19268 		int node_offset_reg = BPF_REG_4;
19269 
19270 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
19271 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19272 			struct_meta_reg = BPF_REG_4;
19273 			node_offset_reg = BPF_REG_5;
19274 		}
19275 
19276 		if (!kptr_struct_meta) {
19277 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19278 				insn_idx);
19279 			return -EFAULT;
19280 		}
19281 
19282 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
19283 						node_offset_reg, insn, insn_buf, cnt);
19284 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
19285 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
19286 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
19287 		*cnt = 1;
19288 	}
19289 	return 0;
19290 }
19291 
19292 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
19293 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
19294 {
19295 	struct bpf_subprog_info *info = env->subprog_info;
19296 	int cnt = env->subprog_cnt;
19297 	struct bpf_prog *prog;
19298 
19299 	/* We only reserve one slot for hidden subprogs in subprog_info. */
19300 	if (env->hidden_subprog_cnt) {
19301 		verbose(env, "verifier internal error: only one hidden subprog supported\n");
19302 		return -EFAULT;
19303 	}
19304 	/* We're not patching any existing instruction, just appending the new
19305 	 * ones for the hidden subprog. Hence all of the adjustment operations
19306 	 * in bpf_patch_insn_data are no-ops.
19307 	 */
19308 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
19309 	if (!prog)
19310 		return -ENOMEM;
19311 	env->prog = prog;
19312 	info[cnt + 1].start = info[cnt].start;
19313 	info[cnt].start = prog->len - len + 1;
19314 	env->subprog_cnt++;
19315 	env->hidden_subprog_cnt++;
19316 	return 0;
19317 }
19318 
19319 /* Do various post-verification rewrites in a single program pass.
19320  * These rewrites simplify JIT and interpreter implementations.
19321  */
19322 static int do_misc_fixups(struct bpf_verifier_env *env)
19323 {
19324 	struct bpf_prog *prog = env->prog;
19325 	enum bpf_attach_type eatype = prog->expected_attach_type;
19326 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
19327 	struct bpf_insn *insn = prog->insnsi;
19328 	const struct bpf_func_proto *fn;
19329 	const int insn_cnt = prog->len;
19330 	const struct bpf_map_ops *ops;
19331 	struct bpf_insn_aux_data *aux;
19332 	struct bpf_insn insn_buf[16];
19333 	struct bpf_prog *new_prog;
19334 	struct bpf_map *map_ptr;
19335 	int i, ret, cnt, delta = 0;
19336 
19337 	if (env->seen_exception && !env->exception_callback_subprog) {
19338 		struct bpf_insn patch[] = {
19339 			env->prog->insnsi[insn_cnt - 1],
19340 			BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
19341 			BPF_EXIT_INSN(),
19342 		};
19343 
19344 		ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
19345 		if (ret < 0)
19346 			return ret;
19347 		prog = env->prog;
19348 		insn = prog->insnsi;
19349 
19350 		env->exception_callback_subprog = env->subprog_cnt - 1;
19351 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
19352 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
19353 	}
19354 
19355 	for (i = 0; i < insn_cnt; i++, insn++) {
19356 		/* Make divide-by-zero exceptions impossible. */
19357 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
19358 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
19359 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
19360 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
19361 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
19362 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
19363 			struct bpf_insn *patchlet;
19364 			struct bpf_insn chk_and_div[] = {
19365 				/* [R,W]x div 0 -> 0 */
19366 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19367 					     BPF_JNE | BPF_K, insn->src_reg,
19368 					     0, 2, 0),
19369 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
19370 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19371 				*insn,
19372 			};
19373 			struct bpf_insn chk_and_mod[] = {
19374 				/* [R,W]x mod 0 -> [R,W]x */
19375 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19376 					     BPF_JEQ | BPF_K, insn->src_reg,
19377 					     0, 1 + (is64 ? 0 : 1), 0),
19378 				*insn,
19379 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19380 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
19381 			};
19382 
19383 			patchlet = isdiv ? chk_and_div : chk_and_mod;
19384 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
19385 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
19386 
19387 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
19388 			if (!new_prog)
19389 				return -ENOMEM;
19390 
19391 			delta    += cnt - 1;
19392 			env->prog = prog = new_prog;
19393 			insn      = new_prog->insnsi + i + delta;
19394 			continue;
19395 		}
19396 
19397 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
19398 		if (BPF_CLASS(insn->code) == BPF_LD &&
19399 		    (BPF_MODE(insn->code) == BPF_ABS ||
19400 		     BPF_MODE(insn->code) == BPF_IND)) {
19401 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
19402 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19403 				verbose(env, "bpf verifier is misconfigured\n");
19404 				return -EINVAL;
19405 			}
19406 
19407 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19408 			if (!new_prog)
19409 				return -ENOMEM;
19410 
19411 			delta    += cnt - 1;
19412 			env->prog = prog = new_prog;
19413 			insn      = new_prog->insnsi + i + delta;
19414 			continue;
19415 		}
19416 
19417 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
19418 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
19419 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
19420 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
19421 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
19422 			struct bpf_insn *patch = &insn_buf[0];
19423 			bool issrc, isneg, isimm;
19424 			u32 off_reg;
19425 
19426 			aux = &env->insn_aux_data[i + delta];
19427 			if (!aux->alu_state ||
19428 			    aux->alu_state == BPF_ALU_NON_POINTER)
19429 				continue;
19430 
19431 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
19432 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
19433 				BPF_ALU_SANITIZE_SRC;
19434 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
19435 
19436 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
19437 			if (isimm) {
19438 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19439 			} else {
19440 				if (isneg)
19441 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19442 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19443 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
19444 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
19445 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
19446 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
19447 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
19448 			}
19449 			if (!issrc)
19450 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
19451 			insn->src_reg = BPF_REG_AX;
19452 			if (isneg)
19453 				insn->code = insn->code == code_add ?
19454 					     code_sub : code_add;
19455 			*patch++ = *insn;
19456 			if (issrc && isneg && !isimm)
19457 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19458 			cnt = patch - insn_buf;
19459 
19460 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19461 			if (!new_prog)
19462 				return -ENOMEM;
19463 
19464 			delta    += cnt - 1;
19465 			env->prog = prog = new_prog;
19466 			insn      = new_prog->insnsi + i + delta;
19467 			continue;
19468 		}
19469 
19470 		if (insn->code != (BPF_JMP | BPF_CALL))
19471 			continue;
19472 		if (insn->src_reg == BPF_PSEUDO_CALL)
19473 			continue;
19474 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19475 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19476 			if (ret)
19477 				return ret;
19478 			if (cnt == 0)
19479 				continue;
19480 
19481 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19482 			if (!new_prog)
19483 				return -ENOMEM;
19484 
19485 			delta	 += cnt - 1;
19486 			env->prog = prog = new_prog;
19487 			insn	  = new_prog->insnsi + i + delta;
19488 			continue;
19489 		}
19490 
19491 		if (insn->imm == BPF_FUNC_get_route_realm)
19492 			prog->dst_needed = 1;
19493 		if (insn->imm == BPF_FUNC_get_prandom_u32)
19494 			bpf_user_rnd_init_once();
19495 		if (insn->imm == BPF_FUNC_override_return)
19496 			prog->kprobe_override = 1;
19497 		if (insn->imm == BPF_FUNC_tail_call) {
19498 			/* If we tail call into other programs, we
19499 			 * cannot make any assumptions since they can
19500 			 * be replaced dynamically during runtime in
19501 			 * the program array.
19502 			 */
19503 			prog->cb_access = 1;
19504 			if (!allow_tail_call_in_subprogs(env))
19505 				prog->aux->stack_depth = MAX_BPF_STACK;
19506 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19507 
19508 			/* mark bpf_tail_call as different opcode to avoid
19509 			 * conditional branch in the interpreter for every normal
19510 			 * call and to prevent accidental JITing by JIT compiler
19511 			 * that doesn't support bpf_tail_call yet
19512 			 */
19513 			insn->imm = 0;
19514 			insn->code = BPF_JMP | BPF_TAIL_CALL;
19515 
19516 			aux = &env->insn_aux_data[i + delta];
19517 			if (env->bpf_capable && !prog->blinding_requested &&
19518 			    prog->jit_requested &&
19519 			    !bpf_map_key_poisoned(aux) &&
19520 			    !bpf_map_ptr_poisoned(aux) &&
19521 			    !bpf_map_ptr_unpriv(aux)) {
19522 				struct bpf_jit_poke_descriptor desc = {
19523 					.reason = BPF_POKE_REASON_TAIL_CALL,
19524 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19525 					.tail_call.key = bpf_map_key_immediate(aux),
19526 					.insn_idx = i + delta,
19527 				};
19528 
19529 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
19530 				if (ret < 0) {
19531 					verbose(env, "adding tail call poke descriptor failed\n");
19532 					return ret;
19533 				}
19534 
19535 				insn->imm = ret + 1;
19536 				continue;
19537 			}
19538 
19539 			if (!bpf_map_ptr_unpriv(aux))
19540 				continue;
19541 
19542 			/* instead of changing every JIT dealing with tail_call
19543 			 * emit two extra insns:
19544 			 * if (index >= max_entries) goto out;
19545 			 * index &= array->index_mask;
19546 			 * to avoid out-of-bounds cpu speculation
19547 			 */
19548 			if (bpf_map_ptr_poisoned(aux)) {
19549 				verbose(env, "tail_call abusing map_ptr\n");
19550 				return -EINVAL;
19551 			}
19552 
19553 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19554 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19555 						  map_ptr->max_entries, 2);
19556 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19557 						    container_of(map_ptr,
19558 								 struct bpf_array,
19559 								 map)->index_mask);
19560 			insn_buf[2] = *insn;
19561 			cnt = 3;
19562 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19563 			if (!new_prog)
19564 				return -ENOMEM;
19565 
19566 			delta    += cnt - 1;
19567 			env->prog = prog = new_prog;
19568 			insn      = new_prog->insnsi + i + delta;
19569 			continue;
19570 		}
19571 
19572 		if (insn->imm == BPF_FUNC_timer_set_callback) {
19573 			/* The verifier will process callback_fn as many times as necessary
19574 			 * with different maps and the register states prepared by
19575 			 * set_timer_callback_state will be accurate.
19576 			 *
19577 			 * The following use case is valid:
19578 			 *   map1 is shared by prog1, prog2, prog3.
19579 			 *   prog1 calls bpf_timer_init for some map1 elements
19580 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
19581 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
19582 			 *   prog3 calls bpf_timer_start for some map1 elements.
19583 			 *     Those that were not both bpf_timer_init-ed and
19584 			 *     bpf_timer_set_callback-ed will return -EINVAL.
19585 			 */
19586 			struct bpf_insn ld_addrs[2] = {
19587 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19588 			};
19589 
19590 			insn_buf[0] = ld_addrs[0];
19591 			insn_buf[1] = ld_addrs[1];
19592 			insn_buf[2] = *insn;
19593 			cnt = 3;
19594 
19595 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19596 			if (!new_prog)
19597 				return -ENOMEM;
19598 
19599 			delta    += cnt - 1;
19600 			env->prog = prog = new_prog;
19601 			insn      = new_prog->insnsi + i + delta;
19602 			goto patch_call_imm;
19603 		}
19604 
19605 		if (is_storage_get_function(insn->imm)) {
19606 			if (!env->prog->aux->sleepable ||
19607 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
19608 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19609 			else
19610 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19611 			insn_buf[1] = *insn;
19612 			cnt = 2;
19613 
19614 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19615 			if (!new_prog)
19616 				return -ENOMEM;
19617 
19618 			delta += cnt - 1;
19619 			env->prog = prog = new_prog;
19620 			insn = new_prog->insnsi + i + delta;
19621 			goto patch_call_imm;
19622 		}
19623 
19624 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
19625 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
19626 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
19627 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
19628 			 */
19629 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
19630 			insn_buf[1] = *insn;
19631 			cnt = 2;
19632 
19633 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19634 			if (!new_prog)
19635 				return -ENOMEM;
19636 
19637 			delta += cnt - 1;
19638 			env->prog = prog = new_prog;
19639 			insn = new_prog->insnsi + i + delta;
19640 			goto patch_call_imm;
19641 		}
19642 
19643 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19644 		 * and other inlining handlers are currently limited to 64 bit
19645 		 * only.
19646 		 */
19647 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19648 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
19649 		     insn->imm == BPF_FUNC_map_update_elem ||
19650 		     insn->imm == BPF_FUNC_map_delete_elem ||
19651 		     insn->imm == BPF_FUNC_map_push_elem   ||
19652 		     insn->imm == BPF_FUNC_map_pop_elem    ||
19653 		     insn->imm == BPF_FUNC_map_peek_elem   ||
19654 		     insn->imm == BPF_FUNC_redirect_map    ||
19655 		     insn->imm == BPF_FUNC_for_each_map_elem ||
19656 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19657 			aux = &env->insn_aux_data[i + delta];
19658 			if (bpf_map_ptr_poisoned(aux))
19659 				goto patch_call_imm;
19660 
19661 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19662 			ops = map_ptr->ops;
19663 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
19664 			    ops->map_gen_lookup) {
19665 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19666 				if (cnt == -EOPNOTSUPP)
19667 					goto patch_map_ops_generic;
19668 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19669 					verbose(env, "bpf verifier is misconfigured\n");
19670 					return -EINVAL;
19671 				}
19672 
19673 				new_prog = bpf_patch_insn_data(env, i + delta,
19674 							       insn_buf, cnt);
19675 				if (!new_prog)
19676 					return -ENOMEM;
19677 
19678 				delta    += cnt - 1;
19679 				env->prog = prog = new_prog;
19680 				insn      = new_prog->insnsi + i + delta;
19681 				continue;
19682 			}
19683 
19684 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19685 				     (void *(*)(struct bpf_map *map, void *key))NULL));
19686 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19687 				     (long (*)(struct bpf_map *map, void *key))NULL));
19688 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19689 				     (long (*)(struct bpf_map *map, void *key, void *value,
19690 					      u64 flags))NULL));
19691 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19692 				     (long (*)(struct bpf_map *map, void *value,
19693 					      u64 flags))NULL));
19694 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19695 				     (long (*)(struct bpf_map *map, void *value))NULL));
19696 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19697 				     (long (*)(struct bpf_map *map, void *value))NULL));
19698 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
19699 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19700 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19701 				     (long (*)(struct bpf_map *map,
19702 					      bpf_callback_t callback_fn,
19703 					      void *callback_ctx,
19704 					      u64 flags))NULL));
19705 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19706 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19707 
19708 patch_map_ops_generic:
19709 			switch (insn->imm) {
19710 			case BPF_FUNC_map_lookup_elem:
19711 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19712 				continue;
19713 			case BPF_FUNC_map_update_elem:
19714 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19715 				continue;
19716 			case BPF_FUNC_map_delete_elem:
19717 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19718 				continue;
19719 			case BPF_FUNC_map_push_elem:
19720 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19721 				continue;
19722 			case BPF_FUNC_map_pop_elem:
19723 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19724 				continue;
19725 			case BPF_FUNC_map_peek_elem:
19726 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19727 				continue;
19728 			case BPF_FUNC_redirect_map:
19729 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
19730 				continue;
19731 			case BPF_FUNC_for_each_map_elem:
19732 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19733 				continue;
19734 			case BPF_FUNC_map_lookup_percpu_elem:
19735 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19736 				continue;
19737 			}
19738 
19739 			goto patch_call_imm;
19740 		}
19741 
19742 		/* Implement bpf_jiffies64 inline. */
19743 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19744 		    insn->imm == BPF_FUNC_jiffies64) {
19745 			struct bpf_insn ld_jiffies_addr[2] = {
19746 				BPF_LD_IMM64(BPF_REG_0,
19747 					     (unsigned long)&jiffies),
19748 			};
19749 
19750 			insn_buf[0] = ld_jiffies_addr[0];
19751 			insn_buf[1] = ld_jiffies_addr[1];
19752 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19753 						  BPF_REG_0, 0);
19754 			cnt = 3;
19755 
19756 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19757 						       cnt);
19758 			if (!new_prog)
19759 				return -ENOMEM;
19760 
19761 			delta    += cnt - 1;
19762 			env->prog = prog = new_prog;
19763 			insn      = new_prog->insnsi + i + delta;
19764 			continue;
19765 		}
19766 
19767 		/* Implement bpf_get_func_arg inline. */
19768 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19769 		    insn->imm == BPF_FUNC_get_func_arg) {
19770 			/* Load nr_args from ctx - 8 */
19771 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19772 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19773 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19774 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19775 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19776 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19777 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19778 			insn_buf[7] = BPF_JMP_A(1);
19779 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19780 			cnt = 9;
19781 
19782 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19783 			if (!new_prog)
19784 				return -ENOMEM;
19785 
19786 			delta    += cnt - 1;
19787 			env->prog = prog = new_prog;
19788 			insn      = new_prog->insnsi + i + delta;
19789 			continue;
19790 		}
19791 
19792 		/* Implement bpf_get_func_ret inline. */
19793 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19794 		    insn->imm == BPF_FUNC_get_func_ret) {
19795 			if (eatype == BPF_TRACE_FEXIT ||
19796 			    eatype == BPF_MODIFY_RETURN) {
19797 				/* Load nr_args from ctx - 8 */
19798 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19799 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19800 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19801 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19802 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19803 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19804 				cnt = 6;
19805 			} else {
19806 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19807 				cnt = 1;
19808 			}
19809 
19810 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19811 			if (!new_prog)
19812 				return -ENOMEM;
19813 
19814 			delta    += cnt - 1;
19815 			env->prog = prog = new_prog;
19816 			insn      = new_prog->insnsi + i + delta;
19817 			continue;
19818 		}
19819 
19820 		/* Implement get_func_arg_cnt inline. */
19821 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19822 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
19823 			/* Load nr_args from ctx - 8 */
19824 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19825 
19826 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19827 			if (!new_prog)
19828 				return -ENOMEM;
19829 
19830 			env->prog = prog = new_prog;
19831 			insn      = new_prog->insnsi + i + delta;
19832 			continue;
19833 		}
19834 
19835 		/* Implement bpf_get_func_ip inline. */
19836 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19837 		    insn->imm == BPF_FUNC_get_func_ip) {
19838 			/* Load IP address from ctx - 16 */
19839 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19840 
19841 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19842 			if (!new_prog)
19843 				return -ENOMEM;
19844 
19845 			env->prog = prog = new_prog;
19846 			insn      = new_prog->insnsi + i + delta;
19847 			continue;
19848 		}
19849 
19850 		/* Implement bpf_kptr_xchg inline */
19851 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19852 		    insn->imm == BPF_FUNC_kptr_xchg &&
19853 		    bpf_jit_supports_ptr_xchg()) {
19854 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
19855 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
19856 			cnt = 2;
19857 
19858 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19859 			if (!new_prog)
19860 				return -ENOMEM;
19861 
19862 			delta    += cnt - 1;
19863 			env->prog = prog = new_prog;
19864 			insn      = new_prog->insnsi + i + delta;
19865 			continue;
19866 		}
19867 patch_call_imm:
19868 		fn = env->ops->get_func_proto(insn->imm, env->prog);
19869 		/* all functions that have prototype and verifier allowed
19870 		 * programs to call them, must be real in-kernel functions
19871 		 */
19872 		if (!fn->func) {
19873 			verbose(env,
19874 				"kernel subsystem misconfigured func %s#%d\n",
19875 				func_id_name(insn->imm), insn->imm);
19876 			return -EFAULT;
19877 		}
19878 		insn->imm = fn->func - __bpf_call_base;
19879 	}
19880 
19881 	/* Since poke tab is now finalized, publish aux to tracker. */
19882 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19883 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19884 		if (!map_ptr->ops->map_poke_track ||
19885 		    !map_ptr->ops->map_poke_untrack ||
19886 		    !map_ptr->ops->map_poke_run) {
19887 			verbose(env, "bpf verifier is misconfigured\n");
19888 			return -EINVAL;
19889 		}
19890 
19891 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19892 		if (ret < 0) {
19893 			verbose(env, "tracking tail call prog failed\n");
19894 			return ret;
19895 		}
19896 	}
19897 
19898 	sort_kfunc_descs_by_imm_off(env->prog);
19899 
19900 	return 0;
19901 }
19902 
19903 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19904 					int position,
19905 					s32 stack_base,
19906 					u32 callback_subprogno,
19907 					u32 *cnt)
19908 {
19909 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19910 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19911 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19912 	int reg_loop_max = BPF_REG_6;
19913 	int reg_loop_cnt = BPF_REG_7;
19914 	int reg_loop_ctx = BPF_REG_8;
19915 
19916 	struct bpf_prog *new_prog;
19917 	u32 callback_start;
19918 	u32 call_insn_offset;
19919 	s32 callback_offset;
19920 
19921 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
19922 	 * be careful to modify this code in sync.
19923 	 */
19924 	struct bpf_insn insn_buf[] = {
19925 		/* Return error and jump to the end of the patch if
19926 		 * expected number of iterations is too big.
19927 		 */
19928 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19929 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19930 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19931 		/* spill R6, R7, R8 to use these as loop vars */
19932 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19933 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19934 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19935 		/* initialize loop vars */
19936 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19937 		BPF_MOV32_IMM(reg_loop_cnt, 0),
19938 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19939 		/* loop header,
19940 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
19941 		 */
19942 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19943 		/* callback call,
19944 		 * correct callback offset would be set after patching
19945 		 */
19946 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19947 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19948 		BPF_CALL_REL(0),
19949 		/* increment loop counter */
19950 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19951 		/* jump to loop header if callback returned 0 */
19952 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19953 		/* return value of bpf_loop,
19954 		 * set R0 to the number of iterations
19955 		 */
19956 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19957 		/* restore original values of R6, R7, R8 */
19958 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19959 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19960 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19961 	};
19962 
19963 	*cnt = ARRAY_SIZE(insn_buf);
19964 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19965 	if (!new_prog)
19966 		return new_prog;
19967 
19968 	/* callback start is known only after patching */
19969 	callback_start = env->subprog_info[callback_subprogno].start;
19970 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19971 	call_insn_offset = position + 12;
19972 	callback_offset = callback_start - call_insn_offset - 1;
19973 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
19974 
19975 	return new_prog;
19976 }
19977 
19978 static bool is_bpf_loop_call(struct bpf_insn *insn)
19979 {
19980 	return insn->code == (BPF_JMP | BPF_CALL) &&
19981 		insn->src_reg == 0 &&
19982 		insn->imm == BPF_FUNC_loop;
19983 }
19984 
19985 /* For all sub-programs in the program (including main) check
19986  * insn_aux_data to see if there are bpf_loop calls that require
19987  * inlining. If such calls are found the calls are replaced with a
19988  * sequence of instructions produced by `inline_bpf_loop` function and
19989  * subprog stack_depth is increased by the size of 3 registers.
19990  * This stack space is used to spill values of the R6, R7, R8.  These
19991  * registers are used to store the loop bound, counter and context
19992  * variables.
19993  */
19994 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19995 {
19996 	struct bpf_subprog_info *subprogs = env->subprog_info;
19997 	int i, cur_subprog = 0, cnt, delta = 0;
19998 	struct bpf_insn *insn = env->prog->insnsi;
19999 	int insn_cnt = env->prog->len;
20000 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
20001 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20002 	u16 stack_depth_extra = 0;
20003 
20004 	for (i = 0; i < insn_cnt; i++, insn++) {
20005 		struct bpf_loop_inline_state *inline_state =
20006 			&env->insn_aux_data[i + delta].loop_inline_state;
20007 
20008 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
20009 			struct bpf_prog *new_prog;
20010 
20011 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
20012 			new_prog = inline_bpf_loop(env,
20013 						   i + delta,
20014 						   -(stack_depth + stack_depth_extra),
20015 						   inline_state->callback_subprogno,
20016 						   &cnt);
20017 			if (!new_prog)
20018 				return -ENOMEM;
20019 
20020 			delta     += cnt - 1;
20021 			env->prog  = new_prog;
20022 			insn       = new_prog->insnsi + i + delta;
20023 		}
20024 
20025 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
20026 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
20027 			cur_subprog++;
20028 			stack_depth = subprogs[cur_subprog].stack_depth;
20029 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20030 			stack_depth_extra = 0;
20031 		}
20032 	}
20033 
20034 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20035 
20036 	return 0;
20037 }
20038 
20039 static void free_states(struct bpf_verifier_env *env)
20040 {
20041 	struct bpf_verifier_state_list *sl, *sln;
20042 	int i;
20043 
20044 	sl = env->free_list;
20045 	while (sl) {
20046 		sln = sl->next;
20047 		free_verifier_state(&sl->state, false);
20048 		kfree(sl);
20049 		sl = sln;
20050 	}
20051 	env->free_list = NULL;
20052 
20053 	if (!env->explored_states)
20054 		return;
20055 
20056 	for (i = 0; i < state_htab_size(env); i++) {
20057 		sl = env->explored_states[i];
20058 
20059 		while (sl) {
20060 			sln = sl->next;
20061 			free_verifier_state(&sl->state, false);
20062 			kfree(sl);
20063 			sl = sln;
20064 		}
20065 		env->explored_states[i] = NULL;
20066 	}
20067 }
20068 
20069 static int do_check_common(struct bpf_verifier_env *env, int subprog)
20070 {
20071 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20072 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
20073 	struct bpf_verifier_state *state;
20074 	struct bpf_reg_state *regs;
20075 	int ret, i;
20076 
20077 	env->prev_linfo = NULL;
20078 	env->pass_cnt++;
20079 
20080 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
20081 	if (!state)
20082 		return -ENOMEM;
20083 	state->curframe = 0;
20084 	state->speculative = false;
20085 	state->branches = 1;
20086 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
20087 	if (!state->frame[0]) {
20088 		kfree(state);
20089 		return -ENOMEM;
20090 	}
20091 	env->cur_state = state;
20092 	init_func_state(env, state->frame[0],
20093 			BPF_MAIN_FUNC /* callsite */,
20094 			0 /* frameno */,
20095 			subprog);
20096 	state->first_insn_idx = env->subprog_info[subprog].start;
20097 	state->last_insn_idx = -1;
20098 
20099 	regs = state->frame[state->curframe]->regs;
20100 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
20101 		const char *sub_name = subprog_name(env, subprog);
20102 		struct bpf_subprog_arg_info *arg;
20103 		struct bpf_reg_state *reg;
20104 
20105 		verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
20106 		ret = btf_prepare_func_args(env, subprog);
20107 		if (ret)
20108 			goto out;
20109 
20110 		if (subprog_is_exc_cb(env, subprog)) {
20111 			state->frame[0]->in_exception_callback_fn = true;
20112 			/* We have already ensured that the callback returns an integer, just
20113 			 * like all global subprogs. We need to determine it only has a single
20114 			 * scalar argument.
20115 			 */
20116 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
20117 				verbose(env, "exception cb only supports single integer argument\n");
20118 				ret = -EINVAL;
20119 				goto out;
20120 			}
20121 		}
20122 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
20123 			arg = &sub->args[i - BPF_REG_1];
20124 			reg = &regs[i];
20125 
20126 			if (arg->arg_type == ARG_PTR_TO_CTX) {
20127 				reg->type = PTR_TO_CTX;
20128 				mark_reg_known_zero(env, regs, i);
20129 			} else if (arg->arg_type == ARG_ANYTHING) {
20130 				reg->type = SCALAR_VALUE;
20131 				mark_reg_unknown(env, regs, i);
20132 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
20133 				/* assume unspecial LOCAL dynptr type */
20134 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
20135 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
20136 				reg->type = PTR_TO_MEM;
20137 				if (arg->arg_type & PTR_MAYBE_NULL)
20138 					reg->type |= PTR_MAYBE_NULL;
20139 				mark_reg_known_zero(env, regs, i);
20140 				reg->mem_size = arg->mem_size;
20141 				reg->id = ++env->id_gen;
20142 			} else {
20143 				WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
20144 					  i - BPF_REG_1, arg->arg_type);
20145 				ret = -EFAULT;
20146 				goto out;
20147 			}
20148 		}
20149 	} else {
20150 		/* if main BPF program has associated BTF info, validate that
20151 		 * it's matching expected signature, and otherwise mark BTF
20152 		 * info for main program as unreliable
20153 		 */
20154 		if (env->prog->aux->func_info_aux) {
20155 			ret = btf_prepare_func_args(env, 0);
20156 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
20157 				env->prog->aux->func_info_aux[0].unreliable = true;
20158 		}
20159 
20160 		/* 1st arg to a function */
20161 		regs[BPF_REG_1].type = PTR_TO_CTX;
20162 		mark_reg_known_zero(env, regs, BPF_REG_1);
20163 	}
20164 
20165 	ret = do_check(env);
20166 out:
20167 	/* check for NULL is necessary, since cur_state can be freed inside
20168 	 * do_check() under memory pressure.
20169 	 */
20170 	if (env->cur_state) {
20171 		free_verifier_state(env->cur_state, true);
20172 		env->cur_state = NULL;
20173 	}
20174 	while (!pop_stack(env, NULL, NULL, false));
20175 	if (!ret && pop_log)
20176 		bpf_vlog_reset(&env->log, 0);
20177 	free_states(env);
20178 	return ret;
20179 }
20180 
20181 /* Lazily verify all global functions based on their BTF, if they are called
20182  * from main BPF program or any of subprograms transitively.
20183  * BPF global subprogs called from dead code are not validated.
20184  * All callable global functions must pass verification.
20185  * Otherwise the whole program is rejected.
20186  * Consider:
20187  * int bar(int);
20188  * int foo(int f)
20189  * {
20190  *    return bar(f);
20191  * }
20192  * int bar(int b)
20193  * {
20194  *    ...
20195  * }
20196  * foo() will be verified first for R1=any_scalar_value. During verification it
20197  * will be assumed that bar() already verified successfully and call to bar()
20198  * from foo() will be checked for type match only. Later bar() will be verified
20199  * independently to check that it's safe for R1=any_scalar_value.
20200  */
20201 static int do_check_subprogs(struct bpf_verifier_env *env)
20202 {
20203 	struct bpf_prog_aux *aux = env->prog->aux;
20204 	struct bpf_func_info_aux *sub_aux;
20205 	int i, ret, new_cnt;
20206 
20207 	if (!aux->func_info)
20208 		return 0;
20209 
20210 	/* exception callback is presumed to be always called */
20211 	if (env->exception_callback_subprog)
20212 		subprog_aux(env, env->exception_callback_subprog)->called = true;
20213 
20214 again:
20215 	new_cnt = 0;
20216 	for (i = 1; i < env->subprog_cnt; i++) {
20217 		if (!subprog_is_global(env, i))
20218 			continue;
20219 
20220 		sub_aux = subprog_aux(env, i);
20221 		if (!sub_aux->called || sub_aux->verified)
20222 			continue;
20223 
20224 		env->insn_idx = env->subprog_info[i].start;
20225 		WARN_ON_ONCE(env->insn_idx == 0);
20226 		ret = do_check_common(env, i);
20227 		if (ret) {
20228 			return ret;
20229 		} else if (env->log.level & BPF_LOG_LEVEL) {
20230 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
20231 				i, subprog_name(env, i));
20232 		}
20233 
20234 		/* We verified new global subprog, it might have called some
20235 		 * more global subprogs that we haven't verified yet, so we
20236 		 * need to do another pass over subprogs to verify those.
20237 		 */
20238 		sub_aux->verified = true;
20239 		new_cnt++;
20240 	}
20241 
20242 	/* We can't loop forever as we verify at least one global subprog on
20243 	 * each pass.
20244 	 */
20245 	if (new_cnt)
20246 		goto again;
20247 
20248 	return 0;
20249 }
20250 
20251 static int do_check_main(struct bpf_verifier_env *env)
20252 {
20253 	int ret;
20254 
20255 	env->insn_idx = 0;
20256 	ret = do_check_common(env, 0);
20257 	if (!ret)
20258 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20259 	return ret;
20260 }
20261 
20262 
20263 static void print_verification_stats(struct bpf_verifier_env *env)
20264 {
20265 	int i;
20266 
20267 	if (env->log.level & BPF_LOG_STATS) {
20268 		verbose(env, "verification time %lld usec\n",
20269 			div_u64(env->verification_time, 1000));
20270 		verbose(env, "stack depth ");
20271 		for (i = 0; i < env->subprog_cnt; i++) {
20272 			u32 depth = env->subprog_info[i].stack_depth;
20273 
20274 			verbose(env, "%d", depth);
20275 			if (i + 1 < env->subprog_cnt)
20276 				verbose(env, "+");
20277 		}
20278 		verbose(env, "\n");
20279 	}
20280 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
20281 		"total_states %d peak_states %d mark_read %d\n",
20282 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
20283 		env->max_states_per_insn, env->total_states,
20284 		env->peak_states, env->longest_mark_read_walk);
20285 }
20286 
20287 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
20288 {
20289 	const struct btf_type *t, *func_proto;
20290 	const struct bpf_struct_ops_desc *st_ops_desc;
20291 	const struct bpf_struct_ops *st_ops;
20292 	const struct btf_member *member;
20293 	struct bpf_prog *prog = env->prog;
20294 	u32 btf_id, member_idx;
20295 	struct btf *btf;
20296 	const char *mname;
20297 
20298 	if (!prog->gpl_compatible) {
20299 		verbose(env, "struct ops programs must have a GPL compatible license\n");
20300 		return -EINVAL;
20301 	}
20302 
20303 	if (!prog->aux->attach_btf_id)
20304 		return -ENOTSUPP;
20305 
20306 	btf = prog->aux->attach_btf;
20307 	if (btf_is_module(btf)) {
20308 		/* Make sure st_ops is valid through the lifetime of env */
20309 		env->attach_btf_mod = btf_try_get_module(btf);
20310 		if (!env->attach_btf_mod) {
20311 			verbose(env, "struct_ops module %s is not found\n",
20312 				btf_get_name(btf));
20313 			return -ENOTSUPP;
20314 		}
20315 	}
20316 
20317 	btf_id = prog->aux->attach_btf_id;
20318 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
20319 	if (!st_ops_desc) {
20320 		verbose(env, "attach_btf_id %u is not a supported struct\n",
20321 			btf_id);
20322 		return -ENOTSUPP;
20323 	}
20324 	st_ops = st_ops_desc->st_ops;
20325 
20326 	t = st_ops_desc->type;
20327 	member_idx = prog->expected_attach_type;
20328 	if (member_idx >= btf_type_vlen(t)) {
20329 		verbose(env, "attach to invalid member idx %u of struct %s\n",
20330 			member_idx, st_ops->name);
20331 		return -EINVAL;
20332 	}
20333 
20334 	member = &btf_type_member(t)[member_idx];
20335 	mname = btf_name_by_offset(btf, member->name_off);
20336 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
20337 					       NULL);
20338 	if (!func_proto) {
20339 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
20340 			mname, member_idx, st_ops->name);
20341 		return -EINVAL;
20342 	}
20343 
20344 	if (st_ops->check_member) {
20345 		int err = st_ops->check_member(t, member, prog);
20346 
20347 		if (err) {
20348 			verbose(env, "attach to unsupported member %s of struct %s\n",
20349 				mname, st_ops->name);
20350 			return err;
20351 		}
20352 	}
20353 
20354 	prog->aux->attach_func_proto = func_proto;
20355 	prog->aux->attach_func_name = mname;
20356 	env->ops = st_ops->verifier_ops;
20357 
20358 	return 0;
20359 }
20360 #define SECURITY_PREFIX "security_"
20361 
20362 static int check_attach_modify_return(unsigned long addr, const char *func_name)
20363 {
20364 	if (within_error_injection_list(addr) ||
20365 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
20366 		return 0;
20367 
20368 	return -EINVAL;
20369 }
20370 
20371 /* list of non-sleepable functions that are otherwise on
20372  * ALLOW_ERROR_INJECTION list
20373  */
20374 BTF_SET_START(btf_non_sleepable_error_inject)
20375 /* Three functions below can be called from sleepable and non-sleepable context.
20376  * Assume non-sleepable from bpf safety point of view.
20377  */
20378 BTF_ID(func, __filemap_add_folio)
20379 BTF_ID(func, should_fail_alloc_page)
20380 BTF_ID(func, should_failslab)
20381 BTF_SET_END(btf_non_sleepable_error_inject)
20382 
20383 static int check_non_sleepable_error_inject(u32 btf_id)
20384 {
20385 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
20386 }
20387 
20388 int bpf_check_attach_target(struct bpf_verifier_log *log,
20389 			    const struct bpf_prog *prog,
20390 			    const struct bpf_prog *tgt_prog,
20391 			    u32 btf_id,
20392 			    struct bpf_attach_target_info *tgt_info)
20393 {
20394 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
20395 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
20396 	const char prefix[] = "btf_trace_";
20397 	int ret = 0, subprog = -1, i;
20398 	const struct btf_type *t;
20399 	bool conservative = true;
20400 	const char *tname;
20401 	struct btf *btf;
20402 	long addr = 0;
20403 	struct module *mod = NULL;
20404 
20405 	if (!btf_id) {
20406 		bpf_log(log, "Tracing programs must provide btf_id\n");
20407 		return -EINVAL;
20408 	}
20409 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
20410 	if (!btf) {
20411 		bpf_log(log,
20412 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
20413 		return -EINVAL;
20414 	}
20415 	t = btf_type_by_id(btf, btf_id);
20416 	if (!t) {
20417 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
20418 		return -EINVAL;
20419 	}
20420 	tname = btf_name_by_offset(btf, t->name_off);
20421 	if (!tname) {
20422 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
20423 		return -EINVAL;
20424 	}
20425 	if (tgt_prog) {
20426 		struct bpf_prog_aux *aux = tgt_prog->aux;
20427 
20428 		if (bpf_prog_is_dev_bound(prog->aux) &&
20429 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
20430 			bpf_log(log, "Target program bound device mismatch");
20431 			return -EINVAL;
20432 		}
20433 
20434 		for (i = 0; i < aux->func_info_cnt; i++)
20435 			if (aux->func_info[i].type_id == btf_id) {
20436 				subprog = i;
20437 				break;
20438 			}
20439 		if (subprog == -1) {
20440 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
20441 			return -EINVAL;
20442 		}
20443 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
20444 			bpf_log(log,
20445 				"%s programs cannot attach to exception callback\n",
20446 				prog_extension ? "Extension" : "FENTRY/FEXIT");
20447 			return -EINVAL;
20448 		}
20449 		conservative = aux->func_info_aux[subprog].unreliable;
20450 		if (prog_extension) {
20451 			if (conservative) {
20452 				bpf_log(log,
20453 					"Cannot replace static functions\n");
20454 				return -EINVAL;
20455 			}
20456 			if (!prog->jit_requested) {
20457 				bpf_log(log,
20458 					"Extension programs should be JITed\n");
20459 				return -EINVAL;
20460 			}
20461 		}
20462 		if (!tgt_prog->jited) {
20463 			bpf_log(log, "Can attach to only JITed progs\n");
20464 			return -EINVAL;
20465 		}
20466 		if (prog_tracing) {
20467 			if (aux->attach_tracing_prog) {
20468 				/*
20469 				 * Target program is an fentry/fexit which is already attached
20470 				 * to another tracing program. More levels of nesting
20471 				 * attachment are not allowed.
20472 				 */
20473 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
20474 				return -EINVAL;
20475 			}
20476 		} else if (tgt_prog->type == prog->type) {
20477 			/*
20478 			 * To avoid potential call chain cycles, prevent attaching of a
20479 			 * program extension to another extension. It's ok to attach
20480 			 * fentry/fexit to extension program.
20481 			 */
20482 			bpf_log(log, "Cannot recursively attach\n");
20483 			return -EINVAL;
20484 		}
20485 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
20486 		    prog_extension &&
20487 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
20488 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
20489 			/* Program extensions can extend all program types
20490 			 * except fentry/fexit. The reason is the following.
20491 			 * The fentry/fexit programs are used for performance
20492 			 * analysis, stats and can be attached to any program
20493 			 * type. When extension program is replacing XDP function
20494 			 * it is necessary to allow performance analysis of all
20495 			 * functions. Both original XDP program and its program
20496 			 * extension. Hence attaching fentry/fexit to
20497 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
20498 			 * fentry/fexit was allowed it would be possible to create
20499 			 * long call chain fentry->extension->fentry->extension
20500 			 * beyond reasonable stack size. Hence extending fentry
20501 			 * is not allowed.
20502 			 */
20503 			bpf_log(log, "Cannot extend fentry/fexit\n");
20504 			return -EINVAL;
20505 		}
20506 	} else {
20507 		if (prog_extension) {
20508 			bpf_log(log, "Cannot replace kernel functions\n");
20509 			return -EINVAL;
20510 		}
20511 	}
20512 
20513 	switch (prog->expected_attach_type) {
20514 	case BPF_TRACE_RAW_TP:
20515 		if (tgt_prog) {
20516 			bpf_log(log,
20517 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
20518 			return -EINVAL;
20519 		}
20520 		if (!btf_type_is_typedef(t)) {
20521 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
20522 				btf_id);
20523 			return -EINVAL;
20524 		}
20525 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
20526 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
20527 				btf_id, tname);
20528 			return -EINVAL;
20529 		}
20530 		tname += sizeof(prefix) - 1;
20531 		t = btf_type_by_id(btf, t->type);
20532 		if (!btf_type_is_ptr(t))
20533 			/* should never happen in valid vmlinux build */
20534 			return -EINVAL;
20535 		t = btf_type_by_id(btf, t->type);
20536 		if (!btf_type_is_func_proto(t))
20537 			/* should never happen in valid vmlinux build */
20538 			return -EINVAL;
20539 
20540 		break;
20541 	case BPF_TRACE_ITER:
20542 		if (!btf_type_is_func(t)) {
20543 			bpf_log(log, "attach_btf_id %u is not a function\n",
20544 				btf_id);
20545 			return -EINVAL;
20546 		}
20547 		t = btf_type_by_id(btf, t->type);
20548 		if (!btf_type_is_func_proto(t))
20549 			return -EINVAL;
20550 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20551 		if (ret)
20552 			return ret;
20553 		break;
20554 	default:
20555 		if (!prog_extension)
20556 			return -EINVAL;
20557 		fallthrough;
20558 	case BPF_MODIFY_RETURN:
20559 	case BPF_LSM_MAC:
20560 	case BPF_LSM_CGROUP:
20561 	case BPF_TRACE_FENTRY:
20562 	case BPF_TRACE_FEXIT:
20563 		if (!btf_type_is_func(t)) {
20564 			bpf_log(log, "attach_btf_id %u is not a function\n",
20565 				btf_id);
20566 			return -EINVAL;
20567 		}
20568 		if (prog_extension &&
20569 		    btf_check_type_match(log, prog, btf, t))
20570 			return -EINVAL;
20571 		t = btf_type_by_id(btf, t->type);
20572 		if (!btf_type_is_func_proto(t))
20573 			return -EINVAL;
20574 
20575 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
20576 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
20577 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
20578 			return -EINVAL;
20579 
20580 		if (tgt_prog && conservative)
20581 			t = NULL;
20582 
20583 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20584 		if (ret < 0)
20585 			return ret;
20586 
20587 		if (tgt_prog) {
20588 			if (subprog == 0)
20589 				addr = (long) tgt_prog->bpf_func;
20590 			else
20591 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20592 		} else {
20593 			if (btf_is_module(btf)) {
20594 				mod = btf_try_get_module(btf);
20595 				if (mod)
20596 					addr = find_kallsyms_symbol_value(mod, tname);
20597 				else
20598 					addr = 0;
20599 			} else {
20600 				addr = kallsyms_lookup_name(tname);
20601 			}
20602 			if (!addr) {
20603 				module_put(mod);
20604 				bpf_log(log,
20605 					"The address of function %s cannot be found\n",
20606 					tname);
20607 				return -ENOENT;
20608 			}
20609 		}
20610 
20611 		if (prog->aux->sleepable) {
20612 			ret = -EINVAL;
20613 			switch (prog->type) {
20614 			case BPF_PROG_TYPE_TRACING:
20615 
20616 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
20617 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20618 				 */
20619 				if (!check_non_sleepable_error_inject(btf_id) &&
20620 				    within_error_injection_list(addr))
20621 					ret = 0;
20622 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
20623 				 * in the fmodret id set with the KF_SLEEPABLE flag.
20624 				 */
20625 				else {
20626 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20627 										prog);
20628 
20629 					if (flags && (*flags & KF_SLEEPABLE))
20630 						ret = 0;
20631 				}
20632 				break;
20633 			case BPF_PROG_TYPE_LSM:
20634 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
20635 				 * Only some of them are sleepable.
20636 				 */
20637 				if (bpf_lsm_is_sleepable_hook(btf_id))
20638 					ret = 0;
20639 				break;
20640 			default:
20641 				break;
20642 			}
20643 			if (ret) {
20644 				module_put(mod);
20645 				bpf_log(log, "%s is not sleepable\n", tname);
20646 				return ret;
20647 			}
20648 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20649 			if (tgt_prog) {
20650 				module_put(mod);
20651 				bpf_log(log, "can't modify return codes of BPF programs\n");
20652 				return -EINVAL;
20653 			}
20654 			ret = -EINVAL;
20655 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20656 			    !check_attach_modify_return(addr, tname))
20657 				ret = 0;
20658 			if (ret) {
20659 				module_put(mod);
20660 				bpf_log(log, "%s() is not modifiable\n", tname);
20661 				return ret;
20662 			}
20663 		}
20664 
20665 		break;
20666 	}
20667 	tgt_info->tgt_addr = addr;
20668 	tgt_info->tgt_name = tname;
20669 	tgt_info->tgt_type = t;
20670 	tgt_info->tgt_mod = mod;
20671 	return 0;
20672 }
20673 
20674 BTF_SET_START(btf_id_deny)
20675 BTF_ID_UNUSED
20676 #ifdef CONFIG_SMP
20677 BTF_ID(func, migrate_disable)
20678 BTF_ID(func, migrate_enable)
20679 #endif
20680 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20681 BTF_ID(func, rcu_read_unlock_strict)
20682 #endif
20683 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20684 BTF_ID(func, preempt_count_add)
20685 BTF_ID(func, preempt_count_sub)
20686 #endif
20687 #ifdef CONFIG_PREEMPT_RCU
20688 BTF_ID(func, __rcu_read_lock)
20689 BTF_ID(func, __rcu_read_unlock)
20690 #endif
20691 BTF_SET_END(btf_id_deny)
20692 
20693 static bool can_be_sleepable(struct bpf_prog *prog)
20694 {
20695 	if (prog->type == BPF_PROG_TYPE_TRACING) {
20696 		switch (prog->expected_attach_type) {
20697 		case BPF_TRACE_FENTRY:
20698 		case BPF_TRACE_FEXIT:
20699 		case BPF_MODIFY_RETURN:
20700 		case BPF_TRACE_ITER:
20701 			return true;
20702 		default:
20703 			return false;
20704 		}
20705 	}
20706 	return prog->type == BPF_PROG_TYPE_LSM ||
20707 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20708 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20709 }
20710 
20711 static int check_attach_btf_id(struct bpf_verifier_env *env)
20712 {
20713 	struct bpf_prog *prog = env->prog;
20714 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20715 	struct bpf_attach_target_info tgt_info = {};
20716 	u32 btf_id = prog->aux->attach_btf_id;
20717 	struct bpf_trampoline *tr;
20718 	int ret;
20719 	u64 key;
20720 
20721 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20722 		if (prog->aux->sleepable)
20723 			/* attach_btf_id checked to be zero already */
20724 			return 0;
20725 		verbose(env, "Syscall programs can only be sleepable\n");
20726 		return -EINVAL;
20727 	}
20728 
20729 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20730 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20731 		return -EINVAL;
20732 	}
20733 
20734 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20735 		return check_struct_ops_btf_id(env);
20736 
20737 	if (prog->type != BPF_PROG_TYPE_TRACING &&
20738 	    prog->type != BPF_PROG_TYPE_LSM &&
20739 	    prog->type != BPF_PROG_TYPE_EXT)
20740 		return 0;
20741 
20742 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20743 	if (ret)
20744 		return ret;
20745 
20746 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20747 		/* to make freplace equivalent to their targets, they need to
20748 		 * inherit env->ops and expected_attach_type for the rest of the
20749 		 * verification
20750 		 */
20751 		env->ops = bpf_verifier_ops[tgt_prog->type];
20752 		prog->expected_attach_type = tgt_prog->expected_attach_type;
20753 	}
20754 
20755 	/* store info about the attachment target that will be used later */
20756 	prog->aux->attach_func_proto = tgt_info.tgt_type;
20757 	prog->aux->attach_func_name = tgt_info.tgt_name;
20758 	prog->aux->mod = tgt_info.tgt_mod;
20759 
20760 	if (tgt_prog) {
20761 		prog->aux->saved_dst_prog_type = tgt_prog->type;
20762 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20763 	}
20764 
20765 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20766 		prog->aux->attach_btf_trace = true;
20767 		return 0;
20768 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20769 		if (!bpf_iter_prog_supported(prog))
20770 			return -EINVAL;
20771 		return 0;
20772 	}
20773 
20774 	if (prog->type == BPF_PROG_TYPE_LSM) {
20775 		ret = bpf_lsm_verify_prog(&env->log, prog);
20776 		if (ret < 0)
20777 			return ret;
20778 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
20779 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
20780 		return -EINVAL;
20781 	}
20782 
20783 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20784 	tr = bpf_trampoline_get(key, &tgt_info);
20785 	if (!tr)
20786 		return -ENOMEM;
20787 
20788 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20789 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20790 
20791 	prog->aux->dst_trampoline = tr;
20792 	return 0;
20793 }
20794 
20795 struct btf *bpf_get_btf_vmlinux(void)
20796 {
20797 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20798 		mutex_lock(&bpf_verifier_lock);
20799 		if (!btf_vmlinux)
20800 			btf_vmlinux = btf_parse_vmlinux();
20801 		mutex_unlock(&bpf_verifier_lock);
20802 	}
20803 	return btf_vmlinux;
20804 }
20805 
20806 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20807 {
20808 	u64 start_time = ktime_get_ns();
20809 	struct bpf_verifier_env *env;
20810 	int i, len, ret = -EINVAL, err;
20811 	u32 log_true_size;
20812 	bool is_priv;
20813 
20814 	/* no program is valid */
20815 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20816 		return -EINVAL;
20817 
20818 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
20819 	 * allocate/free it every time bpf_check() is called
20820 	 */
20821 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20822 	if (!env)
20823 		return -ENOMEM;
20824 
20825 	env->bt.env = env;
20826 
20827 	len = (*prog)->len;
20828 	env->insn_aux_data =
20829 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20830 	ret = -ENOMEM;
20831 	if (!env->insn_aux_data)
20832 		goto err_free_env;
20833 	for (i = 0; i < len; i++)
20834 		env->insn_aux_data[i].orig_idx = i;
20835 	env->prog = *prog;
20836 	env->ops = bpf_verifier_ops[env->prog->type];
20837 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20838 
20839 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
20840 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
20841 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
20842 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
20843 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
20844 
20845 	bpf_get_btf_vmlinux();
20846 
20847 	/* grab the mutex to protect few globals used by verifier */
20848 	if (!is_priv)
20849 		mutex_lock(&bpf_verifier_lock);
20850 
20851 	/* user could have requested verbose verifier output
20852 	 * and supplied buffer to store the verification trace
20853 	 */
20854 	ret = bpf_vlog_init(&env->log, attr->log_level,
20855 			    (char __user *) (unsigned long) attr->log_buf,
20856 			    attr->log_size);
20857 	if (ret)
20858 		goto err_unlock;
20859 
20860 	mark_verifier_state_clean(env);
20861 
20862 	if (IS_ERR(btf_vmlinux)) {
20863 		/* Either gcc or pahole or kernel are broken. */
20864 		verbose(env, "in-kernel BTF is malformed\n");
20865 		ret = PTR_ERR(btf_vmlinux);
20866 		goto skip_full_check;
20867 	}
20868 
20869 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20870 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20871 		env->strict_alignment = true;
20872 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20873 		env->strict_alignment = false;
20874 
20875 	if (is_priv)
20876 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20877 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
20878 
20879 	env->explored_states = kvcalloc(state_htab_size(env),
20880 				       sizeof(struct bpf_verifier_state_list *),
20881 				       GFP_USER);
20882 	ret = -ENOMEM;
20883 	if (!env->explored_states)
20884 		goto skip_full_check;
20885 
20886 	ret = check_btf_info_early(env, attr, uattr);
20887 	if (ret < 0)
20888 		goto skip_full_check;
20889 
20890 	ret = add_subprog_and_kfunc(env);
20891 	if (ret < 0)
20892 		goto skip_full_check;
20893 
20894 	ret = check_subprogs(env);
20895 	if (ret < 0)
20896 		goto skip_full_check;
20897 
20898 	ret = check_btf_info(env, attr, uattr);
20899 	if (ret < 0)
20900 		goto skip_full_check;
20901 
20902 	ret = check_attach_btf_id(env);
20903 	if (ret)
20904 		goto skip_full_check;
20905 
20906 	ret = resolve_pseudo_ldimm64(env);
20907 	if (ret < 0)
20908 		goto skip_full_check;
20909 
20910 	if (bpf_prog_is_offloaded(env->prog->aux)) {
20911 		ret = bpf_prog_offload_verifier_prep(env->prog);
20912 		if (ret)
20913 			goto skip_full_check;
20914 	}
20915 
20916 	ret = check_cfg(env);
20917 	if (ret < 0)
20918 		goto skip_full_check;
20919 
20920 	ret = do_check_main(env);
20921 	ret = ret ?: do_check_subprogs(env);
20922 
20923 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20924 		ret = bpf_prog_offload_finalize(env);
20925 
20926 skip_full_check:
20927 	kvfree(env->explored_states);
20928 
20929 	if (ret == 0)
20930 		ret = check_max_stack_depth(env);
20931 
20932 	/* instruction rewrites happen after this point */
20933 	if (ret == 0)
20934 		ret = optimize_bpf_loop(env);
20935 
20936 	if (is_priv) {
20937 		if (ret == 0)
20938 			opt_hard_wire_dead_code_branches(env);
20939 		if (ret == 0)
20940 			ret = opt_remove_dead_code(env);
20941 		if (ret == 0)
20942 			ret = opt_remove_nops(env);
20943 	} else {
20944 		if (ret == 0)
20945 			sanitize_dead_code(env);
20946 	}
20947 
20948 	if (ret == 0)
20949 		/* program is valid, convert *(u32*)(ctx + off) accesses */
20950 		ret = convert_ctx_accesses(env);
20951 
20952 	if (ret == 0)
20953 		ret = do_misc_fixups(env);
20954 
20955 	/* do 32-bit optimization after insn patching has done so those patched
20956 	 * insns could be handled correctly.
20957 	 */
20958 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20959 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20960 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20961 								     : false;
20962 	}
20963 
20964 	if (ret == 0)
20965 		ret = fixup_call_args(env);
20966 
20967 	env->verification_time = ktime_get_ns() - start_time;
20968 	print_verification_stats(env);
20969 	env->prog->aux->verified_insns = env->insn_processed;
20970 
20971 	/* preserve original error even if log finalization is successful */
20972 	err = bpf_vlog_finalize(&env->log, &log_true_size);
20973 	if (err)
20974 		ret = err;
20975 
20976 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20977 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20978 				  &log_true_size, sizeof(log_true_size))) {
20979 		ret = -EFAULT;
20980 		goto err_release_maps;
20981 	}
20982 
20983 	if (ret)
20984 		goto err_release_maps;
20985 
20986 	if (env->used_map_cnt) {
20987 		/* if program passed verifier, update used_maps in bpf_prog_info */
20988 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20989 							  sizeof(env->used_maps[0]),
20990 							  GFP_KERNEL);
20991 
20992 		if (!env->prog->aux->used_maps) {
20993 			ret = -ENOMEM;
20994 			goto err_release_maps;
20995 		}
20996 
20997 		memcpy(env->prog->aux->used_maps, env->used_maps,
20998 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
20999 		env->prog->aux->used_map_cnt = env->used_map_cnt;
21000 	}
21001 	if (env->used_btf_cnt) {
21002 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
21003 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
21004 							  sizeof(env->used_btfs[0]),
21005 							  GFP_KERNEL);
21006 		if (!env->prog->aux->used_btfs) {
21007 			ret = -ENOMEM;
21008 			goto err_release_maps;
21009 		}
21010 
21011 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
21012 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
21013 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
21014 	}
21015 	if (env->used_map_cnt || env->used_btf_cnt) {
21016 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
21017 		 * bpf_ld_imm64 instructions
21018 		 */
21019 		convert_pseudo_ld_imm64(env);
21020 	}
21021 
21022 	adjust_btf_func(env);
21023 
21024 err_release_maps:
21025 	if (!env->prog->aux->used_maps)
21026 		/* if we didn't copy map pointers into bpf_prog_info, release
21027 		 * them now. Otherwise free_used_maps() will release them.
21028 		 */
21029 		release_maps(env);
21030 	if (!env->prog->aux->used_btfs)
21031 		release_btfs(env);
21032 
21033 	/* extension progs temporarily inherit the attach_type of their targets
21034 	   for verification purposes, so set it back to zero before returning
21035 	 */
21036 	if (env->prog->type == BPF_PROG_TYPE_EXT)
21037 		env->prog->expected_attach_type = 0;
21038 
21039 	*prog = env->prog;
21040 
21041 	module_put(env->attach_btf_mod);
21042 err_unlock:
21043 	if (!is_priv)
21044 		mutex_unlock(&bpf_verifier_lock);
21045 	vfree(env->insn_aux_data);
21046 err_free_env:
21047 	kfree(env);
21048 	return ret;
21049 }
21050