xref: /linux/kernel/bpf/verifier.c (revision 4b660dbd9ee2059850fd30e0df420ca7a38a1856)
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_async_callback_calling_insn(struct bpf_insn *insn)
532 {
533 	return bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm);
534 }
535 
536 static bool is_may_goto_insn(struct bpf_insn *insn)
537 {
538 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
539 }
540 
541 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
542 {
543 	return is_may_goto_insn(&env->prog->insnsi[insn_idx]);
544 }
545 
546 static bool is_storage_get_function(enum bpf_func_id func_id)
547 {
548 	return func_id == BPF_FUNC_sk_storage_get ||
549 	       func_id == BPF_FUNC_inode_storage_get ||
550 	       func_id == BPF_FUNC_task_storage_get ||
551 	       func_id == BPF_FUNC_cgrp_storage_get;
552 }
553 
554 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
555 					const struct bpf_map *map)
556 {
557 	int ref_obj_uses = 0;
558 
559 	if (is_ptr_cast_function(func_id))
560 		ref_obj_uses++;
561 	if (is_acquire_function(func_id, map))
562 		ref_obj_uses++;
563 	if (is_dynptr_ref_function(func_id))
564 		ref_obj_uses++;
565 
566 	return ref_obj_uses > 1;
567 }
568 
569 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
570 {
571 	return BPF_CLASS(insn->code) == BPF_STX &&
572 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
573 	       insn->imm == BPF_CMPXCHG;
574 }
575 
576 static int __get_spi(s32 off)
577 {
578 	return (-off - 1) / BPF_REG_SIZE;
579 }
580 
581 static struct bpf_func_state *func(struct bpf_verifier_env *env,
582 				   const struct bpf_reg_state *reg)
583 {
584 	struct bpf_verifier_state *cur = env->cur_state;
585 
586 	return cur->frame[reg->frameno];
587 }
588 
589 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
590 {
591        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
592 
593        /* We need to check that slots between [spi - nr_slots + 1, spi] are
594 	* within [0, allocated_stack).
595 	*
596 	* Please note that the spi grows downwards. For example, a dynptr
597 	* takes the size of two stack slots; the first slot will be at
598 	* spi and the second slot will be at spi - 1.
599 	*/
600        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
601 }
602 
603 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
604 			          const char *obj_kind, int nr_slots)
605 {
606 	int off, spi;
607 
608 	if (!tnum_is_const(reg->var_off)) {
609 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
610 		return -EINVAL;
611 	}
612 
613 	off = reg->off + reg->var_off.value;
614 	if (off % BPF_REG_SIZE) {
615 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
616 		return -EINVAL;
617 	}
618 
619 	spi = __get_spi(off);
620 	if (spi + 1 < nr_slots) {
621 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
622 		return -EINVAL;
623 	}
624 
625 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
626 		return -ERANGE;
627 	return spi;
628 }
629 
630 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
631 {
632 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
633 }
634 
635 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
636 {
637 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
638 }
639 
640 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
641 {
642 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
643 	case DYNPTR_TYPE_LOCAL:
644 		return BPF_DYNPTR_TYPE_LOCAL;
645 	case DYNPTR_TYPE_RINGBUF:
646 		return BPF_DYNPTR_TYPE_RINGBUF;
647 	case DYNPTR_TYPE_SKB:
648 		return BPF_DYNPTR_TYPE_SKB;
649 	case DYNPTR_TYPE_XDP:
650 		return BPF_DYNPTR_TYPE_XDP;
651 	default:
652 		return BPF_DYNPTR_TYPE_INVALID;
653 	}
654 }
655 
656 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
657 {
658 	switch (type) {
659 	case BPF_DYNPTR_TYPE_LOCAL:
660 		return DYNPTR_TYPE_LOCAL;
661 	case BPF_DYNPTR_TYPE_RINGBUF:
662 		return DYNPTR_TYPE_RINGBUF;
663 	case BPF_DYNPTR_TYPE_SKB:
664 		return DYNPTR_TYPE_SKB;
665 	case BPF_DYNPTR_TYPE_XDP:
666 		return DYNPTR_TYPE_XDP;
667 	default:
668 		return 0;
669 	}
670 }
671 
672 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
673 {
674 	return type == BPF_DYNPTR_TYPE_RINGBUF;
675 }
676 
677 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
678 			      enum bpf_dynptr_type type,
679 			      bool first_slot, int dynptr_id);
680 
681 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
682 				struct bpf_reg_state *reg);
683 
684 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
685 				   struct bpf_reg_state *sreg1,
686 				   struct bpf_reg_state *sreg2,
687 				   enum bpf_dynptr_type type)
688 {
689 	int id = ++env->id_gen;
690 
691 	__mark_dynptr_reg(sreg1, type, true, id);
692 	__mark_dynptr_reg(sreg2, type, false, id);
693 }
694 
695 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
696 			       struct bpf_reg_state *reg,
697 			       enum bpf_dynptr_type type)
698 {
699 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
700 }
701 
702 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
703 				        struct bpf_func_state *state, int spi);
704 
705 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
706 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
707 {
708 	struct bpf_func_state *state = func(env, reg);
709 	enum bpf_dynptr_type type;
710 	int spi, i, err;
711 
712 	spi = dynptr_get_spi(env, reg);
713 	if (spi < 0)
714 		return spi;
715 
716 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
717 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
718 	 * to ensure that for the following example:
719 	 *	[d1][d1][d2][d2]
720 	 * spi    3   2   1   0
721 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
722 	 * case they do belong to same dynptr, second call won't see slot_type
723 	 * as STACK_DYNPTR and will simply skip destruction.
724 	 */
725 	err = destroy_if_dynptr_stack_slot(env, state, spi);
726 	if (err)
727 		return err;
728 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
729 	if (err)
730 		return err;
731 
732 	for (i = 0; i < BPF_REG_SIZE; i++) {
733 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
734 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
735 	}
736 
737 	type = arg_to_dynptr_type(arg_type);
738 	if (type == BPF_DYNPTR_TYPE_INVALID)
739 		return -EINVAL;
740 
741 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
742 			       &state->stack[spi - 1].spilled_ptr, type);
743 
744 	if (dynptr_type_refcounted(type)) {
745 		/* The id is used to track proper releasing */
746 		int id;
747 
748 		if (clone_ref_obj_id)
749 			id = clone_ref_obj_id;
750 		else
751 			id = acquire_reference_state(env, insn_idx);
752 
753 		if (id < 0)
754 			return id;
755 
756 		state->stack[spi].spilled_ptr.ref_obj_id = id;
757 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
758 	}
759 
760 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
761 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
762 
763 	return 0;
764 }
765 
766 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
767 {
768 	int i;
769 
770 	for (i = 0; i < BPF_REG_SIZE; i++) {
771 		state->stack[spi].slot_type[i] = STACK_INVALID;
772 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
773 	}
774 
775 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
776 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
777 
778 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
779 	 *
780 	 * While we don't allow reading STACK_INVALID, it is still possible to
781 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
782 	 * helpers or insns can do partial read of that part without failing,
783 	 * but check_stack_range_initialized, check_stack_read_var_off, and
784 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
785 	 * the slot conservatively. Hence we need to prevent those liveness
786 	 * marking walks.
787 	 *
788 	 * This was not a problem before because STACK_INVALID is only set by
789 	 * default (where the default reg state has its reg->parent as NULL), or
790 	 * in clean_live_states after REG_LIVE_DONE (at which point
791 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
792 	 * verifier state exploration (like we did above). Hence, for our case
793 	 * parentage chain will still be live (i.e. reg->parent may be
794 	 * non-NULL), while earlier reg->parent was NULL, so we need
795 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
796 	 * done later on reads or by mark_dynptr_read as well to unnecessary
797 	 * mark registers in verifier state.
798 	 */
799 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
800 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
801 }
802 
803 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
804 {
805 	struct bpf_func_state *state = func(env, reg);
806 	int spi, ref_obj_id, i;
807 
808 	spi = dynptr_get_spi(env, reg);
809 	if (spi < 0)
810 		return spi;
811 
812 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
813 		invalidate_dynptr(env, state, spi);
814 		return 0;
815 	}
816 
817 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
818 
819 	/* If the dynptr has a ref_obj_id, then we need to invalidate
820 	 * two things:
821 	 *
822 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
823 	 * 2) Any slices derived from this dynptr.
824 	 */
825 
826 	/* Invalidate any slices associated with this dynptr */
827 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
828 
829 	/* Invalidate any dynptr clones */
830 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
831 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
832 			continue;
833 
834 		/* it should always be the case that if the ref obj id
835 		 * matches then the stack slot also belongs to a
836 		 * dynptr
837 		 */
838 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
839 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
840 			return -EFAULT;
841 		}
842 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
843 			invalidate_dynptr(env, state, i);
844 	}
845 
846 	return 0;
847 }
848 
849 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
850 			       struct bpf_reg_state *reg);
851 
852 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
853 {
854 	if (!env->allow_ptr_leaks)
855 		__mark_reg_not_init(env, reg);
856 	else
857 		__mark_reg_unknown(env, reg);
858 }
859 
860 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
861 				        struct bpf_func_state *state, int spi)
862 {
863 	struct bpf_func_state *fstate;
864 	struct bpf_reg_state *dreg;
865 	int i, dynptr_id;
866 
867 	/* We always ensure that STACK_DYNPTR is never set partially,
868 	 * hence just checking for slot_type[0] is enough. This is
869 	 * different for STACK_SPILL, where it may be only set for
870 	 * 1 byte, so code has to use is_spilled_reg.
871 	 */
872 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
873 		return 0;
874 
875 	/* Reposition spi to first slot */
876 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
877 		spi = spi + 1;
878 
879 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
880 		verbose(env, "cannot overwrite referenced dynptr\n");
881 		return -EINVAL;
882 	}
883 
884 	mark_stack_slot_scratched(env, spi);
885 	mark_stack_slot_scratched(env, spi - 1);
886 
887 	/* Writing partially to one dynptr stack slot destroys both. */
888 	for (i = 0; i < BPF_REG_SIZE; i++) {
889 		state->stack[spi].slot_type[i] = STACK_INVALID;
890 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
891 	}
892 
893 	dynptr_id = state->stack[spi].spilled_ptr.id;
894 	/* Invalidate any slices associated with this dynptr */
895 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
896 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
897 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
898 			continue;
899 		if (dreg->dynptr_id == dynptr_id)
900 			mark_reg_invalid(env, dreg);
901 	}));
902 
903 	/* Do not release reference state, we are destroying dynptr on stack,
904 	 * not using some helper to release it. Just reset register.
905 	 */
906 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
907 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
908 
909 	/* Same reason as unmark_stack_slots_dynptr above */
910 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
911 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
912 
913 	return 0;
914 }
915 
916 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
917 {
918 	int spi;
919 
920 	if (reg->type == CONST_PTR_TO_DYNPTR)
921 		return false;
922 
923 	spi = dynptr_get_spi(env, reg);
924 
925 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
926 	 * error because this just means the stack state hasn't been updated yet.
927 	 * We will do check_mem_access to check and update stack bounds later.
928 	 */
929 	if (spi < 0 && spi != -ERANGE)
930 		return false;
931 
932 	/* We don't need to check if the stack slots are marked by previous
933 	 * dynptr initializations because we allow overwriting existing unreferenced
934 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
935 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
936 	 * touching are completely destructed before we reinitialize them for a new
937 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
938 	 * instead of delaying it until the end where the user will get "Unreleased
939 	 * reference" error.
940 	 */
941 	return true;
942 }
943 
944 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
945 {
946 	struct bpf_func_state *state = func(env, reg);
947 	int i, spi;
948 
949 	/* This already represents first slot of initialized bpf_dynptr.
950 	 *
951 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
952 	 * check_func_arg_reg_off's logic, so we don't need to check its
953 	 * offset and alignment.
954 	 */
955 	if (reg->type == CONST_PTR_TO_DYNPTR)
956 		return true;
957 
958 	spi = dynptr_get_spi(env, reg);
959 	if (spi < 0)
960 		return false;
961 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
962 		return false;
963 
964 	for (i = 0; i < BPF_REG_SIZE; i++) {
965 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
966 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
967 			return false;
968 	}
969 
970 	return true;
971 }
972 
973 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
974 				    enum bpf_arg_type arg_type)
975 {
976 	struct bpf_func_state *state = func(env, reg);
977 	enum bpf_dynptr_type dynptr_type;
978 	int spi;
979 
980 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
981 	if (arg_type == ARG_PTR_TO_DYNPTR)
982 		return true;
983 
984 	dynptr_type = arg_to_dynptr_type(arg_type);
985 	if (reg->type == CONST_PTR_TO_DYNPTR) {
986 		return reg->dynptr.type == dynptr_type;
987 	} else {
988 		spi = dynptr_get_spi(env, reg);
989 		if (spi < 0)
990 			return false;
991 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
992 	}
993 }
994 
995 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
996 
997 static bool in_rcu_cs(struct bpf_verifier_env *env);
998 
999 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1000 
1001 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1002 				 struct bpf_kfunc_call_arg_meta *meta,
1003 				 struct bpf_reg_state *reg, int insn_idx,
1004 				 struct btf *btf, u32 btf_id, int nr_slots)
1005 {
1006 	struct bpf_func_state *state = func(env, reg);
1007 	int spi, i, j, id;
1008 
1009 	spi = iter_get_spi(env, reg, nr_slots);
1010 	if (spi < 0)
1011 		return spi;
1012 
1013 	id = acquire_reference_state(env, insn_idx);
1014 	if (id < 0)
1015 		return id;
1016 
1017 	for (i = 0; i < nr_slots; i++) {
1018 		struct bpf_stack_state *slot = &state->stack[spi - i];
1019 		struct bpf_reg_state *st = &slot->spilled_ptr;
1020 
1021 		__mark_reg_known_zero(st);
1022 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1023 		if (is_kfunc_rcu_protected(meta)) {
1024 			if (in_rcu_cs(env))
1025 				st->type |= MEM_RCU;
1026 			else
1027 				st->type |= PTR_UNTRUSTED;
1028 		}
1029 		st->live |= REG_LIVE_WRITTEN;
1030 		st->ref_obj_id = i == 0 ? id : 0;
1031 		st->iter.btf = btf;
1032 		st->iter.btf_id = btf_id;
1033 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1034 		st->iter.depth = 0;
1035 
1036 		for (j = 0; j < BPF_REG_SIZE; j++)
1037 			slot->slot_type[j] = STACK_ITER;
1038 
1039 		mark_stack_slot_scratched(env, spi - i);
1040 	}
1041 
1042 	return 0;
1043 }
1044 
1045 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1046 				   struct bpf_reg_state *reg, int nr_slots)
1047 {
1048 	struct bpf_func_state *state = func(env, reg);
1049 	int spi, i, j;
1050 
1051 	spi = iter_get_spi(env, reg, nr_slots);
1052 	if (spi < 0)
1053 		return spi;
1054 
1055 	for (i = 0; i < nr_slots; i++) {
1056 		struct bpf_stack_state *slot = &state->stack[spi - i];
1057 		struct bpf_reg_state *st = &slot->spilled_ptr;
1058 
1059 		if (i == 0)
1060 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1061 
1062 		__mark_reg_not_init(env, st);
1063 
1064 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1065 		st->live |= REG_LIVE_WRITTEN;
1066 
1067 		for (j = 0; j < BPF_REG_SIZE; j++)
1068 			slot->slot_type[j] = STACK_INVALID;
1069 
1070 		mark_stack_slot_scratched(env, spi - i);
1071 	}
1072 
1073 	return 0;
1074 }
1075 
1076 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1077 				     struct bpf_reg_state *reg, int nr_slots)
1078 {
1079 	struct bpf_func_state *state = func(env, reg);
1080 	int spi, i, j;
1081 
1082 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1083 	 * will do check_mem_access to check and update stack bounds later, so
1084 	 * return true for that case.
1085 	 */
1086 	spi = iter_get_spi(env, reg, nr_slots);
1087 	if (spi == -ERANGE)
1088 		return true;
1089 	if (spi < 0)
1090 		return false;
1091 
1092 	for (i = 0; i < nr_slots; i++) {
1093 		struct bpf_stack_state *slot = &state->stack[spi - i];
1094 
1095 		for (j = 0; j < BPF_REG_SIZE; j++)
1096 			if (slot->slot_type[j] == STACK_ITER)
1097 				return false;
1098 	}
1099 
1100 	return true;
1101 }
1102 
1103 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1104 				   struct btf *btf, u32 btf_id, int nr_slots)
1105 {
1106 	struct bpf_func_state *state = func(env, reg);
1107 	int spi, i, j;
1108 
1109 	spi = iter_get_spi(env, reg, nr_slots);
1110 	if (spi < 0)
1111 		return -EINVAL;
1112 
1113 	for (i = 0; i < nr_slots; i++) {
1114 		struct bpf_stack_state *slot = &state->stack[spi - i];
1115 		struct bpf_reg_state *st = &slot->spilled_ptr;
1116 
1117 		if (st->type & PTR_UNTRUSTED)
1118 			return -EPROTO;
1119 		/* only main (first) slot has ref_obj_id set */
1120 		if (i == 0 && !st->ref_obj_id)
1121 			return -EINVAL;
1122 		if (i != 0 && st->ref_obj_id)
1123 			return -EINVAL;
1124 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1125 			return -EINVAL;
1126 
1127 		for (j = 0; j < BPF_REG_SIZE; j++)
1128 			if (slot->slot_type[j] != STACK_ITER)
1129 				return -EINVAL;
1130 	}
1131 
1132 	return 0;
1133 }
1134 
1135 /* Check if given stack slot is "special":
1136  *   - spilled register state (STACK_SPILL);
1137  *   - dynptr state (STACK_DYNPTR);
1138  *   - iter state (STACK_ITER).
1139  */
1140 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1141 {
1142 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1143 
1144 	switch (type) {
1145 	case STACK_SPILL:
1146 	case STACK_DYNPTR:
1147 	case STACK_ITER:
1148 		return true;
1149 	case STACK_INVALID:
1150 	case STACK_MISC:
1151 	case STACK_ZERO:
1152 		return false;
1153 	default:
1154 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1155 		return true;
1156 	}
1157 }
1158 
1159 /* The reg state of a pointer or a bounded scalar was saved when
1160  * it was spilled to the stack.
1161  */
1162 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1163 {
1164 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1165 }
1166 
1167 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1168 {
1169 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1170 	       stack->spilled_ptr.type == SCALAR_VALUE;
1171 }
1172 
1173 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1174 {
1175 	return stack->slot_type[0] == STACK_SPILL &&
1176 	       stack->spilled_ptr.type == SCALAR_VALUE;
1177 }
1178 
1179 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1180  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1181  * more precise STACK_ZERO.
1182  * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take
1183  * env->allow_ptr_leaks into account and force STACK_MISC, if necessary.
1184  */
1185 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1186 {
1187 	if (*stype == STACK_ZERO)
1188 		return;
1189 	if (env->allow_ptr_leaks && *stype == STACK_INVALID)
1190 		return;
1191 	*stype = STACK_MISC;
1192 }
1193 
1194 static void scrub_spilled_slot(u8 *stype)
1195 {
1196 	if (*stype != STACK_INVALID)
1197 		*stype = STACK_MISC;
1198 }
1199 
1200 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1201  * small to hold src. This is different from krealloc since we don't want to preserve
1202  * the contents of dst.
1203  *
1204  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1205  * not be allocated.
1206  */
1207 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1208 {
1209 	size_t alloc_bytes;
1210 	void *orig = dst;
1211 	size_t bytes;
1212 
1213 	if (ZERO_OR_NULL_PTR(src))
1214 		goto out;
1215 
1216 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1217 		return NULL;
1218 
1219 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1220 	dst = krealloc(orig, alloc_bytes, flags);
1221 	if (!dst) {
1222 		kfree(orig);
1223 		return NULL;
1224 	}
1225 
1226 	memcpy(dst, src, bytes);
1227 out:
1228 	return dst ? dst : ZERO_SIZE_PTR;
1229 }
1230 
1231 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1232  * small to hold new_n items. new items are zeroed out if the array grows.
1233  *
1234  * Contrary to krealloc_array, does not free arr if new_n is zero.
1235  */
1236 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1237 {
1238 	size_t alloc_size;
1239 	void *new_arr;
1240 
1241 	if (!new_n || old_n == new_n)
1242 		goto out;
1243 
1244 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1245 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1246 	if (!new_arr) {
1247 		kfree(arr);
1248 		return NULL;
1249 	}
1250 	arr = new_arr;
1251 
1252 	if (new_n > old_n)
1253 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1254 
1255 out:
1256 	return arr ? arr : ZERO_SIZE_PTR;
1257 }
1258 
1259 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1260 {
1261 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1262 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1263 	if (!dst->refs)
1264 		return -ENOMEM;
1265 
1266 	dst->acquired_refs = src->acquired_refs;
1267 	return 0;
1268 }
1269 
1270 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1271 {
1272 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1273 
1274 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1275 				GFP_KERNEL);
1276 	if (!dst->stack)
1277 		return -ENOMEM;
1278 
1279 	dst->allocated_stack = src->allocated_stack;
1280 	return 0;
1281 }
1282 
1283 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1284 {
1285 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1286 				    sizeof(struct bpf_reference_state));
1287 	if (!state->refs)
1288 		return -ENOMEM;
1289 
1290 	state->acquired_refs = n;
1291 	return 0;
1292 }
1293 
1294 /* Possibly update state->allocated_stack to be at least size bytes. Also
1295  * possibly update the function's high-water mark in its bpf_subprog_info.
1296  */
1297 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1298 {
1299 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1300 
1301 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1302 	size = round_up(size, BPF_REG_SIZE);
1303 	n = size / BPF_REG_SIZE;
1304 
1305 	if (old_n >= n)
1306 		return 0;
1307 
1308 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1309 	if (!state->stack)
1310 		return -ENOMEM;
1311 
1312 	state->allocated_stack = size;
1313 
1314 	/* update known max for given subprogram */
1315 	if (env->subprog_info[state->subprogno].stack_depth < size)
1316 		env->subprog_info[state->subprogno].stack_depth = size;
1317 
1318 	return 0;
1319 }
1320 
1321 /* Acquire a pointer id from the env and update the state->refs to include
1322  * this new pointer reference.
1323  * On success, returns a valid pointer id to associate with the register
1324  * On failure, returns a negative errno.
1325  */
1326 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1327 {
1328 	struct bpf_func_state *state = cur_func(env);
1329 	int new_ofs = state->acquired_refs;
1330 	int id, err;
1331 
1332 	err = resize_reference_state(state, state->acquired_refs + 1);
1333 	if (err)
1334 		return err;
1335 	id = ++env->id_gen;
1336 	state->refs[new_ofs].id = id;
1337 	state->refs[new_ofs].insn_idx = insn_idx;
1338 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1339 
1340 	return id;
1341 }
1342 
1343 /* release function corresponding to acquire_reference_state(). Idempotent. */
1344 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1345 {
1346 	int i, last_idx;
1347 
1348 	last_idx = state->acquired_refs - 1;
1349 	for (i = 0; i < state->acquired_refs; i++) {
1350 		if (state->refs[i].id == ptr_id) {
1351 			/* Cannot release caller references in callbacks */
1352 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1353 				return -EINVAL;
1354 			if (last_idx && i != last_idx)
1355 				memcpy(&state->refs[i], &state->refs[last_idx],
1356 				       sizeof(*state->refs));
1357 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1358 			state->acquired_refs--;
1359 			return 0;
1360 		}
1361 	}
1362 	return -EINVAL;
1363 }
1364 
1365 static void free_func_state(struct bpf_func_state *state)
1366 {
1367 	if (!state)
1368 		return;
1369 	kfree(state->refs);
1370 	kfree(state->stack);
1371 	kfree(state);
1372 }
1373 
1374 static void clear_jmp_history(struct bpf_verifier_state *state)
1375 {
1376 	kfree(state->jmp_history);
1377 	state->jmp_history = NULL;
1378 	state->jmp_history_cnt = 0;
1379 }
1380 
1381 static void free_verifier_state(struct bpf_verifier_state *state,
1382 				bool free_self)
1383 {
1384 	int i;
1385 
1386 	for (i = 0; i <= state->curframe; i++) {
1387 		free_func_state(state->frame[i]);
1388 		state->frame[i] = NULL;
1389 	}
1390 	clear_jmp_history(state);
1391 	if (free_self)
1392 		kfree(state);
1393 }
1394 
1395 /* copy verifier state from src to dst growing dst stack space
1396  * when necessary to accommodate larger src stack
1397  */
1398 static int copy_func_state(struct bpf_func_state *dst,
1399 			   const struct bpf_func_state *src)
1400 {
1401 	int err;
1402 
1403 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1404 	err = copy_reference_state(dst, src);
1405 	if (err)
1406 		return err;
1407 	return copy_stack_state(dst, src);
1408 }
1409 
1410 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1411 			       const struct bpf_verifier_state *src)
1412 {
1413 	struct bpf_func_state *dst;
1414 	int i, err;
1415 
1416 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1417 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1418 					  GFP_USER);
1419 	if (!dst_state->jmp_history)
1420 		return -ENOMEM;
1421 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1422 
1423 	/* if dst has more stack frames then src frame, free them, this is also
1424 	 * necessary in case of exceptional exits using bpf_throw.
1425 	 */
1426 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1427 		free_func_state(dst_state->frame[i]);
1428 		dst_state->frame[i] = NULL;
1429 	}
1430 	dst_state->speculative = src->speculative;
1431 	dst_state->active_rcu_lock = src->active_rcu_lock;
1432 	dst_state->curframe = src->curframe;
1433 	dst_state->active_lock.ptr = src->active_lock.ptr;
1434 	dst_state->active_lock.id = src->active_lock.id;
1435 	dst_state->branches = src->branches;
1436 	dst_state->parent = src->parent;
1437 	dst_state->first_insn_idx = src->first_insn_idx;
1438 	dst_state->last_insn_idx = src->last_insn_idx;
1439 	dst_state->dfs_depth = src->dfs_depth;
1440 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1441 	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1442 	dst_state->may_goto_depth = src->may_goto_depth;
1443 	for (i = 0; i <= src->curframe; i++) {
1444 		dst = dst_state->frame[i];
1445 		if (!dst) {
1446 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1447 			if (!dst)
1448 				return -ENOMEM;
1449 			dst_state->frame[i] = dst;
1450 		}
1451 		err = copy_func_state(dst, src->frame[i]);
1452 		if (err)
1453 			return err;
1454 	}
1455 	return 0;
1456 }
1457 
1458 static u32 state_htab_size(struct bpf_verifier_env *env)
1459 {
1460 	return env->prog->len;
1461 }
1462 
1463 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1464 {
1465 	struct bpf_verifier_state *cur = env->cur_state;
1466 	struct bpf_func_state *state = cur->frame[cur->curframe];
1467 
1468 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1469 }
1470 
1471 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1472 {
1473 	int fr;
1474 
1475 	if (a->curframe != b->curframe)
1476 		return false;
1477 
1478 	for (fr = a->curframe; fr >= 0; fr--)
1479 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1480 			return false;
1481 
1482 	return true;
1483 }
1484 
1485 /* Open coded iterators allow back-edges in the state graph in order to
1486  * check unbounded loops that iterators.
1487  *
1488  * In is_state_visited() it is necessary to know if explored states are
1489  * part of some loops in order to decide whether non-exact states
1490  * comparison could be used:
1491  * - non-exact states comparison establishes sub-state relation and uses
1492  *   read and precision marks to do so, these marks are propagated from
1493  *   children states and thus are not guaranteed to be final in a loop;
1494  * - exact states comparison just checks if current and explored states
1495  *   are identical (and thus form a back-edge).
1496  *
1497  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1498  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1499  * algorithm for loop structure detection and gives an overview of
1500  * relevant terminology. It also has helpful illustrations.
1501  *
1502  * [1] https://api.semanticscholar.org/CorpusID:15784067
1503  *
1504  * We use a similar algorithm but because loop nested structure is
1505  * irrelevant for verifier ours is significantly simpler and resembles
1506  * strongly connected components algorithm from Sedgewick's textbook.
1507  *
1508  * Define topmost loop entry as a first node of the loop traversed in a
1509  * depth first search starting from initial state. The goal of the loop
1510  * tracking algorithm is to associate topmost loop entries with states
1511  * derived from these entries.
1512  *
1513  * For each step in the DFS states traversal algorithm needs to identify
1514  * the following situations:
1515  *
1516  *          initial                     initial                   initial
1517  *            |                           |                         |
1518  *            V                           V                         V
1519  *           ...                         ...           .---------> hdr
1520  *            |                           |            |            |
1521  *            V                           V            |            V
1522  *           cur                     .-> succ          |    .------...
1523  *            |                      |    |            |    |       |
1524  *            V                      |    V            |    V       V
1525  *           succ                    '-- cur           |   ...     ...
1526  *                                                     |    |       |
1527  *                                                     |    V       V
1528  *                                                     |   succ <- cur
1529  *                                                     |    |
1530  *                                                     |    V
1531  *                                                     |   ...
1532  *                                                     |    |
1533  *                                                     '----'
1534  *
1535  *  (A) successor state of cur   (B) successor state of cur or it's entry
1536  *      not yet traversed            are in current DFS path, thus cur and succ
1537  *                                   are members of the same outermost loop
1538  *
1539  *                      initial                  initial
1540  *                        |                        |
1541  *                        V                        V
1542  *                       ...                      ...
1543  *                        |                        |
1544  *                        V                        V
1545  *                .------...               .------...
1546  *                |       |                |       |
1547  *                V       V                V       V
1548  *           .-> hdr     ...              ...     ...
1549  *           |    |       |                |       |
1550  *           |    V       V                V       V
1551  *           |   succ <- cur              succ <- cur
1552  *           |    |                        |
1553  *           |    V                        V
1554  *           |   ...                      ...
1555  *           |    |                        |
1556  *           '----'                       exit
1557  *
1558  * (C) successor state of cur is a part of some loop but this loop
1559  *     does not include cur or successor state is not in a loop at all.
1560  *
1561  * Algorithm could be described as the following python code:
1562  *
1563  *     traversed = set()   # Set of traversed nodes
1564  *     entries = {}        # Mapping from node to loop entry
1565  *     depths = {}         # Depth level assigned to graph node
1566  *     path = set()        # Current DFS path
1567  *
1568  *     # Find outermost loop entry known for n
1569  *     def get_loop_entry(n):
1570  *         h = entries.get(n, None)
1571  *         while h in entries and entries[h] != h:
1572  *             h = entries[h]
1573  *         return h
1574  *
1575  *     # Update n's loop entry if h's outermost entry comes
1576  *     # before n's outermost entry in current DFS path.
1577  *     def update_loop_entry(n, h):
1578  *         n1 = get_loop_entry(n) or n
1579  *         h1 = get_loop_entry(h) or h
1580  *         if h1 in path and depths[h1] <= depths[n1]:
1581  *             entries[n] = h1
1582  *
1583  *     def dfs(n, depth):
1584  *         traversed.add(n)
1585  *         path.add(n)
1586  *         depths[n] = depth
1587  *         for succ in G.successors(n):
1588  *             if succ not in traversed:
1589  *                 # Case A: explore succ and update cur's loop entry
1590  *                 #         only if succ's entry is in current DFS path.
1591  *                 dfs(succ, depth + 1)
1592  *                 h = get_loop_entry(succ)
1593  *                 update_loop_entry(n, h)
1594  *             else:
1595  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1596  *                 update_loop_entry(n, succ)
1597  *         path.remove(n)
1598  *
1599  * To adapt this algorithm for use with verifier:
1600  * - use st->branch == 0 as a signal that DFS of succ had been finished
1601  *   and cur's loop entry has to be updated (case A), handle this in
1602  *   update_branch_counts();
1603  * - use st->branch > 0 as a signal that st is in the current DFS path;
1604  * - handle cases B and C in is_state_visited();
1605  * - update topmost loop entry for intermediate states in get_loop_entry().
1606  */
1607 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1608 {
1609 	struct bpf_verifier_state *topmost = st->loop_entry, *old;
1610 
1611 	while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1612 		topmost = topmost->loop_entry;
1613 	/* Update loop entries for intermediate states to avoid this
1614 	 * traversal in future get_loop_entry() calls.
1615 	 */
1616 	while (st && st->loop_entry != topmost) {
1617 		old = st->loop_entry;
1618 		st->loop_entry = topmost;
1619 		st = old;
1620 	}
1621 	return topmost;
1622 }
1623 
1624 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1625 {
1626 	struct bpf_verifier_state *cur1, *hdr1;
1627 
1628 	cur1 = get_loop_entry(cur) ?: cur;
1629 	hdr1 = get_loop_entry(hdr) ?: hdr;
1630 	/* The head1->branches check decides between cases B and C in
1631 	 * comment for get_loop_entry(). If hdr1->branches == 0 then
1632 	 * head's topmost loop entry is not in current DFS path,
1633 	 * hence 'cur' and 'hdr' are not in the same loop and there is
1634 	 * no need to update cur->loop_entry.
1635 	 */
1636 	if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1637 		cur->loop_entry = hdr;
1638 		hdr->used_as_loop_entry = true;
1639 	}
1640 }
1641 
1642 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1643 {
1644 	while (st) {
1645 		u32 br = --st->branches;
1646 
1647 		/* br == 0 signals that DFS exploration for 'st' is finished,
1648 		 * thus it is necessary to update parent's loop entry if it
1649 		 * turned out that st is a part of some loop.
1650 		 * This is a part of 'case A' in get_loop_entry() comment.
1651 		 */
1652 		if (br == 0 && st->parent && st->loop_entry)
1653 			update_loop_entry(st->parent, st->loop_entry);
1654 
1655 		/* WARN_ON(br > 1) technically makes sense here,
1656 		 * but see comment in push_stack(), hence:
1657 		 */
1658 		WARN_ONCE((int)br < 0,
1659 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1660 			  br);
1661 		if (br)
1662 			break;
1663 		st = st->parent;
1664 	}
1665 }
1666 
1667 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1668 		     int *insn_idx, bool pop_log)
1669 {
1670 	struct bpf_verifier_state *cur = env->cur_state;
1671 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1672 	int err;
1673 
1674 	if (env->head == NULL)
1675 		return -ENOENT;
1676 
1677 	if (cur) {
1678 		err = copy_verifier_state(cur, &head->st);
1679 		if (err)
1680 			return err;
1681 	}
1682 	if (pop_log)
1683 		bpf_vlog_reset(&env->log, head->log_pos);
1684 	if (insn_idx)
1685 		*insn_idx = head->insn_idx;
1686 	if (prev_insn_idx)
1687 		*prev_insn_idx = head->prev_insn_idx;
1688 	elem = head->next;
1689 	free_verifier_state(&head->st, false);
1690 	kfree(head);
1691 	env->head = elem;
1692 	env->stack_size--;
1693 	return 0;
1694 }
1695 
1696 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1697 					     int insn_idx, int prev_insn_idx,
1698 					     bool speculative)
1699 {
1700 	struct bpf_verifier_state *cur = env->cur_state;
1701 	struct bpf_verifier_stack_elem *elem;
1702 	int err;
1703 
1704 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1705 	if (!elem)
1706 		goto err;
1707 
1708 	elem->insn_idx = insn_idx;
1709 	elem->prev_insn_idx = prev_insn_idx;
1710 	elem->next = env->head;
1711 	elem->log_pos = env->log.end_pos;
1712 	env->head = elem;
1713 	env->stack_size++;
1714 	err = copy_verifier_state(&elem->st, cur);
1715 	if (err)
1716 		goto err;
1717 	elem->st.speculative |= speculative;
1718 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1719 		verbose(env, "The sequence of %d jumps is too complex.\n",
1720 			env->stack_size);
1721 		goto err;
1722 	}
1723 	if (elem->st.parent) {
1724 		++elem->st.parent->branches;
1725 		/* WARN_ON(branches > 2) technically makes sense here,
1726 		 * but
1727 		 * 1. speculative states will bump 'branches' for non-branch
1728 		 * instructions
1729 		 * 2. is_state_visited() heuristics may decide not to create
1730 		 * a new state for a sequence of branches and all such current
1731 		 * and cloned states will be pointing to a single parent state
1732 		 * which might have large 'branches' count.
1733 		 */
1734 	}
1735 	return &elem->st;
1736 err:
1737 	free_verifier_state(env->cur_state, true);
1738 	env->cur_state = NULL;
1739 	/* pop all elements and return */
1740 	while (!pop_stack(env, NULL, NULL, false));
1741 	return NULL;
1742 }
1743 
1744 #define CALLER_SAVED_REGS 6
1745 static const int caller_saved[CALLER_SAVED_REGS] = {
1746 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1747 };
1748 
1749 /* This helper doesn't clear reg->id */
1750 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1751 {
1752 	reg->var_off = tnum_const(imm);
1753 	reg->smin_value = (s64)imm;
1754 	reg->smax_value = (s64)imm;
1755 	reg->umin_value = imm;
1756 	reg->umax_value = imm;
1757 
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 unknown part of a register (variable offset or scalar value) as
1765  * known to have the value @imm.
1766  */
1767 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1768 {
1769 	/* Clear off and union(map_ptr, range) */
1770 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1771 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1772 	reg->id = 0;
1773 	reg->ref_obj_id = 0;
1774 	___mark_reg_known(reg, imm);
1775 }
1776 
1777 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1778 {
1779 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1780 	reg->s32_min_value = (s32)imm;
1781 	reg->s32_max_value = (s32)imm;
1782 	reg->u32_min_value = (u32)imm;
1783 	reg->u32_max_value = (u32)imm;
1784 }
1785 
1786 /* Mark the 'variable offset' part of a register as zero.  This should be
1787  * used only on registers holding a pointer type.
1788  */
1789 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1790 {
1791 	__mark_reg_known(reg, 0);
1792 }
1793 
1794 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1795 {
1796 	__mark_reg_known(reg, 0);
1797 	reg->type = SCALAR_VALUE;
1798 	/* all scalars are assumed imprecise initially (unless unprivileged,
1799 	 * in which case everything is forced to be precise)
1800 	 */
1801 	reg->precise = !env->bpf_capable;
1802 }
1803 
1804 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1805 				struct bpf_reg_state *regs, u32 regno)
1806 {
1807 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1808 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1809 		/* Something bad happened, let's kill all regs */
1810 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1811 			__mark_reg_not_init(env, regs + regno);
1812 		return;
1813 	}
1814 	__mark_reg_known_zero(regs + regno);
1815 }
1816 
1817 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1818 			      bool first_slot, int dynptr_id)
1819 {
1820 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1821 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1822 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1823 	 */
1824 	__mark_reg_known_zero(reg);
1825 	reg->type = CONST_PTR_TO_DYNPTR;
1826 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1827 	reg->id = dynptr_id;
1828 	reg->dynptr.type = type;
1829 	reg->dynptr.first_slot = first_slot;
1830 }
1831 
1832 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1833 {
1834 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1835 		const struct bpf_map *map = reg->map_ptr;
1836 
1837 		if (map->inner_map_meta) {
1838 			reg->type = CONST_PTR_TO_MAP;
1839 			reg->map_ptr = map->inner_map_meta;
1840 			/* transfer reg's id which is unique for every map_lookup_elem
1841 			 * as UID of the inner map.
1842 			 */
1843 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1844 				reg->map_uid = reg->id;
1845 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1846 			reg->type = PTR_TO_XDP_SOCK;
1847 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1848 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1849 			reg->type = PTR_TO_SOCKET;
1850 		} else {
1851 			reg->type = PTR_TO_MAP_VALUE;
1852 		}
1853 		return;
1854 	}
1855 
1856 	reg->type &= ~PTR_MAYBE_NULL;
1857 }
1858 
1859 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1860 				struct btf_field_graph_root *ds_head)
1861 {
1862 	__mark_reg_known_zero(&regs[regno]);
1863 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1864 	regs[regno].btf = ds_head->btf;
1865 	regs[regno].btf_id = ds_head->value_btf_id;
1866 	regs[regno].off = ds_head->node_offset;
1867 }
1868 
1869 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1870 {
1871 	return type_is_pkt_pointer(reg->type);
1872 }
1873 
1874 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1875 {
1876 	return reg_is_pkt_pointer(reg) ||
1877 	       reg->type == PTR_TO_PACKET_END;
1878 }
1879 
1880 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1881 {
1882 	return base_type(reg->type) == PTR_TO_MEM &&
1883 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1884 }
1885 
1886 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1887 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1888 				    enum bpf_reg_type which)
1889 {
1890 	/* The register can already have a range from prior markings.
1891 	 * This is fine as long as it hasn't been advanced from its
1892 	 * origin.
1893 	 */
1894 	return reg->type == which &&
1895 	       reg->id == 0 &&
1896 	       reg->off == 0 &&
1897 	       tnum_equals_const(reg->var_off, 0);
1898 }
1899 
1900 /* Reset the min/max bounds of a register */
1901 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1902 {
1903 	reg->smin_value = S64_MIN;
1904 	reg->smax_value = S64_MAX;
1905 	reg->umin_value = 0;
1906 	reg->umax_value = U64_MAX;
1907 
1908 	reg->s32_min_value = S32_MIN;
1909 	reg->s32_max_value = S32_MAX;
1910 	reg->u32_min_value = 0;
1911 	reg->u32_max_value = U32_MAX;
1912 }
1913 
1914 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1915 {
1916 	reg->smin_value = S64_MIN;
1917 	reg->smax_value = S64_MAX;
1918 	reg->umin_value = 0;
1919 	reg->umax_value = U64_MAX;
1920 }
1921 
1922 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1923 {
1924 	reg->s32_min_value = S32_MIN;
1925 	reg->s32_max_value = S32_MAX;
1926 	reg->u32_min_value = 0;
1927 	reg->u32_max_value = U32_MAX;
1928 }
1929 
1930 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1931 {
1932 	struct tnum var32_off = tnum_subreg(reg->var_off);
1933 
1934 	/* min signed is max(sign bit) | min(other bits) */
1935 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1936 			var32_off.value | (var32_off.mask & S32_MIN));
1937 	/* max signed is min(sign bit) | max(other bits) */
1938 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1939 			var32_off.value | (var32_off.mask & S32_MAX));
1940 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1941 	reg->u32_max_value = min(reg->u32_max_value,
1942 				 (u32)(var32_off.value | var32_off.mask));
1943 }
1944 
1945 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1946 {
1947 	/* min signed is max(sign bit) | min(other bits) */
1948 	reg->smin_value = max_t(s64, reg->smin_value,
1949 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1950 	/* max signed is min(sign bit) | max(other bits) */
1951 	reg->smax_value = min_t(s64, reg->smax_value,
1952 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1953 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1954 	reg->umax_value = min(reg->umax_value,
1955 			      reg->var_off.value | reg->var_off.mask);
1956 }
1957 
1958 static void __update_reg_bounds(struct bpf_reg_state *reg)
1959 {
1960 	__update_reg32_bounds(reg);
1961 	__update_reg64_bounds(reg);
1962 }
1963 
1964 /* Uses signed min/max values to inform unsigned, and vice-versa */
1965 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1966 {
1967 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
1968 	 * bits to improve our u32/s32 boundaries.
1969 	 *
1970 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
1971 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
1972 	 * [10, 20] range. But this property holds for any 64-bit range as
1973 	 * long as upper 32 bits in that entire range of values stay the same.
1974 	 *
1975 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
1976 	 * in decimal) has the same upper 32 bits throughout all the values in
1977 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
1978 	 * range.
1979 	 *
1980 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
1981 	 * following the rules outlined below about u64/s64 correspondence
1982 	 * (which equally applies to u32 vs s32 correspondence). In general it
1983 	 * depends on actual hexadecimal values of 32-bit range. They can form
1984 	 * only valid u32, or only valid s32 ranges in some cases.
1985 	 *
1986 	 * So we use all these insights to derive bounds for subregisters here.
1987 	 */
1988 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
1989 		/* u64 to u32 casting preserves validity of low 32 bits as
1990 		 * a range, if upper 32 bits are the same
1991 		 */
1992 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
1993 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
1994 
1995 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
1996 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
1997 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
1998 		}
1999 	}
2000 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2001 		/* low 32 bits should form a proper u32 range */
2002 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2003 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2004 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2005 		}
2006 		/* low 32 bits should form a proper s32 range */
2007 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2008 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2009 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2010 		}
2011 	}
2012 	/* Special case where upper bits form a small sequence of two
2013 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2014 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
2015 	 * going from negative numbers to positive numbers. E.g., let's say we
2016 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2017 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2018 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2019 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2020 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2021 	 * upper 32 bits. As a random example, s64 range
2022 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2023 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2024 	 */
2025 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2026 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2027 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2028 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2029 	}
2030 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2031 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2032 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2033 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2034 	}
2035 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2036 	 * try to learn from that
2037 	 */
2038 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2039 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2040 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2041 	}
2042 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2043 	 * are the same, so combine.  This works even in the negative case, e.g.
2044 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2045 	 */
2046 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2047 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2048 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2049 	}
2050 }
2051 
2052 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2053 {
2054 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2055 	 * try to learn from that. Let's do a bit of ASCII art to see when
2056 	 * this is happening. Let's take u64 range first:
2057 	 *
2058 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2059 	 * |-------------------------------|--------------------------------|
2060 	 *
2061 	 * Valid u64 range is formed when umin and umax are anywhere in the
2062 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2063 	 * straightforward. Let's see how s64 range maps onto the same range
2064 	 * of values, annotated below the line for comparison:
2065 	 *
2066 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2067 	 * |-------------------------------|--------------------------------|
2068 	 * 0                        S64_MAX S64_MIN                        -1
2069 	 *
2070 	 * So s64 values basically start in the middle and they are logically
2071 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2072 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2073 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2074 	 * more visually as mapped to sign-agnostic range of hex values.
2075 	 *
2076 	 *  u64 start                                               u64 end
2077 	 *  _______________________________________________________________
2078 	 * /                                                               \
2079 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2080 	 * |-------------------------------|--------------------------------|
2081 	 * 0                        S64_MAX S64_MIN                        -1
2082 	 *                                / \
2083 	 * >------------------------------   ------------------------------->
2084 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2085 	 *
2086 	 * What this means is that, in general, we can't always derive
2087 	 * something new about u64 from any random s64 range, and vice versa.
2088 	 *
2089 	 * But we can do that in two particular cases. One is when entire
2090 	 * u64/s64 range is *entirely* contained within left half of the above
2091 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2092 	 *
2093 	 * |-------------------------------|--------------------------------|
2094 	 *     ^                   ^            ^                 ^
2095 	 *     A                   B            C                 D
2096 	 *
2097 	 * [A, B] and [C, D] are contained entirely in their respective halves
2098 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2099 	 * will be non-negative both as u64 and s64 (and in fact it will be
2100 	 * identical ranges no matter the signedness). [C, D] treated as s64
2101 	 * will be a range of negative values, while in u64 it will be
2102 	 * non-negative range of values larger than 0x8000000000000000.
2103 	 *
2104 	 * Now, any other range here can't be represented in both u64 and s64
2105 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2106 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2107 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2108 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2109 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2110 	 * ranges as u64. Currently reg_state can't represent two segments per
2111 	 * numeric domain, so in such situations we can only derive maximal
2112 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2113 	 *
2114 	 * So we use these facts to derive umin/umax from smin/smax and vice
2115 	 * versa only if they stay within the same "half". This is equivalent
2116 	 * to checking sign bit: lower half will have sign bit as zero, upper
2117 	 * half have sign bit 1. Below in code we simplify this by just
2118 	 * casting umin/umax as smin/smax and checking if they form valid
2119 	 * range, and vice versa. Those are equivalent checks.
2120 	 */
2121 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2122 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2123 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2124 	}
2125 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2126 	 * are the same, so combine.  This works even in the negative case, e.g.
2127 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2128 	 */
2129 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2130 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2131 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2132 	}
2133 }
2134 
2135 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2136 {
2137 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2138 	 * values on both sides of 64-bit range in hope to have tigher range.
2139 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2140 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2141 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2142 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2143 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2144 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2145 	 * We just need to make sure that derived bounds we are intersecting
2146 	 * with are well-formed ranges in respecitve s64 or u64 domain, just
2147 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2148 	 */
2149 	__u64 new_umin, new_umax;
2150 	__s64 new_smin, new_smax;
2151 
2152 	/* u32 -> u64 tightening, it's always well-formed */
2153 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2154 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2155 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2156 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2157 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2158 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2159 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2160 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2161 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2162 
2163 	/* if s32 can be treated as valid u32 range, we can use it as well */
2164 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2165 		/* s32 -> u64 tightening */
2166 		new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2167 		new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2168 		reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2169 		reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2170 		/* s32 -> s64 tightening */
2171 		new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2172 		new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2173 		reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2174 		reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2175 	}
2176 }
2177 
2178 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2179 {
2180 	__reg32_deduce_bounds(reg);
2181 	__reg64_deduce_bounds(reg);
2182 	__reg_deduce_mixed_bounds(reg);
2183 }
2184 
2185 /* Attempts to improve var_off based on unsigned min/max information */
2186 static void __reg_bound_offset(struct bpf_reg_state *reg)
2187 {
2188 	struct tnum var64_off = tnum_intersect(reg->var_off,
2189 					       tnum_range(reg->umin_value,
2190 							  reg->umax_value));
2191 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2192 					       tnum_range(reg->u32_min_value,
2193 							  reg->u32_max_value));
2194 
2195 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2196 }
2197 
2198 static void reg_bounds_sync(struct bpf_reg_state *reg)
2199 {
2200 	/* We might have learned new bounds from the var_off. */
2201 	__update_reg_bounds(reg);
2202 	/* We might have learned something about the sign bit. */
2203 	__reg_deduce_bounds(reg);
2204 	__reg_deduce_bounds(reg);
2205 	/* We might have learned some bits from the bounds. */
2206 	__reg_bound_offset(reg);
2207 	/* Intersecting with the old var_off might have improved our bounds
2208 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2209 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2210 	 */
2211 	__update_reg_bounds(reg);
2212 }
2213 
2214 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2215 				   struct bpf_reg_state *reg, const char *ctx)
2216 {
2217 	const char *msg;
2218 
2219 	if (reg->umin_value > reg->umax_value ||
2220 	    reg->smin_value > reg->smax_value ||
2221 	    reg->u32_min_value > reg->u32_max_value ||
2222 	    reg->s32_min_value > reg->s32_max_value) {
2223 		    msg = "range bounds violation";
2224 		    goto out;
2225 	}
2226 
2227 	if (tnum_is_const(reg->var_off)) {
2228 		u64 uval = reg->var_off.value;
2229 		s64 sval = (s64)uval;
2230 
2231 		if (reg->umin_value != uval || reg->umax_value != uval ||
2232 		    reg->smin_value != sval || reg->smax_value != sval) {
2233 			msg = "const tnum out of sync with range bounds";
2234 			goto out;
2235 		}
2236 	}
2237 
2238 	if (tnum_subreg_is_const(reg->var_off)) {
2239 		u32 uval32 = tnum_subreg(reg->var_off).value;
2240 		s32 sval32 = (s32)uval32;
2241 
2242 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2243 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2244 			msg = "const subreg tnum out of sync with range bounds";
2245 			goto out;
2246 		}
2247 	}
2248 
2249 	return 0;
2250 out:
2251 	verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2252 		"s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n",
2253 		ctx, msg, reg->umin_value, reg->umax_value,
2254 		reg->smin_value, reg->smax_value,
2255 		reg->u32_min_value, reg->u32_max_value,
2256 		reg->s32_min_value, reg->s32_max_value,
2257 		reg->var_off.value, reg->var_off.mask);
2258 	if (env->test_reg_invariants)
2259 		return -EFAULT;
2260 	__mark_reg_unbounded(reg);
2261 	return 0;
2262 }
2263 
2264 static bool __reg32_bound_s64(s32 a)
2265 {
2266 	return a >= 0 && a <= S32_MAX;
2267 }
2268 
2269 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2270 {
2271 	reg->umin_value = reg->u32_min_value;
2272 	reg->umax_value = reg->u32_max_value;
2273 
2274 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2275 	 * be positive otherwise set to worse case bounds and refine later
2276 	 * from tnum.
2277 	 */
2278 	if (__reg32_bound_s64(reg->s32_min_value) &&
2279 	    __reg32_bound_s64(reg->s32_max_value)) {
2280 		reg->smin_value = reg->s32_min_value;
2281 		reg->smax_value = reg->s32_max_value;
2282 	} else {
2283 		reg->smin_value = 0;
2284 		reg->smax_value = U32_MAX;
2285 	}
2286 }
2287 
2288 /* Mark a register as having a completely unknown (scalar) value. */
2289 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2290 {
2291 	/*
2292 	 * Clear type, off, and union(map_ptr, range) and
2293 	 * padding between 'type' and union
2294 	 */
2295 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2296 	reg->type = SCALAR_VALUE;
2297 	reg->id = 0;
2298 	reg->ref_obj_id = 0;
2299 	reg->var_off = tnum_unknown;
2300 	reg->frameno = 0;
2301 	reg->precise = false;
2302 	__mark_reg_unbounded(reg);
2303 }
2304 
2305 /* Mark a register as having a completely unknown (scalar) value,
2306  * initialize .precise as true when not bpf capable.
2307  */
2308 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2309 			       struct bpf_reg_state *reg)
2310 {
2311 	__mark_reg_unknown_imprecise(reg);
2312 	reg->precise = !env->bpf_capable;
2313 }
2314 
2315 static void mark_reg_unknown(struct bpf_verifier_env *env,
2316 			     struct bpf_reg_state *regs, u32 regno)
2317 {
2318 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2319 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2320 		/* Something bad happened, let's kill all regs except FP */
2321 		for (regno = 0; regno < BPF_REG_FP; regno++)
2322 			__mark_reg_not_init(env, regs + regno);
2323 		return;
2324 	}
2325 	__mark_reg_unknown(env, regs + regno);
2326 }
2327 
2328 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2329 				struct bpf_reg_state *reg)
2330 {
2331 	__mark_reg_unknown(env, reg);
2332 	reg->type = NOT_INIT;
2333 }
2334 
2335 static void mark_reg_not_init(struct bpf_verifier_env *env,
2336 			      struct bpf_reg_state *regs, u32 regno)
2337 {
2338 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2339 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2340 		/* Something bad happened, let's kill all regs except FP */
2341 		for (regno = 0; regno < BPF_REG_FP; regno++)
2342 			__mark_reg_not_init(env, regs + regno);
2343 		return;
2344 	}
2345 	__mark_reg_not_init(env, regs + regno);
2346 }
2347 
2348 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2349 			    struct bpf_reg_state *regs, u32 regno,
2350 			    enum bpf_reg_type reg_type,
2351 			    struct btf *btf, u32 btf_id,
2352 			    enum bpf_type_flag flag)
2353 {
2354 	if (reg_type == SCALAR_VALUE) {
2355 		mark_reg_unknown(env, regs, regno);
2356 		return;
2357 	}
2358 	mark_reg_known_zero(env, regs, regno);
2359 	regs[regno].type = PTR_TO_BTF_ID | flag;
2360 	regs[regno].btf = btf;
2361 	regs[regno].btf_id = btf_id;
2362 }
2363 
2364 #define DEF_NOT_SUBREG	(0)
2365 static void init_reg_state(struct bpf_verifier_env *env,
2366 			   struct bpf_func_state *state)
2367 {
2368 	struct bpf_reg_state *regs = state->regs;
2369 	int i;
2370 
2371 	for (i = 0; i < MAX_BPF_REG; i++) {
2372 		mark_reg_not_init(env, regs, i);
2373 		regs[i].live = REG_LIVE_NONE;
2374 		regs[i].parent = NULL;
2375 		regs[i].subreg_def = DEF_NOT_SUBREG;
2376 	}
2377 
2378 	/* frame pointer */
2379 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2380 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2381 	regs[BPF_REG_FP].frameno = state->frameno;
2382 }
2383 
2384 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2385 {
2386 	return (struct bpf_retval_range){ minval, maxval };
2387 }
2388 
2389 #define BPF_MAIN_FUNC (-1)
2390 static void init_func_state(struct bpf_verifier_env *env,
2391 			    struct bpf_func_state *state,
2392 			    int callsite, int frameno, int subprogno)
2393 {
2394 	state->callsite = callsite;
2395 	state->frameno = frameno;
2396 	state->subprogno = subprogno;
2397 	state->callback_ret_range = retval_range(0, 0);
2398 	init_reg_state(env, state);
2399 	mark_verifier_state_scratched(env);
2400 }
2401 
2402 /* Similar to push_stack(), but for async callbacks */
2403 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2404 						int insn_idx, int prev_insn_idx,
2405 						int subprog)
2406 {
2407 	struct bpf_verifier_stack_elem *elem;
2408 	struct bpf_func_state *frame;
2409 
2410 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2411 	if (!elem)
2412 		goto err;
2413 
2414 	elem->insn_idx = insn_idx;
2415 	elem->prev_insn_idx = prev_insn_idx;
2416 	elem->next = env->head;
2417 	elem->log_pos = env->log.end_pos;
2418 	env->head = elem;
2419 	env->stack_size++;
2420 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2421 		verbose(env,
2422 			"The sequence of %d jumps is too complex for async cb.\n",
2423 			env->stack_size);
2424 		goto err;
2425 	}
2426 	/* Unlike push_stack() do not copy_verifier_state().
2427 	 * The caller state doesn't matter.
2428 	 * This is async callback. It starts in a fresh stack.
2429 	 * Initialize it similar to do_check_common().
2430 	 */
2431 	elem->st.branches = 1;
2432 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2433 	if (!frame)
2434 		goto err;
2435 	init_func_state(env, frame,
2436 			BPF_MAIN_FUNC /* callsite */,
2437 			0 /* frameno within this callchain */,
2438 			subprog /* subprog number within this prog */);
2439 	elem->st.frame[0] = frame;
2440 	return &elem->st;
2441 err:
2442 	free_verifier_state(env->cur_state, true);
2443 	env->cur_state = NULL;
2444 	/* pop all elements and return */
2445 	while (!pop_stack(env, NULL, NULL, false));
2446 	return NULL;
2447 }
2448 
2449 
2450 enum reg_arg_type {
2451 	SRC_OP,		/* register is used as source operand */
2452 	DST_OP,		/* register is used as destination operand */
2453 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2454 };
2455 
2456 static int cmp_subprogs(const void *a, const void *b)
2457 {
2458 	return ((struct bpf_subprog_info *)a)->start -
2459 	       ((struct bpf_subprog_info *)b)->start;
2460 }
2461 
2462 static int find_subprog(struct bpf_verifier_env *env, int off)
2463 {
2464 	struct bpf_subprog_info *p;
2465 
2466 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2467 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2468 	if (!p)
2469 		return -ENOENT;
2470 	return p - env->subprog_info;
2471 
2472 }
2473 
2474 static int add_subprog(struct bpf_verifier_env *env, int off)
2475 {
2476 	int insn_cnt = env->prog->len;
2477 	int ret;
2478 
2479 	if (off >= insn_cnt || off < 0) {
2480 		verbose(env, "call to invalid destination\n");
2481 		return -EINVAL;
2482 	}
2483 	ret = find_subprog(env, off);
2484 	if (ret >= 0)
2485 		return ret;
2486 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2487 		verbose(env, "too many subprograms\n");
2488 		return -E2BIG;
2489 	}
2490 	/* determine subprog starts. The end is one before the next starts */
2491 	env->subprog_info[env->subprog_cnt++].start = off;
2492 	sort(env->subprog_info, env->subprog_cnt,
2493 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2494 	return env->subprog_cnt - 1;
2495 }
2496 
2497 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2498 {
2499 	struct bpf_prog_aux *aux = env->prog->aux;
2500 	struct btf *btf = aux->btf;
2501 	const struct btf_type *t;
2502 	u32 main_btf_id, id;
2503 	const char *name;
2504 	int ret, i;
2505 
2506 	/* Non-zero func_info_cnt implies valid btf */
2507 	if (!aux->func_info_cnt)
2508 		return 0;
2509 	main_btf_id = aux->func_info[0].type_id;
2510 
2511 	t = btf_type_by_id(btf, main_btf_id);
2512 	if (!t) {
2513 		verbose(env, "invalid btf id for main subprog in func_info\n");
2514 		return -EINVAL;
2515 	}
2516 
2517 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2518 	if (IS_ERR(name)) {
2519 		ret = PTR_ERR(name);
2520 		/* If there is no tag present, there is no exception callback */
2521 		if (ret == -ENOENT)
2522 			ret = 0;
2523 		else if (ret == -EEXIST)
2524 			verbose(env, "multiple exception callback tags for main subprog\n");
2525 		return ret;
2526 	}
2527 
2528 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2529 	if (ret < 0) {
2530 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2531 		return ret;
2532 	}
2533 	id = ret;
2534 	t = btf_type_by_id(btf, id);
2535 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2536 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2537 		return -EINVAL;
2538 	}
2539 	ret = 0;
2540 	for (i = 0; i < aux->func_info_cnt; i++) {
2541 		if (aux->func_info[i].type_id != id)
2542 			continue;
2543 		ret = aux->func_info[i].insn_off;
2544 		/* Further func_info and subprog checks will also happen
2545 		 * later, so assume this is the right insn_off for now.
2546 		 */
2547 		if (!ret) {
2548 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2549 			ret = -EINVAL;
2550 		}
2551 	}
2552 	if (!ret) {
2553 		verbose(env, "exception callback type id not found in func_info\n");
2554 		ret = -EINVAL;
2555 	}
2556 	return ret;
2557 }
2558 
2559 #define MAX_KFUNC_DESCS 256
2560 #define MAX_KFUNC_BTFS	256
2561 
2562 struct bpf_kfunc_desc {
2563 	struct btf_func_model func_model;
2564 	u32 func_id;
2565 	s32 imm;
2566 	u16 offset;
2567 	unsigned long addr;
2568 };
2569 
2570 struct bpf_kfunc_btf {
2571 	struct btf *btf;
2572 	struct module *module;
2573 	u16 offset;
2574 };
2575 
2576 struct bpf_kfunc_desc_tab {
2577 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2578 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2579 	 * available, therefore at the end of verification do_misc_fixups()
2580 	 * sorts this by imm and offset.
2581 	 */
2582 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2583 	u32 nr_descs;
2584 };
2585 
2586 struct bpf_kfunc_btf_tab {
2587 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2588 	u32 nr_descs;
2589 };
2590 
2591 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2592 {
2593 	const struct bpf_kfunc_desc *d0 = a;
2594 	const struct bpf_kfunc_desc *d1 = b;
2595 
2596 	/* func_id is not greater than BTF_MAX_TYPE */
2597 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2598 }
2599 
2600 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2601 {
2602 	const struct bpf_kfunc_btf *d0 = a;
2603 	const struct bpf_kfunc_btf *d1 = b;
2604 
2605 	return d0->offset - d1->offset;
2606 }
2607 
2608 static const struct bpf_kfunc_desc *
2609 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2610 {
2611 	struct bpf_kfunc_desc desc = {
2612 		.func_id = func_id,
2613 		.offset = offset,
2614 	};
2615 	struct bpf_kfunc_desc_tab *tab;
2616 
2617 	tab = prog->aux->kfunc_tab;
2618 	return bsearch(&desc, tab->descs, tab->nr_descs,
2619 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2620 }
2621 
2622 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2623 		       u16 btf_fd_idx, u8 **func_addr)
2624 {
2625 	const struct bpf_kfunc_desc *desc;
2626 
2627 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2628 	if (!desc)
2629 		return -EFAULT;
2630 
2631 	*func_addr = (u8 *)desc->addr;
2632 	return 0;
2633 }
2634 
2635 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2636 					 s16 offset)
2637 {
2638 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2639 	struct bpf_kfunc_btf_tab *tab;
2640 	struct bpf_kfunc_btf *b;
2641 	struct module *mod;
2642 	struct btf *btf;
2643 	int btf_fd;
2644 
2645 	tab = env->prog->aux->kfunc_btf_tab;
2646 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2647 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2648 	if (!b) {
2649 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2650 			verbose(env, "too many different module BTFs\n");
2651 			return ERR_PTR(-E2BIG);
2652 		}
2653 
2654 		if (bpfptr_is_null(env->fd_array)) {
2655 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2656 			return ERR_PTR(-EPROTO);
2657 		}
2658 
2659 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2660 					    offset * sizeof(btf_fd),
2661 					    sizeof(btf_fd)))
2662 			return ERR_PTR(-EFAULT);
2663 
2664 		btf = btf_get_by_fd(btf_fd);
2665 		if (IS_ERR(btf)) {
2666 			verbose(env, "invalid module BTF fd specified\n");
2667 			return btf;
2668 		}
2669 
2670 		if (!btf_is_module(btf)) {
2671 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2672 			btf_put(btf);
2673 			return ERR_PTR(-EINVAL);
2674 		}
2675 
2676 		mod = btf_try_get_module(btf);
2677 		if (!mod) {
2678 			btf_put(btf);
2679 			return ERR_PTR(-ENXIO);
2680 		}
2681 
2682 		b = &tab->descs[tab->nr_descs++];
2683 		b->btf = btf;
2684 		b->module = mod;
2685 		b->offset = offset;
2686 
2687 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2688 		     kfunc_btf_cmp_by_off, NULL);
2689 	}
2690 	return b->btf;
2691 }
2692 
2693 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2694 {
2695 	if (!tab)
2696 		return;
2697 
2698 	while (tab->nr_descs--) {
2699 		module_put(tab->descs[tab->nr_descs].module);
2700 		btf_put(tab->descs[tab->nr_descs].btf);
2701 	}
2702 	kfree(tab);
2703 }
2704 
2705 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2706 {
2707 	if (offset) {
2708 		if (offset < 0) {
2709 			/* In the future, this can be allowed to increase limit
2710 			 * of fd index into fd_array, interpreted as u16.
2711 			 */
2712 			verbose(env, "negative offset disallowed for kernel module function call\n");
2713 			return ERR_PTR(-EINVAL);
2714 		}
2715 
2716 		return __find_kfunc_desc_btf(env, offset);
2717 	}
2718 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2719 }
2720 
2721 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2722 {
2723 	const struct btf_type *func, *func_proto;
2724 	struct bpf_kfunc_btf_tab *btf_tab;
2725 	struct bpf_kfunc_desc_tab *tab;
2726 	struct bpf_prog_aux *prog_aux;
2727 	struct bpf_kfunc_desc *desc;
2728 	const char *func_name;
2729 	struct btf *desc_btf;
2730 	unsigned long call_imm;
2731 	unsigned long addr;
2732 	int err;
2733 
2734 	prog_aux = env->prog->aux;
2735 	tab = prog_aux->kfunc_tab;
2736 	btf_tab = prog_aux->kfunc_btf_tab;
2737 	if (!tab) {
2738 		if (!btf_vmlinux) {
2739 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2740 			return -ENOTSUPP;
2741 		}
2742 
2743 		if (!env->prog->jit_requested) {
2744 			verbose(env, "JIT is required for calling kernel function\n");
2745 			return -ENOTSUPP;
2746 		}
2747 
2748 		if (!bpf_jit_supports_kfunc_call()) {
2749 			verbose(env, "JIT does not support calling kernel function\n");
2750 			return -ENOTSUPP;
2751 		}
2752 
2753 		if (!env->prog->gpl_compatible) {
2754 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2755 			return -EINVAL;
2756 		}
2757 
2758 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2759 		if (!tab)
2760 			return -ENOMEM;
2761 		prog_aux->kfunc_tab = tab;
2762 	}
2763 
2764 	/* func_id == 0 is always invalid, but instead of returning an error, be
2765 	 * conservative and wait until the code elimination pass before returning
2766 	 * error, so that invalid calls that get pruned out can be in BPF programs
2767 	 * loaded from userspace.  It is also required that offset be untouched
2768 	 * for such calls.
2769 	 */
2770 	if (!func_id && !offset)
2771 		return 0;
2772 
2773 	if (!btf_tab && offset) {
2774 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2775 		if (!btf_tab)
2776 			return -ENOMEM;
2777 		prog_aux->kfunc_btf_tab = btf_tab;
2778 	}
2779 
2780 	desc_btf = find_kfunc_desc_btf(env, offset);
2781 	if (IS_ERR(desc_btf)) {
2782 		verbose(env, "failed to find BTF for kernel function\n");
2783 		return PTR_ERR(desc_btf);
2784 	}
2785 
2786 	if (find_kfunc_desc(env->prog, func_id, offset))
2787 		return 0;
2788 
2789 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2790 		verbose(env, "too many different kernel function calls\n");
2791 		return -E2BIG;
2792 	}
2793 
2794 	func = btf_type_by_id(desc_btf, func_id);
2795 	if (!func || !btf_type_is_func(func)) {
2796 		verbose(env, "kernel btf_id %u is not a function\n",
2797 			func_id);
2798 		return -EINVAL;
2799 	}
2800 	func_proto = btf_type_by_id(desc_btf, func->type);
2801 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2802 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2803 			func_id);
2804 		return -EINVAL;
2805 	}
2806 
2807 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2808 	addr = kallsyms_lookup_name(func_name);
2809 	if (!addr) {
2810 		verbose(env, "cannot find address for kernel function %s\n",
2811 			func_name);
2812 		return -EINVAL;
2813 	}
2814 	specialize_kfunc(env, func_id, offset, &addr);
2815 
2816 	if (bpf_jit_supports_far_kfunc_call()) {
2817 		call_imm = func_id;
2818 	} else {
2819 		call_imm = BPF_CALL_IMM(addr);
2820 		/* Check whether the relative offset overflows desc->imm */
2821 		if ((unsigned long)(s32)call_imm != call_imm) {
2822 			verbose(env, "address of kernel function %s is out of range\n",
2823 				func_name);
2824 			return -EINVAL;
2825 		}
2826 	}
2827 
2828 	if (bpf_dev_bound_kfunc_id(func_id)) {
2829 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2830 		if (err)
2831 			return err;
2832 	}
2833 
2834 	desc = &tab->descs[tab->nr_descs++];
2835 	desc->func_id = func_id;
2836 	desc->imm = call_imm;
2837 	desc->offset = offset;
2838 	desc->addr = addr;
2839 	err = btf_distill_func_proto(&env->log, desc_btf,
2840 				     func_proto, func_name,
2841 				     &desc->func_model);
2842 	if (!err)
2843 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2844 		     kfunc_desc_cmp_by_id_off, NULL);
2845 	return err;
2846 }
2847 
2848 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2849 {
2850 	const struct bpf_kfunc_desc *d0 = a;
2851 	const struct bpf_kfunc_desc *d1 = b;
2852 
2853 	if (d0->imm != d1->imm)
2854 		return d0->imm < d1->imm ? -1 : 1;
2855 	if (d0->offset != d1->offset)
2856 		return d0->offset < d1->offset ? -1 : 1;
2857 	return 0;
2858 }
2859 
2860 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2861 {
2862 	struct bpf_kfunc_desc_tab *tab;
2863 
2864 	tab = prog->aux->kfunc_tab;
2865 	if (!tab)
2866 		return;
2867 
2868 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2869 	     kfunc_desc_cmp_by_imm_off, NULL);
2870 }
2871 
2872 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2873 {
2874 	return !!prog->aux->kfunc_tab;
2875 }
2876 
2877 const struct btf_func_model *
2878 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2879 			 const struct bpf_insn *insn)
2880 {
2881 	const struct bpf_kfunc_desc desc = {
2882 		.imm = insn->imm,
2883 		.offset = insn->off,
2884 	};
2885 	const struct bpf_kfunc_desc *res;
2886 	struct bpf_kfunc_desc_tab *tab;
2887 
2888 	tab = prog->aux->kfunc_tab;
2889 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2890 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2891 
2892 	return res ? &res->func_model : NULL;
2893 }
2894 
2895 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2896 {
2897 	struct bpf_subprog_info *subprog = env->subprog_info;
2898 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
2899 	struct bpf_insn *insn = env->prog->insnsi;
2900 
2901 	/* Add entry function. */
2902 	ret = add_subprog(env, 0);
2903 	if (ret)
2904 		return ret;
2905 
2906 	for (i = 0; i < insn_cnt; i++, insn++) {
2907 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2908 		    !bpf_pseudo_kfunc_call(insn))
2909 			continue;
2910 
2911 		if (!env->bpf_capable) {
2912 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2913 			return -EPERM;
2914 		}
2915 
2916 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2917 			ret = add_subprog(env, i + insn->imm + 1);
2918 		else
2919 			ret = add_kfunc_call(env, insn->imm, insn->off);
2920 
2921 		if (ret < 0)
2922 			return ret;
2923 	}
2924 
2925 	ret = bpf_find_exception_callback_insn_off(env);
2926 	if (ret < 0)
2927 		return ret;
2928 	ex_cb_insn = ret;
2929 
2930 	/* If ex_cb_insn > 0, this means that the main program has a subprog
2931 	 * marked using BTF decl tag to serve as the exception callback.
2932 	 */
2933 	if (ex_cb_insn) {
2934 		ret = add_subprog(env, ex_cb_insn);
2935 		if (ret < 0)
2936 			return ret;
2937 		for (i = 1; i < env->subprog_cnt; i++) {
2938 			if (env->subprog_info[i].start != ex_cb_insn)
2939 				continue;
2940 			env->exception_callback_subprog = i;
2941 			mark_subprog_exc_cb(env, i);
2942 			break;
2943 		}
2944 	}
2945 
2946 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2947 	 * logic. 'subprog_cnt' should not be increased.
2948 	 */
2949 	subprog[env->subprog_cnt].start = insn_cnt;
2950 
2951 	if (env->log.level & BPF_LOG_LEVEL2)
2952 		for (i = 0; i < env->subprog_cnt; i++)
2953 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2954 
2955 	return 0;
2956 }
2957 
2958 static int check_subprogs(struct bpf_verifier_env *env)
2959 {
2960 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2961 	struct bpf_subprog_info *subprog = env->subprog_info;
2962 	struct bpf_insn *insn = env->prog->insnsi;
2963 	int insn_cnt = env->prog->len;
2964 
2965 	/* now check that all jumps are within the same subprog */
2966 	subprog_start = subprog[cur_subprog].start;
2967 	subprog_end = subprog[cur_subprog + 1].start;
2968 	for (i = 0; i < insn_cnt; i++) {
2969 		u8 code = insn[i].code;
2970 
2971 		if (code == (BPF_JMP | BPF_CALL) &&
2972 		    insn[i].src_reg == 0 &&
2973 		    insn[i].imm == BPF_FUNC_tail_call)
2974 			subprog[cur_subprog].has_tail_call = true;
2975 		if (BPF_CLASS(code) == BPF_LD &&
2976 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2977 			subprog[cur_subprog].has_ld_abs = true;
2978 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2979 			goto next;
2980 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2981 			goto next;
2982 		if (code == (BPF_JMP32 | BPF_JA))
2983 			off = i + insn[i].imm + 1;
2984 		else
2985 			off = i + insn[i].off + 1;
2986 		if (off < subprog_start || off >= subprog_end) {
2987 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2988 			return -EINVAL;
2989 		}
2990 next:
2991 		if (i == subprog_end - 1) {
2992 			/* to avoid fall-through from one subprog into another
2993 			 * the last insn of the subprog should be either exit
2994 			 * or unconditional jump back or bpf_throw call
2995 			 */
2996 			if (code != (BPF_JMP | BPF_EXIT) &&
2997 			    code != (BPF_JMP32 | BPF_JA) &&
2998 			    code != (BPF_JMP | BPF_JA)) {
2999 				verbose(env, "last insn is not an exit or jmp\n");
3000 				return -EINVAL;
3001 			}
3002 			subprog_start = subprog_end;
3003 			cur_subprog++;
3004 			if (cur_subprog < env->subprog_cnt)
3005 				subprog_end = subprog[cur_subprog + 1].start;
3006 		}
3007 	}
3008 	return 0;
3009 }
3010 
3011 /* Parentage chain of this register (or stack slot) should take care of all
3012  * issues like callee-saved registers, stack slot allocation time, etc.
3013  */
3014 static int mark_reg_read(struct bpf_verifier_env *env,
3015 			 const struct bpf_reg_state *state,
3016 			 struct bpf_reg_state *parent, u8 flag)
3017 {
3018 	bool writes = parent == state->parent; /* Observe write marks */
3019 	int cnt = 0;
3020 
3021 	while (parent) {
3022 		/* if read wasn't screened by an earlier write ... */
3023 		if (writes && state->live & REG_LIVE_WRITTEN)
3024 			break;
3025 		if (parent->live & REG_LIVE_DONE) {
3026 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3027 				reg_type_str(env, parent->type),
3028 				parent->var_off.value, parent->off);
3029 			return -EFAULT;
3030 		}
3031 		/* The first condition is more likely to be true than the
3032 		 * second, checked it first.
3033 		 */
3034 		if ((parent->live & REG_LIVE_READ) == flag ||
3035 		    parent->live & REG_LIVE_READ64)
3036 			/* The parentage chain never changes and
3037 			 * this parent was already marked as LIVE_READ.
3038 			 * There is no need to keep walking the chain again and
3039 			 * keep re-marking all parents as LIVE_READ.
3040 			 * This case happens when the same register is read
3041 			 * multiple times without writes into it in-between.
3042 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3043 			 * then no need to set the weak REG_LIVE_READ32.
3044 			 */
3045 			break;
3046 		/* ... then we depend on parent's value */
3047 		parent->live |= flag;
3048 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3049 		if (flag == REG_LIVE_READ64)
3050 			parent->live &= ~REG_LIVE_READ32;
3051 		state = parent;
3052 		parent = state->parent;
3053 		writes = true;
3054 		cnt++;
3055 	}
3056 
3057 	if (env->longest_mark_read_walk < cnt)
3058 		env->longest_mark_read_walk = cnt;
3059 	return 0;
3060 }
3061 
3062 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3063 {
3064 	struct bpf_func_state *state = func(env, reg);
3065 	int spi, ret;
3066 
3067 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3068 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3069 	 * check_kfunc_call.
3070 	 */
3071 	if (reg->type == CONST_PTR_TO_DYNPTR)
3072 		return 0;
3073 	spi = dynptr_get_spi(env, reg);
3074 	if (spi < 0)
3075 		return spi;
3076 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3077 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3078 	 * read.
3079 	 */
3080 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3081 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3082 	if (ret)
3083 		return ret;
3084 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3085 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3086 }
3087 
3088 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3089 			  int spi, int nr_slots)
3090 {
3091 	struct bpf_func_state *state = func(env, reg);
3092 	int err, i;
3093 
3094 	for (i = 0; i < nr_slots; i++) {
3095 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3096 
3097 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3098 		if (err)
3099 			return err;
3100 
3101 		mark_stack_slot_scratched(env, spi - i);
3102 	}
3103 
3104 	return 0;
3105 }
3106 
3107 /* This function is supposed to be used by the following 32-bit optimization
3108  * code only. It returns TRUE if the source or destination register operates
3109  * on 64-bit, otherwise return FALSE.
3110  */
3111 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3112 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3113 {
3114 	u8 code, class, op;
3115 
3116 	code = insn->code;
3117 	class = BPF_CLASS(code);
3118 	op = BPF_OP(code);
3119 	if (class == BPF_JMP) {
3120 		/* BPF_EXIT for "main" will reach here. Return TRUE
3121 		 * conservatively.
3122 		 */
3123 		if (op == BPF_EXIT)
3124 			return true;
3125 		if (op == BPF_CALL) {
3126 			/* BPF to BPF call will reach here because of marking
3127 			 * caller saved clobber with DST_OP_NO_MARK for which we
3128 			 * don't care the register def because they are anyway
3129 			 * marked as NOT_INIT already.
3130 			 */
3131 			if (insn->src_reg == BPF_PSEUDO_CALL)
3132 				return false;
3133 			/* Helper call will reach here because of arg type
3134 			 * check, conservatively return TRUE.
3135 			 */
3136 			if (t == SRC_OP)
3137 				return true;
3138 
3139 			return false;
3140 		}
3141 	}
3142 
3143 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3144 		return false;
3145 
3146 	if (class == BPF_ALU64 || class == BPF_JMP ||
3147 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3148 		return true;
3149 
3150 	if (class == BPF_ALU || class == BPF_JMP32)
3151 		return false;
3152 
3153 	if (class == BPF_LDX) {
3154 		if (t != SRC_OP)
3155 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3156 		/* LDX source must be ptr. */
3157 		return true;
3158 	}
3159 
3160 	if (class == BPF_STX) {
3161 		/* BPF_STX (including atomic variants) has multiple source
3162 		 * operands, one of which is a ptr. Check whether the caller is
3163 		 * asking about it.
3164 		 */
3165 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3166 			return true;
3167 		return BPF_SIZE(code) == BPF_DW;
3168 	}
3169 
3170 	if (class == BPF_LD) {
3171 		u8 mode = BPF_MODE(code);
3172 
3173 		/* LD_IMM64 */
3174 		if (mode == BPF_IMM)
3175 			return true;
3176 
3177 		/* Both LD_IND and LD_ABS return 32-bit data. */
3178 		if (t != SRC_OP)
3179 			return  false;
3180 
3181 		/* Implicit ctx ptr. */
3182 		if (regno == BPF_REG_6)
3183 			return true;
3184 
3185 		/* Explicit source could be any width. */
3186 		return true;
3187 	}
3188 
3189 	if (class == BPF_ST)
3190 		/* The only source register for BPF_ST is a ptr. */
3191 		return true;
3192 
3193 	/* Conservatively return true at default. */
3194 	return true;
3195 }
3196 
3197 /* Return the regno defined by the insn, or -1. */
3198 static int insn_def_regno(const struct bpf_insn *insn)
3199 {
3200 	switch (BPF_CLASS(insn->code)) {
3201 	case BPF_JMP:
3202 	case BPF_JMP32:
3203 	case BPF_ST:
3204 		return -1;
3205 	case BPF_STX:
3206 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3207 		    (insn->imm & BPF_FETCH)) {
3208 			if (insn->imm == BPF_CMPXCHG)
3209 				return BPF_REG_0;
3210 			else
3211 				return insn->src_reg;
3212 		} else {
3213 			return -1;
3214 		}
3215 	default:
3216 		return insn->dst_reg;
3217 	}
3218 }
3219 
3220 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3221 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3222 {
3223 	int dst_reg = insn_def_regno(insn);
3224 
3225 	if (dst_reg == -1)
3226 		return false;
3227 
3228 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3229 }
3230 
3231 static void mark_insn_zext(struct bpf_verifier_env *env,
3232 			   struct bpf_reg_state *reg)
3233 {
3234 	s32 def_idx = reg->subreg_def;
3235 
3236 	if (def_idx == DEF_NOT_SUBREG)
3237 		return;
3238 
3239 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3240 	/* The dst will be zero extended, so won't be sub-register anymore. */
3241 	reg->subreg_def = DEF_NOT_SUBREG;
3242 }
3243 
3244 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3245 			   enum reg_arg_type t)
3246 {
3247 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3248 	struct bpf_reg_state *reg;
3249 	bool rw64;
3250 
3251 	if (regno >= MAX_BPF_REG) {
3252 		verbose(env, "R%d is invalid\n", regno);
3253 		return -EINVAL;
3254 	}
3255 
3256 	mark_reg_scratched(env, regno);
3257 
3258 	reg = &regs[regno];
3259 	rw64 = is_reg64(env, insn, regno, reg, t);
3260 	if (t == SRC_OP) {
3261 		/* check whether register used as source operand can be read */
3262 		if (reg->type == NOT_INIT) {
3263 			verbose(env, "R%d !read_ok\n", regno);
3264 			return -EACCES;
3265 		}
3266 		/* We don't need to worry about FP liveness because it's read-only */
3267 		if (regno == BPF_REG_FP)
3268 			return 0;
3269 
3270 		if (rw64)
3271 			mark_insn_zext(env, reg);
3272 
3273 		return mark_reg_read(env, reg, reg->parent,
3274 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3275 	} else {
3276 		/* check whether register used as dest operand can be written to */
3277 		if (regno == BPF_REG_FP) {
3278 			verbose(env, "frame pointer is read only\n");
3279 			return -EACCES;
3280 		}
3281 		reg->live |= REG_LIVE_WRITTEN;
3282 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3283 		if (t == DST_OP)
3284 			mark_reg_unknown(env, regs, regno);
3285 	}
3286 	return 0;
3287 }
3288 
3289 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3290 			 enum reg_arg_type t)
3291 {
3292 	struct bpf_verifier_state *vstate = env->cur_state;
3293 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3294 
3295 	return __check_reg_arg(env, state->regs, regno, t);
3296 }
3297 
3298 static int insn_stack_access_flags(int frameno, int spi)
3299 {
3300 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3301 }
3302 
3303 static int insn_stack_access_spi(int insn_flags)
3304 {
3305 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3306 }
3307 
3308 static int insn_stack_access_frameno(int insn_flags)
3309 {
3310 	return insn_flags & INSN_F_FRAMENO_MASK;
3311 }
3312 
3313 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3314 {
3315 	env->insn_aux_data[idx].jmp_point = true;
3316 }
3317 
3318 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3319 {
3320 	return env->insn_aux_data[insn_idx].jmp_point;
3321 }
3322 
3323 /* for any branch, call, exit record the history of jmps in the given state */
3324 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3325 			    int insn_flags)
3326 {
3327 	u32 cnt = cur->jmp_history_cnt;
3328 	struct bpf_jmp_history_entry *p;
3329 	size_t alloc_size;
3330 
3331 	/* combine instruction flags if we already recorded this instruction */
3332 	if (env->cur_hist_ent) {
3333 		/* atomic instructions push insn_flags twice, for READ and
3334 		 * WRITE sides, but they should agree on stack slot
3335 		 */
3336 		WARN_ONCE((env->cur_hist_ent->flags & insn_flags) &&
3337 			  (env->cur_hist_ent->flags & insn_flags) != insn_flags,
3338 			  "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n",
3339 			  env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3340 		env->cur_hist_ent->flags |= insn_flags;
3341 		return 0;
3342 	}
3343 
3344 	cnt++;
3345 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3346 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3347 	if (!p)
3348 		return -ENOMEM;
3349 	cur->jmp_history = p;
3350 
3351 	p = &cur->jmp_history[cnt - 1];
3352 	p->idx = env->insn_idx;
3353 	p->prev_idx = env->prev_insn_idx;
3354 	p->flags = insn_flags;
3355 	cur->jmp_history_cnt = cnt;
3356 	env->cur_hist_ent = p;
3357 
3358 	return 0;
3359 }
3360 
3361 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3362 						        u32 hist_end, int insn_idx)
3363 {
3364 	if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3365 		return &st->jmp_history[hist_end - 1];
3366 	return NULL;
3367 }
3368 
3369 /* Backtrack one insn at a time. If idx is not at the top of recorded
3370  * history then previous instruction came from straight line execution.
3371  * Return -ENOENT if we exhausted all instructions within given state.
3372  *
3373  * It's legal to have a bit of a looping with the same starting and ending
3374  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3375  * instruction index is the same as state's first_idx doesn't mean we are
3376  * done. If there is still some jump history left, we should keep going. We
3377  * need to take into account that we might have a jump history between given
3378  * state's parent and itself, due to checkpointing. In this case, we'll have
3379  * history entry recording a jump from last instruction of parent state and
3380  * first instruction of given state.
3381  */
3382 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3383 			     u32 *history)
3384 {
3385 	u32 cnt = *history;
3386 
3387 	if (i == st->first_insn_idx) {
3388 		if (cnt == 0)
3389 			return -ENOENT;
3390 		if (cnt == 1 && st->jmp_history[0].idx == i)
3391 			return -ENOENT;
3392 	}
3393 
3394 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3395 		i = st->jmp_history[cnt - 1].prev_idx;
3396 		(*history)--;
3397 	} else {
3398 		i--;
3399 	}
3400 	return i;
3401 }
3402 
3403 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3404 {
3405 	const struct btf_type *func;
3406 	struct btf *desc_btf;
3407 
3408 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3409 		return NULL;
3410 
3411 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3412 	if (IS_ERR(desc_btf))
3413 		return "<error>";
3414 
3415 	func = btf_type_by_id(desc_btf, insn->imm);
3416 	return btf_name_by_offset(desc_btf, func->name_off);
3417 }
3418 
3419 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3420 {
3421 	bt->frame = frame;
3422 }
3423 
3424 static inline void bt_reset(struct backtrack_state *bt)
3425 {
3426 	struct bpf_verifier_env *env = bt->env;
3427 
3428 	memset(bt, 0, sizeof(*bt));
3429 	bt->env = env;
3430 }
3431 
3432 static inline u32 bt_empty(struct backtrack_state *bt)
3433 {
3434 	u64 mask = 0;
3435 	int i;
3436 
3437 	for (i = 0; i <= bt->frame; i++)
3438 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3439 
3440 	return mask == 0;
3441 }
3442 
3443 static inline int bt_subprog_enter(struct backtrack_state *bt)
3444 {
3445 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3446 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3447 		WARN_ONCE(1, "verifier backtracking bug");
3448 		return -EFAULT;
3449 	}
3450 	bt->frame++;
3451 	return 0;
3452 }
3453 
3454 static inline int bt_subprog_exit(struct backtrack_state *bt)
3455 {
3456 	if (bt->frame == 0) {
3457 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3458 		WARN_ONCE(1, "verifier backtracking bug");
3459 		return -EFAULT;
3460 	}
3461 	bt->frame--;
3462 	return 0;
3463 }
3464 
3465 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3466 {
3467 	bt->reg_masks[frame] |= 1 << reg;
3468 }
3469 
3470 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3471 {
3472 	bt->reg_masks[frame] &= ~(1 << reg);
3473 }
3474 
3475 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3476 {
3477 	bt_set_frame_reg(bt, bt->frame, reg);
3478 }
3479 
3480 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3481 {
3482 	bt_clear_frame_reg(bt, bt->frame, reg);
3483 }
3484 
3485 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3486 {
3487 	bt->stack_masks[frame] |= 1ull << slot;
3488 }
3489 
3490 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3491 {
3492 	bt->stack_masks[frame] &= ~(1ull << slot);
3493 }
3494 
3495 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3496 {
3497 	return bt->reg_masks[frame];
3498 }
3499 
3500 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3501 {
3502 	return bt->reg_masks[bt->frame];
3503 }
3504 
3505 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3506 {
3507 	return bt->stack_masks[frame];
3508 }
3509 
3510 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3511 {
3512 	return bt->stack_masks[bt->frame];
3513 }
3514 
3515 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3516 {
3517 	return bt->reg_masks[bt->frame] & (1 << reg);
3518 }
3519 
3520 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
3521 {
3522 	return bt->stack_masks[frame] & (1ull << slot);
3523 }
3524 
3525 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3526 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3527 {
3528 	DECLARE_BITMAP(mask, 64);
3529 	bool first = true;
3530 	int i, n;
3531 
3532 	buf[0] = '\0';
3533 
3534 	bitmap_from_u64(mask, reg_mask);
3535 	for_each_set_bit(i, mask, 32) {
3536 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3537 		first = false;
3538 		buf += n;
3539 		buf_sz -= n;
3540 		if (buf_sz < 0)
3541 			break;
3542 	}
3543 }
3544 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3545 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3546 {
3547 	DECLARE_BITMAP(mask, 64);
3548 	bool first = true;
3549 	int i, n;
3550 
3551 	buf[0] = '\0';
3552 
3553 	bitmap_from_u64(mask, stack_mask);
3554 	for_each_set_bit(i, mask, 64) {
3555 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3556 		first = false;
3557 		buf += n;
3558 		buf_sz -= n;
3559 		if (buf_sz < 0)
3560 			break;
3561 	}
3562 }
3563 
3564 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3565 
3566 /* For given verifier state backtrack_insn() is called from the last insn to
3567  * the first insn. Its purpose is to compute a bitmask of registers and
3568  * stack slots that needs precision in the parent verifier state.
3569  *
3570  * @idx is an index of the instruction we are currently processing;
3571  * @subseq_idx is an index of the subsequent instruction that:
3572  *   - *would be* executed next, if jump history is viewed in forward order;
3573  *   - *was* processed previously during backtracking.
3574  */
3575 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3576 			  struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
3577 {
3578 	const struct bpf_insn_cbs cbs = {
3579 		.cb_call	= disasm_kfunc_name,
3580 		.cb_print	= verbose,
3581 		.private_data	= env,
3582 	};
3583 	struct bpf_insn *insn = env->prog->insnsi + idx;
3584 	u8 class = BPF_CLASS(insn->code);
3585 	u8 opcode = BPF_OP(insn->code);
3586 	u8 mode = BPF_MODE(insn->code);
3587 	u32 dreg = insn->dst_reg;
3588 	u32 sreg = insn->src_reg;
3589 	u32 spi, i, fr;
3590 
3591 	if (insn->code == 0)
3592 		return 0;
3593 	if (env->log.level & BPF_LOG_LEVEL2) {
3594 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3595 		verbose(env, "mark_precise: frame%d: regs=%s ",
3596 			bt->frame, env->tmp_str_buf);
3597 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3598 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3599 		verbose(env, "%d: ", idx);
3600 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3601 	}
3602 
3603 	if (class == BPF_ALU || class == BPF_ALU64) {
3604 		if (!bt_is_reg_set(bt, dreg))
3605 			return 0;
3606 		if (opcode == BPF_END || opcode == BPF_NEG) {
3607 			/* sreg is reserved and unused
3608 			 * dreg still need precision before this insn
3609 			 */
3610 			return 0;
3611 		} else if (opcode == BPF_MOV) {
3612 			if (BPF_SRC(insn->code) == BPF_X) {
3613 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3614 				 * dreg needs precision after this insn
3615 				 * sreg needs precision before this insn
3616 				 */
3617 				bt_clear_reg(bt, dreg);
3618 				bt_set_reg(bt, sreg);
3619 			} else {
3620 				/* dreg = K
3621 				 * dreg needs precision after this insn.
3622 				 * Corresponding register is already marked
3623 				 * as precise=true in this verifier state.
3624 				 * No further markings in parent are necessary
3625 				 */
3626 				bt_clear_reg(bt, dreg);
3627 			}
3628 		} else {
3629 			if (BPF_SRC(insn->code) == BPF_X) {
3630 				/* dreg += sreg
3631 				 * both dreg and sreg need precision
3632 				 * before this insn
3633 				 */
3634 				bt_set_reg(bt, sreg);
3635 			} /* else dreg += K
3636 			   * dreg still needs precision before this insn
3637 			   */
3638 		}
3639 	} else if (class == BPF_LDX) {
3640 		if (!bt_is_reg_set(bt, dreg))
3641 			return 0;
3642 		bt_clear_reg(bt, dreg);
3643 
3644 		/* scalars can only be spilled into stack w/o losing precision.
3645 		 * Load from any other memory can be zero extended.
3646 		 * The desire to keep that precision is already indicated
3647 		 * by 'precise' mark in corresponding register of this state.
3648 		 * No further tracking necessary.
3649 		 */
3650 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3651 			return 0;
3652 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3653 		 * that [fp - off] slot contains scalar that needs to be
3654 		 * tracked with precision
3655 		 */
3656 		spi = insn_stack_access_spi(hist->flags);
3657 		fr = insn_stack_access_frameno(hist->flags);
3658 		bt_set_frame_slot(bt, fr, spi);
3659 	} else if (class == BPF_STX || class == BPF_ST) {
3660 		if (bt_is_reg_set(bt, dreg))
3661 			/* stx & st shouldn't be using _scalar_ dst_reg
3662 			 * to access memory. It means backtracking
3663 			 * encountered a case of pointer subtraction.
3664 			 */
3665 			return -ENOTSUPP;
3666 		/* scalars can only be spilled into stack */
3667 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3668 			return 0;
3669 		spi = insn_stack_access_spi(hist->flags);
3670 		fr = insn_stack_access_frameno(hist->flags);
3671 		if (!bt_is_frame_slot_set(bt, fr, spi))
3672 			return 0;
3673 		bt_clear_frame_slot(bt, fr, spi);
3674 		if (class == BPF_STX)
3675 			bt_set_reg(bt, sreg);
3676 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3677 		if (bpf_pseudo_call(insn)) {
3678 			int subprog_insn_idx, subprog;
3679 
3680 			subprog_insn_idx = idx + insn->imm + 1;
3681 			subprog = find_subprog(env, subprog_insn_idx);
3682 			if (subprog < 0)
3683 				return -EFAULT;
3684 
3685 			if (subprog_is_global(env, subprog)) {
3686 				/* check that jump history doesn't have any
3687 				 * extra instructions from subprog; the next
3688 				 * instruction after call to global subprog
3689 				 * should be literally next instruction in
3690 				 * caller program
3691 				 */
3692 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3693 				/* r1-r5 are invalidated after subprog call,
3694 				 * so for global func call it shouldn't be set
3695 				 * anymore
3696 				 */
3697 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3698 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3699 					WARN_ONCE(1, "verifier backtracking bug");
3700 					return -EFAULT;
3701 				}
3702 				/* global subprog always sets R0 */
3703 				bt_clear_reg(bt, BPF_REG_0);
3704 				return 0;
3705 			} else {
3706 				/* static subprog call instruction, which
3707 				 * means that we are exiting current subprog,
3708 				 * so only r1-r5 could be still requested as
3709 				 * precise, r0 and r6-r10 or any stack slot in
3710 				 * the current frame should be zero by now
3711 				 */
3712 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3713 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3714 					WARN_ONCE(1, "verifier backtracking bug");
3715 					return -EFAULT;
3716 				}
3717 				/* we are now tracking register spills correctly,
3718 				 * so any instance of leftover slots is a bug
3719 				 */
3720 				if (bt_stack_mask(bt) != 0) {
3721 					verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3722 					WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)");
3723 					return -EFAULT;
3724 				}
3725 				/* propagate r1-r5 to the caller */
3726 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3727 					if (bt_is_reg_set(bt, i)) {
3728 						bt_clear_reg(bt, i);
3729 						bt_set_frame_reg(bt, bt->frame - 1, i);
3730 					}
3731 				}
3732 				if (bt_subprog_exit(bt))
3733 					return -EFAULT;
3734 				return 0;
3735 			}
3736 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3737 			/* exit from callback subprog to callback-calling helper or
3738 			 * kfunc call. Use idx/subseq_idx check to discern it from
3739 			 * straight line code backtracking.
3740 			 * Unlike the subprog call handling above, we shouldn't
3741 			 * propagate precision of r1-r5 (if any requested), as they are
3742 			 * not actually arguments passed directly to callback subprogs
3743 			 */
3744 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3745 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3746 				WARN_ONCE(1, "verifier backtracking bug");
3747 				return -EFAULT;
3748 			}
3749 			if (bt_stack_mask(bt) != 0) {
3750 				verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3751 				WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)");
3752 				return -EFAULT;
3753 			}
3754 			/* clear r1-r5 in callback subprog's mask */
3755 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3756 				bt_clear_reg(bt, i);
3757 			if (bt_subprog_exit(bt))
3758 				return -EFAULT;
3759 			return 0;
3760 		} else if (opcode == BPF_CALL) {
3761 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3762 			 * catch this error later. Make backtracking conservative
3763 			 * with ENOTSUPP.
3764 			 */
3765 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3766 				return -ENOTSUPP;
3767 			/* regular helper call sets R0 */
3768 			bt_clear_reg(bt, BPF_REG_0);
3769 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3770 				/* if backtracing was looking for registers R1-R5
3771 				 * they should have been found already.
3772 				 */
3773 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3774 				WARN_ONCE(1, "verifier backtracking bug");
3775 				return -EFAULT;
3776 			}
3777 		} else if (opcode == BPF_EXIT) {
3778 			bool r0_precise;
3779 
3780 			/* Backtracking to a nested function call, 'idx' is a part of
3781 			 * the inner frame 'subseq_idx' is a part of the outer frame.
3782 			 * In case of a regular function call, instructions giving
3783 			 * precision to registers R1-R5 should have been found already.
3784 			 * In case of a callback, it is ok to have R1-R5 marked for
3785 			 * backtracking, as these registers are set by the function
3786 			 * invoking callback.
3787 			 */
3788 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3789 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3790 					bt_clear_reg(bt, i);
3791 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3792 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3793 				WARN_ONCE(1, "verifier backtracking bug");
3794 				return -EFAULT;
3795 			}
3796 
3797 			/* BPF_EXIT in subprog or callback always returns
3798 			 * right after the call instruction, so by checking
3799 			 * whether the instruction at subseq_idx-1 is subprog
3800 			 * call or not we can distinguish actual exit from
3801 			 * *subprog* from exit from *callback*. In the former
3802 			 * case, we need to propagate r0 precision, if
3803 			 * necessary. In the former we never do that.
3804 			 */
3805 			r0_precise = subseq_idx - 1 >= 0 &&
3806 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3807 				     bt_is_reg_set(bt, BPF_REG_0);
3808 
3809 			bt_clear_reg(bt, BPF_REG_0);
3810 			if (bt_subprog_enter(bt))
3811 				return -EFAULT;
3812 
3813 			if (r0_precise)
3814 				bt_set_reg(bt, BPF_REG_0);
3815 			/* r6-r9 and stack slots will stay set in caller frame
3816 			 * bitmasks until we return back from callee(s)
3817 			 */
3818 			return 0;
3819 		} else if (BPF_SRC(insn->code) == BPF_X) {
3820 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3821 				return 0;
3822 			/* dreg <cond> sreg
3823 			 * Both dreg and sreg need precision before
3824 			 * this insn. If only sreg was marked precise
3825 			 * before it would be equally necessary to
3826 			 * propagate it to dreg.
3827 			 */
3828 			bt_set_reg(bt, dreg);
3829 			bt_set_reg(bt, sreg);
3830 			 /* else dreg <cond> K
3831 			  * Only dreg still needs precision before
3832 			  * this insn, so for the K-based conditional
3833 			  * there is nothing new to be marked.
3834 			  */
3835 		}
3836 	} else if (class == BPF_LD) {
3837 		if (!bt_is_reg_set(bt, dreg))
3838 			return 0;
3839 		bt_clear_reg(bt, dreg);
3840 		/* It's ld_imm64 or ld_abs or ld_ind.
3841 		 * For ld_imm64 no further tracking of precision
3842 		 * into parent is necessary
3843 		 */
3844 		if (mode == BPF_IND || mode == BPF_ABS)
3845 			/* to be analyzed */
3846 			return -ENOTSUPP;
3847 	}
3848 	return 0;
3849 }
3850 
3851 /* the scalar precision tracking algorithm:
3852  * . at the start all registers have precise=false.
3853  * . scalar ranges are tracked as normal through alu and jmp insns.
3854  * . once precise value of the scalar register is used in:
3855  *   .  ptr + scalar alu
3856  *   . if (scalar cond K|scalar)
3857  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3858  *   backtrack through the verifier states and mark all registers and
3859  *   stack slots with spilled constants that these scalar regisers
3860  *   should be precise.
3861  * . during state pruning two registers (or spilled stack slots)
3862  *   are equivalent if both are not precise.
3863  *
3864  * Note the verifier cannot simply walk register parentage chain,
3865  * since many different registers and stack slots could have been
3866  * used to compute single precise scalar.
3867  *
3868  * The approach of starting with precise=true for all registers and then
3869  * backtrack to mark a register as not precise when the verifier detects
3870  * that program doesn't care about specific value (e.g., when helper
3871  * takes register as ARG_ANYTHING parameter) is not safe.
3872  *
3873  * It's ok to walk single parentage chain of the verifier states.
3874  * It's possible that this backtracking will go all the way till 1st insn.
3875  * All other branches will be explored for needing precision later.
3876  *
3877  * The backtracking needs to deal with cases like:
3878  *   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)
3879  * r9 -= r8
3880  * r5 = r9
3881  * if r5 > 0x79f goto pc+7
3882  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3883  * r5 += 1
3884  * ...
3885  * call bpf_perf_event_output#25
3886  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3887  *
3888  * and this case:
3889  * r6 = 1
3890  * call foo // uses callee's r6 inside to compute r0
3891  * r0 += r6
3892  * if r0 == 0 goto
3893  *
3894  * to track above reg_mask/stack_mask needs to be independent for each frame.
3895  *
3896  * Also if parent's curframe > frame where backtracking started,
3897  * the verifier need to mark registers in both frames, otherwise callees
3898  * may incorrectly prune callers. This is similar to
3899  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3900  *
3901  * For now backtracking falls back into conservative marking.
3902  */
3903 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3904 				     struct bpf_verifier_state *st)
3905 {
3906 	struct bpf_func_state *func;
3907 	struct bpf_reg_state *reg;
3908 	int i, j;
3909 
3910 	if (env->log.level & BPF_LOG_LEVEL2) {
3911 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3912 			st->curframe);
3913 	}
3914 
3915 	/* big hammer: mark all scalars precise in this path.
3916 	 * pop_stack may still get !precise scalars.
3917 	 * We also skip current state and go straight to first parent state,
3918 	 * because precision markings in current non-checkpointed state are
3919 	 * not needed. See why in the comment in __mark_chain_precision below.
3920 	 */
3921 	for (st = st->parent; st; st = st->parent) {
3922 		for (i = 0; i <= st->curframe; i++) {
3923 			func = st->frame[i];
3924 			for (j = 0; j < BPF_REG_FP; j++) {
3925 				reg = &func->regs[j];
3926 				if (reg->type != SCALAR_VALUE || reg->precise)
3927 					continue;
3928 				reg->precise = true;
3929 				if (env->log.level & BPF_LOG_LEVEL2) {
3930 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3931 						i, j);
3932 				}
3933 			}
3934 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3935 				if (!is_spilled_reg(&func->stack[j]))
3936 					continue;
3937 				reg = &func->stack[j].spilled_ptr;
3938 				if (reg->type != SCALAR_VALUE || reg->precise)
3939 					continue;
3940 				reg->precise = true;
3941 				if (env->log.level & BPF_LOG_LEVEL2) {
3942 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3943 						i, -(j + 1) * 8);
3944 				}
3945 			}
3946 		}
3947 	}
3948 }
3949 
3950 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3951 {
3952 	struct bpf_func_state *func;
3953 	struct bpf_reg_state *reg;
3954 	int i, j;
3955 
3956 	for (i = 0; i <= st->curframe; i++) {
3957 		func = st->frame[i];
3958 		for (j = 0; j < BPF_REG_FP; j++) {
3959 			reg = &func->regs[j];
3960 			if (reg->type != SCALAR_VALUE)
3961 				continue;
3962 			reg->precise = false;
3963 		}
3964 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3965 			if (!is_spilled_reg(&func->stack[j]))
3966 				continue;
3967 			reg = &func->stack[j].spilled_ptr;
3968 			if (reg->type != SCALAR_VALUE)
3969 				continue;
3970 			reg->precise = false;
3971 		}
3972 	}
3973 }
3974 
3975 static bool idset_contains(struct bpf_idset *s, u32 id)
3976 {
3977 	u32 i;
3978 
3979 	for (i = 0; i < s->count; ++i)
3980 		if (s->ids[i] == id)
3981 			return true;
3982 
3983 	return false;
3984 }
3985 
3986 static int idset_push(struct bpf_idset *s, u32 id)
3987 {
3988 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3989 		return -EFAULT;
3990 	s->ids[s->count++] = id;
3991 	return 0;
3992 }
3993 
3994 static void idset_reset(struct bpf_idset *s)
3995 {
3996 	s->count = 0;
3997 }
3998 
3999 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
4000  * Mark all registers with these IDs as precise.
4001  */
4002 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4003 {
4004 	struct bpf_idset *precise_ids = &env->idset_scratch;
4005 	struct backtrack_state *bt = &env->bt;
4006 	struct bpf_func_state *func;
4007 	struct bpf_reg_state *reg;
4008 	DECLARE_BITMAP(mask, 64);
4009 	int i, fr;
4010 
4011 	idset_reset(precise_ids);
4012 
4013 	for (fr = bt->frame; fr >= 0; fr--) {
4014 		func = st->frame[fr];
4015 
4016 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4017 		for_each_set_bit(i, mask, 32) {
4018 			reg = &func->regs[i];
4019 			if (!reg->id || reg->type != SCALAR_VALUE)
4020 				continue;
4021 			if (idset_push(precise_ids, reg->id))
4022 				return -EFAULT;
4023 		}
4024 
4025 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4026 		for_each_set_bit(i, mask, 64) {
4027 			if (i >= func->allocated_stack / BPF_REG_SIZE)
4028 				break;
4029 			if (!is_spilled_scalar_reg(&func->stack[i]))
4030 				continue;
4031 			reg = &func->stack[i].spilled_ptr;
4032 			if (!reg->id)
4033 				continue;
4034 			if (idset_push(precise_ids, reg->id))
4035 				return -EFAULT;
4036 		}
4037 	}
4038 
4039 	for (fr = 0; fr <= st->curframe; ++fr) {
4040 		func = st->frame[fr];
4041 
4042 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4043 			reg = &func->regs[i];
4044 			if (!reg->id)
4045 				continue;
4046 			if (!idset_contains(precise_ids, reg->id))
4047 				continue;
4048 			bt_set_frame_reg(bt, fr, i);
4049 		}
4050 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4051 			if (!is_spilled_scalar_reg(&func->stack[i]))
4052 				continue;
4053 			reg = &func->stack[i].spilled_ptr;
4054 			if (!reg->id)
4055 				continue;
4056 			if (!idset_contains(precise_ids, reg->id))
4057 				continue;
4058 			bt_set_frame_slot(bt, fr, i);
4059 		}
4060 	}
4061 
4062 	return 0;
4063 }
4064 
4065 /*
4066  * __mark_chain_precision() backtracks BPF program instruction sequence and
4067  * chain of verifier states making sure that register *regno* (if regno >= 0)
4068  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4069  * SCALARS, as well as any other registers and slots that contribute to
4070  * a tracked state of given registers/stack slots, depending on specific BPF
4071  * assembly instructions (see backtrack_insns() for exact instruction handling
4072  * logic). This backtracking relies on recorded jmp_history and is able to
4073  * traverse entire chain of parent states. This process ends only when all the
4074  * necessary registers/slots and their transitive dependencies are marked as
4075  * precise.
4076  *
4077  * One important and subtle aspect is that precise marks *do not matter* in
4078  * the currently verified state (current state). It is important to understand
4079  * why this is the case.
4080  *
4081  * First, note that current state is the state that is not yet "checkpointed",
4082  * i.e., it is not yet put into env->explored_states, and it has no children
4083  * states as well. It's ephemeral, and can end up either a) being discarded if
4084  * compatible explored state is found at some point or BPF_EXIT instruction is
4085  * reached or b) checkpointed and put into env->explored_states, branching out
4086  * into one or more children states.
4087  *
4088  * In the former case, precise markings in current state are completely
4089  * ignored by state comparison code (see regsafe() for details). Only
4090  * checkpointed ("old") state precise markings are important, and if old
4091  * state's register/slot is precise, regsafe() assumes current state's
4092  * register/slot as precise and checks value ranges exactly and precisely. If
4093  * states turn out to be compatible, current state's necessary precise
4094  * markings and any required parent states' precise markings are enforced
4095  * after the fact with propagate_precision() logic, after the fact. But it's
4096  * important to realize that in this case, even after marking current state
4097  * registers/slots as precise, we immediately discard current state. So what
4098  * actually matters is any of the precise markings propagated into current
4099  * state's parent states, which are always checkpointed (due to b) case above).
4100  * As such, for scenario a) it doesn't matter if current state has precise
4101  * markings set or not.
4102  *
4103  * Now, for the scenario b), checkpointing and forking into child(ren)
4104  * state(s). Note that before current state gets to checkpointing step, any
4105  * processed instruction always assumes precise SCALAR register/slot
4106  * knowledge: if precise value or range is useful to prune jump branch, BPF
4107  * verifier takes this opportunity enthusiastically. Similarly, when
4108  * register's value is used to calculate offset or memory address, exact
4109  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4110  * what we mentioned above about state comparison ignoring precise markings
4111  * during state comparison, BPF verifier ignores and also assumes precise
4112  * markings *at will* during instruction verification process. But as verifier
4113  * assumes precision, it also propagates any precision dependencies across
4114  * parent states, which are not yet finalized, so can be further restricted
4115  * based on new knowledge gained from restrictions enforced by their children
4116  * states. This is so that once those parent states are finalized, i.e., when
4117  * they have no more active children state, state comparison logic in
4118  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4119  * required for correctness.
4120  *
4121  * To build a bit more intuition, note also that once a state is checkpointed,
4122  * the path we took to get to that state is not important. This is crucial
4123  * property for state pruning. When state is checkpointed and finalized at
4124  * some instruction index, it can be correctly and safely used to "short
4125  * circuit" any *compatible* state that reaches exactly the same instruction
4126  * index. I.e., if we jumped to that instruction from a completely different
4127  * code path than original finalized state was derived from, it doesn't
4128  * matter, current state can be discarded because from that instruction
4129  * forward having a compatible state will ensure we will safely reach the
4130  * exit. States describe preconditions for further exploration, but completely
4131  * forget the history of how we got here.
4132  *
4133  * This also means that even if we needed precise SCALAR range to get to
4134  * finalized state, but from that point forward *that same* SCALAR register is
4135  * never used in a precise context (i.e., it's precise value is not needed for
4136  * correctness), it's correct and safe to mark such register as "imprecise"
4137  * (i.e., precise marking set to false). This is what we rely on when we do
4138  * not set precise marking in current state. If no child state requires
4139  * precision for any given SCALAR register, it's safe to dictate that it can
4140  * be imprecise. If any child state does require this register to be precise,
4141  * we'll mark it precise later retroactively during precise markings
4142  * propagation from child state to parent states.
4143  *
4144  * Skipping precise marking setting in current state is a mild version of
4145  * relying on the above observation. But we can utilize this property even
4146  * more aggressively by proactively forgetting any precise marking in the
4147  * current state (which we inherited from the parent state), right before we
4148  * checkpoint it and branch off into new child state. This is done by
4149  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4150  * finalized states which help in short circuiting more future states.
4151  */
4152 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4153 {
4154 	struct backtrack_state *bt = &env->bt;
4155 	struct bpf_verifier_state *st = env->cur_state;
4156 	int first_idx = st->first_insn_idx;
4157 	int last_idx = env->insn_idx;
4158 	int subseq_idx = -1;
4159 	struct bpf_func_state *func;
4160 	struct bpf_reg_state *reg;
4161 	bool skip_first = true;
4162 	int i, fr, err;
4163 
4164 	if (!env->bpf_capable)
4165 		return 0;
4166 
4167 	/* set frame number from which we are starting to backtrack */
4168 	bt_init(bt, env->cur_state->curframe);
4169 
4170 	/* Do sanity checks against current state of register and/or stack
4171 	 * slot, but don't set precise flag in current state, as precision
4172 	 * tracking in the current state is unnecessary.
4173 	 */
4174 	func = st->frame[bt->frame];
4175 	if (regno >= 0) {
4176 		reg = &func->regs[regno];
4177 		if (reg->type != SCALAR_VALUE) {
4178 			WARN_ONCE(1, "backtracing misuse");
4179 			return -EFAULT;
4180 		}
4181 		bt_set_reg(bt, regno);
4182 	}
4183 
4184 	if (bt_empty(bt))
4185 		return 0;
4186 
4187 	for (;;) {
4188 		DECLARE_BITMAP(mask, 64);
4189 		u32 history = st->jmp_history_cnt;
4190 		struct bpf_jmp_history_entry *hist;
4191 
4192 		if (env->log.level & BPF_LOG_LEVEL2) {
4193 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4194 				bt->frame, last_idx, first_idx, subseq_idx);
4195 		}
4196 
4197 		/* If some register with scalar ID is marked as precise,
4198 		 * make sure that all registers sharing this ID are also precise.
4199 		 * This is needed to estimate effect of find_equal_scalars().
4200 		 * Do this at the last instruction of each state,
4201 		 * bpf_reg_state::id fields are valid for these instructions.
4202 		 *
4203 		 * Allows to track precision in situation like below:
4204 		 *
4205 		 *     r2 = unknown value
4206 		 *     ...
4207 		 *   --- state #0 ---
4208 		 *     ...
4209 		 *     r1 = r2                 // r1 and r2 now share the same ID
4210 		 *     ...
4211 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4212 		 *     ...
4213 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4214 		 *     ...
4215 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4216 		 *     r3 = r10
4217 		 *     r3 += r1                // need to mark both r1 and r2
4218 		 */
4219 		if (mark_precise_scalar_ids(env, st))
4220 			return -EFAULT;
4221 
4222 		if (last_idx < 0) {
4223 			/* we are at the entry into subprog, which
4224 			 * is expected for global funcs, but only if
4225 			 * requested precise registers are R1-R5
4226 			 * (which are global func's input arguments)
4227 			 */
4228 			if (st->curframe == 0 &&
4229 			    st->frame[0]->subprogno > 0 &&
4230 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4231 			    bt_stack_mask(bt) == 0 &&
4232 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4233 				bitmap_from_u64(mask, bt_reg_mask(bt));
4234 				for_each_set_bit(i, mask, 32) {
4235 					reg = &st->frame[0]->regs[i];
4236 					bt_clear_reg(bt, i);
4237 					if (reg->type == SCALAR_VALUE)
4238 						reg->precise = true;
4239 				}
4240 				return 0;
4241 			}
4242 
4243 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4244 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4245 			WARN_ONCE(1, "verifier backtracking bug");
4246 			return -EFAULT;
4247 		}
4248 
4249 		for (i = last_idx;;) {
4250 			if (skip_first) {
4251 				err = 0;
4252 				skip_first = false;
4253 			} else {
4254 				hist = get_jmp_hist_entry(st, history, i);
4255 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4256 			}
4257 			if (err == -ENOTSUPP) {
4258 				mark_all_scalars_precise(env, env->cur_state);
4259 				bt_reset(bt);
4260 				return 0;
4261 			} else if (err) {
4262 				return err;
4263 			}
4264 			if (bt_empty(bt))
4265 				/* Found assignment(s) into tracked register in this state.
4266 				 * Since this state is already marked, just return.
4267 				 * Nothing to be tracked further in the parent state.
4268 				 */
4269 				return 0;
4270 			subseq_idx = i;
4271 			i = get_prev_insn_idx(st, i, &history);
4272 			if (i == -ENOENT)
4273 				break;
4274 			if (i >= env->prog->len) {
4275 				/* This can happen if backtracking reached insn 0
4276 				 * and there are still reg_mask or stack_mask
4277 				 * to backtrack.
4278 				 * It means the backtracking missed the spot where
4279 				 * particular register was initialized with a constant.
4280 				 */
4281 				verbose(env, "BUG backtracking idx %d\n", i);
4282 				WARN_ONCE(1, "verifier backtracking bug");
4283 				return -EFAULT;
4284 			}
4285 		}
4286 		st = st->parent;
4287 		if (!st)
4288 			break;
4289 
4290 		for (fr = bt->frame; fr >= 0; fr--) {
4291 			func = st->frame[fr];
4292 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4293 			for_each_set_bit(i, mask, 32) {
4294 				reg = &func->regs[i];
4295 				if (reg->type != SCALAR_VALUE) {
4296 					bt_clear_frame_reg(bt, fr, i);
4297 					continue;
4298 				}
4299 				if (reg->precise)
4300 					bt_clear_frame_reg(bt, fr, i);
4301 				else
4302 					reg->precise = true;
4303 			}
4304 
4305 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4306 			for_each_set_bit(i, mask, 64) {
4307 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4308 					verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n",
4309 						i, func->allocated_stack / BPF_REG_SIZE);
4310 					WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)");
4311 					return -EFAULT;
4312 				}
4313 
4314 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4315 					bt_clear_frame_slot(bt, fr, i);
4316 					continue;
4317 				}
4318 				reg = &func->stack[i].spilled_ptr;
4319 				if (reg->precise)
4320 					bt_clear_frame_slot(bt, fr, i);
4321 				else
4322 					reg->precise = true;
4323 			}
4324 			if (env->log.level & BPF_LOG_LEVEL2) {
4325 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4326 					     bt_frame_reg_mask(bt, fr));
4327 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4328 					fr, env->tmp_str_buf);
4329 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4330 					       bt_frame_stack_mask(bt, fr));
4331 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4332 				print_verifier_state(env, func, true);
4333 			}
4334 		}
4335 
4336 		if (bt_empty(bt))
4337 			return 0;
4338 
4339 		subseq_idx = first_idx;
4340 		last_idx = st->last_insn_idx;
4341 		first_idx = st->first_insn_idx;
4342 	}
4343 
4344 	/* if we still have requested precise regs or slots, we missed
4345 	 * something (e.g., stack access through non-r10 register), so
4346 	 * fallback to marking all precise
4347 	 */
4348 	if (!bt_empty(bt)) {
4349 		mark_all_scalars_precise(env, env->cur_state);
4350 		bt_reset(bt);
4351 	}
4352 
4353 	return 0;
4354 }
4355 
4356 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4357 {
4358 	return __mark_chain_precision(env, regno);
4359 }
4360 
4361 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4362  * desired reg and stack masks across all relevant frames
4363  */
4364 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4365 {
4366 	return __mark_chain_precision(env, -1);
4367 }
4368 
4369 static bool is_spillable_regtype(enum bpf_reg_type type)
4370 {
4371 	switch (base_type(type)) {
4372 	case PTR_TO_MAP_VALUE:
4373 	case PTR_TO_STACK:
4374 	case PTR_TO_CTX:
4375 	case PTR_TO_PACKET:
4376 	case PTR_TO_PACKET_META:
4377 	case PTR_TO_PACKET_END:
4378 	case PTR_TO_FLOW_KEYS:
4379 	case CONST_PTR_TO_MAP:
4380 	case PTR_TO_SOCKET:
4381 	case PTR_TO_SOCK_COMMON:
4382 	case PTR_TO_TCP_SOCK:
4383 	case PTR_TO_XDP_SOCK:
4384 	case PTR_TO_BTF_ID:
4385 	case PTR_TO_BUF:
4386 	case PTR_TO_MEM:
4387 	case PTR_TO_FUNC:
4388 	case PTR_TO_MAP_KEY:
4389 	case PTR_TO_ARENA:
4390 		return true;
4391 	default:
4392 		return false;
4393 	}
4394 }
4395 
4396 /* Does this register contain a constant zero? */
4397 static bool register_is_null(struct bpf_reg_state *reg)
4398 {
4399 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4400 }
4401 
4402 /* check if register is a constant scalar value */
4403 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4404 {
4405 	return reg->type == SCALAR_VALUE &&
4406 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4407 }
4408 
4409 /* assuming is_reg_const() is true, return constant value of a register */
4410 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4411 {
4412 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4413 }
4414 
4415 static bool __is_pointer_value(bool allow_ptr_leaks,
4416 			       const struct bpf_reg_state *reg)
4417 {
4418 	if (allow_ptr_leaks)
4419 		return false;
4420 
4421 	return reg->type != SCALAR_VALUE;
4422 }
4423 
4424 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4425 					struct bpf_reg_state *src_reg)
4426 {
4427 	if (src_reg->type == SCALAR_VALUE && !src_reg->id &&
4428 	    !tnum_is_const(src_reg->var_off))
4429 		/* Ensure that src_reg has a valid ID that will be copied to
4430 		 * dst_reg and then will be used by find_equal_scalars() to
4431 		 * propagate min/max range.
4432 		 */
4433 		src_reg->id = ++env->id_gen;
4434 }
4435 
4436 /* Copy src state preserving dst->parent and dst->live fields */
4437 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4438 {
4439 	struct bpf_reg_state *parent = dst->parent;
4440 	enum bpf_reg_liveness live = dst->live;
4441 
4442 	*dst = *src;
4443 	dst->parent = parent;
4444 	dst->live = live;
4445 }
4446 
4447 static void save_register_state(struct bpf_verifier_env *env,
4448 				struct bpf_func_state *state,
4449 				int spi, struct bpf_reg_state *reg,
4450 				int size)
4451 {
4452 	int i;
4453 
4454 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4455 	if (size == BPF_REG_SIZE)
4456 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4457 
4458 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4459 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4460 
4461 	/* size < 8 bytes spill */
4462 	for (; i; i--)
4463 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4464 }
4465 
4466 static bool is_bpf_st_mem(struct bpf_insn *insn)
4467 {
4468 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4469 }
4470 
4471 static int get_reg_width(struct bpf_reg_state *reg)
4472 {
4473 	return fls64(reg->umax_value);
4474 }
4475 
4476 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4477  * stack boundary and alignment are checked in check_mem_access()
4478  */
4479 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4480 				       /* stack frame we're writing to */
4481 				       struct bpf_func_state *state,
4482 				       int off, int size, int value_regno,
4483 				       int insn_idx)
4484 {
4485 	struct bpf_func_state *cur; /* state of the current function */
4486 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4487 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4488 	struct bpf_reg_state *reg = NULL;
4489 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
4490 
4491 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4492 	 * so it's aligned access and [off, off + size) are within stack limits
4493 	 */
4494 	if (!env->allow_ptr_leaks &&
4495 	    is_spilled_reg(&state->stack[spi]) &&
4496 	    size != BPF_REG_SIZE) {
4497 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4498 		return -EACCES;
4499 	}
4500 
4501 	cur = env->cur_state->frame[env->cur_state->curframe];
4502 	if (value_regno >= 0)
4503 		reg = &cur->regs[value_regno];
4504 	if (!env->bypass_spec_v4) {
4505 		bool sanitize = reg && is_spillable_regtype(reg->type);
4506 
4507 		for (i = 0; i < size; i++) {
4508 			u8 type = state->stack[spi].slot_type[i];
4509 
4510 			if (type != STACK_MISC && type != STACK_ZERO) {
4511 				sanitize = true;
4512 				break;
4513 			}
4514 		}
4515 
4516 		if (sanitize)
4517 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4518 	}
4519 
4520 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4521 	if (err)
4522 		return err;
4523 
4524 	mark_stack_slot_scratched(env, spi);
4525 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
4526 		bool reg_value_fits;
4527 
4528 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
4529 		/* Make sure that reg had an ID to build a relation on spill. */
4530 		if (reg_value_fits)
4531 			assign_scalar_id_before_mov(env, reg);
4532 		save_register_state(env, state, spi, reg, size);
4533 		/* Break the relation on a narrowing spill. */
4534 		if (!reg_value_fits)
4535 			state->stack[spi].spilled_ptr.id = 0;
4536 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4537 		   env->bpf_capable) {
4538 		struct bpf_reg_state fake_reg = {};
4539 
4540 		__mark_reg_known(&fake_reg, insn->imm);
4541 		fake_reg.type = SCALAR_VALUE;
4542 		save_register_state(env, state, spi, &fake_reg, size);
4543 	} else if (reg && is_spillable_regtype(reg->type)) {
4544 		/* register containing pointer is being spilled into stack */
4545 		if (size != BPF_REG_SIZE) {
4546 			verbose_linfo(env, insn_idx, "; ");
4547 			verbose(env, "invalid size of register spill\n");
4548 			return -EACCES;
4549 		}
4550 		if (state != cur && reg->type == PTR_TO_STACK) {
4551 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4552 			return -EINVAL;
4553 		}
4554 		save_register_state(env, state, spi, reg, size);
4555 	} else {
4556 		u8 type = STACK_MISC;
4557 
4558 		/* regular write of data into stack destroys any spilled ptr */
4559 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4560 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4561 		if (is_stack_slot_special(&state->stack[spi]))
4562 			for (i = 0; i < BPF_REG_SIZE; i++)
4563 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4564 
4565 		/* only mark the slot as written if all 8 bytes were written
4566 		 * otherwise read propagation may incorrectly stop too soon
4567 		 * when stack slots are partially written.
4568 		 * This heuristic means that read propagation will be
4569 		 * conservative, since it will add reg_live_read marks
4570 		 * to stack slots all the way to first state when programs
4571 		 * writes+reads less than 8 bytes
4572 		 */
4573 		if (size == BPF_REG_SIZE)
4574 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4575 
4576 		/* when we zero initialize stack slots mark them as such */
4577 		if ((reg && register_is_null(reg)) ||
4578 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4579 			/* STACK_ZERO case happened because register spill
4580 			 * wasn't properly aligned at the stack slot boundary,
4581 			 * so it's not a register spill anymore; force
4582 			 * originating register to be precise to make
4583 			 * STACK_ZERO correct for subsequent states
4584 			 */
4585 			err = mark_chain_precision(env, value_regno);
4586 			if (err)
4587 				return err;
4588 			type = STACK_ZERO;
4589 		}
4590 
4591 		/* Mark slots affected by this stack write. */
4592 		for (i = 0; i < size; i++)
4593 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
4594 		insn_flags = 0; /* not a register spill */
4595 	}
4596 
4597 	if (insn_flags)
4598 		return push_jmp_history(env, env->cur_state, insn_flags);
4599 	return 0;
4600 }
4601 
4602 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4603  * known to contain a variable offset.
4604  * This function checks whether the write is permitted and conservatively
4605  * tracks the effects of the write, considering that each stack slot in the
4606  * dynamic range is potentially written to.
4607  *
4608  * 'off' includes 'regno->off'.
4609  * 'value_regno' can be -1, meaning that an unknown value is being written to
4610  * the stack.
4611  *
4612  * Spilled pointers in range are not marked as written because we don't know
4613  * what's going to be actually written. This means that read propagation for
4614  * future reads cannot be terminated by this write.
4615  *
4616  * For privileged programs, uninitialized stack slots are considered
4617  * initialized by this write (even though we don't know exactly what offsets
4618  * are going to be written to). The idea is that we don't want the verifier to
4619  * reject future reads that access slots written to through variable offsets.
4620  */
4621 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4622 				     /* func where register points to */
4623 				     struct bpf_func_state *state,
4624 				     int ptr_regno, int off, int size,
4625 				     int value_regno, int insn_idx)
4626 {
4627 	struct bpf_func_state *cur; /* state of the current function */
4628 	int min_off, max_off;
4629 	int i, err;
4630 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4631 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4632 	bool writing_zero = false;
4633 	/* set if the fact that we're writing a zero is used to let any
4634 	 * stack slots remain STACK_ZERO
4635 	 */
4636 	bool zero_used = false;
4637 
4638 	cur = env->cur_state->frame[env->cur_state->curframe];
4639 	ptr_reg = &cur->regs[ptr_regno];
4640 	min_off = ptr_reg->smin_value + off;
4641 	max_off = ptr_reg->smax_value + off + size;
4642 	if (value_regno >= 0)
4643 		value_reg = &cur->regs[value_regno];
4644 	if ((value_reg && register_is_null(value_reg)) ||
4645 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4646 		writing_zero = true;
4647 
4648 	for (i = min_off; i < max_off; i++) {
4649 		int spi;
4650 
4651 		spi = __get_spi(i);
4652 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4653 		if (err)
4654 			return err;
4655 	}
4656 
4657 	/* Variable offset writes destroy any spilled pointers in range. */
4658 	for (i = min_off; i < max_off; i++) {
4659 		u8 new_type, *stype;
4660 		int slot, spi;
4661 
4662 		slot = -i - 1;
4663 		spi = slot / BPF_REG_SIZE;
4664 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4665 		mark_stack_slot_scratched(env, spi);
4666 
4667 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4668 			/* Reject the write if range we may write to has not
4669 			 * been initialized beforehand. If we didn't reject
4670 			 * here, the ptr status would be erased below (even
4671 			 * though not all slots are actually overwritten),
4672 			 * possibly opening the door to leaks.
4673 			 *
4674 			 * We do however catch STACK_INVALID case below, and
4675 			 * only allow reading possibly uninitialized memory
4676 			 * later for CAP_PERFMON, as the write may not happen to
4677 			 * that slot.
4678 			 */
4679 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4680 				insn_idx, i);
4681 			return -EINVAL;
4682 		}
4683 
4684 		/* If writing_zero and the spi slot contains a spill of value 0,
4685 		 * maintain the spill type.
4686 		 */
4687 		if (writing_zero && *stype == STACK_SPILL &&
4688 		    is_spilled_scalar_reg(&state->stack[spi])) {
4689 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
4690 
4691 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
4692 				zero_used = true;
4693 				continue;
4694 			}
4695 		}
4696 
4697 		/* Erase all other spilled pointers. */
4698 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4699 
4700 		/* Update the slot type. */
4701 		new_type = STACK_MISC;
4702 		if (writing_zero && *stype == STACK_ZERO) {
4703 			new_type = STACK_ZERO;
4704 			zero_used = true;
4705 		}
4706 		/* If the slot is STACK_INVALID, we check whether it's OK to
4707 		 * pretend that it will be initialized by this write. The slot
4708 		 * might not actually be written to, and so if we mark it as
4709 		 * initialized future reads might leak uninitialized memory.
4710 		 * For privileged programs, we will accept such reads to slots
4711 		 * that may or may not be written because, if we're reject
4712 		 * them, the error would be too confusing.
4713 		 */
4714 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4715 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4716 					insn_idx, i);
4717 			return -EINVAL;
4718 		}
4719 		*stype = new_type;
4720 	}
4721 	if (zero_used) {
4722 		/* backtracking doesn't work for STACK_ZERO yet. */
4723 		err = mark_chain_precision(env, value_regno);
4724 		if (err)
4725 			return err;
4726 	}
4727 	return 0;
4728 }
4729 
4730 /* When register 'dst_regno' is assigned some values from stack[min_off,
4731  * max_off), we set the register's type according to the types of the
4732  * respective stack slots. If all the stack values are known to be zeros, then
4733  * so is the destination reg. Otherwise, the register is considered to be
4734  * SCALAR. This function does not deal with register filling; the caller must
4735  * ensure that all spilled registers in the stack range have been marked as
4736  * read.
4737  */
4738 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4739 				/* func where src register points to */
4740 				struct bpf_func_state *ptr_state,
4741 				int min_off, int max_off, int dst_regno)
4742 {
4743 	struct bpf_verifier_state *vstate = env->cur_state;
4744 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4745 	int i, slot, spi;
4746 	u8 *stype;
4747 	int zeros = 0;
4748 
4749 	for (i = min_off; i < max_off; i++) {
4750 		slot = -i - 1;
4751 		spi = slot / BPF_REG_SIZE;
4752 		mark_stack_slot_scratched(env, spi);
4753 		stype = ptr_state->stack[spi].slot_type;
4754 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4755 			break;
4756 		zeros++;
4757 	}
4758 	if (zeros == max_off - min_off) {
4759 		/* Any access_size read into register is zero extended,
4760 		 * so the whole register == const_zero.
4761 		 */
4762 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
4763 	} else {
4764 		/* have read misc data from the stack */
4765 		mark_reg_unknown(env, state->regs, dst_regno);
4766 	}
4767 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4768 }
4769 
4770 /* Read the stack at 'off' and put the results into the register indicated by
4771  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4772  * spilled reg.
4773  *
4774  * 'dst_regno' can be -1, meaning that the read value is not going to a
4775  * register.
4776  *
4777  * The access is assumed to be within the current stack bounds.
4778  */
4779 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4780 				      /* func where src register points to */
4781 				      struct bpf_func_state *reg_state,
4782 				      int off, int size, int dst_regno)
4783 {
4784 	struct bpf_verifier_state *vstate = env->cur_state;
4785 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4786 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4787 	struct bpf_reg_state *reg;
4788 	u8 *stype, type;
4789 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
4790 
4791 	stype = reg_state->stack[spi].slot_type;
4792 	reg = &reg_state->stack[spi].spilled_ptr;
4793 
4794 	mark_stack_slot_scratched(env, spi);
4795 
4796 	if (is_spilled_reg(&reg_state->stack[spi])) {
4797 		u8 spill_size = 1;
4798 
4799 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4800 			spill_size++;
4801 
4802 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4803 			if (reg->type != SCALAR_VALUE) {
4804 				verbose_linfo(env, env->insn_idx, "; ");
4805 				verbose(env, "invalid size of register fill\n");
4806 				return -EACCES;
4807 			}
4808 
4809 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4810 			if (dst_regno < 0)
4811 				return 0;
4812 
4813 			if (size <= spill_size &&
4814 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
4815 				/* The earlier check_reg_arg() has decided the
4816 				 * subreg_def for this insn.  Save it first.
4817 				 */
4818 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4819 
4820 				copy_register_state(&state->regs[dst_regno], reg);
4821 				state->regs[dst_regno].subreg_def = subreg_def;
4822 
4823 				/* Break the relation on a narrowing fill.
4824 				 * coerce_reg_to_size will adjust the boundaries.
4825 				 */
4826 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
4827 					state->regs[dst_regno].id = 0;
4828 			} else {
4829 				int spill_cnt = 0, zero_cnt = 0;
4830 
4831 				for (i = 0; i < size; i++) {
4832 					type = stype[(slot - i) % BPF_REG_SIZE];
4833 					if (type == STACK_SPILL) {
4834 						spill_cnt++;
4835 						continue;
4836 					}
4837 					if (type == STACK_MISC)
4838 						continue;
4839 					if (type == STACK_ZERO) {
4840 						zero_cnt++;
4841 						continue;
4842 					}
4843 					if (type == STACK_INVALID && env->allow_uninit_stack)
4844 						continue;
4845 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4846 						off, i, size);
4847 					return -EACCES;
4848 				}
4849 
4850 				if (spill_cnt == size &&
4851 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
4852 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4853 					/* this IS register fill, so keep insn_flags */
4854 				} else if (zero_cnt == size) {
4855 					/* similarly to mark_reg_stack_read(), preserve zeroes */
4856 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4857 					insn_flags = 0; /* not restoring original register state */
4858 				} else {
4859 					mark_reg_unknown(env, state->regs, dst_regno);
4860 					insn_flags = 0; /* not restoring original register state */
4861 				}
4862 			}
4863 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4864 		} else if (dst_regno >= 0) {
4865 			/* restore register state from stack */
4866 			copy_register_state(&state->regs[dst_regno], reg);
4867 			/* mark reg as written since spilled pointer state likely
4868 			 * has its liveness marks cleared by is_state_visited()
4869 			 * which resets stack/reg liveness for state transitions
4870 			 */
4871 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4872 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4873 			/* If dst_regno==-1, the caller is asking us whether
4874 			 * it is acceptable to use this value as a SCALAR_VALUE
4875 			 * (e.g. for XADD).
4876 			 * We must not allow unprivileged callers to do that
4877 			 * with spilled pointers.
4878 			 */
4879 			verbose(env, "leaking pointer from stack off %d\n",
4880 				off);
4881 			return -EACCES;
4882 		}
4883 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4884 	} else {
4885 		for (i = 0; i < size; i++) {
4886 			type = stype[(slot - i) % BPF_REG_SIZE];
4887 			if (type == STACK_MISC)
4888 				continue;
4889 			if (type == STACK_ZERO)
4890 				continue;
4891 			if (type == STACK_INVALID && env->allow_uninit_stack)
4892 				continue;
4893 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4894 				off, i, size);
4895 			return -EACCES;
4896 		}
4897 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4898 		if (dst_regno >= 0)
4899 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4900 		insn_flags = 0; /* we are not restoring spilled register */
4901 	}
4902 	if (insn_flags)
4903 		return push_jmp_history(env, env->cur_state, insn_flags);
4904 	return 0;
4905 }
4906 
4907 enum bpf_access_src {
4908 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4909 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4910 };
4911 
4912 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4913 					 int regno, int off, int access_size,
4914 					 bool zero_size_allowed,
4915 					 enum bpf_access_src type,
4916 					 struct bpf_call_arg_meta *meta);
4917 
4918 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4919 {
4920 	return cur_regs(env) + regno;
4921 }
4922 
4923 /* Read the stack at 'ptr_regno + off' and put the result into the register
4924  * 'dst_regno'.
4925  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4926  * but not its variable offset.
4927  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4928  *
4929  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4930  * filling registers (i.e. reads of spilled register cannot be detected when
4931  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4932  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4933  * offset; for a fixed offset check_stack_read_fixed_off should be used
4934  * instead.
4935  */
4936 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4937 				    int ptr_regno, int off, int size, int dst_regno)
4938 {
4939 	/* The state of the source register. */
4940 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4941 	struct bpf_func_state *ptr_state = func(env, reg);
4942 	int err;
4943 	int min_off, max_off;
4944 
4945 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4946 	 */
4947 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4948 					    false, ACCESS_DIRECT, NULL);
4949 	if (err)
4950 		return err;
4951 
4952 	min_off = reg->smin_value + off;
4953 	max_off = reg->smax_value + off;
4954 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4955 	return 0;
4956 }
4957 
4958 /* check_stack_read dispatches to check_stack_read_fixed_off or
4959  * check_stack_read_var_off.
4960  *
4961  * The caller must ensure that the offset falls within the allocated stack
4962  * bounds.
4963  *
4964  * 'dst_regno' is a register which will receive the value from the stack. It
4965  * can be -1, meaning that the read value is not going to a register.
4966  */
4967 static int check_stack_read(struct bpf_verifier_env *env,
4968 			    int ptr_regno, int off, int size,
4969 			    int dst_regno)
4970 {
4971 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4972 	struct bpf_func_state *state = func(env, reg);
4973 	int err;
4974 	/* Some accesses are only permitted with a static offset. */
4975 	bool var_off = !tnum_is_const(reg->var_off);
4976 
4977 	/* The offset is required to be static when reads don't go to a
4978 	 * register, in order to not leak pointers (see
4979 	 * check_stack_read_fixed_off).
4980 	 */
4981 	if (dst_regno < 0 && var_off) {
4982 		char tn_buf[48];
4983 
4984 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4985 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4986 			tn_buf, off, size);
4987 		return -EACCES;
4988 	}
4989 	/* Variable offset is prohibited for unprivileged mode for simplicity
4990 	 * since it requires corresponding support in Spectre masking for stack
4991 	 * ALU. See also retrieve_ptr_limit(). The check in
4992 	 * check_stack_access_for_ptr_arithmetic() called by
4993 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4994 	 * with variable offsets, therefore no check is required here. Further,
4995 	 * just checking it here would be insufficient as speculative stack
4996 	 * writes could still lead to unsafe speculative behaviour.
4997 	 */
4998 	if (!var_off) {
4999 		off += reg->var_off.value;
5000 		err = check_stack_read_fixed_off(env, state, off, size,
5001 						 dst_regno);
5002 	} else {
5003 		/* Variable offset stack reads need more conservative handling
5004 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5005 		 * branch.
5006 		 */
5007 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5008 					       dst_regno);
5009 	}
5010 	return err;
5011 }
5012 
5013 
5014 /* check_stack_write dispatches to check_stack_write_fixed_off or
5015  * check_stack_write_var_off.
5016  *
5017  * 'ptr_regno' is the register used as a pointer into the stack.
5018  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5019  * 'value_regno' is the register whose value we're writing to the stack. It can
5020  * be -1, meaning that we're not writing from a register.
5021  *
5022  * The caller must ensure that the offset falls within the maximum stack size.
5023  */
5024 static int check_stack_write(struct bpf_verifier_env *env,
5025 			     int ptr_regno, int off, int size,
5026 			     int value_regno, int insn_idx)
5027 {
5028 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5029 	struct bpf_func_state *state = func(env, reg);
5030 	int err;
5031 
5032 	if (tnum_is_const(reg->var_off)) {
5033 		off += reg->var_off.value;
5034 		err = check_stack_write_fixed_off(env, state, off, size,
5035 						  value_regno, insn_idx);
5036 	} else {
5037 		/* Variable offset stack reads need more conservative handling
5038 		 * than fixed offset ones.
5039 		 */
5040 		err = check_stack_write_var_off(env, state,
5041 						ptr_regno, off, size,
5042 						value_regno, insn_idx);
5043 	}
5044 	return err;
5045 }
5046 
5047 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5048 				 int off, int size, enum bpf_access_type type)
5049 {
5050 	struct bpf_reg_state *regs = cur_regs(env);
5051 	struct bpf_map *map = regs[regno].map_ptr;
5052 	u32 cap = bpf_map_flags_to_cap(map);
5053 
5054 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5055 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5056 			map->value_size, off, size);
5057 		return -EACCES;
5058 	}
5059 
5060 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5061 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5062 			map->value_size, off, size);
5063 		return -EACCES;
5064 	}
5065 
5066 	return 0;
5067 }
5068 
5069 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5070 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5071 			      int off, int size, u32 mem_size,
5072 			      bool zero_size_allowed)
5073 {
5074 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5075 	struct bpf_reg_state *reg;
5076 
5077 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5078 		return 0;
5079 
5080 	reg = &cur_regs(env)[regno];
5081 	switch (reg->type) {
5082 	case PTR_TO_MAP_KEY:
5083 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5084 			mem_size, off, size);
5085 		break;
5086 	case PTR_TO_MAP_VALUE:
5087 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5088 			mem_size, off, size);
5089 		break;
5090 	case PTR_TO_PACKET:
5091 	case PTR_TO_PACKET_META:
5092 	case PTR_TO_PACKET_END:
5093 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5094 			off, size, regno, reg->id, off, mem_size);
5095 		break;
5096 	case PTR_TO_MEM:
5097 	default:
5098 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5099 			mem_size, off, size);
5100 	}
5101 
5102 	return -EACCES;
5103 }
5104 
5105 /* check read/write into a memory region with possible variable offset */
5106 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5107 				   int off, int size, u32 mem_size,
5108 				   bool zero_size_allowed)
5109 {
5110 	struct bpf_verifier_state *vstate = env->cur_state;
5111 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5112 	struct bpf_reg_state *reg = &state->regs[regno];
5113 	int err;
5114 
5115 	/* We may have adjusted the register pointing to memory region, so we
5116 	 * need to try adding each of min_value and max_value to off
5117 	 * to make sure our theoretical access will be safe.
5118 	 *
5119 	 * The minimum value is only important with signed
5120 	 * comparisons where we can't assume the floor of a
5121 	 * value is 0.  If we are using signed variables for our
5122 	 * index'es we need to make sure that whatever we use
5123 	 * will have a set floor within our range.
5124 	 */
5125 	if (reg->smin_value < 0 &&
5126 	    (reg->smin_value == S64_MIN ||
5127 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5128 	      reg->smin_value + off < 0)) {
5129 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5130 			regno);
5131 		return -EACCES;
5132 	}
5133 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5134 				 mem_size, zero_size_allowed);
5135 	if (err) {
5136 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5137 			regno);
5138 		return err;
5139 	}
5140 
5141 	/* If we haven't set a max value then we need to bail since we can't be
5142 	 * sure we won't do bad things.
5143 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5144 	 */
5145 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5146 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5147 			regno);
5148 		return -EACCES;
5149 	}
5150 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5151 				 mem_size, zero_size_allowed);
5152 	if (err) {
5153 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5154 			regno);
5155 		return err;
5156 	}
5157 
5158 	return 0;
5159 }
5160 
5161 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5162 			       const struct bpf_reg_state *reg, int regno,
5163 			       bool fixed_off_ok)
5164 {
5165 	/* Access to this pointer-typed register or passing it to a helper
5166 	 * is only allowed in its original, unmodified form.
5167 	 */
5168 
5169 	if (reg->off < 0) {
5170 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5171 			reg_type_str(env, reg->type), regno, reg->off);
5172 		return -EACCES;
5173 	}
5174 
5175 	if (!fixed_off_ok && reg->off) {
5176 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5177 			reg_type_str(env, reg->type), regno, reg->off);
5178 		return -EACCES;
5179 	}
5180 
5181 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5182 		char tn_buf[48];
5183 
5184 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5185 		verbose(env, "variable %s access var_off=%s disallowed\n",
5186 			reg_type_str(env, reg->type), tn_buf);
5187 		return -EACCES;
5188 	}
5189 
5190 	return 0;
5191 }
5192 
5193 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5194 		             const struct bpf_reg_state *reg, int regno)
5195 {
5196 	return __check_ptr_off_reg(env, reg, regno, false);
5197 }
5198 
5199 static int map_kptr_match_type(struct bpf_verifier_env *env,
5200 			       struct btf_field *kptr_field,
5201 			       struct bpf_reg_state *reg, u32 regno)
5202 {
5203 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5204 	int perm_flags;
5205 	const char *reg_name = "";
5206 
5207 	if (btf_is_kernel(reg->btf)) {
5208 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5209 
5210 		/* Only unreferenced case accepts untrusted pointers */
5211 		if (kptr_field->type == BPF_KPTR_UNREF)
5212 			perm_flags |= PTR_UNTRUSTED;
5213 	} else {
5214 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5215 		if (kptr_field->type == BPF_KPTR_PERCPU)
5216 			perm_flags |= MEM_PERCPU;
5217 	}
5218 
5219 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5220 		goto bad_type;
5221 
5222 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5223 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5224 
5225 	/* For ref_ptr case, release function check should ensure we get one
5226 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5227 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5228 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5229 	 * reg->off and reg->ref_obj_id are not needed here.
5230 	 */
5231 	if (__check_ptr_off_reg(env, reg, regno, true))
5232 		return -EACCES;
5233 
5234 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5235 	 * we also need to take into account the reg->off.
5236 	 *
5237 	 * We want to support cases like:
5238 	 *
5239 	 * struct foo {
5240 	 *         struct bar br;
5241 	 *         struct baz bz;
5242 	 * };
5243 	 *
5244 	 * struct foo *v;
5245 	 * v = func();	      // PTR_TO_BTF_ID
5246 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5247 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5248 	 *                    // first member type of struct after comparison fails
5249 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5250 	 *                    // to match type
5251 	 *
5252 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5253 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5254 	 * the struct to match type against first member of struct, i.e. reject
5255 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5256 	 * strict mode to true for type match.
5257 	 */
5258 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5259 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5260 				  kptr_field->type != BPF_KPTR_UNREF))
5261 		goto bad_type;
5262 	return 0;
5263 bad_type:
5264 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5265 		reg_type_str(env, reg->type), reg_name);
5266 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5267 	if (kptr_field->type == BPF_KPTR_UNREF)
5268 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5269 			targ_name);
5270 	else
5271 		verbose(env, "\n");
5272 	return -EINVAL;
5273 }
5274 
5275 static bool in_sleepable(struct bpf_verifier_env *env)
5276 {
5277 	return env->prog->sleepable;
5278 }
5279 
5280 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5281  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5282  */
5283 static bool in_rcu_cs(struct bpf_verifier_env *env)
5284 {
5285 	return env->cur_state->active_rcu_lock ||
5286 	       env->cur_state->active_lock.ptr ||
5287 	       !in_sleepable(env);
5288 }
5289 
5290 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5291 BTF_SET_START(rcu_protected_types)
5292 BTF_ID(struct, prog_test_ref_kfunc)
5293 #ifdef CONFIG_CGROUPS
5294 BTF_ID(struct, cgroup)
5295 #endif
5296 #ifdef CONFIG_BPF_JIT
5297 BTF_ID(struct, bpf_cpumask)
5298 #endif
5299 BTF_ID(struct, task_struct)
5300 BTF_SET_END(rcu_protected_types)
5301 
5302 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5303 {
5304 	if (!btf_is_kernel(btf))
5305 		return true;
5306 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5307 }
5308 
5309 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5310 {
5311 	struct btf_struct_meta *meta;
5312 
5313 	if (btf_is_kernel(kptr_field->kptr.btf))
5314 		return NULL;
5315 
5316 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5317 				    kptr_field->kptr.btf_id);
5318 
5319 	return meta ? meta->record : NULL;
5320 }
5321 
5322 static bool rcu_safe_kptr(const struct btf_field *field)
5323 {
5324 	const struct btf_field_kptr *kptr = &field->kptr;
5325 
5326 	return field->type == BPF_KPTR_PERCPU ||
5327 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5328 }
5329 
5330 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5331 {
5332 	struct btf_record *rec;
5333 	u32 ret;
5334 
5335 	ret = PTR_MAYBE_NULL;
5336 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5337 		ret |= MEM_RCU;
5338 		if (kptr_field->type == BPF_KPTR_PERCPU)
5339 			ret |= MEM_PERCPU;
5340 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5341 			ret |= MEM_ALLOC;
5342 
5343 		rec = kptr_pointee_btf_record(kptr_field);
5344 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5345 			ret |= NON_OWN_REF;
5346 	} else {
5347 		ret |= PTR_UNTRUSTED;
5348 	}
5349 
5350 	return ret;
5351 }
5352 
5353 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5354 				 int value_regno, int insn_idx,
5355 				 struct btf_field *kptr_field)
5356 {
5357 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5358 	int class = BPF_CLASS(insn->code);
5359 	struct bpf_reg_state *val_reg;
5360 
5361 	/* Things we already checked for in check_map_access and caller:
5362 	 *  - Reject cases where variable offset may touch kptr
5363 	 *  - size of access (must be BPF_DW)
5364 	 *  - tnum_is_const(reg->var_off)
5365 	 *  - kptr_field->offset == off + reg->var_off.value
5366 	 */
5367 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5368 	if (BPF_MODE(insn->code) != BPF_MEM) {
5369 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5370 		return -EACCES;
5371 	}
5372 
5373 	/* We only allow loading referenced kptr, since it will be marked as
5374 	 * untrusted, similar to unreferenced kptr.
5375 	 */
5376 	if (class != BPF_LDX &&
5377 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5378 		verbose(env, "store to referenced kptr disallowed\n");
5379 		return -EACCES;
5380 	}
5381 
5382 	if (class == BPF_LDX) {
5383 		val_reg = reg_state(env, value_regno);
5384 		/* We can simply mark the value_regno receiving the pointer
5385 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5386 		 */
5387 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5388 				kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5389 		/* For mark_ptr_or_null_reg */
5390 		val_reg->id = ++env->id_gen;
5391 	} else if (class == BPF_STX) {
5392 		val_reg = reg_state(env, value_regno);
5393 		if (!register_is_null(val_reg) &&
5394 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5395 			return -EACCES;
5396 	} else if (class == BPF_ST) {
5397 		if (insn->imm) {
5398 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5399 				kptr_field->offset);
5400 			return -EACCES;
5401 		}
5402 	} else {
5403 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5404 		return -EACCES;
5405 	}
5406 	return 0;
5407 }
5408 
5409 /* check read/write into a map element with possible variable offset */
5410 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5411 			    int off, int size, bool zero_size_allowed,
5412 			    enum bpf_access_src src)
5413 {
5414 	struct bpf_verifier_state *vstate = env->cur_state;
5415 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5416 	struct bpf_reg_state *reg = &state->regs[regno];
5417 	struct bpf_map *map = reg->map_ptr;
5418 	struct btf_record *rec;
5419 	int err, i;
5420 
5421 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5422 				      zero_size_allowed);
5423 	if (err)
5424 		return err;
5425 
5426 	if (IS_ERR_OR_NULL(map->record))
5427 		return 0;
5428 	rec = map->record;
5429 	for (i = 0; i < rec->cnt; i++) {
5430 		struct btf_field *field = &rec->fields[i];
5431 		u32 p = field->offset;
5432 
5433 		/* If any part of a field  can be touched by load/store, reject
5434 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5435 		 * it is sufficient to check x1 < y2 && y1 < x2.
5436 		 */
5437 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5438 		    p < reg->umax_value + off + size) {
5439 			switch (field->type) {
5440 			case BPF_KPTR_UNREF:
5441 			case BPF_KPTR_REF:
5442 			case BPF_KPTR_PERCPU:
5443 				if (src != ACCESS_DIRECT) {
5444 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5445 					return -EACCES;
5446 				}
5447 				if (!tnum_is_const(reg->var_off)) {
5448 					verbose(env, "kptr access cannot have variable offset\n");
5449 					return -EACCES;
5450 				}
5451 				if (p != off + reg->var_off.value) {
5452 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5453 						p, off + reg->var_off.value);
5454 					return -EACCES;
5455 				}
5456 				if (size != bpf_size_to_bytes(BPF_DW)) {
5457 					verbose(env, "kptr access size must be BPF_DW\n");
5458 					return -EACCES;
5459 				}
5460 				break;
5461 			default:
5462 				verbose(env, "%s cannot be accessed directly by load/store\n",
5463 					btf_field_type_name(field->type));
5464 				return -EACCES;
5465 			}
5466 		}
5467 	}
5468 	return 0;
5469 }
5470 
5471 #define MAX_PACKET_OFF 0xffff
5472 
5473 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5474 				       const struct bpf_call_arg_meta *meta,
5475 				       enum bpf_access_type t)
5476 {
5477 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5478 
5479 	switch (prog_type) {
5480 	/* Program types only with direct read access go here! */
5481 	case BPF_PROG_TYPE_LWT_IN:
5482 	case BPF_PROG_TYPE_LWT_OUT:
5483 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5484 	case BPF_PROG_TYPE_SK_REUSEPORT:
5485 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5486 	case BPF_PROG_TYPE_CGROUP_SKB:
5487 		if (t == BPF_WRITE)
5488 			return false;
5489 		fallthrough;
5490 
5491 	/* Program types with direct read + write access go here! */
5492 	case BPF_PROG_TYPE_SCHED_CLS:
5493 	case BPF_PROG_TYPE_SCHED_ACT:
5494 	case BPF_PROG_TYPE_XDP:
5495 	case BPF_PROG_TYPE_LWT_XMIT:
5496 	case BPF_PROG_TYPE_SK_SKB:
5497 	case BPF_PROG_TYPE_SK_MSG:
5498 		if (meta)
5499 			return meta->pkt_access;
5500 
5501 		env->seen_direct_write = true;
5502 		return true;
5503 
5504 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5505 		if (t == BPF_WRITE)
5506 			env->seen_direct_write = true;
5507 
5508 		return true;
5509 
5510 	default:
5511 		return false;
5512 	}
5513 }
5514 
5515 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5516 			       int size, bool zero_size_allowed)
5517 {
5518 	struct bpf_reg_state *regs = cur_regs(env);
5519 	struct bpf_reg_state *reg = &regs[regno];
5520 	int err;
5521 
5522 	/* We may have added a variable offset to the packet pointer; but any
5523 	 * reg->range we have comes after that.  We are only checking the fixed
5524 	 * offset.
5525 	 */
5526 
5527 	/* We don't allow negative numbers, because we aren't tracking enough
5528 	 * detail to prove they're safe.
5529 	 */
5530 	if (reg->smin_value < 0) {
5531 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5532 			regno);
5533 		return -EACCES;
5534 	}
5535 
5536 	err = reg->range < 0 ? -EINVAL :
5537 	      __check_mem_access(env, regno, off, size, reg->range,
5538 				 zero_size_allowed);
5539 	if (err) {
5540 		verbose(env, "R%d offset is outside of the packet\n", regno);
5541 		return err;
5542 	}
5543 
5544 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5545 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5546 	 * otherwise find_good_pkt_pointers would have refused to set range info
5547 	 * that __check_mem_access would have rejected this pkt access.
5548 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5549 	 */
5550 	env->prog->aux->max_pkt_offset =
5551 		max_t(u32, env->prog->aux->max_pkt_offset,
5552 		      off + reg->umax_value + size - 1);
5553 
5554 	return err;
5555 }
5556 
5557 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5558 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5559 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5560 			    struct btf **btf, u32 *btf_id)
5561 {
5562 	struct bpf_insn_access_aux info = {
5563 		.reg_type = *reg_type,
5564 		.log = &env->log,
5565 	};
5566 
5567 	if (env->ops->is_valid_access &&
5568 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5569 		/* A non zero info.ctx_field_size indicates that this field is a
5570 		 * candidate for later verifier transformation to load the whole
5571 		 * field and then apply a mask when accessed with a narrower
5572 		 * access than actual ctx access size. A zero info.ctx_field_size
5573 		 * will only allow for whole field access and rejects any other
5574 		 * type of narrower access.
5575 		 */
5576 		*reg_type = info.reg_type;
5577 
5578 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5579 			*btf = info.btf;
5580 			*btf_id = info.btf_id;
5581 		} else {
5582 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5583 		}
5584 		/* remember the offset of last byte accessed in ctx */
5585 		if (env->prog->aux->max_ctx_offset < off + size)
5586 			env->prog->aux->max_ctx_offset = off + size;
5587 		return 0;
5588 	}
5589 
5590 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5591 	return -EACCES;
5592 }
5593 
5594 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5595 				  int size)
5596 {
5597 	if (size < 0 || off < 0 ||
5598 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5599 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5600 			off, size);
5601 		return -EACCES;
5602 	}
5603 	return 0;
5604 }
5605 
5606 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5607 			     u32 regno, int off, int size,
5608 			     enum bpf_access_type t)
5609 {
5610 	struct bpf_reg_state *regs = cur_regs(env);
5611 	struct bpf_reg_state *reg = &regs[regno];
5612 	struct bpf_insn_access_aux info = {};
5613 	bool valid;
5614 
5615 	if (reg->smin_value < 0) {
5616 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5617 			regno);
5618 		return -EACCES;
5619 	}
5620 
5621 	switch (reg->type) {
5622 	case PTR_TO_SOCK_COMMON:
5623 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5624 		break;
5625 	case PTR_TO_SOCKET:
5626 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5627 		break;
5628 	case PTR_TO_TCP_SOCK:
5629 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5630 		break;
5631 	case PTR_TO_XDP_SOCK:
5632 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5633 		break;
5634 	default:
5635 		valid = false;
5636 	}
5637 
5638 
5639 	if (valid) {
5640 		env->insn_aux_data[insn_idx].ctx_field_size =
5641 			info.ctx_field_size;
5642 		return 0;
5643 	}
5644 
5645 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5646 		regno, reg_type_str(env, reg->type), off, size);
5647 
5648 	return -EACCES;
5649 }
5650 
5651 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5652 {
5653 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5654 }
5655 
5656 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5657 {
5658 	const struct bpf_reg_state *reg = reg_state(env, regno);
5659 
5660 	return reg->type == PTR_TO_CTX;
5661 }
5662 
5663 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5664 {
5665 	const struct bpf_reg_state *reg = reg_state(env, regno);
5666 
5667 	return type_is_sk_pointer(reg->type);
5668 }
5669 
5670 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5671 {
5672 	const struct bpf_reg_state *reg = reg_state(env, regno);
5673 
5674 	return type_is_pkt_pointer(reg->type);
5675 }
5676 
5677 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5678 {
5679 	const struct bpf_reg_state *reg = reg_state(env, regno);
5680 
5681 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5682 	return reg->type == PTR_TO_FLOW_KEYS;
5683 }
5684 
5685 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5686 #ifdef CONFIG_NET
5687 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5688 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5689 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5690 #endif
5691 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5692 };
5693 
5694 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5695 {
5696 	/* A referenced register is always trusted. */
5697 	if (reg->ref_obj_id)
5698 		return true;
5699 
5700 	/* Types listed in the reg2btf_ids are always trusted */
5701 	if (reg2btf_ids[base_type(reg->type)])
5702 		return true;
5703 
5704 	/* If a register is not referenced, it is trusted if it has the
5705 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5706 	 * other type modifiers may be safe, but we elect to take an opt-in
5707 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5708 	 * not.
5709 	 *
5710 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5711 	 * for whether a register is trusted.
5712 	 */
5713 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5714 	       !bpf_type_has_unsafe_modifiers(reg->type);
5715 }
5716 
5717 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5718 {
5719 	return reg->type & MEM_RCU;
5720 }
5721 
5722 static void clear_trusted_flags(enum bpf_type_flag *flag)
5723 {
5724 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5725 }
5726 
5727 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5728 				   const struct bpf_reg_state *reg,
5729 				   int off, int size, bool strict)
5730 {
5731 	struct tnum reg_off;
5732 	int ip_align;
5733 
5734 	/* Byte size accesses are always allowed. */
5735 	if (!strict || size == 1)
5736 		return 0;
5737 
5738 	/* For platforms that do not have a Kconfig enabling
5739 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5740 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5741 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5742 	 * to this code only in strict mode where we want to emulate
5743 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5744 	 * unconditional IP align value of '2'.
5745 	 */
5746 	ip_align = 2;
5747 
5748 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5749 	if (!tnum_is_aligned(reg_off, size)) {
5750 		char tn_buf[48];
5751 
5752 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5753 		verbose(env,
5754 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5755 			ip_align, tn_buf, reg->off, off, size);
5756 		return -EACCES;
5757 	}
5758 
5759 	return 0;
5760 }
5761 
5762 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5763 				       const struct bpf_reg_state *reg,
5764 				       const char *pointer_desc,
5765 				       int off, int size, bool strict)
5766 {
5767 	struct tnum reg_off;
5768 
5769 	/* Byte size accesses are always allowed. */
5770 	if (!strict || size == 1)
5771 		return 0;
5772 
5773 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5774 	if (!tnum_is_aligned(reg_off, size)) {
5775 		char tn_buf[48];
5776 
5777 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5778 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5779 			pointer_desc, tn_buf, reg->off, off, size);
5780 		return -EACCES;
5781 	}
5782 
5783 	return 0;
5784 }
5785 
5786 static int check_ptr_alignment(struct bpf_verifier_env *env,
5787 			       const struct bpf_reg_state *reg, int off,
5788 			       int size, bool strict_alignment_once)
5789 {
5790 	bool strict = env->strict_alignment || strict_alignment_once;
5791 	const char *pointer_desc = "";
5792 
5793 	switch (reg->type) {
5794 	case PTR_TO_PACKET:
5795 	case PTR_TO_PACKET_META:
5796 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5797 		 * right in front, treat it the very same way.
5798 		 */
5799 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5800 	case PTR_TO_FLOW_KEYS:
5801 		pointer_desc = "flow keys ";
5802 		break;
5803 	case PTR_TO_MAP_KEY:
5804 		pointer_desc = "key ";
5805 		break;
5806 	case PTR_TO_MAP_VALUE:
5807 		pointer_desc = "value ";
5808 		break;
5809 	case PTR_TO_CTX:
5810 		pointer_desc = "context ";
5811 		break;
5812 	case PTR_TO_STACK:
5813 		pointer_desc = "stack ";
5814 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5815 		 * and check_stack_read_fixed_off() relies on stack accesses being
5816 		 * aligned.
5817 		 */
5818 		strict = true;
5819 		break;
5820 	case PTR_TO_SOCKET:
5821 		pointer_desc = "sock ";
5822 		break;
5823 	case PTR_TO_SOCK_COMMON:
5824 		pointer_desc = "sock_common ";
5825 		break;
5826 	case PTR_TO_TCP_SOCK:
5827 		pointer_desc = "tcp_sock ";
5828 		break;
5829 	case PTR_TO_XDP_SOCK:
5830 		pointer_desc = "xdp_sock ";
5831 		break;
5832 	case PTR_TO_ARENA:
5833 		return 0;
5834 	default:
5835 		break;
5836 	}
5837 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5838 					   strict);
5839 }
5840 
5841 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
5842 {
5843 	if (env->prog->jit_requested)
5844 		return round_up(stack_depth, 16);
5845 
5846 	/* round up to 32-bytes, since this is granularity
5847 	 * of interpreter stack size
5848 	 */
5849 	return round_up(max_t(u32, stack_depth, 1), 32);
5850 }
5851 
5852 /* starting from main bpf function walk all instructions of the function
5853  * and recursively walk all callees that given function can call.
5854  * Ignore jump and exit insns.
5855  * Since recursion is prevented by check_cfg() this algorithm
5856  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5857  */
5858 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5859 {
5860 	struct bpf_subprog_info *subprog = env->subprog_info;
5861 	struct bpf_insn *insn = env->prog->insnsi;
5862 	int depth = 0, frame = 0, i, subprog_end;
5863 	bool tail_call_reachable = false;
5864 	int ret_insn[MAX_CALL_FRAMES];
5865 	int ret_prog[MAX_CALL_FRAMES];
5866 	int j;
5867 
5868 	i = subprog[idx].start;
5869 process_func:
5870 	/* protect against potential stack overflow that might happen when
5871 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5872 	 * depth for such case down to 256 so that the worst case scenario
5873 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5874 	 * 8k).
5875 	 *
5876 	 * To get the idea what might happen, see an example:
5877 	 * func1 -> sub rsp, 128
5878 	 *  subfunc1 -> sub rsp, 256
5879 	 *  tailcall1 -> add rsp, 256
5880 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5881 	 *   subfunc2 -> sub rsp, 64
5882 	 *   subfunc22 -> sub rsp, 128
5883 	 *   tailcall2 -> add rsp, 128
5884 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5885 	 *
5886 	 * tailcall will unwind the current stack frame but it will not get rid
5887 	 * of caller's stack as shown on the example above.
5888 	 */
5889 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5890 		verbose(env,
5891 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5892 			depth);
5893 		return -EACCES;
5894 	}
5895 	depth += round_up_stack_depth(env, subprog[idx].stack_depth);
5896 	if (depth > MAX_BPF_STACK) {
5897 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5898 			frame + 1, depth);
5899 		return -EACCES;
5900 	}
5901 continue_func:
5902 	subprog_end = subprog[idx + 1].start;
5903 	for (; i < subprog_end; i++) {
5904 		int next_insn, sidx;
5905 
5906 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
5907 			bool err = false;
5908 
5909 			if (!is_bpf_throw_kfunc(insn + i))
5910 				continue;
5911 			if (subprog[idx].is_cb)
5912 				err = true;
5913 			for (int c = 0; c < frame && !err; c++) {
5914 				if (subprog[ret_prog[c]].is_cb) {
5915 					err = true;
5916 					break;
5917 				}
5918 			}
5919 			if (!err)
5920 				continue;
5921 			verbose(env,
5922 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5923 				i, idx);
5924 			return -EINVAL;
5925 		}
5926 
5927 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5928 			continue;
5929 		/* remember insn and function to return to */
5930 		ret_insn[frame] = i + 1;
5931 		ret_prog[frame] = idx;
5932 
5933 		/* find the callee */
5934 		next_insn = i + insn[i].imm + 1;
5935 		sidx = find_subprog(env, next_insn);
5936 		if (sidx < 0) {
5937 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5938 				  next_insn);
5939 			return -EFAULT;
5940 		}
5941 		if (subprog[sidx].is_async_cb) {
5942 			if (subprog[sidx].has_tail_call) {
5943 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5944 				return -EFAULT;
5945 			}
5946 			/* async callbacks don't increase bpf prog stack size unless called directly */
5947 			if (!bpf_pseudo_call(insn + i))
5948 				continue;
5949 			if (subprog[sidx].is_exception_cb) {
5950 				verbose(env, "insn %d cannot call exception cb directly\n", i);
5951 				return -EINVAL;
5952 			}
5953 		}
5954 		i = next_insn;
5955 		idx = sidx;
5956 
5957 		if (subprog[idx].has_tail_call)
5958 			tail_call_reachable = true;
5959 
5960 		frame++;
5961 		if (frame >= MAX_CALL_FRAMES) {
5962 			verbose(env, "the call stack of %d frames is too deep !\n",
5963 				frame);
5964 			return -E2BIG;
5965 		}
5966 		goto process_func;
5967 	}
5968 	/* if tail call got detected across bpf2bpf calls then mark each of the
5969 	 * currently present subprog frames as tail call reachable subprogs;
5970 	 * this info will be utilized by JIT so that we will be preserving the
5971 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5972 	 */
5973 	if (tail_call_reachable)
5974 		for (j = 0; j < frame; j++) {
5975 			if (subprog[ret_prog[j]].is_exception_cb) {
5976 				verbose(env, "cannot tail call within exception cb\n");
5977 				return -EINVAL;
5978 			}
5979 			subprog[ret_prog[j]].tail_call_reachable = true;
5980 		}
5981 	if (subprog[0].tail_call_reachable)
5982 		env->prog->aux->tail_call_reachable = true;
5983 
5984 	/* end of for() loop means the last insn of the 'subprog'
5985 	 * was reached. Doesn't matter whether it was JA or EXIT
5986 	 */
5987 	if (frame == 0)
5988 		return 0;
5989 	depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
5990 	frame--;
5991 	i = ret_insn[frame];
5992 	idx = ret_prog[frame];
5993 	goto continue_func;
5994 }
5995 
5996 static int check_max_stack_depth(struct bpf_verifier_env *env)
5997 {
5998 	struct bpf_subprog_info *si = env->subprog_info;
5999 	int ret;
6000 
6001 	for (int i = 0; i < env->subprog_cnt; i++) {
6002 		if (!i || si[i].is_async_cb) {
6003 			ret = check_max_stack_depth_subprog(env, i);
6004 			if (ret < 0)
6005 				return ret;
6006 		}
6007 		continue;
6008 	}
6009 	return 0;
6010 }
6011 
6012 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6013 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6014 				  const struct bpf_insn *insn, int idx)
6015 {
6016 	int start = idx + insn->imm + 1, subprog;
6017 
6018 	subprog = find_subprog(env, start);
6019 	if (subprog < 0) {
6020 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6021 			  start);
6022 		return -EFAULT;
6023 	}
6024 	return env->subprog_info[subprog].stack_depth;
6025 }
6026 #endif
6027 
6028 static int __check_buffer_access(struct bpf_verifier_env *env,
6029 				 const char *buf_info,
6030 				 const struct bpf_reg_state *reg,
6031 				 int regno, int off, int size)
6032 {
6033 	if (off < 0) {
6034 		verbose(env,
6035 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6036 			regno, buf_info, off, size);
6037 		return -EACCES;
6038 	}
6039 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6040 		char tn_buf[48];
6041 
6042 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6043 		verbose(env,
6044 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6045 			regno, off, tn_buf);
6046 		return -EACCES;
6047 	}
6048 
6049 	return 0;
6050 }
6051 
6052 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6053 				  const struct bpf_reg_state *reg,
6054 				  int regno, int off, int size)
6055 {
6056 	int err;
6057 
6058 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6059 	if (err)
6060 		return err;
6061 
6062 	if (off + size > env->prog->aux->max_tp_access)
6063 		env->prog->aux->max_tp_access = off + size;
6064 
6065 	return 0;
6066 }
6067 
6068 static int check_buffer_access(struct bpf_verifier_env *env,
6069 			       const struct bpf_reg_state *reg,
6070 			       int regno, int off, int size,
6071 			       bool zero_size_allowed,
6072 			       u32 *max_access)
6073 {
6074 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6075 	int err;
6076 
6077 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6078 	if (err)
6079 		return err;
6080 
6081 	if (off + size > *max_access)
6082 		*max_access = off + size;
6083 
6084 	return 0;
6085 }
6086 
6087 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6088 static void zext_32_to_64(struct bpf_reg_state *reg)
6089 {
6090 	reg->var_off = tnum_subreg(reg->var_off);
6091 	__reg_assign_32_into_64(reg);
6092 }
6093 
6094 /* truncate register to smaller size (in bytes)
6095  * must be called with size < BPF_REG_SIZE
6096  */
6097 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6098 {
6099 	u64 mask;
6100 
6101 	/* clear high bits in bit representation */
6102 	reg->var_off = tnum_cast(reg->var_off, size);
6103 
6104 	/* fix arithmetic bounds */
6105 	mask = ((u64)1 << (size * 8)) - 1;
6106 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6107 		reg->umin_value &= mask;
6108 		reg->umax_value &= mask;
6109 	} else {
6110 		reg->umin_value = 0;
6111 		reg->umax_value = mask;
6112 	}
6113 	reg->smin_value = reg->umin_value;
6114 	reg->smax_value = reg->umax_value;
6115 
6116 	/* If size is smaller than 32bit register the 32bit register
6117 	 * values are also truncated so we push 64-bit bounds into
6118 	 * 32-bit bounds. Above were truncated < 32-bits already.
6119 	 */
6120 	if (size < 4)
6121 		__mark_reg32_unbounded(reg);
6122 
6123 	reg_bounds_sync(reg);
6124 }
6125 
6126 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6127 {
6128 	if (size == 1) {
6129 		reg->smin_value = reg->s32_min_value = S8_MIN;
6130 		reg->smax_value = reg->s32_max_value = S8_MAX;
6131 	} else if (size == 2) {
6132 		reg->smin_value = reg->s32_min_value = S16_MIN;
6133 		reg->smax_value = reg->s32_max_value = S16_MAX;
6134 	} else {
6135 		/* size == 4 */
6136 		reg->smin_value = reg->s32_min_value = S32_MIN;
6137 		reg->smax_value = reg->s32_max_value = S32_MAX;
6138 	}
6139 	reg->umin_value = reg->u32_min_value = 0;
6140 	reg->umax_value = U64_MAX;
6141 	reg->u32_max_value = U32_MAX;
6142 	reg->var_off = tnum_unknown;
6143 }
6144 
6145 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6146 {
6147 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6148 	u64 top_smax_value, top_smin_value;
6149 	u64 num_bits = size * 8;
6150 
6151 	if (tnum_is_const(reg->var_off)) {
6152 		u64_cval = reg->var_off.value;
6153 		if (size == 1)
6154 			reg->var_off = tnum_const((s8)u64_cval);
6155 		else if (size == 2)
6156 			reg->var_off = tnum_const((s16)u64_cval);
6157 		else
6158 			/* size == 4 */
6159 			reg->var_off = tnum_const((s32)u64_cval);
6160 
6161 		u64_cval = reg->var_off.value;
6162 		reg->smax_value = reg->smin_value = u64_cval;
6163 		reg->umax_value = reg->umin_value = u64_cval;
6164 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6165 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6166 		return;
6167 	}
6168 
6169 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6170 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6171 
6172 	if (top_smax_value != top_smin_value)
6173 		goto out;
6174 
6175 	/* find the s64_min and s64_min after sign extension */
6176 	if (size == 1) {
6177 		init_s64_max = (s8)reg->smax_value;
6178 		init_s64_min = (s8)reg->smin_value;
6179 	} else if (size == 2) {
6180 		init_s64_max = (s16)reg->smax_value;
6181 		init_s64_min = (s16)reg->smin_value;
6182 	} else {
6183 		init_s64_max = (s32)reg->smax_value;
6184 		init_s64_min = (s32)reg->smin_value;
6185 	}
6186 
6187 	s64_max = max(init_s64_max, init_s64_min);
6188 	s64_min = min(init_s64_max, init_s64_min);
6189 
6190 	/* both of s64_max/s64_min positive or negative */
6191 	if ((s64_max >= 0) == (s64_min >= 0)) {
6192 		reg->smin_value = reg->s32_min_value = s64_min;
6193 		reg->smax_value = reg->s32_max_value = s64_max;
6194 		reg->umin_value = reg->u32_min_value = s64_min;
6195 		reg->umax_value = reg->u32_max_value = s64_max;
6196 		reg->var_off = tnum_range(s64_min, s64_max);
6197 		return;
6198 	}
6199 
6200 out:
6201 	set_sext64_default_val(reg, size);
6202 }
6203 
6204 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6205 {
6206 	if (size == 1) {
6207 		reg->s32_min_value = S8_MIN;
6208 		reg->s32_max_value = S8_MAX;
6209 	} else {
6210 		/* size == 2 */
6211 		reg->s32_min_value = S16_MIN;
6212 		reg->s32_max_value = S16_MAX;
6213 	}
6214 	reg->u32_min_value = 0;
6215 	reg->u32_max_value = U32_MAX;
6216 }
6217 
6218 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6219 {
6220 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6221 	u32 top_smax_value, top_smin_value;
6222 	u32 num_bits = size * 8;
6223 
6224 	if (tnum_is_const(reg->var_off)) {
6225 		u32_val = reg->var_off.value;
6226 		if (size == 1)
6227 			reg->var_off = tnum_const((s8)u32_val);
6228 		else
6229 			reg->var_off = tnum_const((s16)u32_val);
6230 
6231 		u32_val = reg->var_off.value;
6232 		reg->s32_min_value = reg->s32_max_value = u32_val;
6233 		reg->u32_min_value = reg->u32_max_value = u32_val;
6234 		return;
6235 	}
6236 
6237 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6238 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6239 
6240 	if (top_smax_value != top_smin_value)
6241 		goto out;
6242 
6243 	/* find the s32_min and s32_min after sign extension */
6244 	if (size == 1) {
6245 		init_s32_max = (s8)reg->s32_max_value;
6246 		init_s32_min = (s8)reg->s32_min_value;
6247 	} else {
6248 		/* size == 2 */
6249 		init_s32_max = (s16)reg->s32_max_value;
6250 		init_s32_min = (s16)reg->s32_min_value;
6251 	}
6252 	s32_max = max(init_s32_max, init_s32_min);
6253 	s32_min = min(init_s32_max, init_s32_min);
6254 
6255 	if ((s32_min >= 0) == (s32_max >= 0)) {
6256 		reg->s32_min_value = s32_min;
6257 		reg->s32_max_value = s32_max;
6258 		reg->u32_min_value = (u32)s32_min;
6259 		reg->u32_max_value = (u32)s32_max;
6260 		return;
6261 	}
6262 
6263 out:
6264 	set_sext32_default_val(reg, size);
6265 }
6266 
6267 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6268 {
6269 	/* A map is considered read-only if the following condition are true:
6270 	 *
6271 	 * 1) BPF program side cannot change any of the map content. The
6272 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6273 	 *    and was set at map creation time.
6274 	 * 2) The map value(s) have been initialized from user space by a
6275 	 *    loader and then "frozen", such that no new map update/delete
6276 	 *    operations from syscall side are possible for the rest of
6277 	 *    the map's lifetime from that point onwards.
6278 	 * 3) Any parallel/pending map update/delete operations from syscall
6279 	 *    side have been completed. Only after that point, it's safe to
6280 	 *    assume that map value(s) are immutable.
6281 	 */
6282 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6283 	       READ_ONCE(map->frozen) &&
6284 	       !bpf_map_write_active(map);
6285 }
6286 
6287 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6288 			       bool is_ldsx)
6289 {
6290 	void *ptr;
6291 	u64 addr;
6292 	int err;
6293 
6294 	err = map->ops->map_direct_value_addr(map, &addr, off);
6295 	if (err)
6296 		return err;
6297 	ptr = (void *)(long)addr + off;
6298 
6299 	switch (size) {
6300 	case sizeof(u8):
6301 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6302 		break;
6303 	case sizeof(u16):
6304 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6305 		break;
6306 	case sizeof(u32):
6307 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6308 		break;
6309 	case sizeof(u64):
6310 		*val = *(u64 *)ptr;
6311 		break;
6312 	default:
6313 		return -EINVAL;
6314 	}
6315 	return 0;
6316 }
6317 
6318 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6319 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6320 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6321 
6322 /*
6323  * Allow list few fields as RCU trusted or full trusted.
6324  * This logic doesn't allow mix tagging and will be removed once GCC supports
6325  * btf_type_tag.
6326  */
6327 
6328 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6329 BTF_TYPE_SAFE_RCU(struct task_struct) {
6330 	const cpumask_t *cpus_ptr;
6331 	struct css_set __rcu *cgroups;
6332 	struct task_struct __rcu *real_parent;
6333 	struct task_struct *group_leader;
6334 };
6335 
6336 BTF_TYPE_SAFE_RCU(struct cgroup) {
6337 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6338 	struct kernfs_node *kn;
6339 };
6340 
6341 BTF_TYPE_SAFE_RCU(struct css_set) {
6342 	struct cgroup *dfl_cgrp;
6343 };
6344 
6345 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6346 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6347 	struct file __rcu *exe_file;
6348 };
6349 
6350 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6351  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6352  */
6353 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6354 	struct sock *sk;
6355 };
6356 
6357 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6358 	struct sock *sk;
6359 };
6360 
6361 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6362 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6363 	struct seq_file *seq;
6364 };
6365 
6366 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6367 	struct bpf_iter_meta *meta;
6368 	struct task_struct *task;
6369 };
6370 
6371 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6372 	struct file *file;
6373 };
6374 
6375 BTF_TYPE_SAFE_TRUSTED(struct file) {
6376 	struct inode *f_inode;
6377 };
6378 
6379 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6380 	/* no negative dentry-s in places where bpf can see it */
6381 	struct inode *d_inode;
6382 };
6383 
6384 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6385 	struct sock *sk;
6386 };
6387 
6388 static bool type_is_rcu(struct bpf_verifier_env *env,
6389 			struct bpf_reg_state *reg,
6390 			const char *field_name, u32 btf_id)
6391 {
6392 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6393 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6394 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6395 
6396 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6397 }
6398 
6399 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6400 				struct bpf_reg_state *reg,
6401 				const char *field_name, u32 btf_id)
6402 {
6403 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6404 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6405 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6406 
6407 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6408 }
6409 
6410 static bool type_is_trusted(struct bpf_verifier_env *env,
6411 			    struct bpf_reg_state *reg,
6412 			    const char *field_name, u32 btf_id)
6413 {
6414 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6415 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6416 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6417 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6418 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6419 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6420 
6421 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6422 }
6423 
6424 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6425 				   struct bpf_reg_state *regs,
6426 				   int regno, int off, int size,
6427 				   enum bpf_access_type atype,
6428 				   int value_regno)
6429 {
6430 	struct bpf_reg_state *reg = regs + regno;
6431 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6432 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6433 	const char *field_name = NULL;
6434 	enum bpf_type_flag flag = 0;
6435 	u32 btf_id = 0;
6436 	int ret;
6437 
6438 	if (!env->allow_ptr_leaks) {
6439 		verbose(env,
6440 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6441 			tname);
6442 		return -EPERM;
6443 	}
6444 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6445 		verbose(env,
6446 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6447 			tname);
6448 		return -EINVAL;
6449 	}
6450 	if (off < 0) {
6451 		verbose(env,
6452 			"R%d is ptr_%s invalid negative access: off=%d\n",
6453 			regno, tname, off);
6454 		return -EACCES;
6455 	}
6456 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6457 		char tn_buf[48];
6458 
6459 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6460 		verbose(env,
6461 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6462 			regno, tname, off, tn_buf);
6463 		return -EACCES;
6464 	}
6465 
6466 	if (reg->type & MEM_USER) {
6467 		verbose(env,
6468 			"R%d is ptr_%s access user memory: off=%d\n",
6469 			regno, tname, off);
6470 		return -EACCES;
6471 	}
6472 
6473 	if (reg->type & MEM_PERCPU) {
6474 		verbose(env,
6475 			"R%d is ptr_%s access percpu memory: off=%d\n",
6476 			regno, tname, off);
6477 		return -EACCES;
6478 	}
6479 
6480 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6481 		if (!btf_is_kernel(reg->btf)) {
6482 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6483 			return -EFAULT;
6484 		}
6485 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6486 	} else {
6487 		/* Writes are permitted with default btf_struct_access for
6488 		 * program allocated objects (which always have ref_obj_id > 0),
6489 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6490 		 */
6491 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6492 			verbose(env, "only read is supported\n");
6493 			return -EACCES;
6494 		}
6495 
6496 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6497 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
6498 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6499 			return -EFAULT;
6500 		}
6501 
6502 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6503 	}
6504 
6505 	if (ret < 0)
6506 		return ret;
6507 
6508 	if (ret != PTR_TO_BTF_ID) {
6509 		/* just mark; */
6510 
6511 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6512 		/* If this is an untrusted pointer, all pointers formed by walking it
6513 		 * also inherit the untrusted flag.
6514 		 */
6515 		flag = PTR_UNTRUSTED;
6516 
6517 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6518 		/* By default any pointer obtained from walking a trusted pointer is no
6519 		 * longer trusted, unless the field being accessed has explicitly been
6520 		 * marked as inheriting its parent's state of trust (either full or RCU).
6521 		 * For example:
6522 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6523 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6524 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6525 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6526 		 *
6527 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6528 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6529 		 */
6530 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6531 			flag |= PTR_TRUSTED;
6532 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6533 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6534 				/* ignore __rcu tag and mark it MEM_RCU */
6535 				flag |= MEM_RCU;
6536 			} else if (flag & MEM_RCU ||
6537 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6538 				/* __rcu tagged pointers can be NULL */
6539 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6540 
6541 				/* We always trust them */
6542 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6543 				    flag & PTR_UNTRUSTED)
6544 					flag &= ~PTR_UNTRUSTED;
6545 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6546 				/* keep as-is */
6547 			} else {
6548 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6549 				clear_trusted_flags(&flag);
6550 			}
6551 		} else {
6552 			/*
6553 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6554 			 * aggressively mark as untrusted otherwise such
6555 			 * pointers will be plain PTR_TO_BTF_ID without flags
6556 			 * and will be allowed to be passed into helpers for
6557 			 * compat reasons.
6558 			 */
6559 			flag = PTR_UNTRUSTED;
6560 		}
6561 	} else {
6562 		/* Old compat. Deprecated */
6563 		clear_trusted_flags(&flag);
6564 	}
6565 
6566 	if (atype == BPF_READ && value_regno >= 0)
6567 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6568 
6569 	return 0;
6570 }
6571 
6572 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6573 				   struct bpf_reg_state *regs,
6574 				   int regno, int off, int size,
6575 				   enum bpf_access_type atype,
6576 				   int value_regno)
6577 {
6578 	struct bpf_reg_state *reg = regs + regno;
6579 	struct bpf_map *map = reg->map_ptr;
6580 	struct bpf_reg_state map_reg;
6581 	enum bpf_type_flag flag = 0;
6582 	const struct btf_type *t;
6583 	const char *tname;
6584 	u32 btf_id;
6585 	int ret;
6586 
6587 	if (!btf_vmlinux) {
6588 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6589 		return -ENOTSUPP;
6590 	}
6591 
6592 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6593 		verbose(env, "map_ptr access not supported for map type %d\n",
6594 			map->map_type);
6595 		return -ENOTSUPP;
6596 	}
6597 
6598 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6599 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6600 
6601 	if (!env->allow_ptr_leaks) {
6602 		verbose(env,
6603 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6604 			tname);
6605 		return -EPERM;
6606 	}
6607 
6608 	if (off < 0) {
6609 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6610 			regno, tname, off);
6611 		return -EACCES;
6612 	}
6613 
6614 	if (atype != BPF_READ) {
6615 		verbose(env, "only read from %s is supported\n", tname);
6616 		return -EACCES;
6617 	}
6618 
6619 	/* Simulate access to a PTR_TO_BTF_ID */
6620 	memset(&map_reg, 0, sizeof(map_reg));
6621 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6622 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6623 	if (ret < 0)
6624 		return ret;
6625 
6626 	if (value_regno >= 0)
6627 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6628 
6629 	return 0;
6630 }
6631 
6632 /* Check that the stack access at the given offset is within bounds. The
6633  * maximum valid offset is -1.
6634  *
6635  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6636  * -state->allocated_stack for reads.
6637  */
6638 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6639                                           s64 off,
6640                                           struct bpf_func_state *state,
6641                                           enum bpf_access_type t)
6642 {
6643 	int min_valid_off;
6644 
6645 	if (t == BPF_WRITE || env->allow_uninit_stack)
6646 		min_valid_off = -MAX_BPF_STACK;
6647 	else
6648 		min_valid_off = -state->allocated_stack;
6649 
6650 	if (off < min_valid_off || off > -1)
6651 		return -EACCES;
6652 	return 0;
6653 }
6654 
6655 /* Check that the stack access at 'regno + off' falls within the maximum stack
6656  * bounds.
6657  *
6658  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6659  */
6660 static int check_stack_access_within_bounds(
6661 		struct bpf_verifier_env *env,
6662 		int regno, int off, int access_size,
6663 		enum bpf_access_src src, enum bpf_access_type type)
6664 {
6665 	struct bpf_reg_state *regs = cur_regs(env);
6666 	struct bpf_reg_state *reg = regs + regno;
6667 	struct bpf_func_state *state = func(env, reg);
6668 	s64 min_off, max_off;
6669 	int err;
6670 	char *err_extra;
6671 
6672 	if (src == ACCESS_HELPER)
6673 		/* We don't know if helpers are reading or writing (or both). */
6674 		err_extra = " indirect access to";
6675 	else if (type == BPF_READ)
6676 		err_extra = " read from";
6677 	else
6678 		err_extra = " write to";
6679 
6680 	if (tnum_is_const(reg->var_off)) {
6681 		min_off = (s64)reg->var_off.value + off;
6682 		max_off = min_off + access_size;
6683 	} else {
6684 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6685 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6686 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6687 				err_extra, regno);
6688 			return -EACCES;
6689 		}
6690 		min_off = reg->smin_value + off;
6691 		max_off = reg->smax_value + off + access_size;
6692 	}
6693 
6694 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6695 	if (!err && max_off > 0)
6696 		err = -EINVAL; /* out of stack access into non-negative offsets */
6697 
6698 	if (err) {
6699 		if (tnum_is_const(reg->var_off)) {
6700 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6701 				err_extra, regno, off, access_size);
6702 		} else {
6703 			char tn_buf[48];
6704 
6705 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6706 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
6707 				err_extra, regno, tn_buf, off, access_size);
6708 		}
6709 		return err;
6710 	}
6711 
6712 	/* Note that there is no stack access with offset zero, so the needed stack
6713 	 * size is -min_off, not -min_off+1.
6714 	 */
6715 	return grow_stack_state(env, state, -min_off /* size */);
6716 }
6717 
6718 /* check whether memory at (regno + off) is accessible for t = (read | write)
6719  * if t==write, value_regno is a register which value is stored into memory
6720  * if t==read, value_regno is a register which will receive the value from memory
6721  * if t==write && value_regno==-1, some unknown value is stored into memory
6722  * if t==read && value_regno==-1, don't care what we read from memory
6723  */
6724 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6725 			    int off, int bpf_size, enum bpf_access_type t,
6726 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6727 {
6728 	struct bpf_reg_state *regs = cur_regs(env);
6729 	struct bpf_reg_state *reg = regs + regno;
6730 	int size, err = 0;
6731 
6732 	size = bpf_size_to_bytes(bpf_size);
6733 	if (size < 0)
6734 		return size;
6735 
6736 	/* alignment checks will add in reg->off themselves */
6737 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6738 	if (err)
6739 		return err;
6740 
6741 	/* for access checks, reg->off is just part of off */
6742 	off += reg->off;
6743 
6744 	if (reg->type == PTR_TO_MAP_KEY) {
6745 		if (t == BPF_WRITE) {
6746 			verbose(env, "write to change key R%d not allowed\n", regno);
6747 			return -EACCES;
6748 		}
6749 
6750 		err = check_mem_region_access(env, regno, off, size,
6751 					      reg->map_ptr->key_size, false);
6752 		if (err)
6753 			return err;
6754 		if (value_regno >= 0)
6755 			mark_reg_unknown(env, regs, value_regno);
6756 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6757 		struct btf_field *kptr_field = NULL;
6758 
6759 		if (t == BPF_WRITE && value_regno >= 0 &&
6760 		    is_pointer_value(env, value_regno)) {
6761 			verbose(env, "R%d leaks addr into map\n", value_regno);
6762 			return -EACCES;
6763 		}
6764 		err = check_map_access_type(env, regno, off, size, t);
6765 		if (err)
6766 			return err;
6767 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6768 		if (err)
6769 			return err;
6770 		if (tnum_is_const(reg->var_off))
6771 			kptr_field = btf_record_find(reg->map_ptr->record,
6772 						     off + reg->var_off.value, BPF_KPTR);
6773 		if (kptr_field) {
6774 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6775 		} else if (t == BPF_READ && value_regno >= 0) {
6776 			struct bpf_map *map = reg->map_ptr;
6777 
6778 			/* if map is read-only, track its contents as scalars */
6779 			if (tnum_is_const(reg->var_off) &&
6780 			    bpf_map_is_rdonly(map) &&
6781 			    map->ops->map_direct_value_addr) {
6782 				int map_off = off + reg->var_off.value;
6783 				u64 val = 0;
6784 
6785 				err = bpf_map_direct_read(map, map_off, size,
6786 							  &val, is_ldsx);
6787 				if (err)
6788 					return err;
6789 
6790 				regs[value_regno].type = SCALAR_VALUE;
6791 				__mark_reg_known(&regs[value_regno], val);
6792 			} else {
6793 				mark_reg_unknown(env, regs, value_regno);
6794 			}
6795 		}
6796 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6797 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6798 
6799 		if (type_may_be_null(reg->type)) {
6800 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6801 				reg_type_str(env, reg->type));
6802 			return -EACCES;
6803 		}
6804 
6805 		if (t == BPF_WRITE && rdonly_mem) {
6806 			verbose(env, "R%d cannot write into %s\n",
6807 				regno, reg_type_str(env, reg->type));
6808 			return -EACCES;
6809 		}
6810 
6811 		if (t == BPF_WRITE && value_regno >= 0 &&
6812 		    is_pointer_value(env, value_regno)) {
6813 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6814 			return -EACCES;
6815 		}
6816 
6817 		err = check_mem_region_access(env, regno, off, size,
6818 					      reg->mem_size, false);
6819 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6820 			mark_reg_unknown(env, regs, value_regno);
6821 	} else if (reg->type == PTR_TO_CTX) {
6822 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6823 		struct btf *btf = NULL;
6824 		u32 btf_id = 0;
6825 
6826 		if (t == BPF_WRITE && value_regno >= 0 &&
6827 		    is_pointer_value(env, value_regno)) {
6828 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6829 			return -EACCES;
6830 		}
6831 
6832 		err = check_ptr_off_reg(env, reg, regno);
6833 		if (err < 0)
6834 			return err;
6835 
6836 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6837 				       &btf_id);
6838 		if (err)
6839 			verbose_linfo(env, insn_idx, "; ");
6840 		if (!err && t == BPF_READ && value_regno >= 0) {
6841 			/* ctx access returns either a scalar, or a
6842 			 * PTR_TO_PACKET[_META,_END]. In the latter
6843 			 * case, we know the offset is zero.
6844 			 */
6845 			if (reg_type == SCALAR_VALUE) {
6846 				mark_reg_unknown(env, regs, value_regno);
6847 			} else {
6848 				mark_reg_known_zero(env, regs,
6849 						    value_regno);
6850 				if (type_may_be_null(reg_type))
6851 					regs[value_regno].id = ++env->id_gen;
6852 				/* A load of ctx field could have different
6853 				 * actual load size with the one encoded in the
6854 				 * insn. When the dst is PTR, it is for sure not
6855 				 * a sub-register.
6856 				 */
6857 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6858 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6859 					regs[value_regno].btf = btf;
6860 					regs[value_regno].btf_id = btf_id;
6861 				}
6862 			}
6863 			regs[value_regno].type = reg_type;
6864 		}
6865 
6866 	} else if (reg->type == PTR_TO_STACK) {
6867 		/* Basic bounds checks. */
6868 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6869 		if (err)
6870 			return err;
6871 
6872 		if (t == BPF_READ)
6873 			err = check_stack_read(env, regno, off, size,
6874 					       value_regno);
6875 		else
6876 			err = check_stack_write(env, regno, off, size,
6877 						value_regno, insn_idx);
6878 	} else if (reg_is_pkt_pointer(reg)) {
6879 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6880 			verbose(env, "cannot write into packet\n");
6881 			return -EACCES;
6882 		}
6883 		if (t == BPF_WRITE && value_regno >= 0 &&
6884 		    is_pointer_value(env, value_regno)) {
6885 			verbose(env, "R%d leaks addr into packet\n",
6886 				value_regno);
6887 			return -EACCES;
6888 		}
6889 		err = check_packet_access(env, regno, off, size, false);
6890 		if (!err && t == BPF_READ && value_regno >= 0)
6891 			mark_reg_unknown(env, regs, value_regno);
6892 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6893 		if (t == BPF_WRITE && value_regno >= 0 &&
6894 		    is_pointer_value(env, value_regno)) {
6895 			verbose(env, "R%d leaks addr into flow keys\n",
6896 				value_regno);
6897 			return -EACCES;
6898 		}
6899 
6900 		err = check_flow_keys_access(env, off, size);
6901 		if (!err && t == BPF_READ && value_regno >= 0)
6902 			mark_reg_unknown(env, regs, value_regno);
6903 	} else if (type_is_sk_pointer(reg->type)) {
6904 		if (t == BPF_WRITE) {
6905 			verbose(env, "R%d cannot write into %s\n",
6906 				regno, reg_type_str(env, reg->type));
6907 			return -EACCES;
6908 		}
6909 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6910 		if (!err && value_regno >= 0)
6911 			mark_reg_unknown(env, regs, value_regno);
6912 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6913 		err = check_tp_buffer_access(env, reg, regno, off, size);
6914 		if (!err && t == BPF_READ && value_regno >= 0)
6915 			mark_reg_unknown(env, regs, value_regno);
6916 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6917 		   !type_may_be_null(reg->type)) {
6918 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6919 					      value_regno);
6920 	} else if (reg->type == CONST_PTR_TO_MAP) {
6921 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6922 					      value_regno);
6923 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6924 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6925 		u32 *max_access;
6926 
6927 		if (rdonly_mem) {
6928 			if (t == BPF_WRITE) {
6929 				verbose(env, "R%d cannot write into %s\n",
6930 					regno, reg_type_str(env, reg->type));
6931 				return -EACCES;
6932 			}
6933 			max_access = &env->prog->aux->max_rdonly_access;
6934 		} else {
6935 			max_access = &env->prog->aux->max_rdwr_access;
6936 		}
6937 
6938 		err = check_buffer_access(env, reg, regno, off, size, false,
6939 					  max_access);
6940 
6941 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6942 			mark_reg_unknown(env, regs, value_regno);
6943 	} else if (reg->type == PTR_TO_ARENA) {
6944 		if (t == BPF_READ && value_regno >= 0)
6945 			mark_reg_unknown(env, regs, value_regno);
6946 	} else {
6947 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6948 			reg_type_str(env, reg->type));
6949 		return -EACCES;
6950 	}
6951 
6952 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6953 	    regs[value_regno].type == SCALAR_VALUE) {
6954 		if (!is_ldsx)
6955 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6956 			coerce_reg_to_size(&regs[value_regno], size);
6957 		else
6958 			coerce_reg_to_size_sx(&regs[value_regno], size);
6959 	}
6960 	return err;
6961 }
6962 
6963 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6964 {
6965 	int load_reg;
6966 	int err;
6967 
6968 	switch (insn->imm) {
6969 	case BPF_ADD:
6970 	case BPF_ADD | BPF_FETCH:
6971 	case BPF_AND:
6972 	case BPF_AND | BPF_FETCH:
6973 	case BPF_OR:
6974 	case BPF_OR | BPF_FETCH:
6975 	case BPF_XOR:
6976 	case BPF_XOR | BPF_FETCH:
6977 	case BPF_XCHG:
6978 	case BPF_CMPXCHG:
6979 		break;
6980 	default:
6981 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6982 		return -EINVAL;
6983 	}
6984 
6985 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6986 		verbose(env, "invalid atomic operand size\n");
6987 		return -EINVAL;
6988 	}
6989 
6990 	/* check src1 operand */
6991 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6992 	if (err)
6993 		return err;
6994 
6995 	/* check src2 operand */
6996 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6997 	if (err)
6998 		return err;
6999 
7000 	if (insn->imm == BPF_CMPXCHG) {
7001 		/* Check comparison of R0 with memory location */
7002 		const u32 aux_reg = BPF_REG_0;
7003 
7004 		err = check_reg_arg(env, aux_reg, SRC_OP);
7005 		if (err)
7006 			return err;
7007 
7008 		if (is_pointer_value(env, aux_reg)) {
7009 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7010 			return -EACCES;
7011 		}
7012 	}
7013 
7014 	if (is_pointer_value(env, insn->src_reg)) {
7015 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7016 		return -EACCES;
7017 	}
7018 
7019 	if (is_ctx_reg(env, insn->dst_reg) ||
7020 	    is_pkt_reg(env, insn->dst_reg) ||
7021 	    is_flow_key_reg(env, insn->dst_reg) ||
7022 	    is_sk_reg(env, insn->dst_reg)) {
7023 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7024 			insn->dst_reg,
7025 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7026 		return -EACCES;
7027 	}
7028 
7029 	if (insn->imm & BPF_FETCH) {
7030 		if (insn->imm == BPF_CMPXCHG)
7031 			load_reg = BPF_REG_0;
7032 		else
7033 			load_reg = insn->src_reg;
7034 
7035 		/* check and record load of old value */
7036 		err = check_reg_arg(env, load_reg, DST_OP);
7037 		if (err)
7038 			return err;
7039 	} else {
7040 		/* This instruction accesses a memory location but doesn't
7041 		 * actually load it into a register.
7042 		 */
7043 		load_reg = -1;
7044 	}
7045 
7046 	/* Check whether we can read the memory, with second call for fetch
7047 	 * case to simulate the register fill.
7048 	 */
7049 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7050 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7051 	if (!err && load_reg >= 0)
7052 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7053 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
7054 				       true, false);
7055 	if (err)
7056 		return err;
7057 
7058 	/* Check whether we can write into the same memory. */
7059 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7060 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7061 	if (err)
7062 		return err;
7063 	return 0;
7064 }
7065 
7066 /* When register 'regno' is used to read the stack (either directly or through
7067  * a helper function) make sure that it's within stack boundary and, depending
7068  * on the access type and privileges, that all elements of the stack are
7069  * initialized.
7070  *
7071  * 'off' includes 'regno->off', but not its dynamic part (if any).
7072  *
7073  * All registers that have been spilled on the stack in the slots within the
7074  * read offsets are marked as read.
7075  */
7076 static int check_stack_range_initialized(
7077 		struct bpf_verifier_env *env, int regno, int off,
7078 		int access_size, bool zero_size_allowed,
7079 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7080 {
7081 	struct bpf_reg_state *reg = reg_state(env, regno);
7082 	struct bpf_func_state *state = func(env, reg);
7083 	int err, min_off, max_off, i, j, slot, spi;
7084 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7085 	enum bpf_access_type bounds_check_type;
7086 	/* Some accesses can write anything into the stack, others are
7087 	 * read-only.
7088 	 */
7089 	bool clobber = false;
7090 
7091 	if (access_size == 0 && !zero_size_allowed) {
7092 		verbose(env, "invalid zero-sized read\n");
7093 		return -EACCES;
7094 	}
7095 
7096 	if (type == ACCESS_HELPER) {
7097 		/* The bounds checks for writes are more permissive than for
7098 		 * reads. However, if raw_mode is not set, we'll do extra
7099 		 * checks below.
7100 		 */
7101 		bounds_check_type = BPF_WRITE;
7102 		clobber = true;
7103 	} else {
7104 		bounds_check_type = BPF_READ;
7105 	}
7106 	err = check_stack_access_within_bounds(env, regno, off, access_size,
7107 					       type, bounds_check_type);
7108 	if (err)
7109 		return err;
7110 
7111 
7112 	if (tnum_is_const(reg->var_off)) {
7113 		min_off = max_off = reg->var_off.value + off;
7114 	} else {
7115 		/* Variable offset is prohibited for unprivileged mode for
7116 		 * simplicity since it requires corresponding support in
7117 		 * Spectre masking for stack ALU.
7118 		 * See also retrieve_ptr_limit().
7119 		 */
7120 		if (!env->bypass_spec_v1) {
7121 			char tn_buf[48];
7122 
7123 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7124 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7125 				regno, err_extra, tn_buf);
7126 			return -EACCES;
7127 		}
7128 		/* Only initialized buffer on stack is allowed to be accessed
7129 		 * with variable offset. With uninitialized buffer it's hard to
7130 		 * guarantee that whole memory is marked as initialized on
7131 		 * helper return since specific bounds are unknown what may
7132 		 * cause uninitialized stack leaking.
7133 		 */
7134 		if (meta && meta->raw_mode)
7135 			meta = NULL;
7136 
7137 		min_off = reg->smin_value + off;
7138 		max_off = reg->smax_value + off;
7139 	}
7140 
7141 	if (meta && meta->raw_mode) {
7142 		/* Ensure we won't be overwriting dynptrs when simulating byte
7143 		 * by byte access in check_helper_call using meta.access_size.
7144 		 * This would be a problem if we have a helper in the future
7145 		 * which takes:
7146 		 *
7147 		 *	helper(uninit_mem, len, dynptr)
7148 		 *
7149 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7150 		 * may end up writing to dynptr itself when touching memory from
7151 		 * arg 1. This can be relaxed on a case by case basis for known
7152 		 * safe cases, but reject due to the possibilitiy of aliasing by
7153 		 * default.
7154 		 */
7155 		for (i = min_off; i < max_off + access_size; i++) {
7156 			int stack_off = -i - 1;
7157 
7158 			spi = __get_spi(i);
7159 			/* raw_mode may write past allocated_stack */
7160 			if (state->allocated_stack <= stack_off)
7161 				continue;
7162 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7163 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7164 				return -EACCES;
7165 			}
7166 		}
7167 		meta->access_size = access_size;
7168 		meta->regno = regno;
7169 		return 0;
7170 	}
7171 
7172 	for (i = min_off; i < max_off + access_size; i++) {
7173 		u8 *stype;
7174 
7175 		slot = -i - 1;
7176 		spi = slot / BPF_REG_SIZE;
7177 		if (state->allocated_stack <= slot) {
7178 			verbose(env, "verifier bug: allocated_stack too small");
7179 			return -EFAULT;
7180 		}
7181 
7182 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7183 		if (*stype == STACK_MISC)
7184 			goto mark;
7185 		if ((*stype == STACK_ZERO) ||
7186 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7187 			if (clobber) {
7188 				/* helper can write anything into the stack */
7189 				*stype = STACK_MISC;
7190 			}
7191 			goto mark;
7192 		}
7193 
7194 		if (is_spilled_reg(&state->stack[spi]) &&
7195 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7196 		     env->allow_ptr_leaks)) {
7197 			if (clobber) {
7198 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7199 				for (j = 0; j < BPF_REG_SIZE; j++)
7200 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7201 			}
7202 			goto mark;
7203 		}
7204 
7205 		if (tnum_is_const(reg->var_off)) {
7206 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7207 				err_extra, regno, min_off, i - min_off, access_size);
7208 		} else {
7209 			char tn_buf[48];
7210 
7211 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7212 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7213 				err_extra, regno, tn_buf, i - min_off, access_size);
7214 		}
7215 		return -EACCES;
7216 mark:
7217 		/* reading any byte out of 8-byte 'spill_slot' will cause
7218 		 * the whole slot to be marked as 'read'
7219 		 */
7220 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7221 			      state->stack[spi].spilled_ptr.parent,
7222 			      REG_LIVE_READ64);
7223 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7224 		 * be sure that whether stack slot is written to or not. Hence,
7225 		 * we must still conservatively propagate reads upwards even if
7226 		 * helper may write to the entire memory range.
7227 		 */
7228 	}
7229 	return 0;
7230 }
7231 
7232 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7233 				   int access_size, bool zero_size_allowed,
7234 				   struct bpf_call_arg_meta *meta)
7235 {
7236 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7237 	u32 *max_access;
7238 
7239 	switch (base_type(reg->type)) {
7240 	case PTR_TO_PACKET:
7241 	case PTR_TO_PACKET_META:
7242 		return check_packet_access(env, regno, reg->off, access_size,
7243 					   zero_size_allowed);
7244 	case PTR_TO_MAP_KEY:
7245 		if (meta && meta->raw_mode) {
7246 			verbose(env, "R%d cannot write into %s\n", regno,
7247 				reg_type_str(env, reg->type));
7248 			return -EACCES;
7249 		}
7250 		return check_mem_region_access(env, regno, reg->off, access_size,
7251 					       reg->map_ptr->key_size, false);
7252 	case PTR_TO_MAP_VALUE:
7253 		if (check_map_access_type(env, regno, reg->off, access_size,
7254 					  meta && meta->raw_mode ? BPF_WRITE :
7255 					  BPF_READ))
7256 			return -EACCES;
7257 		return check_map_access(env, regno, reg->off, access_size,
7258 					zero_size_allowed, ACCESS_HELPER);
7259 	case PTR_TO_MEM:
7260 		if (type_is_rdonly_mem(reg->type)) {
7261 			if (meta && meta->raw_mode) {
7262 				verbose(env, "R%d cannot write into %s\n", regno,
7263 					reg_type_str(env, reg->type));
7264 				return -EACCES;
7265 			}
7266 		}
7267 		return check_mem_region_access(env, regno, reg->off,
7268 					       access_size, reg->mem_size,
7269 					       zero_size_allowed);
7270 	case PTR_TO_BUF:
7271 		if (type_is_rdonly_mem(reg->type)) {
7272 			if (meta && meta->raw_mode) {
7273 				verbose(env, "R%d cannot write into %s\n", regno,
7274 					reg_type_str(env, reg->type));
7275 				return -EACCES;
7276 			}
7277 
7278 			max_access = &env->prog->aux->max_rdonly_access;
7279 		} else {
7280 			max_access = &env->prog->aux->max_rdwr_access;
7281 		}
7282 		return check_buffer_access(env, reg, regno, reg->off,
7283 					   access_size, zero_size_allowed,
7284 					   max_access);
7285 	case PTR_TO_STACK:
7286 		return check_stack_range_initialized(
7287 				env,
7288 				regno, reg->off, access_size,
7289 				zero_size_allowed, ACCESS_HELPER, meta);
7290 	case PTR_TO_BTF_ID:
7291 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7292 					       access_size, BPF_READ, -1);
7293 	case PTR_TO_CTX:
7294 		/* in case the function doesn't know how to access the context,
7295 		 * (because we are in a program of type SYSCALL for example), we
7296 		 * can not statically check its size.
7297 		 * Dynamically check it now.
7298 		 */
7299 		if (!env->ops->convert_ctx_access) {
7300 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7301 			int offset = access_size - 1;
7302 
7303 			/* Allow zero-byte read from PTR_TO_CTX */
7304 			if (access_size == 0)
7305 				return zero_size_allowed ? 0 : -EACCES;
7306 
7307 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7308 						atype, -1, false, false);
7309 		}
7310 
7311 		fallthrough;
7312 	default: /* scalar_value or invalid ptr */
7313 		/* Allow zero-byte read from NULL, regardless of pointer type */
7314 		if (zero_size_allowed && access_size == 0 &&
7315 		    register_is_null(reg))
7316 			return 0;
7317 
7318 		verbose(env, "R%d type=%s ", regno,
7319 			reg_type_str(env, reg->type));
7320 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7321 		return -EACCES;
7322 	}
7323 }
7324 
7325 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7326  * size.
7327  *
7328  * @regno is the register containing the access size. regno-1 is the register
7329  * containing the pointer.
7330  */
7331 static int check_mem_size_reg(struct bpf_verifier_env *env,
7332 			      struct bpf_reg_state *reg, u32 regno,
7333 			      bool zero_size_allowed,
7334 			      struct bpf_call_arg_meta *meta)
7335 {
7336 	int err;
7337 
7338 	/* This is used to refine r0 return value bounds for helpers
7339 	 * that enforce this value as an upper bound on return values.
7340 	 * See do_refine_retval_range() for helpers that can refine
7341 	 * the return value. C type of helper is u32 so we pull register
7342 	 * bound from umax_value however, if negative verifier errors
7343 	 * out. Only upper bounds can be learned because retval is an
7344 	 * int type and negative retvals are allowed.
7345 	 */
7346 	meta->msize_max_value = reg->umax_value;
7347 
7348 	/* The register is SCALAR_VALUE; the access check
7349 	 * happens using its boundaries.
7350 	 */
7351 	if (!tnum_is_const(reg->var_off))
7352 		/* For unprivileged variable accesses, disable raw
7353 		 * mode so that the program is required to
7354 		 * initialize all the memory that the helper could
7355 		 * just partially fill up.
7356 		 */
7357 		meta = NULL;
7358 
7359 	if (reg->smin_value < 0) {
7360 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7361 			regno);
7362 		return -EACCES;
7363 	}
7364 
7365 	if (reg->umin_value == 0 && !zero_size_allowed) {
7366 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7367 			regno, reg->umin_value, reg->umax_value);
7368 		return -EACCES;
7369 	}
7370 
7371 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7372 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7373 			regno);
7374 		return -EACCES;
7375 	}
7376 	err = check_helper_mem_access(env, regno - 1,
7377 				      reg->umax_value,
7378 				      zero_size_allowed, meta);
7379 	if (!err)
7380 		err = mark_chain_precision(env, regno);
7381 	return err;
7382 }
7383 
7384 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7385 			 u32 regno, u32 mem_size)
7386 {
7387 	bool may_be_null = type_may_be_null(reg->type);
7388 	struct bpf_reg_state saved_reg;
7389 	struct bpf_call_arg_meta meta;
7390 	int err;
7391 
7392 	if (register_is_null(reg))
7393 		return 0;
7394 
7395 	memset(&meta, 0, sizeof(meta));
7396 	/* Assuming that the register contains a value check if the memory
7397 	 * access is safe. Temporarily save and restore the register's state as
7398 	 * the conversion shouldn't be visible to a caller.
7399 	 */
7400 	if (may_be_null) {
7401 		saved_reg = *reg;
7402 		mark_ptr_not_null_reg(reg);
7403 	}
7404 
7405 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7406 	/* Check access for BPF_WRITE */
7407 	meta.raw_mode = true;
7408 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7409 
7410 	if (may_be_null)
7411 		*reg = saved_reg;
7412 
7413 	return err;
7414 }
7415 
7416 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7417 				    u32 regno)
7418 {
7419 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7420 	bool may_be_null = type_may_be_null(mem_reg->type);
7421 	struct bpf_reg_state saved_reg;
7422 	struct bpf_call_arg_meta meta;
7423 	int err;
7424 
7425 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7426 
7427 	memset(&meta, 0, sizeof(meta));
7428 
7429 	if (may_be_null) {
7430 		saved_reg = *mem_reg;
7431 		mark_ptr_not_null_reg(mem_reg);
7432 	}
7433 
7434 	err = check_mem_size_reg(env, reg, regno, true, &meta);
7435 	/* Check access for BPF_WRITE */
7436 	meta.raw_mode = true;
7437 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7438 
7439 	if (may_be_null)
7440 		*mem_reg = saved_reg;
7441 	return err;
7442 }
7443 
7444 /* Implementation details:
7445  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7446  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7447  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7448  * Two separate bpf_obj_new will also have different reg->id.
7449  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7450  * clears reg->id after value_or_null->value transition, since the verifier only
7451  * cares about the range of access to valid map value pointer and doesn't care
7452  * about actual address of the map element.
7453  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7454  * reg->id > 0 after value_or_null->value transition. By doing so
7455  * two bpf_map_lookups will be considered two different pointers that
7456  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7457  * returned from bpf_obj_new.
7458  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7459  * dead-locks.
7460  * Since only one bpf_spin_lock is allowed the checks are simpler than
7461  * reg_is_refcounted() logic. The verifier needs to remember only
7462  * one spin_lock instead of array of acquired_refs.
7463  * cur_state->active_lock remembers which map value element or allocated
7464  * object got locked and clears it after bpf_spin_unlock.
7465  */
7466 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7467 			     bool is_lock)
7468 {
7469 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7470 	struct bpf_verifier_state *cur = env->cur_state;
7471 	bool is_const = tnum_is_const(reg->var_off);
7472 	u64 val = reg->var_off.value;
7473 	struct bpf_map *map = NULL;
7474 	struct btf *btf = NULL;
7475 	struct btf_record *rec;
7476 
7477 	if (!is_const) {
7478 		verbose(env,
7479 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7480 			regno);
7481 		return -EINVAL;
7482 	}
7483 	if (reg->type == PTR_TO_MAP_VALUE) {
7484 		map = reg->map_ptr;
7485 		if (!map->btf) {
7486 			verbose(env,
7487 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7488 				map->name);
7489 			return -EINVAL;
7490 		}
7491 	} else {
7492 		btf = reg->btf;
7493 	}
7494 
7495 	rec = reg_btf_record(reg);
7496 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7497 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7498 			map ? map->name : "kptr");
7499 		return -EINVAL;
7500 	}
7501 	if (rec->spin_lock_off != val + reg->off) {
7502 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7503 			val + reg->off, rec->spin_lock_off);
7504 		return -EINVAL;
7505 	}
7506 	if (is_lock) {
7507 		if (cur->active_lock.ptr) {
7508 			verbose(env,
7509 				"Locking two bpf_spin_locks are not allowed\n");
7510 			return -EINVAL;
7511 		}
7512 		if (map)
7513 			cur->active_lock.ptr = map;
7514 		else
7515 			cur->active_lock.ptr = btf;
7516 		cur->active_lock.id = reg->id;
7517 	} else {
7518 		void *ptr;
7519 
7520 		if (map)
7521 			ptr = map;
7522 		else
7523 			ptr = btf;
7524 
7525 		if (!cur->active_lock.ptr) {
7526 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7527 			return -EINVAL;
7528 		}
7529 		if (cur->active_lock.ptr != ptr ||
7530 		    cur->active_lock.id != reg->id) {
7531 			verbose(env, "bpf_spin_unlock of different lock\n");
7532 			return -EINVAL;
7533 		}
7534 
7535 		invalidate_non_owning_refs(env);
7536 
7537 		cur->active_lock.ptr = NULL;
7538 		cur->active_lock.id = 0;
7539 	}
7540 	return 0;
7541 }
7542 
7543 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7544 			      struct bpf_call_arg_meta *meta)
7545 {
7546 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7547 	bool is_const = tnum_is_const(reg->var_off);
7548 	struct bpf_map *map = reg->map_ptr;
7549 	u64 val = reg->var_off.value;
7550 
7551 	if (!is_const) {
7552 		verbose(env,
7553 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7554 			regno);
7555 		return -EINVAL;
7556 	}
7557 	if (!map->btf) {
7558 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7559 			map->name);
7560 		return -EINVAL;
7561 	}
7562 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7563 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7564 		return -EINVAL;
7565 	}
7566 	if (map->record->timer_off != val + reg->off) {
7567 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7568 			val + reg->off, map->record->timer_off);
7569 		return -EINVAL;
7570 	}
7571 	if (meta->map_ptr) {
7572 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7573 		return -EFAULT;
7574 	}
7575 	meta->map_uid = reg->map_uid;
7576 	meta->map_ptr = map;
7577 	return 0;
7578 }
7579 
7580 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7581 			     struct bpf_call_arg_meta *meta)
7582 {
7583 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7584 	struct bpf_map *map_ptr = reg->map_ptr;
7585 	struct btf_field *kptr_field;
7586 	u32 kptr_off;
7587 
7588 	if (!tnum_is_const(reg->var_off)) {
7589 		verbose(env,
7590 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7591 			regno);
7592 		return -EINVAL;
7593 	}
7594 	if (!map_ptr->btf) {
7595 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7596 			map_ptr->name);
7597 		return -EINVAL;
7598 	}
7599 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7600 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7601 		return -EINVAL;
7602 	}
7603 
7604 	meta->map_ptr = map_ptr;
7605 	kptr_off = reg->off + reg->var_off.value;
7606 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7607 	if (!kptr_field) {
7608 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7609 		return -EACCES;
7610 	}
7611 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7612 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7613 		return -EACCES;
7614 	}
7615 	meta->kptr_field = kptr_field;
7616 	return 0;
7617 }
7618 
7619 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7620  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7621  *
7622  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7623  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7624  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7625  *
7626  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7627  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7628  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7629  * mutate the view of the dynptr and also possibly destroy it. In the latter
7630  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7631  * memory that dynptr points to.
7632  *
7633  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7634  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7635  * readonly dynptr view yet, hence only the first case is tracked and checked.
7636  *
7637  * This is consistent with how C applies the const modifier to a struct object,
7638  * where the pointer itself inside bpf_dynptr becomes const but not what it
7639  * points to.
7640  *
7641  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7642  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7643  */
7644 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7645 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7646 {
7647 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7648 	int err;
7649 
7650 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7651 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7652 	 */
7653 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7654 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7655 		return -EFAULT;
7656 	}
7657 
7658 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7659 	 *		 constructing a mutable bpf_dynptr object.
7660 	 *
7661 	 *		 Currently, this is only possible with PTR_TO_STACK
7662 	 *		 pointing to a region of at least 16 bytes which doesn't
7663 	 *		 contain an existing bpf_dynptr.
7664 	 *
7665 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7666 	 *		 mutated or destroyed. However, the memory it points to
7667 	 *		 may be mutated.
7668 	 *
7669 	 *  None       - Points to a initialized dynptr that can be mutated and
7670 	 *		 destroyed, including mutation of the memory it points
7671 	 *		 to.
7672 	 */
7673 	if (arg_type & MEM_UNINIT) {
7674 		int i;
7675 
7676 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7677 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7678 			return -EINVAL;
7679 		}
7680 
7681 		/* we write BPF_DW bits (8 bytes) at a time */
7682 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7683 			err = check_mem_access(env, insn_idx, regno,
7684 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7685 			if (err)
7686 				return err;
7687 		}
7688 
7689 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7690 	} else /* MEM_RDONLY and None case from above */ {
7691 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7692 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7693 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7694 			return -EINVAL;
7695 		}
7696 
7697 		if (!is_dynptr_reg_valid_init(env, reg)) {
7698 			verbose(env,
7699 				"Expected an initialized dynptr as arg #%d\n",
7700 				regno);
7701 			return -EINVAL;
7702 		}
7703 
7704 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7705 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7706 			verbose(env,
7707 				"Expected a dynptr of type %s as arg #%d\n",
7708 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7709 			return -EINVAL;
7710 		}
7711 
7712 		err = mark_dynptr_read(env, reg);
7713 	}
7714 	return err;
7715 }
7716 
7717 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7718 {
7719 	struct bpf_func_state *state = func(env, reg);
7720 
7721 	return state->stack[spi].spilled_ptr.ref_obj_id;
7722 }
7723 
7724 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7725 {
7726 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7727 }
7728 
7729 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7730 {
7731 	return meta->kfunc_flags & KF_ITER_NEW;
7732 }
7733 
7734 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7735 {
7736 	return meta->kfunc_flags & KF_ITER_NEXT;
7737 }
7738 
7739 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7740 {
7741 	return meta->kfunc_flags & KF_ITER_DESTROY;
7742 }
7743 
7744 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7745 {
7746 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7747 	 * kfunc is iter state pointer
7748 	 */
7749 	return arg == 0 && is_iter_kfunc(meta);
7750 }
7751 
7752 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7753 			    struct bpf_kfunc_call_arg_meta *meta)
7754 {
7755 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7756 	const struct btf_type *t;
7757 	const struct btf_param *arg;
7758 	int spi, err, i, nr_slots;
7759 	u32 btf_id;
7760 
7761 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7762 	arg = &btf_params(meta->func_proto)[0];
7763 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7764 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7765 	nr_slots = t->size / BPF_REG_SIZE;
7766 
7767 	if (is_iter_new_kfunc(meta)) {
7768 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7769 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7770 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7771 				iter_type_str(meta->btf, btf_id), regno);
7772 			return -EINVAL;
7773 		}
7774 
7775 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7776 			err = check_mem_access(env, insn_idx, regno,
7777 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7778 			if (err)
7779 				return err;
7780 		}
7781 
7782 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
7783 		if (err)
7784 			return err;
7785 	} else {
7786 		/* iter_next() or iter_destroy() expect initialized iter state*/
7787 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
7788 		switch (err) {
7789 		case 0:
7790 			break;
7791 		case -EINVAL:
7792 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7793 				iter_type_str(meta->btf, btf_id), regno);
7794 			return err;
7795 		case -EPROTO:
7796 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
7797 			return err;
7798 		default:
7799 			return err;
7800 		}
7801 
7802 		spi = iter_get_spi(env, reg, nr_slots);
7803 		if (spi < 0)
7804 			return spi;
7805 
7806 		err = mark_iter_read(env, reg, spi, nr_slots);
7807 		if (err)
7808 			return err;
7809 
7810 		/* remember meta->iter info for process_iter_next_call() */
7811 		meta->iter.spi = spi;
7812 		meta->iter.frameno = reg->frameno;
7813 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7814 
7815 		if (is_iter_destroy_kfunc(meta)) {
7816 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7817 			if (err)
7818 				return err;
7819 		}
7820 	}
7821 
7822 	return 0;
7823 }
7824 
7825 /* Look for a previous loop entry at insn_idx: nearest parent state
7826  * stopped at insn_idx with callsites matching those in cur->frame.
7827  */
7828 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7829 						  struct bpf_verifier_state *cur,
7830 						  int insn_idx)
7831 {
7832 	struct bpf_verifier_state_list *sl;
7833 	struct bpf_verifier_state *st;
7834 
7835 	/* Explored states are pushed in stack order, most recent states come first */
7836 	sl = *explored_state(env, insn_idx);
7837 	for (; sl; sl = sl->next) {
7838 		/* If st->branches != 0 state is a part of current DFS verification path,
7839 		 * hence cur & st for a loop.
7840 		 */
7841 		st = &sl->state;
7842 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7843 		    st->dfs_depth < cur->dfs_depth)
7844 			return st;
7845 	}
7846 
7847 	return NULL;
7848 }
7849 
7850 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7851 static bool regs_exact(const struct bpf_reg_state *rold,
7852 		       const struct bpf_reg_state *rcur,
7853 		       struct bpf_idmap *idmap);
7854 
7855 static void maybe_widen_reg(struct bpf_verifier_env *env,
7856 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7857 			    struct bpf_idmap *idmap)
7858 {
7859 	if (rold->type != SCALAR_VALUE)
7860 		return;
7861 	if (rold->type != rcur->type)
7862 		return;
7863 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7864 		return;
7865 	__mark_reg_unknown(env, rcur);
7866 }
7867 
7868 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7869 				   struct bpf_verifier_state *old,
7870 				   struct bpf_verifier_state *cur)
7871 {
7872 	struct bpf_func_state *fold, *fcur;
7873 	int i, fr;
7874 
7875 	reset_idmap_scratch(env);
7876 	for (fr = old->curframe; fr >= 0; fr--) {
7877 		fold = old->frame[fr];
7878 		fcur = cur->frame[fr];
7879 
7880 		for (i = 0; i < MAX_BPF_REG; i++)
7881 			maybe_widen_reg(env,
7882 					&fold->regs[i],
7883 					&fcur->regs[i],
7884 					&env->idmap_scratch);
7885 
7886 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7887 			if (!is_spilled_reg(&fold->stack[i]) ||
7888 			    !is_spilled_reg(&fcur->stack[i]))
7889 				continue;
7890 
7891 			maybe_widen_reg(env,
7892 					&fold->stack[i].spilled_ptr,
7893 					&fcur->stack[i].spilled_ptr,
7894 					&env->idmap_scratch);
7895 		}
7896 	}
7897 	return 0;
7898 }
7899 
7900 /* process_iter_next_call() is called when verifier gets to iterator's next
7901  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7902  * to it as just "iter_next()" in comments below.
7903  *
7904  * BPF verifier relies on a crucial contract for any iter_next()
7905  * implementation: it should *eventually* return NULL, and once that happens
7906  * it should keep returning NULL. That is, once iterator exhausts elements to
7907  * iterate, it should never reset or spuriously return new elements.
7908  *
7909  * With the assumption of such contract, process_iter_next_call() simulates
7910  * a fork in the verifier state to validate loop logic correctness and safety
7911  * without having to simulate infinite amount of iterations.
7912  *
7913  * In current state, we first assume that iter_next() returned NULL and
7914  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7915  * conditions we should not form an infinite loop and should eventually reach
7916  * exit.
7917  *
7918  * Besides that, we also fork current state and enqueue it for later
7919  * verification. In a forked state we keep iterator state as ACTIVE
7920  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7921  * also bump iteration depth to prevent erroneous infinite loop detection
7922  * later on (see iter_active_depths_differ() comment for details). In this
7923  * state we assume that we'll eventually loop back to another iter_next()
7924  * calls (it could be in exactly same location or in some other instruction,
7925  * it doesn't matter, we don't make any unnecessary assumptions about this,
7926  * everything revolves around iterator state in a stack slot, not which
7927  * instruction is calling iter_next()). When that happens, we either will come
7928  * to iter_next() with equivalent state and can conclude that next iteration
7929  * will proceed in exactly the same way as we just verified, so it's safe to
7930  * assume that loop converges. If not, we'll go on another iteration
7931  * simulation with a different input state, until all possible starting states
7932  * are validated or we reach maximum number of instructions limit.
7933  *
7934  * This way, we will either exhaustively discover all possible input states
7935  * that iterator loop can start with and eventually will converge, or we'll
7936  * effectively regress into bounded loop simulation logic and either reach
7937  * maximum number of instructions if loop is not provably convergent, or there
7938  * is some statically known limit on number of iterations (e.g., if there is
7939  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7940  *
7941  * Iteration convergence logic in is_state_visited() relies on exact
7942  * states comparison, which ignores read and precision marks.
7943  * This is necessary because read and precision marks are not finalized
7944  * while in the loop. Exact comparison might preclude convergence for
7945  * simple programs like below:
7946  *
7947  *     i = 0;
7948  *     while(iter_next(&it))
7949  *       i++;
7950  *
7951  * At each iteration step i++ would produce a new distinct state and
7952  * eventually instruction processing limit would be reached.
7953  *
7954  * To avoid such behavior speculatively forget (widen) range for
7955  * imprecise scalar registers, if those registers were not precise at the
7956  * end of the previous iteration and do not match exactly.
7957  *
7958  * This is a conservative heuristic that allows to verify wide range of programs,
7959  * however it precludes verification of programs that conjure an
7960  * imprecise value on the first loop iteration and use it as precise on a second.
7961  * For example, the following safe program would fail to verify:
7962  *
7963  *     struct bpf_num_iter it;
7964  *     int arr[10];
7965  *     int i = 0, a = 0;
7966  *     bpf_iter_num_new(&it, 0, 10);
7967  *     while (bpf_iter_num_next(&it)) {
7968  *       if (a == 0) {
7969  *         a = 1;
7970  *         i = 7; // Because i changed verifier would forget
7971  *                // it's range on second loop entry.
7972  *       } else {
7973  *         arr[i] = 42; // This would fail to verify.
7974  *       }
7975  *     }
7976  *     bpf_iter_num_destroy(&it);
7977  */
7978 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7979 				  struct bpf_kfunc_call_arg_meta *meta)
7980 {
7981 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7982 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7983 	struct bpf_reg_state *cur_iter, *queued_iter;
7984 	int iter_frameno = meta->iter.frameno;
7985 	int iter_spi = meta->iter.spi;
7986 
7987 	BTF_TYPE_EMIT(struct bpf_iter);
7988 
7989 	cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7990 
7991 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7992 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7993 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7994 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7995 		return -EFAULT;
7996 	}
7997 
7998 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7999 		/* Because iter_next() call is a checkpoint is_state_visitied()
8000 		 * should guarantee parent state with same call sites and insn_idx.
8001 		 */
8002 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8003 		    !same_callsites(cur_st->parent, cur_st)) {
8004 			verbose(env, "bug: bad parent state for iter next call");
8005 			return -EFAULT;
8006 		}
8007 		/* Note cur_st->parent in the call below, it is necessary to skip
8008 		 * checkpoint created for cur_st by is_state_visited()
8009 		 * right at this instruction.
8010 		 */
8011 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
8012 		/* branch out active iter state */
8013 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
8014 		if (!queued_st)
8015 			return -ENOMEM;
8016 
8017 		queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8018 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
8019 		queued_iter->iter.depth++;
8020 		if (prev_st)
8021 			widen_imprecise_scalars(env, prev_st, queued_st);
8022 
8023 		queued_fr = queued_st->frame[queued_st->curframe];
8024 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
8025 	}
8026 
8027 	/* switch to DRAINED state, but keep the depth unchanged */
8028 	/* mark current iter state as drained and assume returned NULL */
8029 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8030 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
8031 
8032 	return 0;
8033 }
8034 
8035 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8036 {
8037 	return type == ARG_CONST_SIZE ||
8038 	       type == ARG_CONST_SIZE_OR_ZERO;
8039 }
8040 
8041 static bool arg_type_is_release(enum bpf_arg_type type)
8042 {
8043 	return type & OBJ_RELEASE;
8044 }
8045 
8046 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8047 {
8048 	return base_type(type) == ARG_PTR_TO_DYNPTR;
8049 }
8050 
8051 static int int_ptr_type_to_size(enum bpf_arg_type type)
8052 {
8053 	if (type == ARG_PTR_TO_INT)
8054 		return sizeof(u32);
8055 	else if (type == ARG_PTR_TO_LONG)
8056 		return sizeof(u64);
8057 
8058 	return -EINVAL;
8059 }
8060 
8061 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8062 				 const struct bpf_call_arg_meta *meta,
8063 				 enum bpf_arg_type *arg_type)
8064 {
8065 	if (!meta->map_ptr) {
8066 		/* kernel subsystem misconfigured verifier */
8067 		verbose(env, "invalid map_ptr to access map->type\n");
8068 		return -EACCES;
8069 	}
8070 
8071 	switch (meta->map_ptr->map_type) {
8072 	case BPF_MAP_TYPE_SOCKMAP:
8073 	case BPF_MAP_TYPE_SOCKHASH:
8074 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8075 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8076 		} else {
8077 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8078 			return -EINVAL;
8079 		}
8080 		break;
8081 	case BPF_MAP_TYPE_BLOOM_FILTER:
8082 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8083 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8084 		break;
8085 	default:
8086 		break;
8087 	}
8088 	return 0;
8089 }
8090 
8091 struct bpf_reg_types {
8092 	const enum bpf_reg_type types[10];
8093 	u32 *btf_id;
8094 };
8095 
8096 static const struct bpf_reg_types sock_types = {
8097 	.types = {
8098 		PTR_TO_SOCK_COMMON,
8099 		PTR_TO_SOCKET,
8100 		PTR_TO_TCP_SOCK,
8101 		PTR_TO_XDP_SOCK,
8102 	},
8103 };
8104 
8105 #ifdef CONFIG_NET
8106 static const struct bpf_reg_types btf_id_sock_common_types = {
8107 	.types = {
8108 		PTR_TO_SOCK_COMMON,
8109 		PTR_TO_SOCKET,
8110 		PTR_TO_TCP_SOCK,
8111 		PTR_TO_XDP_SOCK,
8112 		PTR_TO_BTF_ID,
8113 		PTR_TO_BTF_ID | PTR_TRUSTED,
8114 	},
8115 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8116 };
8117 #endif
8118 
8119 static const struct bpf_reg_types mem_types = {
8120 	.types = {
8121 		PTR_TO_STACK,
8122 		PTR_TO_PACKET,
8123 		PTR_TO_PACKET_META,
8124 		PTR_TO_MAP_KEY,
8125 		PTR_TO_MAP_VALUE,
8126 		PTR_TO_MEM,
8127 		PTR_TO_MEM | MEM_RINGBUF,
8128 		PTR_TO_BUF,
8129 		PTR_TO_BTF_ID | PTR_TRUSTED,
8130 	},
8131 };
8132 
8133 static const struct bpf_reg_types int_ptr_types = {
8134 	.types = {
8135 		PTR_TO_STACK,
8136 		PTR_TO_PACKET,
8137 		PTR_TO_PACKET_META,
8138 		PTR_TO_MAP_KEY,
8139 		PTR_TO_MAP_VALUE,
8140 	},
8141 };
8142 
8143 static const struct bpf_reg_types spin_lock_types = {
8144 	.types = {
8145 		PTR_TO_MAP_VALUE,
8146 		PTR_TO_BTF_ID | MEM_ALLOC,
8147 	}
8148 };
8149 
8150 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8151 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8152 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8153 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8154 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8155 static const struct bpf_reg_types btf_ptr_types = {
8156 	.types = {
8157 		PTR_TO_BTF_ID,
8158 		PTR_TO_BTF_ID | PTR_TRUSTED,
8159 		PTR_TO_BTF_ID | MEM_RCU,
8160 	},
8161 };
8162 static const struct bpf_reg_types percpu_btf_ptr_types = {
8163 	.types = {
8164 		PTR_TO_BTF_ID | MEM_PERCPU,
8165 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8166 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8167 	}
8168 };
8169 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8170 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8171 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8172 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8173 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8174 static const struct bpf_reg_types dynptr_types = {
8175 	.types = {
8176 		PTR_TO_STACK,
8177 		CONST_PTR_TO_DYNPTR,
8178 	}
8179 };
8180 
8181 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8182 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8183 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8184 	[ARG_CONST_SIZE]		= &scalar_types,
8185 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8186 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8187 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8188 	[ARG_PTR_TO_CTX]		= &context_types,
8189 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8190 #ifdef CONFIG_NET
8191 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8192 #endif
8193 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8194 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8195 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8196 	[ARG_PTR_TO_MEM]		= &mem_types,
8197 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8198 	[ARG_PTR_TO_INT]		= &int_ptr_types,
8199 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
8200 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8201 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8202 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8203 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8204 	[ARG_PTR_TO_TIMER]		= &timer_types,
8205 	[ARG_PTR_TO_KPTR]		= &kptr_types,
8206 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8207 };
8208 
8209 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8210 			  enum bpf_arg_type arg_type,
8211 			  const u32 *arg_btf_id,
8212 			  struct bpf_call_arg_meta *meta)
8213 {
8214 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8215 	enum bpf_reg_type expected, type = reg->type;
8216 	const struct bpf_reg_types *compatible;
8217 	int i, j;
8218 
8219 	compatible = compatible_reg_types[base_type(arg_type)];
8220 	if (!compatible) {
8221 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8222 		return -EFAULT;
8223 	}
8224 
8225 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8226 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8227 	 *
8228 	 * Same for MAYBE_NULL:
8229 	 *
8230 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8231 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8232 	 *
8233 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8234 	 *
8235 	 * Therefore we fold these flags depending on the arg_type before comparison.
8236 	 */
8237 	if (arg_type & MEM_RDONLY)
8238 		type &= ~MEM_RDONLY;
8239 	if (arg_type & PTR_MAYBE_NULL)
8240 		type &= ~PTR_MAYBE_NULL;
8241 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8242 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8243 
8244 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) {
8245 		type &= ~MEM_ALLOC;
8246 		type &= ~MEM_PERCPU;
8247 	}
8248 
8249 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8250 		expected = compatible->types[i];
8251 		if (expected == NOT_INIT)
8252 			break;
8253 
8254 		if (type == expected)
8255 			goto found;
8256 	}
8257 
8258 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8259 	for (j = 0; j + 1 < i; j++)
8260 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8261 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8262 	return -EACCES;
8263 
8264 found:
8265 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8266 		return 0;
8267 
8268 	if (compatible == &mem_types) {
8269 		if (!(arg_type & MEM_RDONLY)) {
8270 			verbose(env,
8271 				"%s() may write into memory pointed by R%d type=%s\n",
8272 				func_id_name(meta->func_id),
8273 				regno, reg_type_str(env, reg->type));
8274 			return -EACCES;
8275 		}
8276 		return 0;
8277 	}
8278 
8279 	switch ((int)reg->type) {
8280 	case PTR_TO_BTF_ID:
8281 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8282 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
8283 	case PTR_TO_BTF_ID | MEM_RCU:
8284 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8285 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8286 	{
8287 		/* For bpf_sk_release, it needs to match against first member
8288 		 * 'struct sock_common', hence make an exception for it. This
8289 		 * allows bpf_sk_release to work for multiple socket types.
8290 		 */
8291 		bool strict_type_match = arg_type_is_release(arg_type) &&
8292 					 meta->func_id != BPF_FUNC_sk_release;
8293 
8294 		if (type_may_be_null(reg->type) &&
8295 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8296 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8297 			return -EACCES;
8298 		}
8299 
8300 		if (!arg_btf_id) {
8301 			if (!compatible->btf_id) {
8302 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8303 				return -EFAULT;
8304 			}
8305 			arg_btf_id = compatible->btf_id;
8306 		}
8307 
8308 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8309 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8310 				return -EACCES;
8311 		} else {
8312 			if (arg_btf_id == BPF_PTR_POISON) {
8313 				verbose(env, "verifier internal error:");
8314 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8315 					regno);
8316 				return -EACCES;
8317 			}
8318 
8319 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8320 						  btf_vmlinux, *arg_btf_id,
8321 						  strict_type_match)) {
8322 				verbose(env, "R%d is of type %s but %s is expected\n",
8323 					regno, btf_type_name(reg->btf, reg->btf_id),
8324 					btf_type_name(btf_vmlinux, *arg_btf_id));
8325 				return -EACCES;
8326 			}
8327 		}
8328 		break;
8329 	}
8330 	case PTR_TO_BTF_ID | MEM_ALLOC:
8331 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8332 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8333 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8334 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8335 			return -EFAULT;
8336 		}
8337 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8338 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8339 				return -EACCES;
8340 		}
8341 		break;
8342 	case PTR_TO_BTF_ID | MEM_PERCPU:
8343 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8344 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8345 		/* Handled by helper specific checks */
8346 		break;
8347 	default:
8348 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8349 		return -EFAULT;
8350 	}
8351 	return 0;
8352 }
8353 
8354 static struct btf_field *
8355 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8356 {
8357 	struct btf_field *field;
8358 	struct btf_record *rec;
8359 
8360 	rec = reg_btf_record(reg);
8361 	if (!rec)
8362 		return NULL;
8363 
8364 	field = btf_record_find(rec, off, fields);
8365 	if (!field)
8366 		return NULL;
8367 
8368 	return field;
8369 }
8370 
8371 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8372 				  const struct bpf_reg_state *reg, int regno,
8373 				  enum bpf_arg_type arg_type)
8374 {
8375 	u32 type = reg->type;
8376 
8377 	/* When referenced register is passed to release function, its fixed
8378 	 * offset must be 0.
8379 	 *
8380 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8381 	 * meta->release_regno.
8382 	 */
8383 	if (arg_type_is_release(arg_type)) {
8384 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8385 		 * may not directly point to the object being released, but to
8386 		 * dynptr pointing to such object, which might be at some offset
8387 		 * on the stack. In that case, we simply to fallback to the
8388 		 * default handling.
8389 		 */
8390 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8391 			return 0;
8392 
8393 		/* Doing check_ptr_off_reg check for the offset will catch this
8394 		 * because fixed_off_ok is false, but checking here allows us
8395 		 * to give the user a better error message.
8396 		 */
8397 		if (reg->off) {
8398 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8399 				regno);
8400 			return -EINVAL;
8401 		}
8402 		return __check_ptr_off_reg(env, reg, regno, false);
8403 	}
8404 
8405 	switch (type) {
8406 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8407 	case PTR_TO_STACK:
8408 	case PTR_TO_PACKET:
8409 	case PTR_TO_PACKET_META:
8410 	case PTR_TO_MAP_KEY:
8411 	case PTR_TO_MAP_VALUE:
8412 	case PTR_TO_MEM:
8413 	case PTR_TO_MEM | MEM_RDONLY:
8414 	case PTR_TO_MEM | MEM_RINGBUF:
8415 	case PTR_TO_BUF:
8416 	case PTR_TO_BUF | MEM_RDONLY:
8417 	case PTR_TO_ARENA:
8418 	case SCALAR_VALUE:
8419 		return 0;
8420 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8421 	 * fixed offset.
8422 	 */
8423 	case PTR_TO_BTF_ID:
8424 	case PTR_TO_BTF_ID | MEM_ALLOC:
8425 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8426 	case PTR_TO_BTF_ID | MEM_RCU:
8427 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8428 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8429 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8430 		 * its fixed offset must be 0. In the other cases, fixed offset
8431 		 * can be non-zero. This was already checked above. So pass
8432 		 * fixed_off_ok as true to allow fixed offset for all other
8433 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8434 		 * still need to do checks instead of returning.
8435 		 */
8436 		return __check_ptr_off_reg(env, reg, regno, true);
8437 	default:
8438 		return __check_ptr_off_reg(env, reg, regno, false);
8439 	}
8440 }
8441 
8442 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8443 						const struct bpf_func_proto *fn,
8444 						struct bpf_reg_state *regs)
8445 {
8446 	struct bpf_reg_state *state = NULL;
8447 	int i;
8448 
8449 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8450 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8451 			if (state) {
8452 				verbose(env, "verifier internal error: multiple dynptr args\n");
8453 				return NULL;
8454 			}
8455 			state = &regs[BPF_REG_1 + i];
8456 		}
8457 
8458 	if (!state)
8459 		verbose(env, "verifier internal error: no dynptr arg found\n");
8460 
8461 	return state;
8462 }
8463 
8464 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8465 {
8466 	struct bpf_func_state *state = func(env, reg);
8467 	int spi;
8468 
8469 	if (reg->type == CONST_PTR_TO_DYNPTR)
8470 		return reg->id;
8471 	spi = dynptr_get_spi(env, reg);
8472 	if (spi < 0)
8473 		return spi;
8474 	return state->stack[spi].spilled_ptr.id;
8475 }
8476 
8477 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8478 {
8479 	struct bpf_func_state *state = func(env, reg);
8480 	int spi;
8481 
8482 	if (reg->type == CONST_PTR_TO_DYNPTR)
8483 		return reg->ref_obj_id;
8484 	spi = dynptr_get_spi(env, reg);
8485 	if (spi < 0)
8486 		return spi;
8487 	return state->stack[spi].spilled_ptr.ref_obj_id;
8488 }
8489 
8490 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8491 					    struct bpf_reg_state *reg)
8492 {
8493 	struct bpf_func_state *state = func(env, reg);
8494 	int spi;
8495 
8496 	if (reg->type == CONST_PTR_TO_DYNPTR)
8497 		return reg->dynptr.type;
8498 
8499 	spi = __get_spi(reg->off);
8500 	if (spi < 0) {
8501 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8502 		return BPF_DYNPTR_TYPE_INVALID;
8503 	}
8504 
8505 	return state->stack[spi].spilled_ptr.dynptr.type;
8506 }
8507 
8508 static int check_reg_const_str(struct bpf_verifier_env *env,
8509 			       struct bpf_reg_state *reg, u32 regno)
8510 {
8511 	struct bpf_map *map = reg->map_ptr;
8512 	int err;
8513 	int map_off;
8514 	u64 map_addr;
8515 	char *str_ptr;
8516 
8517 	if (reg->type != PTR_TO_MAP_VALUE)
8518 		return -EINVAL;
8519 
8520 	if (!bpf_map_is_rdonly(map)) {
8521 		verbose(env, "R%d does not point to a readonly map'\n", regno);
8522 		return -EACCES;
8523 	}
8524 
8525 	if (!tnum_is_const(reg->var_off)) {
8526 		verbose(env, "R%d is not a constant address'\n", regno);
8527 		return -EACCES;
8528 	}
8529 
8530 	if (!map->ops->map_direct_value_addr) {
8531 		verbose(env, "no direct value access support for this map type\n");
8532 		return -EACCES;
8533 	}
8534 
8535 	err = check_map_access(env, regno, reg->off,
8536 			       map->value_size - reg->off, false,
8537 			       ACCESS_HELPER);
8538 	if (err)
8539 		return err;
8540 
8541 	map_off = reg->off + reg->var_off.value;
8542 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8543 	if (err) {
8544 		verbose(env, "direct value access on string failed\n");
8545 		return err;
8546 	}
8547 
8548 	str_ptr = (char *)(long)(map_addr);
8549 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8550 		verbose(env, "string is not zero-terminated\n");
8551 		return -EINVAL;
8552 	}
8553 	return 0;
8554 }
8555 
8556 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8557 			  struct bpf_call_arg_meta *meta,
8558 			  const struct bpf_func_proto *fn,
8559 			  int insn_idx)
8560 {
8561 	u32 regno = BPF_REG_1 + arg;
8562 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8563 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8564 	enum bpf_reg_type type = reg->type;
8565 	u32 *arg_btf_id = NULL;
8566 	int err = 0;
8567 
8568 	if (arg_type == ARG_DONTCARE)
8569 		return 0;
8570 
8571 	err = check_reg_arg(env, regno, SRC_OP);
8572 	if (err)
8573 		return err;
8574 
8575 	if (arg_type == ARG_ANYTHING) {
8576 		if (is_pointer_value(env, regno)) {
8577 			verbose(env, "R%d leaks addr into helper function\n",
8578 				regno);
8579 			return -EACCES;
8580 		}
8581 		return 0;
8582 	}
8583 
8584 	if (type_is_pkt_pointer(type) &&
8585 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8586 		verbose(env, "helper access to the packet is not allowed\n");
8587 		return -EACCES;
8588 	}
8589 
8590 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8591 		err = resolve_map_arg_type(env, meta, &arg_type);
8592 		if (err)
8593 			return err;
8594 	}
8595 
8596 	if (register_is_null(reg) && type_may_be_null(arg_type))
8597 		/* A NULL register has a SCALAR_VALUE type, so skip
8598 		 * type checking.
8599 		 */
8600 		goto skip_type_check;
8601 
8602 	/* arg_btf_id and arg_size are in a union. */
8603 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8604 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8605 		arg_btf_id = fn->arg_btf_id[arg];
8606 
8607 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8608 	if (err)
8609 		return err;
8610 
8611 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8612 	if (err)
8613 		return err;
8614 
8615 skip_type_check:
8616 	if (arg_type_is_release(arg_type)) {
8617 		if (arg_type_is_dynptr(arg_type)) {
8618 			struct bpf_func_state *state = func(env, reg);
8619 			int spi;
8620 
8621 			/* Only dynptr created on stack can be released, thus
8622 			 * the get_spi and stack state checks for spilled_ptr
8623 			 * should only be done before process_dynptr_func for
8624 			 * PTR_TO_STACK.
8625 			 */
8626 			if (reg->type == PTR_TO_STACK) {
8627 				spi = dynptr_get_spi(env, reg);
8628 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8629 					verbose(env, "arg %d is an unacquired reference\n", regno);
8630 					return -EINVAL;
8631 				}
8632 			} else {
8633 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8634 				return -EINVAL;
8635 			}
8636 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8637 			verbose(env, "R%d must be referenced when passed to release function\n",
8638 				regno);
8639 			return -EINVAL;
8640 		}
8641 		if (meta->release_regno) {
8642 			verbose(env, "verifier internal error: more than one release argument\n");
8643 			return -EFAULT;
8644 		}
8645 		meta->release_regno = regno;
8646 	}
8647 
8648 	if (reg->ref_obj_id) {
8649 		if (meta->ref_obj_id) {
8650 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8651 				regno, reg->ref_obj_id,
8652 				meta->ref_obj_id);
8653 			return -EFAULT;
8654 		}
8655 		meta->ref_obj_id = reg->ref_obj_id;
8656 	}
8657 
8658 	switch (base_type(arg_type)) {
8659 	case ARG_CONST_MAP_PTR:
8660 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8661 		if (meta->map_ptr) {
8662 			/* Use map_uid (which is unique id of inner map) to reject:
8663 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8664 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8665 			 * if (inner_map1 && inner_map2) {
8666 			 *     timer = bpf_map_lookup_elem(inner_map1);
8667 			 *     if (timer)
8668 			 *         // mismatch would have been allowed
8669 			 *         bpf_timer_init(timer, inner_map2);
8670 			 * }
8671 			 *
8672 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8673 			 */
8674 			if (meta->map_ptr != reg->map_ptr ||
8675 			    meta->map_uid != reg->map_uid) {
8676 				verbose(env,
8677 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8678 					meta->map_uid, reg->map_uid);
8679 				return -EINVAL;
8680 			}
8681 		}
8682 		meta->map_ptr = reg->map_ptr;
8683 		meta->map_uid = reg->map_uid;
8684 		break;
8685 	case ARG_PTR_TO_MAP_KEY:
8686 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8687 		 * check that [key, key + map->key_size) are within
8688 		 * stack limits and initialized
8689 		 */
8690 		if (!meta->map_ptr) {
8691 			/* in function declaration map_ptr must come before
8692 			 * map_key, so that it's verified and known before
8693 			 * we have to check map_key here. Otherwise it means
8694 			 * that kernel subsystem misconfigured verifier
8695 			 */
8696 			verbose(env, "invalid map_ptr to access map->key\n");
8697 			return -EACCES;
8698 		}
8699 		err = check_helper_mem_access(env, regno,
8700 					      meta->map_ptr->key_size, false,
8701 					      NULL);
8702 		break;
8703 	case ARG_PTR_TO_MAP_VALUE:
8704 		if (type_may_be_null(arg_type) && register_is_null(reg))
8705 			return 0;
8706 
8707 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8708 		 * check [value, value + map->value_size) validity
8709 		 */
8710 		if (!meta->map_ptr) {
8711 			/* kernel subsystem misconfigured verifier */
8712 			verbose(env, "invalid map_ptr to access map->value\n");
8713 			return -EACCES;
8714 		}
8715 		meta->raw_mode = arg_type & MEM_UNINIT;
8716 		err = check_helper_mem_access(env, regno,
8717 					      meta->map_ptr->value_size, false,
8718 					      meta);
8719 		break;
8720 	case ARG_PTR_TO_PERCPU_BTF_ID:
8721 		if (!reg->btf_id) {
8722 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8723 			return -EACCES;
8724 		}
8725 		meta->ret_btf = reg->btf;
8726 		meta->ret_btf_id = reg->btf_id;
8727 		break;
8728 	case ARG_PTR_TO_SPIN_LOCK:
8729 		if (in_rbtree_lock_required_cb(env)) {
8730 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8731 			return -EACCES;
8732 		}
8733 		if (meta->func_id == BPF_FUNC_spin_lock) {
8734 			err = process_spin_lock(env, regno, true);
8735 			if (err)
8736 				return err;
8737 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8738 			err = process_spin_lock(env, regno, false);
8739 			if (err)
8740 				return err;
8741 		} else {
8742 			verbose(env, "verifier internal error\n");
8743 			return -EFAULT;
8744 		}
8745 		break;
8746 	case ARG_PTR_TO_TIMER:
8747 		err = process_timer_func(env, regno, meta);
8748 		if (err)
8749 			return err;
8750 		break;
8751 	case ARG_PTR_TO_FUNC:
8752 		meta->subprogno = reg->subprogno;
8753 		break;
8754 	case ARG_PTR_TO_MEM:
8755 		/* The access to this pointer is only checked when we hit the
8756 		 * next is_mem_size argument below.
8757 		 */
8758 		meta->raw_mode = arg_type & MEM_UNINIT;
8759 		if (arg_type & MEM_FIXED_SIZE) {
8760 			err = check_helper_mem_access(env, regno,
8761 						      fn->arg_size[arg], false,
8762 						      meta);
8763 		}
8764 		break;
8765 	case ARG_CONST_SIZE:
8766 		err = check_mem_size_reg(env, reg, regno, false, meta);
8767 		break;
8768 	case ARG_CONST_SIZE_OR_ZERO:
8769 		err = check_mem_size_reg(env, reg, regno, true, meta);
8770 		break;
8771 	case ARG_PTR_TO_DYNPTR:
8772 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8773 		if (err)
8774 			return err;
8775 		break;
8776 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8777 		if (!tnum_is_const(reg->var_off)) {
8778 			verbose(env, "R%d is not a known constant'\n",
8779 				regno);
8780 			return -EACCES;
8781 		}
8782 		meta->mem_size = reg->var_off.value;
8783 		err = mark_chain_precision(env, regno);
8784 		if (err)
8785 			return err;
8786 		break;
8787 	case ARG_PTR_TO_INT:
8788 	case ARG_PTR_TO_LONG:
8789 	{
8790 		int size = int_ptr_type_to_size(arg_type);
8791 
8792 		err = check_helper_mem_access(env, regno, size, false, meta);
8793 		if (err)
8794 			return err;
8795 		err = check_ptr_alignment(env, reg, 0, size, true);
8796 		break;
8797 	}
8798 	case ARG_PTR_TO_CONST_STR:
8799 	{
8800 		err = check_reg_const_str(env, reg, regno);
8801 		if (err)
8802 			return err;
8803 		break;
8804 	}
8805 	case ARG_PTR_TO_KPTR:
8806 		err = process_kptr_func(env, regno, meta);
8807 		if (err)
8808 			return err;
8809 		break;
8810 	}
8811 
8812 	return err;
8813 }
8814 
8815 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8816 {
8817 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8818 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8819 
8820 	if (func_id != BPF_FUNC_map_update_elem)
8821 		return false;
8822 
8823 	/* It's not possible to get access to a locked struct sock in these
8824 	 * contexts, so updating is safe.
8825 	 */
8826 	switch (type) {
8827 	case BPF_PROG_TYPE_TRACING:
8828 		if (eatype == BPF_TRACE_ITER)
8829 			return true;
8830 		break;
8831 	case BPF_PROG_TYPE_SOCKET_FILTER:
8832 	case BPF_PROG_TYPE_SCHED_CLS:
8833 	case BPF_PROG_TYPE_SCHED_ACT:
8834 	case BPF_PROG_TYPE_XDP:
8835 	case BPF_PROG_TYPE_SK_REUSEPORT:
8836 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8837 	case BPF_PROG_TYPE_SK_LOOKUP:
8838 		return true;
8839 	default:
8840 		break;
8841 	}
8842 
8843 	verbose(env, "cannot update sockmap in this context\n");
8844 	return false;
8845 }
8846 
8847 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8848 {
8849 	return env->prog->jit_requested &&
8850 	       bpf_jit_supports_subprog_tailcalls();
8851 }
8852 
8853 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8854 					struct bpf_map *map, int func_id)
8855 {
8856 	if (!map)
8857 		return 0;
8858 
8859 	/* We need a two way check, first is from map perspective ... */
8860 	switch (map->map_type) {
8861 	case BPF_MAP_TYPE_PROG_ARRAY:
8862 		if (func_id != BPF_FUNC_tail_call)
8863 			goto error;
8864 		break;
8865 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8866 		if (func_id != BPF_FUNC_perf_event_read &&
8867 		    func_id != BPF_FUNC_perf_event_output &&
8868 		    func_id != BPF_FUNC_skb_output &&
8869 		    func_id != BPF_FUNC_perf_event_read_value &&
8870 		    func_id != BPF_FUNC_xdp_output)
8871 			goto error;
8872 		break;
8873 	case BPF_MAP_TYPE_RINGBUF:
8874 		if (func_id != BPF_FUNC_ringbuf_output &&
8875 		    func_id != BPF_FUNC_ringbuf_reserve &&
8876 		    func_id != BPF_FUNC_ringbuf_query &&
8877 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8878 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8879 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8880 			goto error;
8881 		break;
8882 	case BPF_MAP_TYPE_USER_RINGBUF:
8883 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8884 			goto error;
8885 		break;
8886 	case BPF_MAP_TYPE_STACK_TRACE:
8887 		if (func_id != BPF_FUNC_get_stackid)
8888 			goto error;
8889 		break;
8890 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8891 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8892 		    func_id != BPF_FUNC_current_task_under_cgroup)
8893 			goto error;
8894 		break;
8895 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8896 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8897 		if (func_id != BPF_FUNC_get_local_storage)
8898 			goto error;
8899 		break;
8900 	case BPF_MAP_TYPE_DEVMAP:
8901 	case BPF_MAP_TYPE_DEVMAP_HASH:
8902 		if (func_id != BPF_FUNC_redirect_map &&
8903 		    func_id != BPF_FUNC_map_lookup_elem)
8904 			goto error;
8905 		break;
8906 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8907 	 * appear.
8908 	 */
8909 	case BPF_MAP_TYPE_CPUMAP:
8910 		if (func_id != BPF_FUNC_redirect_map)
8911 			goto error;
8912 		break;
8913 	case BPF_MAP_TYPE_XSKMAP:
8914 		if (func_id != BPF_FUNC_redirect_map &&
8915 		    func_id != BPF_FUNC_map_lookup_elem)
8916 			goto error;
8917 		break;
8918 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8919 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8920 		if (func_id != BPF_FUNC_map_lookup_elem)
8921 			goto error;
8922 		break;
8923 	case BPF_MAP_TYPE_SOCKMAP:
8924 		if (func_id != BPF_FUNC_sk_redirect_map &&
8925 		    func_id != BPF_FUNC_sock_map_update &&
8926 		    func_id != BPF_FUNC_map_delete_elem &&
8927 		    func_id != BPF_FUNC_msg_redirect_map &&
8928 		    func_id != BPF_FUNC_sk_select_reuseport &&
8929 		    func_id != BPF_FUNC_map_lookup_elem &&
8930 		    !may_update_sockmap(env, func_id))
8931 			goto error;
8932 		break;
8933 	case BPF_MAP_TYPE_SOCKHASH:
8934 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8935 		    func_id != BPF_FUNC_sock_hash_update &&
8936 		    func_id != BPF_FUNC_map_delete_elem &&
8937 		    func_id != BPF_FUNC_msg_redirect_hash &&
8938 		    func_id != BPF_FUNC_sk_select_reuseport &&
8939 		    func_id != BPF_FUNC_map_lookup_elem &&
8940 		    !may_update_sockmap(env, func_id))
8941 			goto error;
8942 		break;
8943 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8944 		if (func_id != BPF_FUNC_sk_select_reuseport)
8945 			goto error;
8946 		break;
8947 	case BPF_MAP_TYPE_QUEUE:
8948 	case BPF_MAP_TYPE_STACK:
8949 		if (func_id != BPF_FUNC_map_peek_elem &&
8950 		    func_id != BPF_FUNC_map_pop_elem &&
8951 		    func_id != BPF_FUNC_map_push_elem)
8952 			goto error;
8953 		break;
8954 	case BPF_MAP_TYPE_SK_STORAGE:
8955 		if (func_id != BPF_FUNC_sk_storage_get &&
8956 		    func_id != BPF_FUNC_sk_storage_delete &&
8957 		    func_id != BPF_FUNC_kptr_xchg)
8958 			goto error;
8959 		break;
8960 	case BPF_MAP_TYPE_INODE_STORAGE:
8961 		if (func_id != BPF_FUNC_inode_storage_get &&
8962 		    func_id != BPF_FUNC_inode_storage_delete &&
8963 		    func_id != BPF_FUNC_kptr_xchg)
8964 			goto error;
8965 		break;
8966 	case BPF_MAP_TYPE_TASK_STORAGE:
8967 		if (func_id != BPF_FUNC_task_storage_get &&
8968 		    func_id != BPF_FUNC_task_storage_delete &&
8969 		    func_id != BPF_FUNC_kptr_xchg)
8970 			goto error;
8971 		break;
8972 	case BPF_MAP_TYPE_CGRP_STORAGE:
8973 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8974 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8975 		    func_id != BPF_FUNC_kptr_xchg)
8976 			goto error;
8977 		break;
8978 	case BPF_MAP_TYPE_BLOOM_FILTER:
8979 		if (func_id != BPF_FUNC_map_peek_elem &&
8980 		    func_id != BPF_FUNC_map_push_elem)
8981 			goto error;
8982 		break;
8983 	default:
8984 		break;
8985 	}
8986 
8987 	/* ... and second from the function itself. */
8988 	switch (func_id) {
8989 	case BPF_FUNC_tail_call:
8990 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8991 			goto error;
8992 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8993 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8994 			return -EINVAL;
8995 		}
8996 		break;
8997 	case BPF_FUNC_perf_event_read:
8998 	case BPF_FUNC_perf_event_output:
8999 	case BPF_FUNC_perf_event_read_value:
9000 	case BPF_FUNC_skb_output:
9001 	case BPF_FUNC_xdp_output:
9002 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
9003 			goto error;
9004 		break;
9005 	case BPF_FUNC_ringbuf_output:
9006 	case BPF_FUNC_ringbuf_reserve:
9007 	case BPF_FUNC_ringbuf_query:
9008 	case BPF_FUNC_ringbuf_reserve_dynptr:
9009 	case BPF_FUNC_ringbuf_submit_dynptr:
9010 	case BPF_FUNC_ringbuf_discard_dynptr:
9011 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
9012 			goto error;
9013 		break;
9014 	case BPF_FUNC_user_ringbuf_drain:
9015 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
9016 			goto error;
9017 		break;
9018 	case BPF_FUNC_get_stackid:
9019 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
9020 			goto error;
9021 		break;
9022 	case BPF_FUNC_current_task_under_cgroup:
9023 	case BPF_FUNC_skb_under_cgroup:
9024 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
9025 			goto error;
9026 		break;
9027 	case BPF_FUNC_redirect_map:
9028 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
9029 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
9030 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
9031 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
9032 			goto error;
9033 		break;
9034 	case BPF_FUNC_sk_redirect_map:
9035 	case BPF_FUNC_msg_redirect_map:
9036 	case BPF_FUNC_sock_map_update:
9037 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
9038 			goto error;
9039 		break;
9040 	case BPF_FUNC_sk_redirect_hash:
9041 	case BPF_FUNC_msg_redirect_hash:
9042 	case BPF_FUNC_sock_hash_update:
9043 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
9044 			goto error;
9045 		break;
9046 	case BPF_FUNC_get_local_storage:
9047 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
9048 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
9049 			goto error;
9050 		break;
9051 	case BPF_FUNC_sk_select_reuseport:
9052 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
9053 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
9054 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
9055 			goto error;
9056 		break;
9057 	case BPF_FUNC_map_pop_elem:
9058 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9059 		    map->map_type != BPF_MAP_TYPE_STACK)
9060 			goto error;
9061 		break;
9062 	case BPF_FUNC_map_peek_elem:
9063 	case BPF_FUNC_map_push_elem:
9064 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9065 		    map->map_type != BPF_MAP_TYPE_STACK &&
9066 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9067 			goto error;
9068 		break;
9069 	case BPF_FUNC_map_lookup_percpu_elem:
9070 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9071 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9072 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9073 			goto error;
9074 		break;
9075 	case BPF_FUNC_sk_storage_get:
9076 	case BPF_FUNC_sk_storage_delete:
9077 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9078 			goto error;
9079 		break;
9080 	case BPF_FUNC_inode_storage_get:
9081 	case BPF_FUNC_inode_storage_delete:
9082 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9083 			goto error;
9084 		break;
9085 	case BPF_FUNC_task_storage_get:
9086 	case BPF_FUNC_task_storage_delete:
9087 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9088 			goto error;
9089 		break;
9090 	case BPF_FUNC_cgrp_storage_get:
9091 	case BPF_FUNC_cgrp_storage_delete:
9092 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9093 			goto error;
9094 		break;
9095 	default:
9096 		break;
9097 	}
9098 
9099 	return 0;
9100 error:
9101 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9102 		map->map_type, func_id_name(func_id), func_id);
9103 	return -EINVAL;
9104 }
9105 
9106 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9107 {
9108 	int count = 0;
9109 
9110 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
9111 		count++;
9112 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
9113 		count++;
9114 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
9115 		count++;
9116 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
9117 		count++;
9118 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9119 		count++;
9120 
9121 	/* We only support one arg being in raw mode at the moment,
9122 	 * which is sufficient for the helper functions we have
9123 	 * right now.
9124 	 */
9125 	return count <= 1;
9126 }
9127 
9128 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9129 {
9130 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9131 	bool has_size = fn->arg_size[arg] != 0;
9132 	bool is_next_size = false;
9133 
9134 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9135 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9136 
9137 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9138 		return is_next_size;
9139 
9140 	return has_size == is_next_size || is_next_size == is_fixed;
9141 }
9142 
9143 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9144 {
9145 	/* bpf_xxx(..., buf, len) call will access 'len'
9146 	 * bytes from memory 'buf'. Both arg types need
9147 	 * to be paired, so make sure there's no buggy
9148 	 * helper function specification.
9149 	 */
9150 	if (arg_type_is_mem_size(fn->arg1_type) ||
9151 	    check_args_pair_invalid(fn, 0) ||
9152 	    check_args_pair_invalid(fn, 1) ||
9153 	    check_args_pair_invalid(fn, 2) ||
9154 	    check_args_pair_invalid(fn, 3) ||
9155 	    check_args_pair_invalid(fn, 4))
9156 		return false;
9157 
9158 	return true;
9159 }
9160 
9161 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9162 {
9163 	int i;
9164 
9165 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9166 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9167 			return !!fn->arg_btf_id[i];
9168 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9169 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9170 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9171 		    /* arg_btf_id and arg_size are in a union. */
9172 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9173 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9174 			return false;
9175 	}
9176 
9177 	return true;
9178 }
9179 
9180 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9181 {
9182 	return check_raw_mode_ok(fn) &&
9183 	       check_arg_pair_ok(fn) &&
9184 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9185 }
9186 
9187 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9188  * are now invalid, so turn them into unknown SCALAR_VALUE.
9189  *
9190  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9191  * since these slices point to packet data.
9192  */
9193 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9194 {
9195 	struct bpf_func_state *state;
9196 	struct bpf_reg_state *reg;
9197 
9198 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9199 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9200 			mark_reg_invalid(env, reg);
9201 	}));
9202 }
9203 
9204 enum {
9205 	AT_PKT_END = -1,
9206 	BEYOND_PKT_END = -2,
9207 };
9208 
9209 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9210 {
9211 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9212 	struct bpf_reg_state *reg = &state->regs[regn];
9213 
9214 	if (reg->type != PTR_TO_PACKET)
9215 		/* PTR_TO_PACKET_META is not supported yet */
9216 		return;
9217 
9218 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9219 	 * How far beyond pkt_end it goes is unknown.
9220 	 * if (!range_open) it's the case of pkt >= pkt_end
9221 	 * if (range_open) it's the case of pkt > pkt_end
9222 	 * hence this pointer is at least 1 byte bigger than pkt_end
9223 	 */
9224 	if (range_open)
9225 		reg->range = BEYOND_PKT_END;
9226 	else
9227 		reg->range = AT_PKT_END;
9228 }
9229 
9230 /* The pointer with the specified id has released its reference to kernel
9231  * resources. Identify all copies of the same pointer and clear the reference.
9232  */
9233 static int release_reference(struct bpf_verifier_env *env,
9234 			     int ref_obj_id)
9235 {
9236 	struct bpf_func_state *state;
9237 	struct bpf_reg_state *reg;
9238 	int err;
9239 
9240 	err = release_reference_state(cur_func(env), ref_obj_id);
9241 	if (err)
9242 		return err;
9243 
9244 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9245 		if (reg->ref_obj_id == ref_obj_id)
9246 			mark_reg_invalid(env, reg);
9247 	}));
9248 
9249 	return 0;
9250 }
9251 
9252 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9253 {
9254 	struct bpf_func_state *unused;
9255 	struct bpf_reg_state *reg;
9256 
9257 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9258 		if (type_is_non_owning_ref(reg->type))
9259 			mark_reg_invalid(env, reg);
9260 	}));
9261 }
9262 
9263 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9264 				    struct bpf_reg_state *regs)
9265 {
9266 	int i;
9267 
9268 	/* after the call registers r0 - r5 were scratched */
9269 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9270 		mark_reg_not_init(env, regs, caller_saved[i]);
9271 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9272 	}
9273 }
9274 
9275 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9276 				   struct bpf_func_state *caller,
9277 				   struct bpf_func_state *callee,
9278 				   int insn_idx);
9279 
9280 static int set_callee_state(struct bpf_verifier_env *env,
9281 			    struct bpf_func_state *caller,
9282 			    struct bpf_func_state *callee, int insn_idx);
9283 
9284 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9285 			    set_callee_state_fn set_callee_state_cb,
9286 			    struct bpf_verifier_state *state)
9287 {
9288 	struct bpf_func_state *caller, *callee;
9289 	int err;
9290 
9291 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9292 		verbose(env, "the call stack of %d frames is too deep\n",
9293 			state->curframe + 2);
9294 		return -E2BIG;
9295 	}
9296 
9297 	if (state->frame[state->curframe + 1]) {
9298 		verbose(env, "verifier bug. Frame %d already allocated\n",
9299 			state->curframe + 1);
9300 		return -EFAULT;
9301 	}
9302 
9303 	caller = state->frame[state->curframe];
9304 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9305 	if (!callee)
9306 		return -ENOMEM;
9307 	state->frame[state->curframe + 1] = callee;
9308 
9309 	/* callee cannot access r0, r6 - r9 for reading and has to write
9310 	 * into its own stack before reading from it.
9311 	 * callee can read/write into caller's stack
9312 	 */
9313 	init_func_state(env, callee,
9314 			/* remember the callsite, it will be used by bpf_exit */
9315 			callsite,
9316 			state->curframe + 1 /* frameno within this callchain */,
9317 			subprog /* subprog number within this prog */);
9318 	/* Transfer references to the callee */
9319 	err = copy_reference_state(callee, caller);
9320 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9321 	if (err)
9322 		goto err_out;
9323 
9324 	/* only increment it after check_reg_arg() finished */
9325 	state->curframe++;
9326 
9327 	return 0;
9328 
9329 err_out:
9330 	free_func_state(callee);
9331 	state->frame[state->curframe + 1] = NULL;
9332 	return err;
9333 }
9334 
9335 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
9336 				    const struct btf *btf,
9337 				    struct bpf_reg_state *regs)
9338 {
9339 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
9340 	struct bpf_verifier_log *log = &env->log;
9341 	u32 i;
9342 	int ret;
9343 
9344 	ret = btf_prepare_func_args(env, subprog);
9345 	if (ret)
9346 		return ret;
9347 
9348 	/* check that BTF function arguments match actual types that the
9349 	 * verifier sees.
9350 	 */
9351 	for (i = 0; i < sub->arg_cnt; i++) {
9352 		u32 regno = i + 1;
9353 		struct bpf_reg_state *reg = &regs[regno];
9354 		struct bpf_subprog_arg_info *arg = &sub->args[i];
9355 
9356 		if (arg->arg_type == ARG_ANYTHING) {
9357 			if (reg->type != SCALAR_VALUE) {
9358 				bpf_log(log, "R%d is not a scalar\n", regno);
9359 				return -EINVAL;
9360 			}
9361 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
9362 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9363 			if (ret < 0)
9364 				return ret;
9365 			/* If function expects ctx type in BTF check that caller
9366 			 * is passing PTR_TO_CTX.
9367 			 */
9368 			if (reg->type != PTR_TO_CTX) {
9369 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
9370 				return -EINVAL;
9371 			}
9372 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
9373 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9374 			if (ret < 0)
9375 				return ret;
9376 			if (check_mem_reg(env, reg, regno, arg->mem_size))
9377 				return -EINVAL;
9378 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
9379 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
9380 				return -EINVAL;
9381 			}
9382 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
9383 			/*
9384 			 * Can pass any value and the kernel won't crash, but
9385 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
9386 			 * else is a bug in the bpf program. Point it out to
9387 			 * the user at the verification time instead of
9388 			 * run-time debug nightmare.
9389 			 */
9390 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
9391 				bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
9392 				return -EINVAL;
9393 			}
9394 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
9395 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
9396 			if (ret)
9397 				return ret;
9398 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
9399 			struct bpf_call_arg_meta meta;
9400 			int err;
9401 
9402 			if (register_is_null(reg) && type_may_be_null(arg->arg_type))
9403 				continue;
9404 
9405 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
9406 			err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
9407 			err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
9408 			if (err)
9409 				return err;
9410 		} else {
9411 			bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n",
9412 				i, arg->arg_type);
9413 			return -EFAULT;
9414 		}
9415 	}
9416 
9417 	return 0;
9418 }
9419 
9420 /* Compare BTF of a function call with given bpf_reg_state.
9421  * Returns:
9422  * EFAULT - there is a verifier bug. Abort verification.
9423  * EINVAL - there is a type mismatch or BTF is not available.
9424  * 0 - BTF matches with what bpf_reg_state expects.
9425  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
9426  */
9427 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
9428 				  struct bpf_reg_state *regs)
9429 {
9430 	struct bpf_prog *prog = env->prog;
9431 	struct btf *btf = prog->aux->btf;
9432 	u32 btf_id;
9433 	int err;
9434 
9435 	if (!prog->aux->func_info)
9436 		return -EINVAL;
9437 
9438 	btf_id = prog->aux->func_info[subprog].type_id;
9439 	if (!btf_id)
9440 		return -EFAULT;
9441 
9442 	if (prog->aux->func_info_aux[subprog].unreliable)
9443 		return -EINVAL;
9444 
9445 	err = btf_check_func_arg_match(env, subprog, btf, regs);
9446 	/* Compiler optimizations can remove arguments from static functions
9447 	 * or mismatched type can be passed into a global function.
9448 	 * In such cases mark the function as unreliable from BTF point of view.
9449 	 */
9450 	if (err)
9451 		prog->aux->func_info_aux[subprog].unreliable = true;
9452 	return err;
9453 }
9454 
9455 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9456 			      int insn_idx, int subprog,
9457 			      set_callee_state_fn set_callee_state_cb)
9458 {
9459 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9460 	struct bpf_func_state *caller, *callee;
9461 	int err;
9462 
9463 	caller = state->frame[state->curframe];
9464 	err = btf_check_subprog_call(env, subprog, caller->regs);
9465 	if (err == -EFAULT)
9466 		return err;
9467 
9468 	/* set_callee_state is used for direct subprog calls, but we are
9469 	 * interested in validating only BPF helpers that can call subprogs as
9470 	 * callbacks
9471 	 */
9472 	env->subprog_info[subprog].is_cb = true;
9473 	if (bpf_pseudo_kfunc_call(insn) &&
9474 	    !is_sync_callback_calling_kfunc(insn->imm)) {
9475 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9476 			func_id_name(insn->imm), insn->imm);
9477 		return -EFAULT;
9478 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9479 		   !is_callback_calling_function(insn->imm)) { /* helper */
9480 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9481 			func_id_name(insn->imm), insn->imm);
9482 		return -EFAULT;
9483 	}
9484 
9485 	if (is_async_callback_calling_insn(insn)) {
9486 		struct bpf_verifier_state *async_cb;
9487 
9488 		/* there is no real recursion here. timer callbacks are async */
9489 		env->subprog_info[subprog].is_async_cb = true;
9490 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9491 					 insn_idx, subprog);
9492 		if (!async_cb)
9493 			return -EFAULT;
9494 		callee = async_cb->frame[0];
9495 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9496 
9497 		/* Convert bpf_timer_set_callback() args into timer callback args */
9498 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9499 		if (err)
9500 			return err;
9501 
9502 		return 0;
9503 	}
9504 
9505 	/* for callback functions enqueue entry to callback and
9506 	 * proceed with next instruction within current frame.
9507 	 */
9508 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9509 	if (!callback_state)
9510 		return -ENOMEM;
9511 
9512 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9513 			       callback_state);
9514 	if (err)
9515 		return err;
9516 
9517 	callback_state->callback_unroll_depth++;
9518 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9519 	caller->callback_depth = 0;
9520 	return 0;
9521 }
9522 
9523 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9524 			   int *insn_idx)
9525 {
9526 	struct bpf_verifier_state *state = env->cur_state;
9527 	struct bpf_func_state *caller;
9528 	int err, subprog, target_insn;
9529 
9530 	target_insn = *insn_idx + insn->imm + 1;
9531 	subprog = find_subprog(env, target_insn);
9532 	if (subprog < 0) {
9533 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9534 		return -EFAULT;
9535 	}
9536 
9537 	caller = state->frame[state->curframe];
9538 	err = btf_check_subprog_call(env, subprog, caller->regs);
9539 	if (err == -EFAULT)
9540 		return err;
9541 	if (subprog_is_global(env, subprog)) {
9542 		const char *sub_name = subprog_name(env, subprog);
9543 
9544 		/* Only global subprogs cannot be called with a lock held. */
9545 		if (env->cur_state->active_lock.ptr) {
9546 			verbose(env, "global function calls are not allowed while holding a lock,\n"
9547 				     "use static function instead\n");
9548 			return -EINVAL;
9549 		}
9550 
9551 		if (err) {
9552 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
9553 				subprog, sub_name);
9554 			return err;
9555 		}
9556 
9557 		verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
9558 			subprog, sub_name);
9559 		/* mark global subprog for verifying after main prog */
9560 		subprog_aux(env, subprog)->called = true;
9561 		clear_caller_saved_regs(env, caller->regs);
9562 
9563 		/* All global functions return a 64-bit SCALAR_VALUE */
9564 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9565 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9566 
9567 		/* continue with next insn after call */
9568 		return 0;
9569 	}
9570 
9571 	/* for regular function entry setup new frame and continue
9572 	 * from that frame.
9573 	 */
9574 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9575 	if (err)
9576 		return err;
9577 
9578 	clear_caller_saved_regs(env, caller->regs);
9579 
9580 	/* and go analyze first insn of the callee */
9581 	*insn_idx = env->subprog_info[subprog].start - 1;
9582 
9583 	if (env->log.level & BPF_LOG_LEVEL) {
9584 		verbose(env, "caller:\n");
9585 		print_verifier_state(env, caller, true);
9586 		verbose(env, "callee:\n");
9587 		print_verifier_state(env, state->frame[state->curframe], true);
9588 	}
9589 
9590 	return 0;
9591 }
9592 
9593 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9594 				   struct bpf_func_state *caller,
9595 				   struct bpf_func_state *callee)
9596 {
9597 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9598 	 *      void *callback_ctx, u64 flags);
9599 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9600 	 *      void *callback_ctx);
9601 	 */
9602 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9603 
9604 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9605 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9606 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9607 
9608 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9609 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9610 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9611 
9612 	/* pointer to stack or null */
9613 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9614 
9615 	/* unused */
9616 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9617 	return 0;
9618 }
9619 
9620 static int set_callee_state(struct bpf_verifier_env *env,
9621 			    struct bpf_func_state *caller,
9622 			    struct bpf_func_state *callee, int insn_idx)
9623 {
9624 	int i;
9625 
9626 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9627 	 * pointers, which connects us up to the liveness chain
9628 	 */
9629 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9630 		callee->regs[i] = caller->regs[i];
9631 	return 0;
9632 }
9633 
9634 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9635 				       struct bpf_func_state *caller,
9636 				       struct bpf_func_state *callee,
9637 				       int insn_idx)
9638 {
9639 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9640 	struct bpf_map *map;
9641 	int err;
9642 
9643 	if (bpf_map_ptr_poisoned(insn_aux)) {
9644 		verbose(env, "tail_call abusing map_ptr\n");
9645 		return -EINVAL;
9646 	}
9647 
9648 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9649 	if (!map->ops->map_set_for_each_callback_args ||
9650 	    !map->ops->map_for_each_callback) {
9651 		verbose(env, "callback function not allowed for map\n");
9652 		return -ENOTSUPP;
9653 	}
9654 
9655 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9656 	if (err)
9657 		return err;
9658 
9659 	callee->in_callback_fn = true;
9660 	callee->callback_ret_range = retval_range(0, 1);
9661 	return 0;
9662 }
9663 
9664 static int set_loop_callback_state(struct bpf_verifier_env *env,
9665 				   struct bpf_func_state *caller,
9666 				   struct bpf_func_state *callee,
9667 				   int insn_idx)
9668 {
9669 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9670 	 *	    u64 flags);
9671 	 * callback_fn(u32 index, void *callback_ctx);
9672 	 */
9673 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9674 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9675 
9676 	/* unused */
9677 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9678 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9679 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9680 
9681 	callee->in_callback_fn = true;
9682 	callee->callback_ret_range = retval_range(0, 1);
9683 	return 0;
9684 }
9685 
9686 static int set_timer_callback_state(struct bpf_verifier_env *env,
9687 				    struct bpf_func_state *caller,
9688 				    struct bpf_func_state *callee,
9689 				    int insn_idx)
9690 {
9691 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9692 
9693 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9694 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9695 	 */
9696 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9697 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9698 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9699 
9700 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9701 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9702 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9703 
9704 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9705 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9706 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9707 
9708 	/* unused */
9709 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9710 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9711 	callee->in_async_callback_fn = true;
9712 	callee->callback_ret_range = retval_range(0, 1);
9713 	return 0;
9714 }
9715 
9716 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9717 				       struct bpf_func_state *caller,
9718 				       struct bpf_func_state *callee,
9719 				       int insn_idx)
9720 {
9721 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9722 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9723 	 * (callback_fn)(struct task_struct *task,
9724 	 *               struct vm_area_struct *vma, void *callback_ctx);
9725 	 */
9726 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9727 
9728 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9729 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9730 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9731 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
9732 
9733 	/* pointer to stack or null */
9734 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9735 
9736 	/* unused */
9737 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9738 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9739 	callee->in_callback_fn = true;
9740 	callee->callback_ret_range = retval_range(0, 1);
9741 	return 0;
9742 }
9743 
9744 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9745 					   struct bpf_func_state *caller,
9746 					   struct bpf_func_state *callee,
9747 					   int insn_idx)
9748 {
9749 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9750 	 *			  callback_ctx, u64 flags);
9751 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9752 	 */
9753 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9754 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9755 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9756 
9757 	/* unused */
9758 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9759 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9760 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9761 
9762 	callee->in_callback_fn = true;
9763 	callee->callback_ret_range = retval_range(0, 1);
9764 	return 0;
9765 }
9766 
9767 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9768 					 struct bpf_func_state *caller,
9769 					 struct bpf_func_state *callee,
9770 					 int insn_idx)
9771 {
9772 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9773 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9774 	 *
9775 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9776 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9777 	 * by this point, so look at 'root'
9778 	 */
9779 	struct btf_field *field;
9780 
9781 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9782 				      BPF_RB_ROOT);
9783 	if (!field || !field->graph_root.value_btf_id)
9784 		return -EFAULT;
9785 
9786 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9787 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9788 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9789 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9790 
9791 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9792 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9793 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9794 	callee->in_callback_fn = true;
9795 	callee->callback_ret_range = retval_range(0, 1);
9796 	return 0;
9797 }
9798 
9799 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9800 
9801 /* Are we currently verifying the callback for a rbtree helper that must
9802  * be called with lock held? If so, no need to complain about unreleased
9803  * lock
9804  */
9805 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9806 {
9807 	struct bpf_verifier_state *state = env->cur_state;
9808 	struct bpf_insn *insn = env->prog->insnsi;
9809 	struct bpf_func_state *callee;
9810 	int kfunc_btf_id;
9811 
9812 	if (!state->curframe)
9813 		return false;
9814 
9815 	callee = state->frame[state->curframe];
9816 
9817 	if (!callee->in_callback_fn)
9818 		return false;
9819 
9820 	kfunc_btf_id = insn[callee->callsite].imm;
9821 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9822 }
9823 
9824 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg)
9825 {
9826 	return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
9827 }
9828 
9829 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9830 {
9831 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9832 	struct bpf_func_state *caller, *callee;
9833 	struct bpf_reg_state *r0;
9834 	bool in_callback_fn;
9835 	int err;
9836 
9837 	callee = state->frame[state->curframe];
9838 	r0 = &callee->regs[BPF_REG_0];
9839 	if (r0->type == PTR_TO_STACK) {
9840 		/* technically it's ok to return caller's stack pointer
9841 		 * (or caller's caller's pointer) back to the caller,
9842 		 * since these pointers are valid. Only current stack
9843 		 * pointer will be invalid as soon as function exits,
9844 		 * but let's be conservative
9845 		 */
9846 		verbose(env, "cannot return stack pointer to the caller\n");
9847 		return -EINVAL;
9848 	}
9849 
9850 	caller = state->frame[state->curframe - 1];
9851 	if (callee->in_callback_fn) {
9852 		if (r0->type != SCALAR_VALUE) {
9853 			verbose(env, "R0 not a scalar value\n");
9854 			return -EACCES;
9855 		}
9856 
9857 		/* we are going to rely on register's precise value */
9858 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9859 		err = err ?: mark_chain_precision(env, BPF_REG_0);
9860 		if (err)
9861 			return err;
9862 
9863 		/* enforce R0 return value range */
9864 		if (!retval_range_within(callee->callback_ret_range, r0)) {
9865 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
9866 					       "At callback return", "R0");
9867 			return -EINVAL;
9868 		}
9869 		if (!calls_callback(env, callee->callsite)) {
9870 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9871 				*insn_idx, callee->callsite);
9872 			return -EFAULT;
9873 		}
9874 	} else {
9875 		/* return to the caller whatever r0 had in the callee */
9876 		caller->regs[BPF_REG_0] = *r0;
9877 	}
9878 
9879 	/* callback_fn frame should have released its own additions to parent's
9880 	 * reference state at this point, or check_reference_leak would
9881 	 * complain, hence it must be the same as the caller. There is no need
9882 	 * to copy it back.
9883 	 */
9884 	if (!callee->in_callback_fn) {
9885 		/* Transfer references to the caller */
9886 		err = copy_reference_state(caller, callee);
9887 		if (err)
9888 			return err;
9889 	}
9890 
9891 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9892 	 * there function call logic would reschedule callback visit. If iteration
9893 	 * converges is_state_visited() would prune that visit eventually.
9894 	 */
9895 	in_callback_fn = callee->in_callback_fn;
9896 	if (in_callback_fn)
9897 		*insn_idx = callee->callsite;
9898 	else
9899 		*insn_idx = callee->callsite + 1;
9900 
9901 	if (env->log.level & BPF_LOG_LEVEL) {
9902 		verbose(env, "returning from callee:\n");
9903 		print_verifier_state(env, callee, true);
9904 		verbose(env, "to caller at %d:\n", *insn_idx);
9905 		print_verifier_state(env, caller, true);
9906 	}
9907 	/* clear everything in the callee. In case of exceptional exits using
9908 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
9909 	free_func_state(callee);
9910 	state->frame[state->curframe--] = NULL;
9911 
9912 	/* for callbacks widen imprecise scalars to make programs like below verify:
9913 	 *
9914 	 *   struct ctx { int i; }
9915 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9916 	 *   ...
9917 	 *   struct ctx = { .i = 0; }
9918 	 *   bpf_loop(100, cb, &ctx, 0);
9919 	 *
9920 	 * This is similar to what is done in process_iter_next_call() for open
9921 	 * coded iterators.
9922 	 */
9923 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9924 	if (prev_st) {
9925 		err = widen_imprecise_scalars(env, prev_st, state);
9926 		if (err)
9927 			return err;
9928 	}
9929 	return 0;
9930 }
9931 
9932 static int do_refine_retval_range(struct bpf_verifier_env *env,
9933 				  struct bpf_reg_state *regs, int ret_type,
9934 				  int func_id,
9935 				  struct bpf_call_arg_meta *meta)
9936 {
9937 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9938 
9939 	if (ret_type != RET_INTEGER)
9940 		return 0;
9941 
9942 	switch (func_id) {
9943 	case BPF_FUNC_get_stack:
9944 	case BPF_FUNC_get_task_stack:
9945 	case BPF_FUNC_probe_read_str:
9946 	case BPF_FUNC_probe_read_kernel_str:
9947 	case BPF_FUNC_probe_read_user_str:
9948 		ret_reg->smax_value = meta->msize_max_value;
9949 		ret_reg->s32_max_value = meta->msize_max_value;
9950 		ret_reg->smin_value = -MAX_ERRNO;
9951 		ret_reg->s32_min_value = -MAX_ERRNO;
9952 		reg_bounds_sync(ret_reg);
9953 		break;
9954 	case BPF_FUNC_get_smp_processor_id:
9955 		ret_reg->umax_value = nr_cpu_ids - 1;
9956 		ret_reg->u32_max_value = nr_cpu_ids - 1;
9957 		ret_reg->smax_value = nr_cpu_ids - 1;
9958 		ret_reg->s32_max_value = nr_cpu_ids - 1;
9959 		ret_reg->umin_value = 0;
9960 		ret_reg->u32_min_value = 0;
9961 		ret_reg->smin_value = 0;
9962 		ret_reg->s32_min_value = 0;
9963 		reg_bounds_sync(ret_reg);
9964 		break;
9965 	}
9966 
9967 	return reg_bounds_sanity_check(env, ret_reg, "retval");
9968 }
9969 
9970 static int
9971 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9972 		int func_id, int insn_idx)
9973 {
9974 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9975 	struct bpf_map *map = meta->map_ptr;
9976 
9977 	if (func_id != BPF_FUNC_tail_call &&
9978 	    func_id != BPF_FUNC_map_lookup_elem &&
9979 	    func_id != BPF_FUNC_map_update_elem &&
9980 	    func_id != BPF_FUNC_map_delete_elem &&
9981 	    func_id != BPF_FUNC_map_push_elem &&
9982 	    func_id != BPF_FUNC_map_pop_elem &&
9983 	    func_id != BPF_FUNC_map_peek_elem &&
9984 	    func_id != BPF_FUNC_for_each_map_elem &&
9985 	    func_id != BPF_FUNC_redirect_map &&
9986 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9987 		return 0;
9988 
9989 	if (map == NULL) {
9990 		verbose(env, "kernel subsystem misconfigured verifier\n");
9991 		return -EINVAL;
9992 	}
9993 
9994 	/* In case of read-only, some additional restrictions
9995 	 * need to be applied in order to prevent altering the
9996 	 * state of the map from program side.
9997 	 */
9998 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9999 	    (func_id == BPF_FUNC_map_delete_elem ||
10000 	     func_id == BPF_FUNC_map_update_elem ||
10001 	     func_id == BPF_FUNC_map_push_elem ||
10002 	     func_id == BPF_FUNC_map_pop_elem)) {
10003 		verbose(env, "write into map forbidden\n");
10004 		return -EACCES;
10005 	}
10006 
10007 	if (!BPF_MAP_PTR(aux->map_ptr_state))
10008 		bpf_map_ptr_store(aux, meta->map_ptr,
10009 				  !meta->map_ptr->bypass_spec_v1);
10010 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
10011 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
10012 				  !meta->map_ptr->bypass_spec_v1);
10013 	return 0;
10014 }
10015 
10016 static int
10017 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10018 		int func_id, int insn_idx)
10019 {
10020 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10021 	struct bpf_reg_state *regs = cur_regs(env), *reg;
10022 	struct bpf_map *map = meta->map_ptr;
10023 	u64 val, max;
10024 	int err;
10025 
10026 	if (func_id != BPF_FUNC_tail_call)
10027 		return 0;
10028 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
10029 		verbose(env, "kernel subsystem misconfigured verifier\n");
10030 		return -EINVAL;
10031 	}
10032 
10033 	reg = &regs[BPF_REG_3];
10034 	val = reg->var_off.value;
10035 	max = map->max_entries;
10036 
10037 	if (!(is_reg_const(reg, false) && val < max)) {
10038 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10039 		return 0;
10040 	}
10041 
10042 	err = mark_chain_precision(env, BPF_REG_3);
10043 	if (err)
10044 		return err;
10045 	if (bpf_map_key_unseen(aux))
10046 		bpf_map_key_store(aux, val);
10047 	else if (!bpf_map_key_poisoned(aux) &&
10048 		  bpf_map_key_immediate(aux) != val)
10049 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10050 	return 0;
10051 }
10052 
10053 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
10054 {
10055 	struct bpf_func_state *state = cur_func(env);
10056 	bool refs_lingering = false;
10057 	int i;
10058 
10059 	if (!exception_exit && state->frameno && !state->in_callback_fn)
10060 		return 0;
10061 
10062 	for (i = 0; i < state->acquired_refs; i++) {
10063 		if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
10064 			continue;
10065 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
10066 			state->refs[i].id, state->refs[i].insn_idx);
10067 		refs_lingering = true;
10068 	}
10069 	return refs_lingering ? -EINVAL : 0;
10070 }
10071 
10072 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
10073 				   struct bpf_reg_state *regs)
10074 {
10075 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
10076 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
10077 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
10078 	struct bpf_bprintf_data data = {};
10079 	int err, fmt_map_off, num_args;
10080 	u64 fmt_addr;
10081 	char *fmt;
10082 
10083 	/* data must be an array of u64 */
10084 	if (data_len_reg->var_off.value % 8)
10085 		return -EINVAL;
10086 	num_args = data_len_reg->var_off.value / 8;
10087 
10088 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
10089 	 * and map_direct_value_addr is set.
10090 	 */
10091 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
10092 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
10093 						  fmt_map_off);
10094 	if (err) {
10095 		verbose(env, "verifier bug\n");
10096 		return -EFAULT;
10097 	}
10098 	fmt = (char *)(long)fmt_addr + fmt_map_off;
10099 
10100 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
10101 	 * can focus on validating the format specifiers.
10102 	 */
10103 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
10104 	if (err < 0)
10105 		verbose(env, "Invalid format string\n");
10106 
10107 	return err;
10108 }
10109 
10110 static int check_get_func_ip(struct bpf_verifier_env *env)
10111 {
10112 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10113 	int func_id = BPF_FUNC_get_func_ip;
10114 
10115 	if (type == BPF_PROG_TYPE_TRACING) {
10116 		if (!bpf_prog_has_trampoline(env->prog)) {
10117 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
10118 				func_id_name(func_id), func_id);
10119 			return -ENOTSUPP;
10120 		}
10121 		return 0;
10122 	} else if (type == BPF_PROG_TYPE_KPROBE) {
10123 		return 0;
10124 	}
10125 
10126 	verbose(env, "func %s#%d not supported for program type %d\n",
10127 		func_id_name(func_id), func_id, type);
10128 	return -ENOTSUPP;
10129 }
10130 
10131 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
10132 {
10133 	return &env->insn_aux_data[env->insn_idx];
10134 }
10135 
10136 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10137 {
10138 	struct bpf_reg_state *regs = cur_regs(env);
10139 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
10140 	bool reg_is_null = register_is_null(reg);
10141 
10142 	if (reg_is_null)
10143 		mark_chain_precision(env, BPF_REG_4);
10144 
10145 	return reg_is_null;
10146 }
10147 
10148 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10149 {
10150 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10151 
10152 	if (!state->initialized) {
10153 		state->initialized = 1;
10154 		state->fit_for_inline = loop_flag_is_zero(env);
10155 		state->callback_subprogno = subprogno;
10156 		return;
10157 	}
10158 
10159 	if (!state->fit_for_inline)
10160 		return;
10161 
10162 	state->fit_for_inline = (loop_flag_is_zero(env) &&
10163 				 state->callback_subprogno == subprogno);
10164 }
10165 
10166 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10167 			     int *insn_idx_p)
10168 {
10169 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10170 	bool returns_cpu_specific_alloc_ptr = false;
10171 	const struct bpf_func_proto *fn = NULL;
10172 	enum bpf_return_type ret_type;
10173 	enum bpf_type_flag ret_flag;
10174 	struct bpf_reg_state *regs;
10175 	struct bpf_call_arg_meta meta;
10176 	int insn_idx = *insn_idx_p;
10177 	bool changes_data;
10178 	int i, err, func_id;
10179 
10180 	/* find function prototype */
10181 	func_id = insn->imm;
10182 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
10183 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
10184 			func_id);
10185 		return -EINVAL;
10186 	}
10187 
10188 	if (env->ops->get_func_proto)
10189 		fn = env->ops->get_func_proto(func_id, env->prog);
10190 	if (!fn) {
10191 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
10192 			func_id);
10193 		return -EINVAL;
10194 	}
10195 
10196 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
10197 	if (!env->prog->gpl_compatible && fn->gpl_only) {
10198 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10199 		return -EINVAL;
10200 	}
10201 
10202 	if (fn->allowed && !fn->allowed(env->prog)) {
10203 		verbose(env, "helper call is not allowed in probe\n");
10204 		return -EINVAL;
10205 	}
10206 
10207 	if (!in_sleepable(env) && fn->might_sleep) {
10208 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
10209 		return -EINVAL;
10210 	}
10211 
10212 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
10213 	changes_data = bpf_helper_changes_pkt_data(fn->func);
10214 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10215 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10216 			func_id_name(func_id), func_id);
10217 		return -EINVAL;
10218 	}
10219 
10220 	memset(&meta, 0, sizeof(meta));
10221 	meta.pkt_access = fn->pkt_access;
10222 
10223 	err = check_func_proto(fn, func_id);
10224 	if (err) {
10225 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10226 			func_id_name(func_id), func_id);
10227 		return err;
10228 	}
10229 
10230 	if (env->cur_state->active_rcu_lock) {
10231 		if (fn->might_sleep) {
10232 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10233 				func_id_name(func_id), func_id);
10234 			return -EINVAL;
10235 		}
10236 
10237 		if (in_sleepable(env) && is_storage_get_function(func_id))
10238 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10239 	}
10240 
10241 	meta.func_id = func_id;
10242 	/* check args */
10243 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10244 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10245 		if (err)
10246 			return err;
10247 	}
10248 
10249 	err = record_func_map(env, &meta, func_id, insn_idx);
10250 	if (err)
10251 		return err;
10252 
10253 	err = record_func_key(env, &meta, func_id, insn_idx);
10254 	if (err)
10255 		return err;
10256 
10257 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10258 	 * is inferred from register state.
10259 	 */
10260 	for (i = 0; i < meta.access_size; i++) {
10261 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10262 				       BPF_WRITE, -1, false, false);
10263 		if (err)
10264 			return err;
10265 	}
10266 
10267 	regs = cur_regs(env);
10268 
10269 	if (meta.release_regno) {
10270 		err = -EINVAL;
10271 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10272 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10273 		 * is safe to do directly.
10274 		 */
10275 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10276 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10277 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10278 				return -EFAULT;
10279 			}
10280 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10281 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10282 			u32 ref_obj_id = meta.ref_obj_id;
10283 			bool in_rcu = in_rcu_cs(env);
10284 			struct bpf_func_state *state;
10285 			struct bpf_reg_state *reg;
10286 
10287 			err = release_reference_state(cur_func(env), ref_obj_id);
10288 			if (!err) {
10289 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10290 					if (reg->ref_obj_id == ref_obj_id) {
10291 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10292 							reg->ref_obj_id = 0;
10293 							reg->type &= ~MEM_ALLOC;
10294 							reg->type |= MEM_RCU;
10295 						} else {
10296 							mark_reg_invalid(env, reg);
10297 						}
10298 					}
10299 				}));
10300 			}
10301 		} else if (meta.ref_obj_id) {
10302 			err = release_reference(env, meta.ref_obj_id);
10303 		} else if (register_is_null(&regs[meta.release_regno])) {
10304 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10305 			 * released is NULL, which must be > R0.
10306 			 */
10307 			err = 0;
10308 		}
10309 		if (err) {
10310 			verbose(env, "func %s#%d reference has not been acquired before\n",
10311 				func_id_name(func_id), func_id);
10312 			return err;
10313 		}
10314 	}
10315 
10316 	switch (func_id) {
10317 	case BPF_FUNC_tail_call:
10318 		err = check_reference_leak(env, false);
10319 		if (err) {
10320 			verbose(env, "tail_call would lead to reference leak\n");
10321 			return err;
10322 		}
10323 		break;
10324 	case BPF_FUNC_get_local_storage:
10325 		/* check that flags argument in get_local_storage(map, flags) is 0,
10326 		 * this is required because get_local_storage() can't return an error.
10327 		 */
10328 		if (!register_is_null(&regs[BPF_REG_2])) {
10329 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10330 			return -EINVAL;
10331 		}
10332 		break;
10333 	case BPF_FUNC_for_each_map_elem:
10334 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10335 					 set_map_elem_callback_state);
10336 		break;
10337 	case BPF_FUNC_timer_set_callback:
10338 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10339 					 set_timer_callback_state);
10340 		break;
10341 	case BPF_FUNC_find_vma:
10342 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10343 					 set_find_vma_callback_state);
10344 		break;
10345 	case BPF_FUNC_snprintf:
10346 		err = check_bpf_snprintf_call(env, regs);
10347 		break;
10348 	case BPF_FUNC_loop:
10349 		update_loop_inline_state(env, meta.subprogno);
10350 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10351 		 * is finished, thus mark it precise.
10352 		 */
10353 		err = mark_chain_precision(env, BPF_REG_1);
10354 		if (err)
10355 			return err;
10356 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10357 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10358 						 set_loop_callback_state);
10359 		} else {
10360 			cur_func(env)->callback_depth = 0;
10361 			if (env->log.level & BPF_LOG_LEVEL2)
10362 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10363 					env->cur_state->curframe);
10364 		}
10365 		break;
10366 	case BPF_FUNC_dynptr_from_mem:
10367 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10368 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10369 				reg_type_str(env, regs[BPF_REG_1].type));
10370 			return -EACCES;
10371 		}
10372 		break;
10373 	case BPF_FUNC_set_retval:
10374 		if (prog_type == BPF_PROG_TYPE_LSM &&
10375 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10376 			if (!env->prog->aux->attach_func_proto->type) {
10377 				/* Make sure programs that attach to void
10378 				 * hooks don't try to modify return value.
10379 				 */
10380 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10381 				return -EINVAL;
10382 			}
10383 		}
10384 		break;
10385 	case BPF_FUNC_dynptr_data:
10386 	{
10387 		struct bpf_reg_state *reg;
10388 		int id, ref_obj_id;
10389 
10390 		reg = get_dynptr_arg_reg(env, fn, regs);
10391 		if (!reg)
10392 			return -EFAULT;
10393 
10394 
10395 		if (meta.dynptr_id) {
10396 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10397 			return -EFAULT;
10398 		}
10399 		if (meta.ref_obj_id) {
10400 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10401 			return -EFAULT;
10402 		}
10403 
10404 		id = dynptr_id(env, reg);
10405 		if (id < 0) {
10406 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10407 			return id;
10408 		}
10409 
10410 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10411 		if (ref_obj_id < 0) {
10412 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10413 			return ref_obj_id;
10414 		}
10415 
10416 		meta.dynptr_id = id;
10417 		meta.ref_obj_id = ref_obj_id;
10418 
10419 		break;
10420 	}
10421 	case BPF_FUNC_dynptr_write:
10422 	{
10423 		enum bpf_dynptr_type dynptr_type;
10424 		struct bpf_reg_state *reg;
10425 
10426 		reg = get_dynptr_arg_reg(env, fn, regs);
10427 		if (!reg)
10428 			return -EFAULT;
10429 
10430 		dynptr_type = dynptr_get_type(env, reg);
10431 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10432 			return -EFAULT;
10433 
10434 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10435 			/* this will trigger clear_all_pkt_pointers(), which will
10436 			 * invalidate all dynptr slices associated with the skb
10437 			 */
10438 			changes_data = true;
10439 
10440 		break;
10441 	}
10442 	case BPF_FUNC_per_cpu_ptr:
10443 	case BPF_FUNC_this_cpu_ptr:
10444 	{
10445 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
10446 		const struct btf_type *type;
10447 
10448 		if (reg->type & MEM_RCU) {
10449 			type = btf_type_by_id(reg->btf, reg->btf_id);
10450 			if (!type || !btf_type_is_struct(type)) {
10451 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
10452 				return -EFAULT;
10453 			}
10454 			returns_cpu_specific_alloc_ptr = true;
10455 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10456 		}
10457 		break;
10458 	}
10459 	case BPF_FUNC_user_ringbuf_drain:
10460 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10461 					 set_user_ringbuf_callback_state);
10462 		break;
10463 	}
10464 
10465 	if (err)
10466 		return err;
10467 
10468 	/* reset caller saved regs */
10469 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10470 		mark_reg_not_init(env, regs, caller_saved[i]);
10471 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10472 	}
10473 
10474 	/* helper call returns 64-bit value. */
10475 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10476 
10477 	/* update return register (already marked as written above) */
10478 	ret_type = fn->ret_type;
10479 	ret_flag = type_flag(ret_type);
10480 
10481 	switch (base_type(ret_type)) {
10482 	case RET_INTEGER:
10483 		/* sets type to SCALAR_VALUE */
10484 		mark_reg_unknown(env, regs, BPF_REG_0);
10485 		break;
10486 	case RET_VOID:
10487 		regs[BPF_REG_0].type = NOT_INIT;
10488 		break;
10489 	case RET_PTR_TO_MAP_VALUE:
10490 		/* There is no offset yet applied, variable or fixed */
10491 		mark_reg_known_zero(env, regs, BPF_REG_0);
10492 		/* remember map_ptr, so that check_map_access()
10493 		 * can check 'value_size' boundary of memory access
10494 		 * to map element returned from bpf_map_lookup_elem()
10495 		 */
10496 		if (meta.map_ptr == NULL) {
10497 			verbose(env,
10498 				"kernel subsystem misconfigured verifier\n");
10499 			return -EINVAL;
10500 		}
10501 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10502 		regs[BPF_REG_0].map_uid = meta.map_uid;
10503 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10504 		if (!type_may_be_null(ret_type) &&
10505 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10506 			regs[BPF_REG_0].id = ++env->id_gen;
10507 		}
10508 		break;
10509 	case RET_PTR_TO_SOCKET:
10510 		mark_reg_known_zero(env, regs, BPF_REG_0);
10511 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10512 		break;
10513 	case RET_PTR_TO_SOCK_COMMON:
10514 		mark_reg_known_zero(env, regs, BPF_REG_0);
10515 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10516 		break;
10517 	case RET_PTR_TO_TCP_SOCK:
10518 		mark_reg_known_zero(env, regs, BPF_REG_0);
10519 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10520 		break;
10521 	case RET_PTR_TO_MEM:
10522 		mark_reg_known_zero(env, regs, BPF_REG_0);
10523 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10524 		regs[BPF_REG_0].mem_size = meta.mem_size;
10525 		break;
10526 	case RET_PTR_TO_MEM_OR_BTF_ID:
10527 	{
10528 		const struct btf_type *t;
10529 
10530 		mark_reg_known_zero(env, regs, BPF_REG_0);
10531 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10532 		if (!btf_type_is_struct(t)) {
10533 			u32 tsize;
10534 			const struct btf_type *ret;
10535 			const char *tname;
10536 
10537 			/* resolve the type size of ksym. */
10538 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10539 			if (IS_ERR(ret)) {
10540 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10541 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10542 					tname, PTR_ERR(ret));
10543 				return -EINVAL;
10544 			}
10545 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10546 			regs[BPF_REG_0].mem_size = tsize;
10547 		} else {
10548 			if (returns_cpu_specific_alloc_ptr) {
10549 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10550 			} else {
10551 				/* MEM_RDONLY may be carried from ret_flag, but it
10552 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10553 				 * it will confuse the check of PTR_TO_BTF_ID in
10554 				 * check_mem_access().
10555 				 */
10556 				ret_flag &= ~MEM_RDONLY;
10557 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10558 			}
10559 
10560 			regs[BPF_REG_0].btf = meta.ret_btf;
10561 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10562 		}
10563 		break;
10564 	}
10565 	case RET_PTR_TO_BTF_ID:
10566 	{
10567 		struct btf *ret_btf;
10568 		int ret_btf_id;
10569 
10570 		mark_reg_known_zero(env, regs, BPF_REG_0);
10571 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10572 		if (func_id == BPF_FUNC_kptr_xchg) {
10573 			ret_btf = meta.kptr_field->kptr.btf;
10574 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10575 			if (!btf_is_kernel(ret_btf)) {
10576 				regs[BPF_REG_0].type |= MEM_ALLOC;
10577 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10578 					regs[BPF_REG_0].type |= MEM_PERCPU;
10579 			}
10580 		} else {
10581 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10582 				verbose(env, "verifier internal error:");
10583 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10584 					func_id_name(func_id));
10585 				return -EINVAL;
10586 			}
10587 			ret_btf = btf_vmlinux;
10588 			ret_btf_id = *fn->ret_btf_id;
10589 		}
10590 		if (ret_btf_id == 0) {
10591 			verbose(env, "invalid return type %u of func %s#%d\n",
10592 				base_type(ret_type), func_id_name(func_id),
10593 				func_id);
10594 			return -EINVAL;
10595 		}
10596 		regs[BPF_REG_0].btf = ret_btf;
10597 		regs[BPF_REG_0].btf_id = ret_btf_id;
10598 		break;
10599 	}
10600 	default:
10601 		verbose(env, "unknown return type %u of func %s#%d\n",
10602 			base_type(ret_type), func_id_name(func_id), func_id);
10603 		return -EINVAL;
10604 	}
10605 
10606 	if (type_may_be_null(regs[BPF_REG_0].type))
10607 		regs[BPF_REG_0].id = ++env->id_gen;
10608 
10609 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10610 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10611 			func_id_name(func_id), func_id);
10612 		return -EFAULT;
10613 	}
10614 
10615 	if (is_dynptr_ref_function(func_id))
10616 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10617 
10618 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10619 		/* For release_reference() */
10620 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10621 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10622 		int id = acquire_reference_state(env, insn_idx);
10623 
10624 		if (id < 0)
10625 			return id;
10626 		/* For mark_ptr_or_null_reg() */
10627 		regs[BPF_REG_0].id = id;
10628 		/* For release_reference() */
10629 		regs[BPF_REG_0].ref_obj_id = id;
10630 	}
10631 
10632 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
10633 	if (err)
10634 		return err;
10635 
10636 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10637 	if (err)
10638 		return err;
10639 
10640 	if ((func_id == BPF_FUNC_get_stack ||
10641 	     func_id == BPF_FUNC_get_task_stack) &&
10642 	    !env->prog->has_callchain_buf) {
10643 		const char *err_str;
10644 
10645 #ifdef CONFIG_PERF_EVENTS
10646 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10647 		err_str = "cannot get callchain buffer for func %s#%d\n";
10648 #else
10649 		err = -ENOTSUPP;
10650 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10651 #endif
10652 		if (err) {
10653 			verbose(env, err_str, func_id_name(func_id), func_id);
10654 			return err;
10655 		}
10656 
10657 		env->prog->has_callchain_buf = true;
10658 	}
10659 
10660 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10661 		env->prog->call_get_stack = true;
10662 
10663 	if (func_id == BPF_FUNC_get_func_ip) {
10664 		if (check_get_func_ip(env))
10665 			return -ENOTSUPP;
10666 		env->prog->call_get_func_ip = true;
10667 	}
10668 
10669 	if (changes_data)
10670 		clear_all_pkt_pointers(env);
10671 	return 0;
10672 }
10673 
10674 /* mark_btf_func_reg_size() is used when the reg size is determined by
10675  * the BTF func_proto's return value size and argument.
10676  */
10677 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10678 				   size_t reg_size)
10679 {
10680 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10681 
10682 	if (regno == BPF_REG_0) {
10683 		/* Function return value */
10684 		reg->live |= REG_LIVE_WRITTEN;
10685 		reg->subreg_def = reg_size == sizeof(u64) ?
10686 			DEF_NOT_SUBREG : env->insn_idx + 1;
10687 	} else {
10688 		/* Function argument */
10689 		if (reg_size == sizeof(u64)) {
10690 			mark_insn_zext(env, reg);
10691 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10692 		} else {
10693 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10694 		}
10695 	}
10696 }
10697 
10698 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10699 {
10700 	return meta->kfunc_flags & KF_ACQUIRE;
10701 }
10702 
10703 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10704 {
10705 	return meta->kfunc_flags & KF_RELEASE;
10706 }
10707 
10708 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10709 {
10710 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10711 }
10712 
10713 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10714 {
10715 	return meta->kfunc_flags & KF_SLEEPABLE;
10716 }
10717 
10718 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10719 {
10720 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10721 }
10722 
10723 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10724 {
10725 	return meta->kfunc_flags & KF_RCU;
10726 }
10727 
10728 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
10729 {
10730 	return meta->kfunc_flags & KF_RCU_PROTECTED;
10731 }
10732 
10733 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10734 				  const struct btf_param *arg,
10735 				  const struct bpf_reg_state *reg)
10736 {
10737 	const struct btf_type *t;
10738 
10739 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10740 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10741 		return false;
10742 
10743 	return btf_param_match_suffix(btf, arg, "__sz");
10744 }
10745 
10746 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10747 					const struct btf_param *arg,
10748 					const struct bpf_reg_state *reg)
10749 {
10750 	const struct btf_type *t;
10751 
10752 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10753 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10754 		return false;
10755 
10756 	return btf_param_match_suffix(btf, arg, "__szk");
10757 }
10758 
10759 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10760 {
10761 	return btf_param_match_suffix(btf, arg, "__opt");
10762 }
10763 
10764 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10765 {
10766 	return btf_param_match_suffix(btf, arg, "__k");
10767 }
10768 
10769 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10770 {
10771 	return btf_param_match_suffix(btf, arg, "__ign");
10772 }
10773 
10774 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
10775 {
10776 	return btf_param_match_suffix(btf, arg, "__map");
10777 }
10778 
10779 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10780 {
10781 	return btf_param_match_suffix(btf, arg, "__alloc");
10782 }
10783 
10784 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10785 {
10786 	return btf_param_match_suffix(btf, arg, "__uninit");
10787 }
10788 
10789 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10790 {
10791 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
10792 }
10793 
10794 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
10795 {
10796 	return btf_param_match_suffix(btf, arg, "__nullable");
10797 }
10798 
10799 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
10800 {
10801 	return btf_param_match_suffix(btf, arg, "__str");
10802 }
10803 
10804 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10805 					  const struct btf_param *arg,
10806 					  const char *name)
10807 {
10808 	int len, target_len = strlen(name);
10809 	const char *param_name;
10810 
10811 	param_name = btf_name_by_offset(btf, arg->name_off);
10812 	if (str_is_empty(param_name))
10813 		return false;
10814 	len = strlen(param_name);
10815 	if (len != target_len)
10816 		return false;
10817 	if (strcmp(param_name, name))
10818 		return false;
10819 
10820 	return true;
10821 }
10822 
10823 enum {
10824 	KF_ARG_DYNPTR_ID,
10825 	KF_ARG_LIST_HEAD_ID,
10826 	KF_ARG_LIST_NODE_ID,
10827 	KF_ARG_RB_ROOT_ID,
10828 	KF_ARG_RB_NODE_ID,
10829 };
10830 
10831 BTF_ID_LIST(kf_arg_btf_ids)
10832 BTF_ID(struct, bpf_dynptr_kern)
10833 BTF_ID(struct, bpf_list_head)
10834 BTF_ID(struct, bpf_list_node)
10835 BTF_ID(struct, bpf_rb_root)
10836 BTF_ID(struct, bpf_rb_node)
10837 
10838 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10839 				    const struct btf_param *arg, int type)
10840 {
10841 	const struct btf_type *t;
10842 	u32 res_id;
10843 
10844 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10845 	if (!t)
10846 		return false;
10847 	if (!btf_type_is_ptr(t))
10848 		return false;
10849 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10850 	if (!t)
10851 		return false;
10852 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10853 }
10854 
10855 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10856 {
10857 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10858 }
10859 
10860 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10861 {
10862 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10863 }
10864 
10865 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10866 {
10867 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10868 }
10869 
10870 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10871 {
10872 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10873 }
10874 
10875 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10876 {
10877 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10878 }
10879 
10880 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10881 				  const struct btf_param *arg)
10882 {
10883 	const struct btf_type *t;
10884 
10885 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10886 	if (!t)
10887 		return false;
10888 
10889 	return true;
10890 }
10891 
10892 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10893 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10894 					const struct btf *btf,
10895 					const struct btf_type *t, int rec)
10896 {
10897 	const struct btf_type *member_type;
10898 	const struct btf_member *member;
10899 	u32 i;
10900 
10901 	if (!btf_type_is_struct(t))
10902 		return false;
10903 
10904 	for_each_member(i, t, member) {
10905 		const struct btf_array *array;
10906 
10907 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10908 		if (btf_type_is_struct(member_type)) {
10909 			if (rec >= 3) {
10910 				verbose(env, "max struct nesting depth exceeded\n");
10911 				return false;
10912 			}
10913 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10914 				return false;
10915 			continue;
10916 		}
10917 		if (btf_type_is_array(member_type)) {
10918 			array = btf_array(member_type);
10919 			if (!array->nelems)
10920 				return false;
10921 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10922 			if (!btf_type_is_scalar(member_type))
10923 				return false;
10924 			continue;
10925 		}
10926 		if (!btf_type_is_scalar(member_type))
10927 			return false;
10928 	}
10929 	return true;
10930 }
10931 
10932 enum kfunc_ptr_arg_type {
10933 	KF_ARG_PTR_TO_CTX,
10934 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10935 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10936 	KF_ARG_PTR_TO_DYNPTR,
10937 	KF_ARG_PTR_TO_ITER,
10938 	KF_ARG_PTR_TO_LIST_HEAD,
10939 	KF_ARG_PTR_TO_LIST_NODE,
10940 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10941 	KF_ARG_PTR_TO_MEM,
10942 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10943 	KF_ARG_PTR_TO_CALLBACK,
10944 	KF_ARG_PTR_TO_RB_ROOT,
10945 	KF_ARG_PTR_TO_RB_NODE,
10946 	KF_ARG_PTR_TO_NULL,
10947 	KF_ARG_PTR_TO_CONST_STR,
10948 	KF_ARG_PTR_TO_MAP,
10949 };
10950 
10951 enum special_kfunc_type {
10952 	KF_bpf_obj_new_impl,
10953 	KF_bpf_obj_drop_impl,
10954 	KF_bpf_refcount_acquire_impl,
10955 	KF_bpf_list_push_front_impl,
10956 	KF_bpf_list_push_back_impl,
10957 	KF_bpf_list_pop_front,
10958 	KF_bpf_list_pop_back,
10959 	KF_bpf_cast_to_kern_ctx,
10960 	KF_bpf_rdonly_cast,
10961 	KF_bpf_rcu_read_lock,
10962 	KF_bpf_rcu_read_unlock,
10963 	KF_bpf_rbtree_remove,
10964 	KF_bpf_rbtree_add_impl,
10965 	KF_bpf_rbtree_first,
10966 	KF_bpf_dynptr_from_skb,
10967 	KF_bpf_dynptr_from_xdp,
10968 	KF_bpf_dynptr_slice,
10969 	KF_bpf_dynptr_slice_rdwr,
10970 	KF_bpf_dynptr_clone,
10971 	KF_bpf_percpu_obj_new_impl,
10972 	KF_bpf_percpu_obj_drop_impl,
10973 	KF_bpf_throw,
10974 	KF_bpf_iter_css_task_new,
10975 };
10976 
10977 BTF_SET_START(special_kfunc_set)
10978 BTF_ID(func, bpf_obj_new_impl)
10979 BTF_ID(func, bpf_obj_drop_impl)
10980 BTF_ID(func, bpf_refcount_acquire_impl)
10981 BTF_ID(func, bpf_list_push_front_impl)
10982 BTF_ID(func, bpf_list_push_back_impl)
10983 BTF_ID(func, bpf_list_pop_front)
10984 BTF_ID(func, bpf_list_pop_back)
10985 BTF_ID(func, bpf_cast_to_kern_ctx)
10986 BTF_ID(func, bpf_rdonly_cast)
10987 BTF_ID(func, bpf_rbtree_remove)
10988 BTF_ID(func, bpf_rbtree_add_impl)
10989 BTF_ID(func, bpf_rbtree_first)
10990 BTF_ID(func, bpf_dynptr_from_skb)
10991 BTF_ID(func, bpf_dynptr_from_xdp)
10992 BTF_ID(func, bpf_dynptr_slice)
10993 BTF_ID(func, bpf_dynptr_slice_rdwr)
10994 BTF_ID(func, bpf_dynptr_clone)
10995 BTF_ID(func, bpf_percpu_obj_new_impl)
10996 BTF_ID(func, bpf_percpu_obj_drop_impl)
10997 BTF_ID(func, bpf_throw)
10998 #ifdef CONFIG_CGROUPS
10999 BTF_ID(func, bpf_iter_css_task_new)
11000 #endif
11001 BTF_SET_END(special_kfunc_set)
11002 
11003 BTF_ID_LIST(special_kfunc_list)
11004 BTF_ID(func, bpf_obj_new_impl)
11005 BTF_ID(func, bpf_obj_drop_impl)
11006 BTF_ID(func, bpf_refcount_acquire_impl)
11007 BTF_ID(func, bpf_list_push_front_impl)
11008 BTF_ID(func, bpf_list_push_back_impl)
11009 BTF_ID(func, bpf_list_pop_front)
11010 BTF_ID(func, bpf_list_pop_back)
11011 BTF_ID(func, bpf_cast_to_kern_ctx)
11012 BTF_ID(func, bpf_rdonly_cast)
11013 BTF_ID(func, bpf_rcu_read_lock)
11014 BTF_ID(func, bpf_rcu_read_unlock)
11015 BTF_ID(func, bpf_rbtree_remove)
11016 BTF_ID(func, bpf_rbtree_add_impl)
11017 BTF_ID(func, bpf_rbtree_first)
11018 BTF_ID(func, bpf_dynptr_from_skb)
11019 BTF_ID(func, bpf_dynptr_from_xdp)
11020 BTF_ID(func, bpf_dynptr_slice)
11021 BTF_ID(func, bpf_dynptr_slice_rdwr)
11022 BTF_ID(func, bpf_dynptr_clone)
11023 BTF_ID(func, bpf_percpu_obj_new_impl)
11024 BTF_ID(func, bpf_percpu_obj_drop_impl)
11025 BTF_ID(func, bpf_throw)
11026 #ifdef CONFIG_CGROUPS
11027 BTF_ID(func, bpf_iter_css_task_new)
11028 #else
11029 BTF_ID_UNUSED
11030 #endif
11031 
11032 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
11033 {
11034 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
11035 	    meta->arg_owning_ref) {
11036 		return false;
11037 	}
11038 
11039 	return meta->kfunc_flags & KF_RET_NULL;
11040 }
11041 
11042 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
11043 {
11044 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
11045 }
11046 
11047 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
11048 {
11049 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
11050 }
11051 
11052 static enum kfunc_ptr_arg_type
11053 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
11054 		       struct bpf_kfunc_call_arg_meta *meta,
11055 		       const struct btf_type *t, const struct btf_type *ref_t,
11056 		       const char *ref_tname, const struct btf_param *args,
11057 		       int argno, int nargs)
11058 {
11059 	u32 regno = argno + 1;
11060 	struct bpf_reg_state *regs = cur_regs(env);
11061 	struct bpf_reg_state *reg = &regs[regno];
11062 	bool arg_mem_size = false;
11063 
11064 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
11065 		return KF_ARG_PTR_TO_CTX;
11066 
11067 	/* In this function, we verify the kfunc's BTF as per the argument type,
11068 	 * leaving the rest of the verification with respect to the register
11069 	 * type to our caller. When a set of conditions hold in the BTF type of
11070 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
11071 	 */
11072 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
11073 		return KF_ARG_PTR_TO_CTX;
11074 
11075 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
11076 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
11077 
11078 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
11079 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
11080 
11081 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
11082 		return KF_ARG_PTR_TO_DYNPTR;
11083 
11084 	if (is_kfunc_arg_iter(meta, argno))
11085 		return KF_ARG_PTR_TO_ITER;
11086 
11087 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
11088 		return KF_ARG_PTR_TO_LIST_HEAD;
11089 
11090 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
11091 		return KF_ARG_PTR_TO_LIST_NODE;
11092 
11093 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
11094 		return KF_ARG_PTR_TO_RB_ROOT;
11095 
11096 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
11097 		return KF_ARG_PTR_TO_RB_NODE;
11098 
11099 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
11100 		return KF_ARG_PTR_TO_CONST_STR;
11101 
11102 	if (is_kfunc_arg_map(meta->btf, &args[argno]))
11103 		return KF_ARG_PTR_TO_MAP;
11104 
11105 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11106 		if (!btf_type_is_struct(ref_t)) {
11107 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
11108 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
11109 			return -EINVAL;
11110 		}
11111 		return KF_ARG_PTR_TO_BTF_ID;
11112 	}
11113 
11114 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
11115 		return KF_ARG_PTR_TO_CALLBACK;
11116 
11117 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
11118 		return KF_ARG_PTR_TO_NULL;
11119 
11120 	if (argno + 1 < nargs &&
11121 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
11122 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
11123 		arg_mem_size = true;
11124 
11125 	/* This is the catch all argument type of register types supported by
11126 	 * check_helper_mem_access. However, we only allow when argument type is
11127 	 * pointer to scalar, or struct composed (recursively) of scalars. When
11128 	 * arg_mem_size is true, the pointer can be void *.
11129 	 */
11130 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11131 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11132 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
11133 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11134 		return -EINVAL;
11135 	}
11136 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11137 }
11138 
11139 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11140 					struct bpf_reg_state *reg,
11141 					const struct btf_type *ref_t,
11142 					const char *ref_tname, u32 ref_id,
11143 					struct bpf_kfunc_call_arg_meta *meta,
11144 					int argno)
11145 {
11146 	const struct btf_type *reg_ref_t;
11147 	bool strict_type_match = false;
11148 	const struct btf *reg_btf;
11149 	const char *reg_ref_tname;
11150 	u32 reg_ref_id;
11151 
11152 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
11153 		reg_btf = reg->btf;
11154 		reg_ref_id = reg->btf_id;
11155 	} else {
11156 		reg_btf = btf_vmlinux;
11157 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11158 	}
11159 
11160 	/* Enforce strict type matching for calls to kfuncs that are acquiring
11161 	 * or releasing a reference, or are no-cast aliases. We do _not_
11162 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
11163 	 * as we want to enable BPF programs to pass types that are bitwise
11164 	 * equivalent without forcing them to explicitly cast with something
11165 	 * like bpf_cast_to_kern_ctx().
11166 	 *
11167 	 * For example, say we had a type like the following:
11168 	 *
11169 	 * struct bpf_cpumask {
11170 	 *	cpumask_t cpumask;
11171 	 *	refcount_t usage;
11172 	 * };
11173 	 *
11174 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11175 	 * to a struct cpumask, so it would be safe to pass a struct
11176 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11177 	 *
11178 	 * The philosophy here is similar to how we allow scalars of different
11179 	 * types to be passed to kfuncs as long as the size is the same. The
11180 	 * only difference here is that we're simply allowing
11181 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
11182 	 * resolve types.
11183 	 */
11184 	if (is_kfunc_acquire(meta) ||
11185 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
11186 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11187 		strict_type_match = true;
11188 
11189 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
11190 
11191 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
11192 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11193 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
11194 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
11195 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
11196 			btf_type_str(reg_ref_t), reg_ref_tname);
11197 		return -EINVAL;
11198 	}
11199 	return 0;
11200 }
11201 
11202 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11203 {
11204 	struct bpf_verifier_state *state = env->cur_state;
11205 	struct btf_record *rec = reg_btf_record(reg);
11206 
11207 	if (!state->active_lock.ptr) {
11208 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
11209 		return -EFAULT;
11210 	}
11211 
11212 	if (type_flag(reg->type) & NON_OWN_REF) {
11213 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
11214 		return -EFAULT;
11215 	}
11216 
11217 	reg->type |= NON_OWN_REF;
11218 	if (rec->refcount_off >= 0)
11219 		reg->type |= MEM_RCU;
11220 
11221 	return 0;
11222 }
11223 
11224 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
11225 {
11226 	struct bpf_func_state *state, *unused;
11227 	struct bpf_reg_state *reg;
11228 	int i;
11229 
11230 	state = cur_func(env);
11231 
11232 	if (!ref_obj_id) {
11233 		verbose(env, "verifier internal error: ref_obj_id is zero for "
11234 			     "owning -> non-owning conversion\n");
11235 		return -EFAULT;
11236 	}
11237 
11238 	for (i = 0; i < state->acquired_refs; i++) {
11239 		if (state->refs[i].id != ref_obj_id)
11240 			continue;
11241 
11242 		/* Clear ref_obj_id here so release_reference doesn't clobber
11243 		 * the whole reg
11244 		 */
11245 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11246 			if (reg->ref_obj_id == ref_obj_id) {
11247 				reg->ref_obj_id = 0;
11248 				ref_set_non_owning(env, reg);
11249 			}
11250 		}));
11251 		return 0;
11252 	}
11253 
11254 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
11255 	return -EFAULT;
11256 }
11257 
11258 /* Implementation details:
11259  *
11260  * Each register points to some region of memory, which we define as an
11261  * allocation. Each allocation may embed a bpf_spin_lock which protects any
11262  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11263  * allocation. The lock and the data it protects are colocated in the same
11264  * memory region.
11265  *
11266  * Hence, everytime a register holds a pointer value pointing to such
11267  * allocation, the verifier preserves a unique reg->id for it.
11268  *
11269  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11270  * bpf_spin_lock is called.
11271  *
11272  * To enable this, lock state in the verifier captures two values:
11273  *	active_lock.ptr = Register's type specific pointer
11274  *	active_lock.id  = A unique ID for each register pointer value
11275  *
11276  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11277  * supported register types.
11278  *
11279  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11280  * allocated objects is the reg->btf pointer.
11281  *
11282  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11283  * can establish the provenance of the map value statically for each distinct
11284  * lookup into such maps. They always contain a single map value hence unique
11285  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11286  *
11287  * So, in case of global variables, they use array maps with max_entries = 1,
11288  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11289  * into the same map value as max_entries is 1, as described above).
11290  *
11291  * In case of inner map lookups, the inner map pointer has same map_ptr as the
11292  * outer map pointer (in verifier context), but each lookup into an inner map
11293  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11294  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11295  * will get different reg->id assigned to each lookup, hence different
11296  * active_lock.id.
11297  *
11298  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11299  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11300  * returned from bpf_obj_new. Each allocation receives a new reg->id.
11301  */
11302 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11303 {
11304 	void *ptr;
11305 	u32 id;
11306 
11307 	switch ((int)reg->type) {
11308 	case PTR_TO_MAP_VALUE:
11309 		ptr = reg->map_ptr;
11310 		break;
11311 	case PTR_TO_BTF_ID | MEM_ALLOC:
11312 		ptr = reg->btf;
11313 		break;
11314 	default:
11315 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11316 		return -EFAULT;
11317 	}
11318 	id = reg->id;
11319 
11320 	if (!env->cur_state->active_lock.ptr)
11321 		return -EINVAL;
11322 	if (env->cur_state->active_lock.ptr != ptr ||
11323 	    env->cur_state->active_lock.id != id) {
11324 		verbose(env, "held lock and object are not in the same allocation\n");
11325 		return -EINVAL;
11326 	}
11327 	return 0;
11328 }
11329 
11330 static bool is_bpf_list_api_kfunc(u32 btf_id)
11331 {
11332 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11333 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11334 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11335 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11336 }
11337 
11338 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11339 {
11340 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11341 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11342 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11343 }
11344 
11345 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11346 {
11347 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11348 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11349 }
11350 
11351 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11352 {
11353 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11354 }
11355 
11356 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
11357 {
11358 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11359 	       insn->imm == special_kfunc_list[KF_bpf_throw];
11360 }
11361 
11362 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11363 {
11364 	return is_bpf_rbtree_api_kfunc(btf_id);
11365 }
11366 
11367 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11368 					  enum btf_field_type head_field_type,
11369 					  u32 kfunc_btf_id)
11370 {
11371 	bool ret;
11372 
11373 	switch (head_field_type) {
11374 	case BPF_LIST_HEAD:
11375 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11376 		break;
11377 	case BPF_RB_ROOT:
11378 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11379 		break;
11380 	default:
11381 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11382 			btf_field_type_name(head_field_type));
11383 		return false;
11384 	}
11385 
11386 	if (!ret)
11387 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11388 			btf_field_type_name(head_field_type));
11389 	return ret;
11390 }
11391 
11392 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11393 					  enum btf_field_type node_field_type,
11394 					  u32 kfunc_btf_id)
11395 {
11396 	bool ret;
11397 
11398 	switch (node_field_type) {
11399 	case BPF_LIST_NODE:
11400 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11401 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11402 		break;
11403 	case BPF_RB_NODE:
11404 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11405 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11406 		break;
11407 	default:
11408 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11409 			btf_field_type_name(node_field_type));
11410 		return false;
11411 	}
11412 
11413 	if (!ret)
11414 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11415 			btf_field_type_name(node_field_type));
11416 	return ret;
11417 }
11418 
11419 static int
11420 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11421 				   struct bpf_reg_state *reg, u32 regno,
11422 				   struct bpf_kfunc_call_arg_meta *meta,
11423 				   enum btf_field_type head_field_type,
11424 				   struct btf_field **head_field)
11425 {
11426 	const char *head_type_name;
11427 	struct btf_field *field;
11428 	struct btf_record *rec;
11429 	u32 head_off;
11430 
11431 	if (meta->btf != btf_vmlinux) {
11432 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11433 		return -EFAULT;
11434 	}
11435 
11436 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11437 		return -EFAULT;
11438 
11439 	head_type_name = btf_field_type_name(head_field_type);
11440 	if (!tnum_is_const(reg->var_off)) {
11441 		verbose(env,
11442 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11443 			regno, head_type_name);
11444 		return -EINVAL;
11445 	}
11446 
11447 	rec = reg_btf_record(reg);
11448 	head_off = reg->off + reg->var_off.value;
11449 	field = btf_record_find(rec, head_off, head_field_type);
11450 	if (!field) {
11451 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11452 		return -EINVAL;
11453 	}
11454 
11455 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11456 	if (check_reg_allocation_locked(env, reg)) {
11457 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11458 			rec->spin_lock_off, head_type_name);
11459 		return -EINVAL;
11460 	}
11461 
11462 	if (*head_field) {
11463 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11464 		return -EFAULT;
11465 	}
11466 	*head_field = field;
11467 	return 0;
11468 }
11469 
11470 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11471 					   struct bpf_reg_state *reg, u32 regno,
11472 					   struct bpf_kfunc_call_arg_meta *meta)
11473 {
11474 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11475 							  &meta->arg_list_head.field);
11476 }
11477 
11478 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11479 					     struct bpf_reg_state *reg, u32 regno,
11480 					     struct bpf_kfunc_call_arg_meta *meta)
11481 {
11482 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11483 							  &meta->arg_rbtree_root.field);
11484 }
11485 
11486 static int
11487 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11488 				   struct bpf_reg_state *reg, u32 regno,
11489 				   struct bpf_kfunc_call_arg_meta *meta,
11490 				   enum btf_field_type head_field_type,
11491 				   enum btf_field_type node_field_type,
11492 				   struct btf_field **node_field)
11493 {
11494 	const char *node_type_name;
11495 	const struct btf_type *et, *t;
11496 	struct btf_field *field;
11497 	u32 node_off;
11498 
11499 	if (meta->btf != btf_vmlinux) {
11500 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11501 		return -EFAULT;
11502 	}
11503 
11504 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11505 		return -EFAULT;
11506 
11507 	node_type_name = btf_field_type_name(node_field_type);
11508 	if (!tnum_is_const(reg->var_off)) {
11509 		verbose(env,
11510 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11511 			regno, node_type_name);
11512 		return -EINVAL;
11513 	}
11514 
11515 	node_off = reg->off + reg->var_off.value;
11516 	field = reg_find_field_offset(reg, node_off, node_field_type);
11517 	if (!field || field->offset != node_off) {
11518 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11519 		return -EINVAL;
11520 	}
11521 
11522 	field = *node_field;
11523 
11524 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11525 	t = btf_type_by_id(reg->btf, reg->btf_id);
11526 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11527 				  field->graph_root.value_btf_id, true)) {
11528 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11529 			"in struct %s, but arg is at offset=%d in struct %s\n",
11530 			btf_field_type_name(head_field_type),
11531 			btf_field_type_name(node_field_type),
11532 			field->graph_root.node_offset,
11533 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11534 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11535 		return -EINVAL;
11536 	}
11537 	meta->arg_btf = reg->btf;
11538 	meta->arg_btf_id = reg->btf_id;
11539 
11540 	if (node_off != field->graph_root.node_offset) {
11541 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11542 			node_off, btf_field_type_name(node_field_type),
11543 			field->graph_root.node_offset,
11544 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11545 		return -EINVAL;
11546 	}
11547 
11548 	return 0;
11549 }
11550 
11551 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11552 					   struct bpf_reg_state *reg, u32 regno,
11553 					   struct bpf_kfunc_call_arg_meta *meta)
11554 {
11555 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11556 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11557 						  &meta->arg_list_head.field);
11558 }
11559 
11560 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11561 					     struct bpf_reg_state *reg, u32 regno,
11562 					     struct bpf_kfunc_call_arg_meta *meta)
11563 {
11564 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11565 						  BPF_RB_ROOT, BPF_RB_NODE,
11566 						  &meta->arg_rbtree_root.field);
11567 }
11568 
11569 /*
11570  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
11571  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
11572  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
11573  * them can only be attached to some specific hook points.
11574  */
11575 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11576 {
11577 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11578 
11579 	switch (prog_type) {
11580 	case BPF_PROG_TYPE_LSM:
11581 		return true;
11582 	case BPF_PROG_TYPE_TRACING:
11583 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
11584 			return true;
11585 		fallthrough;
11586 	default:
11587 		return in_sleepable(env);
11588 	}
11589 }
11590 
11591 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11592 			    int insn_idx)
11593 {
11594 	const char *func_name = meta->func_name, *ref_tname;
11595 	const struct btf *btf = meta->btf;
11596 	const struct btf_param *args;
11597 	struct btf_record *rec;
11598 	u32 i, nargs;
11599 	int ret;
11600 
11601 	args = (const struct btf_param *)(meta->func_proto + 1);
11602 	nargs = btf_type_vlen(meta->func_proto);
11603 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11604 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11605 			MAX_BPF_FUNC_REG_ARGS);
11606 		return -EINVAL;
11607 	}
11608 
11609 	/* Check that BTF function arguments match actual types that the
11610 	 * verifier sees.
11611 	 */
11612 	for (i = 0; i < nargs; i++) {
11613 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11614 		const struct btf_type *t, *ref_t, *resolve_ret;
11615 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11616 		u32 regno = i + 1, ref_id, type_size;
11617 		bool is_ret_buf_sz = false;
11618 		int kf_arg_type;
11619 
11620 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11621 
11622 		if (is_kfunc_arg_ignore(btf, &args[i]))
11623 			continue;
11624 
11625 		if (btf_type_is_scalar(t)) {
11626 			if (reg->type != SCALAR_VALUE) {
11627 				verbose(env, "R%d is not a scalar\n", regno);
11628 				return -EINVAL;
11629 			}
11630 
11631 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11632 				if (meta->arg_constant.found) {
11633 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11634 					return -EFAULT;
11635 				}
11636 				if (!tnum_is_const(reg->var_off)) {
11637 					verbose(env, "R%d must be a known constant\n", regno);
11638 					return -EINVAL;
11639 				}
11640 				ret = mark_chain_precision(env, regno);
11641 				if (ret < 0)
11642 					return ret;
11643 				meta->arg_constant.found = true;
11644 				meta->arg_constant.value = reg->var_off.value;
11645 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11646 				meta->r0_rdonly = true;
11647 				is_ret_buf_sz = true;
11648 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11649 				is_ret_buf_sz = true;
11650 			}
11651 
11652 			if (is_ret_buf_sz) {
11653 				if (meta->r0_size) {
11654 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11655 					return -EINVAL;
11656 				}
11657 
11658 				if (!tnum_is_const(reg->var_off)) {
11659 					verbose(env, "R%d is not a const\n", regno);
11660 					return -EINVAL;
11661 				}
11662 
11663 				meta->r0_size = reg->var_off.value;
11664 				ret = mark_chain_precision(env, regno);
11665 				if (ret)
11666 					return ret;
11667 			}
11668 			continue;
11669 		}
11670 
11671 		if (!btf_type_is_ptr(t)) {
11672 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11673 			return -EINVAL;
11674 		}
11675 
11676 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11677 		    (register_is_null(reg) || type_may_be_null(reg->type)) &&
11678 			!is_kfunc_arg_nullable(meta->btf, &args[i])) {
11679 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11680 			return -EACCES;
11681 		}
11682 
11683 		if (reg->ref_obj_id) {
11684 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
11685 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11686 					regno, reg->ref_obj_id,
11687 					meta->ref_obj_id);
11688 				return -EFAULT;
11689 			}
11690 			meta->ref_obj_id = reg->ref_obj_id;
11691 			if (is_kfunc_release(meta))
11692 				meta->release_regno = regno;
11693 		}
11694 
11695 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11696 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11697 
11698 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11699 		if (kf_arg_type < 0)
11700 			return kf_arg_type;
11701 
11702 		switch (kf_arg_type) {
11703 		case KF_ARG_PTR_TO_NULL:
11704 			continue;
11705 		case KF_ARG_PTR_TO_MAP:
11706 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11707 		case KF_ARG_PTR_TO_BTF_ID:
11708 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11709 				break;
11710 
11711 			if (!is_trusted_reg(reg)) {
11712 				if (!is_kfunc_rcu(meta)) {
11713 					verbose(env, "R%d must be referenced or trusted\n", regno);
11714 					return -EINVAL;
11715 				}
11716 				if (!is_rcu_reg(reg)) {
11717 					verbose(env, "R%d must be a rcu pointer\n", regno);
11718 					return -EINVAL;
11719 				}
11720 			}
11721 
11722 			fallthrough;
11723 		case KF_ARG_PTR_TO_CTX:
11724 			/* Trusted arguments have the same offset checks as release arguments */
11725 			arg_type |= OBJ_RELEASE;
11726 			break;
11727 		case KF_ARG_PTR_TO_DYNPTR:
11728 		case KF_ARG_PTR_TO_ITER:
11729 		case KF_ARG_PTR_TO_LIST_HEAD:
11730 		case KF_ARG_PTR_TO_LIST_NODE:
11731 		case KF_ARG_PTR_TO_RB_ROOT:
11732 		case KF_ARG_PTR_TO_RB_NODE:
11733 		case KF_ARG_PTR_TO_MEM:
11734 		case KF_ARG_PTR_TO_MEM_SIZE:
11735 		case KF_ARG_PTR_TO_CALLBACK:
11736 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11737 		case KF_ARG_PTR_TO_CONST_STR:
11738 			/* Trusted by default */
11739 			break;
11740 		default:
11741 			WARN_ON_ONCE(1);
11742 			return -EFAULT;
11743 		}
11744 
11745 		if (is_kfunc_release(meta) && reg->ref_obj_id)
11746 			arg_type |= OBJ_RELEASE;
11747 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11748 		if (ret < 0)
11749 			return ret;
11750 
11751 		switch (kf_arg_type) {
11752 		case KF_ARG_PTR_TO_CTX:
11753 			if (reg->type != PTR_TO_CTX) {
11754 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11755 				return -EINVAL;
11756 			}
11757 
11758 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11759 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11760 				if (ret < 0)
11761 					return -EINVAL;
11762 				meta->ret_btf_id  = ret;
11763 			}
11764 			break;
11765 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11766 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
11767 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
11768 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
11769 					return -EINVAL;
11770 				}
11771 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
11772 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
11773 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
11774 					return -EINVAL;
11775 				}
11776 			} else {
11777 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11778 				return -EINVAL;
11779 			}
11780 			if (!reg->ref_obj_id) {
11781 				verbose(env, "allocated object must be referenced\n");
11782 				return -EINVAL;
11783 			}
11784 			if (meta->btf == btf_vmlinux) {
11785 				meta->arg_btf = reg->btf;
11786 				meta->arg_btf_id = reg->btf_id;
11787 			}
11788 			break;
11789 		case KF_ARG_PTR_TO_DYNPTR:
11790 		{
11791 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11792 			int clone_ref_obj_id = 0;
11793 
11794 			if (reg->type != PTR_TO_STACK &&
11795 			    reg->type != CONST_PTR_TO_DYNPTR) {
11796 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11797 				return -EINVAL;
11798 			}
11799 
11800 			if (reg->type == CONST_PTR_TO_DYNPTR)
11801 				dynptr_arg_type |= MEM_RDONLY;
11802 
11803 			if (is_kfunc_arg_uninit(btf, &args[i]))
11804 				dynptr_arg_type |= MEM_UNINIT;
11805 
11806 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11807 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11808 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11809 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
11810 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11811 				   (dynptr_arg_type & MEM_UNINIT)) {
11812 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11813 
11814 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11815 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11816 					return -EFAULT;
11817 				}
11818 
11819 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11820 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11821 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11822 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11823 					return -EFAULT;
11824 				}
11825 			}
11826 
11827 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11828 			if (ret < 0)
11829 				return ret;
11830 
11831 			if (!(dynptr_arg_type & MEM_UNINIT)) {
11832 				int id = dynptr_id(env, reg);
11833 
11834 				if (id < 0) {
11835 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11836 					return id;
11837 				}
11838 				meta->initialized_dynptr.id = id;
11839 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11840 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11841 			}
11842 
11843 			break;
11844 		}
11845 		case KF_ARG_PTR_TO_ITER:
11846 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
11847 				if (!check_css_task_iter_allowlist(env)) {
11848 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
11849 					return -EINVAL;
11850 				}
11851 			}
11852 			ret = process_iter_arg(env, regno, insn_idx, meta);
11853 			if (ret < 0)
11854 				return ret;
11855 			break;
11856 		case KF_ARG_PTR_TO_LIST_HEAD:
11857 			if (reg->type != PTR_TO_MAP_VALUE &&
11858 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11859 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11860 				return -EINVAL;
11861 			}
11862 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11863 				verbose(env, "allocated object must be referenced\n");
11864 				return -EINVAL;
11865 			}
11866 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11867 			if (ret < 0)
11868 				return ret;
11869 			break;
11870 		case KF_ARG_PTR_TO_RB_ROOT:
11871 			if (reg->type != PTR_TO_MAP_VALUE &&
11872 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11873 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11874 				return -EINVAL;
11875 			}
11876 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11877 				verbose(env, "allocated object must be referenced\n");
11878 				return -EINVAL;
11879 			}
11880 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11881 			if (ret < 0)
11882 				return ret;
11883 			break;
11884 		case KF_ARG_PTR_TO_LIST_NODE:
11885 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11886 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11887 				return -EINVAL;
11888 			}
11889 			if (!reg->ref_obj_id) {
11890 				verbose(env, "allocated object must be referenced\n");
11891 				return -EINVAL;
11892 			}
11893 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11894 			if (ret < 0)
11895 				return ret;
11896 			break;
11897 		case KF_ARG_PTR_TO_RB_NODE:
11898 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11899 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11900 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
11901 					return -EINVAL;
11902 				}
11903 				if (in_rbtree_lock_required_cb(env)) {
11904 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11905 					return -EINVAL;
11906 				}
11907 			} else {
11908 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11909 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
11910 					return -EINVAL;
11911 				}
11912 				if (!reg->ref_obj_id) {
11913 					verbose(env, "allocated object must be referenced\n");
11914 					return -EINVAL;
11915 				}
11916 			}
11917 
11918 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11919 			if (ret < 0)
11920 				return ret;
11921 			break;
11922 		case KF_ARG_PTR_TO_MAP:
11923 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
11924 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
11925 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
11926 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11927 			fallthrough;
11928 		case KF_ARG_PTR_TO_BTF_ID:
11929 			/* Only base_type is checked, further checks are done here */
11930 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11931 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11932 			    !reg2btf_ids[base_type(reg->type)]) {
11933 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11934 				verbose(env, "expected %s or socket\n",
11935 					reg_type_str(env, base_type(reg->type) |
11936 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11937 				return -EINVAL;
11938 			}
11939 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11940 			if (ret < 0)
11941 				return ret;
11942 			break;
11943 		case KF_ARG_PTR_TO_MEM:
11944 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11945 			if (IS_ERR(resolve_ret)) {
11946 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11947 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11948 				return -EINVAL;
11949 			}
11950 			ret = check_mem_reg(env, reg, regno, type_size);
11951 			if (ret < 0)
11952 				return ret;
11953 			break;
11954 		case KF_ARG_PTR_TO_MEM_SIZE:
11955 		{
11956 			struct bpf_reg_state *buff_reg = &regs[regno];
11957 			const struct btf_param *buff_arg = &args[i];
11958 			struct bpf_reg_state *size_reg = &regs[regno + 1];
11959 			const struct btf_param *size_arg = &args[i + 1];
11960 
11961 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11962 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11963 				if (ret < 0) {
11964 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11965 					return ret;
11966 				}
11967 			}
11968 
11969 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11970 				if (meta->arg_constant.found) {
11971 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11972 					return -EFAULT;
11973 				}
11974 				if (!tnum_is_const(size_reg->var_off)) {
11975 					verbose(env, "R%d must be a known constant\n", regno + 1);
11976 					return -EINVAL;
11977 				}
11978 				meta->arg_constant.found = true;
11979 				meta->arg_constant.value = size_reg->var_off.value;
11980 			}
11981 
11982 			/* Skip next '__sz' or '__szk' argument */
11983 			i++;
11984 			break;
11985 		}
11986 		case KF_ARG_PTR_TO_CALLBACK:
11987 			if (reg->type != PTR_TO_FUNC) {
11988 				verbose(env, "arg%d expected pointer to func\n", i);
11989 				return -EINVAL;
11990 			}
11991 			meta->subprogno = reg->subprogno;
11992 			break;
11993 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11994 			if (!type_is_ptr_alloc_obj(reg->type)) {
11995 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11996 				return -EINVAL;
11997 			}
11998 			if (!type_is_non_owning_ref(reg->type))
11999 				meta->arg_owning_ref = true;
12000 
12001 			rec = reg_btf_record(reg);
12002 			if (!rec) {
12003 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
12004 				return -EFAULT;
12005 			}
12006 
12007 			if (rec->refcount_off < 0) {
12008 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
12009 				return -EINVAL;
12010 			}
12011 
12012 			meta->arg_btf = reg->btf;
12013 			meta->arg_btf_id = reg->btf_id;
12014 			break;
12015 		case KF_ARG_PTR_TO_CONST_STR:
12016 			if (reg->type != PTR_TO_MAP_VALUE) {
12017 				verbose(env, "arg#%d doesn't point to a const string\n", i);
12018 				return -EINVAL;
12019 			}
12020 			ret = check_reg_const_str(env, reg, regno);
12021 			if (ret)
12022 				return ret;
12023 			break;
12024 		}
12025 	}
12026 
12027 	if (is_kfunc_release(meta) && !meta->release_regno) {
12028 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
12029 			func_name);
12030 		return -EINVAL;
12031 	}
12032 
12033 	return 0;
12034 }
12035 
12036 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
12037 			    struct bpf_insn *insn,
12038 			    struct bpf_kfunc_call_arg_meta *meta,
12039 			    const char **kfunc_name)
12040 {
12041 	const struct btf_type *func, *func_proto;
12042 	u32 func_id, *kfunc_flags;
12043 	const char *func_name;
12044 	struct btf *desc_btf;
12045 
12046 	if (kfunc_name)
12047 		*kfunc_name = NULL;
12048 
12049 	if (!insn->imm)
12050 		return -EINVAL;
12051 
12052 	desc_btf = find_kfunc_desc_btf(env, insn->off);
12053 	if (IS_ERR(desc_btf))
12054 		return PTR_ERR(desc_btf);
12055 
12056 	func_id = insn->imm;
12057 	func = btf_type_by_id(desc_btf, func_id);
12058 	func_name = btf_name_by_offset(desc_btf, func->name_off);
12059 	if (kfunc_name)
12060 		*kfunc_name = func_name;
12061 	func_proto = btf_type_by_id(desc_btf, func->type);
12062 
12063 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
12064 	if (!kfunc_flags) {
12065 		return -EACCES;
12066 	}
12067 
12068 	memset(meta, 0, sizeof(*meta));
12069 	meta->btf = desc_btf;
12070 	meta->func_id = func_id;
12071 	meta->kfunc_flags = *kfunc_flags;
12072 	meta->func_proto = func_proto;
12073 	meta->func_name = func_name;
12074 
12075 	return 0;
12076 }
12077 
12078 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
12079 
12080 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12081 			    int *insn_idx_p)
12082 {
12083 	const struct btf_type *t, *ptr_type;
12084 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
12085 	struct bpf_reg_state *regs = cur_regs(env);
12086 	const char *func_name, *ptr_type_name;
12087 	bool sleepable, rcu_lock, rcu_unlock;
12088 	struct bpf_kfunc_call_arg_meta meta;
12089 	struct bpf_insn_aux_data *insn_aux;
12090 	int err, insn_idx = *insn_idx_p;
12091 	const struct btf_param *args;
12092 	const struct btf_type *ret_t;
12093 	struct btf *desc_btf;
12094 
12095 	/* skip for now, but return error when we find this in fixup_kfunc_call */
12096 	if (!insn->imm)
12097 		return 0;
12098 
12099 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
12100 	if (err == -EACCES && func_name)
12101 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
12102 	if (err)
12103 		return err;
12104 	desc_btf = meta.btf;
12105 	insn_aux = &env->insn_aux_data[insn_idx];
12106 
12107 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
12108 
12109 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
12110 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
12111 		return -EACCES;
12112 	}
12113 
12114 	sleepable = is_kfunc_sleepable(&meta);
12115 	if (sleepable && !in_sleepable(env)) {
12116 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
12117 		return -EACCES;
12118 	}
12119 
12120 	/* Check the arguments */
12121 	err = check_kfunc_args(env, &meta, insn_idx);
12122 	if (err < 0)
12123 		return err;
12124 
12125 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12126 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12127 					 set_rbtree_add_callback_state);
12128 		if (err) {
12129 			verbose(env, "kfunc %s#%d failed callback verification\n",
12130 				func_name, meta.func_id);
12131 			return err;
12132 		}
12133 	}
12134 
12135 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
12136 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
12137 
12138 	if (env->cur_state->active_rcu_lock) {
12139 		struct bpf_func_state *state;
12140 		struct bpf_reg_state *reg;
12141 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
12142 
12143 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
12144 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
12145 			return -EACCES;
12146 		}
12147 
12148 		if (rcu_lock) {
12149 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
12150 			return -EINVAL;
12151 		} else if (rcu_unlock) {
12152 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
12153 				if (reg->type & MEM_RCU) {
12154 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
12155 					reg->type |= PTR_UNTRUSTED;
12156 				}
12157 			}));
12158 			env->cur_state->active_rcu_lock = false;
12159 		} else if (sleepable) {
12160 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
12161 			return -EACCES;
12162 		}
12163 	} else if (rcu_lock) {
12164 		env->cur_state->active_rcu_lock = true;
12165 	} else if (rcu_unlock) {
12166 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
12167 		return -EINVAL;
12168 	}
12169 
12170 	/* In case of release function, we get register number of refcounted
12171 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
12172 	 */
12173 	if (meta.release_regno) {
12174 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
12175 		if (err) {
12176 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12177 				func_name, meta.func_id);
12178 			return err;
12179 		}
12180 	}
12181 
12182 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12183 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12184 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12185 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
12186 		insn_aux->insert_off = regs[BPF_REG_2].off;
12187 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
12188 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
12189 		if (err) {
12190 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
12191 				func_name, meta.func_id);
12192 			return err;
12193 		}
12194 
12195 		err = release_reference(env, release_ref_obj_id);
12196 		if (err) {
12197 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12198 				func_name, meta.func_id);
12199 			return err;
12200 		}
12201 	}
12202 
12203 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
12204 		if (!bpf_jit_supports_exceptions()) {
12205 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
12206 				func_name, meta.func_id);
12207 			return -ENOTSUPP;
12208 		}
12209 		env->seen_exception = true;
12210 
12211 		/* In the case of the default callback, the cookie value passed
12212 		 * to bpf_throw becomes the return value of the program.
12213 		 */
12214 		if (!env->exception_callback_subprog) {
12215 			err = check_return_code(env, BPF_REG_1, "R1");
12216 			if (err < 0)
12217 				return err;
12218 		}
12219 	}
12220 
12221 	for (i = 0; i < CALLER_SAVED_REGS; i++)
12222 		mark_reg_not_init(env, regs, caller_saved[i]);
12223 
12224 	/* Check return type */
12225 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
12226 
12227 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
12228 		/* Only exception is bpf_obj_new_impl */
12229 		if (meta.btf != btf_vmlinux ||
12230 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
12231 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
12232 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
12233 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
12234 			return -EINVAL;
12235 		}
12236 	}
12237 
12238 	if (btf_type_is_scalar(t)) {
12239 		mark_reg_unknown(env, regs, BPF_REG_0);
12240 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
12241 	} else if (btf_type_is_ptr(t)) {
12242 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
12243 
12244 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12245 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
12246 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12247 				struct btf_struct_meta *struct_meta;
12248 				struct btf *ret_btf;
12249 				u32 ret_btf_id;
12250 
12251 				if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
12252 					return -ENOMEM;
12253 
12254 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
12255 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12256 					return -EINVAL;
12257 				}
12258 
12259 				ret_btf = env->prog->aux->btf;
12260 				ret_btf_id = meta.arg_constant.value;
12261 
12262 				/* This may be NULL due to user not supplying a BTF */
12263 				if (!ret_btf) {
12264 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12265 					return -EINVAL;
12266 				}
12267 
12268 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12269 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
12270 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12271 					return -EINVAL;
12272 				}
12273 
12274 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12275 					if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
12276 						verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
12277 							ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
12278 						return -EINVAL;
12279 					}
12280 
12281 					if (!bpf_global_percpu_ma_set) {
12282 						mutex_lock(&bpf_percpu_ma_lock);
12283 						if (!bpf_global_percpu_ma_set) {
12284 							/* Charge memory allocated with bpf_global_percpu_ma to
12285 							 * root memcg. The obj_cgroup for root memcg is NULL.
12286 							 */
12287 							err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
12288 							if (!err)
12289 								bpf_global_percpu_ma_set = true;
12290 						}
12291 						mutex_unlock(&bpf_percpu_ma_lock);
12292 						if (err)
12293 							return err;
12294 					}
12295 
12296 					mutex_lock(&bpf_percpu_ma_lock);
12297 					err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
12298 					mutex_unlock(&bpf_percpu_ma_lock);
12299 					if (err)
12300 						return err;
12301 				}
12302 
12303 				struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12304 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12305 					if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12306 						verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12307 						return -EINVAL;
12308 					}
12309 
12310 					if (struct_meta) {
12311 						verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12312 						return -EINVAL;
12313 					}
12314 				}
12315 
12316 				mark_reg_known_zero(env, regs, BPF_REG_0);
12317 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12318 				regs[BPF_REG_0].btf = ret_btf;
12319 				regs[BPF_REG_0].btf_id = ret_btf_id;
12320 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12321 					regs[BPF_REG_0].type |= MEM_PERCPU;
12322 
12323 				insn_aux->obj_new_size = ret_t->size;
12324 				insn_aux->kptr_struct_meta = struct_meta;
12325 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12326 				mark_reg_known_zero(env, regs, BPF_REG_0);
12327 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12328 				regs[BPF_REG_0].btf = meta.arg_btf;
12329 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
12330 
12331 				insn_aux->kptr_struct_meta =
12332 					btf_find_struct_meta(meta.arg_btf,
12333 							     meta.arg_btf_id);
12334 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12335 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12336 				struct btf_field *field = meta.arg_list_head.field;
12337 
12338 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12339 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12340 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12341 				struct btf_field *field = meta.arg_rbtree_root.field;
12342 
12343 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12344 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12345 				mark_reg_known_zero(env, regs, BPF_REG_0);
12346 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12347 				regs[BPF_REG_0].btf = desc_btf;
12348 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12349 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12350 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12351 				if (!ret_t || !btf_type_is_struct(ret_t)) {
12352 					verbose(env,
12353 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
12354 					return -EINVAL;
12355 				}
12356 
12357 				mark_reg_known_zero(env, regs, BPF_REG_0);
12358 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12359 				regs[BPF_REG_0].btf = desc_btf;
12360 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
12361 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12362 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12363 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
12364 
12365 				mark_reg_known_zero(env, regs, BPF_REG_0);
12366 
12367 				if (!meta.arg_constant.found) {
12368 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
12369 					return -EFAULT;
12370 				}
12371 
12372 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
12373 
12374 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12375 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12376 
12377 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12378 					regs[BPF_REG_0].type |= MEM_RDONLY;
12379 				} else {
12380 					/* this will set env->seen_direct_write to true */
12381 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12382 						verbose(env, "the prog does not allow writes to packet data\n");
12383 						return -EINVAL;
12384 					}
12385 				}
12386 
12387 				if (!meta.initialized_dynptr.id) {
12388 					verbose(env, "verifier internal error: no dynptr id\n");
12389 					return -EFAULT;
12390 				}
12391 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
12392 
12393 				/* we don't need to set BPF_REG_0's ref obj id
12394 				 * because packet slices are not refcounted (see
12395 				 * dynptr_type_refcounted)
12396 				 */
12397 			} else {
12398 				verbose(env, "kernel function %s unhandled dynamic return type\n",
12399 					meta.func_name);
12400 				return -EFAULT;
12401 			}
12402 		} else if (btf_type_is_void(ptr_type)) {
12403 			/* kfunc returning 'void *' is equivalent to returning scalar */
12404 			mark_reg_unknown(env, regs, BPF_REG_0);
12405 		} else if (!__btf_type_is_struct(ptr_type)) {
12406 			if (!meta.r0_size) {
12407 				__u32 sz;
12408 
12409 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
12410 					meta.r0_size = sz;
12411 					meta.r0_rdonly = true;
12412 				}
12413 			}
12414 			if (!meta.r0_size) {
12415 				ptr_type_name = btf_name_by_offset(desc_btf,
12416 								   ptr_type->name_off);
12417 				verbose(env,
12418 					"kernel function %s returns pointer type %s %s is not supported\n",
12419 					func_name,
12420 					btf_type_str(ptr_type),
12421 					ptr_type_name);
12422 				return -EINVAL;
12423 			}
12424 
12425 			mark_reg_known_zero(env, regs, BPF_REG_0);
12426 			regs[BPF_REG_0].type = PTR_TO_MEM;
12427 			regs[BPF_REG_0].mem_size = meta.r0_size;
12428 
12429 			if (meta.r0_rdonly)
12430 				regs[BPF_REG_0].type |= MEM_RDONLY;
12431 
12432 			/* Ensures we don't access the memory after a release_reference() */
12433 			if (meta.ref_obj_id)
12434 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12435 		} else {
12436 			mark_reg_known_zero(env, regs, BPF_REG_0);
12437 			regs[BPF_REG_0].btf = desc_btf;
12438 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12439 			regs[BPF_REG_0].btf_id = ptr_type_id;
12440 		}
12441 
12442 		if (is_kfunc_ret_null(&meta)) {
12443 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12444 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12445 			regs[BPF_REG_0].id = ++env->id_gen;
12446 		}
12447 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12448 		if (is_kfunc_acquire(&meta)) {
12449 			int id = acquire_reference_state(env, insn_idx);
12450 
12451 			if (id < 0)
12452 				return id;
12453 			if (is_kfunc_ret_null(&meta))
12454 				regs[BPF_REG_0].id = id;
12455 			regs[BPF_REG_0].ref_obj_id = id;
12456 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12457 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12458 		}
12459 
12460 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12461 			regs[BPF_REG_0].id = ++env->id_gen;
12462 	} else if (btf_type_is_void(t)) {
12463 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12464 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
12465 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12466 				insn_aux->kptr_struct_meta =
12467 					btf_find_struct_meta(meta.arg_btf,
12468 							     meta.arg_btf_id);
12469 			}
12470 		}
12471 	}
12472 
12473 	nargs = btf_type_vlen(meta.func_proto);
12474 	args = (const struct btf_param *)(meta.func_proto + 1);
12475 	for (i = 0; i < nargs; i++) {
12476 		u32 regno = i + 1;
12477 
12478 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12479 		if (btf_type_is_ptr(t))
12480 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12481 		else
12482 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12483 			mark_btf_func_reg_size(env, regno, t->size);
12484 	}
12485 
12486 	if (is_iter_next_kfunc(&meta)) {
12487 		err = process_iter_next_call(env, insn_idx, &meta);
12488 		if (err)
12489 			return err;
12490 	}
12491 
12492 	return 0;
12493 }
12494 
12495 static bool signed_add_overflows(s64 a, s64 b)
12496 {
12497 	/* Do the add in u64, where overflow is well-defined */
12498 	s64 res = (s64)((u64)a + (u64)b);
12499 
12500 	if (b < 0)
12501 		return res > a;
12502 	return res < a;
12503 }
12504 
12505 static bool signed_add32_overflows(s32 a, s32 b)
12506 {
12507 	/* Do the add in u32, where overflow is well-defined */
12508 	s32 res = (s32)((u32)a + (u32)b);
12509 
12510 	if (b < 0)
12511 		return res > a;
12512 	return res < a;
12513 }
12514 
12515 static bool signed_sub_overflows(s64 a, s64 b)
12516 {
12517 	/* Do the sub in u64, where overflow is well-defined */
12518 	s64 res = (s64)((u64)a - (u64)b);
12519 
12520 	if (b < 0)
12521 		return res < a;
12522 	return res > a;
12523 }
12524 
12525 static bool signed_sub32_overflows(s32 a, s32 b)
12526 {
12527 	/* Do the sub in u32, where overflow is well-defined */
12528 	s32 res = (s32)((u32)a - (u32)b);
12529 
12530 	if (b < 0)
12531 		return res < a;
12532 	return res > a;
12533 }
12534 
12535 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12536 				  const struct bpf_reg_state *reg,
12537 				  enum bpf_reg_type type)
12538 {
12539 	bool known = tnum_is_const(reg->var_off);
12540 	s64 val = reg->var_off.value;
12541 	s64 smin = reg->smin_value;
12542 
12543 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12544 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12545 			reg_type_str(env, type), val);
12546 		return false;
12547 	}
12548 
12549 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12550 		verbose(env, "%s pointer offset %d is not allowed\n",
12551 			reg_type_str(env, type), reg->off);
12552 		return false;
12553 	}
12554 
12555 	if (smin == S64_MIN) {
12556 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12557 			reg_type_str(env, type));
12558 		return false;
12559 	}
12560 
12561 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12562 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12563 			smin, reg_type_str(env, type));
12564 		return false;
12565 	}
12566 
12567 	return true;
12568 }
12569 
12570 enum {
12571 	REASON_BOUNDS	= -1,
12572 	REASON_TYPE	= -2,
12573 	REASON_PATHS	= -3,
12574 	REASON_LIMIT	= -4,
12575 	REASON_STACK	= -5,
12576 };
12577 
12578 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12579 			      u32 *alu_limit, bool mask_to_left)
12580 {
12581 	u32 max = 0, ptr_limit = 0;
12582 
12583 	switch (ptr_reg->type) {
12584 	case PTR_TO_STACK:
12585 		/* Offset 0 is out-of-bounds, but acceptable start for the
12586 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12587 		 * offset where we would need to deal with min/max bounds is
12588 		 * currently prohibited for unprivileged.
12589 		 */
12590 		max = MAX_BPF_STACK + mask_to_left;
12591 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12592 		break;
12593 	case PTR_TO_MAP_VALUE:
12594 		max = ptr_reg->map_ptr->value_size;
12595 		ptr_limit = (mask_to_left ?
12596 			     ptr_reg->smin_value :
12597 			     ptr_reg->umax_value) + ptr_reg->off;
12598 		break;
12599 	default:
12600 		return REASON_TYPE;
12601 	}
12602 
12603 	if (ptr_limit >= max)
12604 		return REASON_LIMIT;
12605 	*alu_limit = ptr_limit;
12606 	return 0;
12607 }
12608 
12609 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12610 				    const struct bpf_insn *insn)
12611 {
12612 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12613 }
12614 
12615 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12616 				       u32 alu_state, u32 alu_limit)
12617 {
12618 	/* If we arrived here from different branches with different
12619 	 * state or limits to sanitize, then this won't work.
12620 	 */
12621 	if (aux->alu_state &&
12622 	    (aux->alu_state != alu_state ||
12623 	     aux->alu_limit != alu_limit))
12624 		return REASON_PATHS;
12625 
12626 	/* Corresponding fixup done in do_misc_fixups(). */
12627 	aux->alu_state = alu_state;
12628 	aux->alu_limit = alu_limit;
12629 	return 0;
12630 }
12631 
12632 static int sanitize_val_alu(struct bpf_verifier_env *env,
12633 			    struct bpf_insn *insn)
12634 {
12635 	struct bpf_insn_aux_data *aux = cur_aux(env);
12636 
12637 	if (can_skip_alu_sanitation(env, insn))
12638 		return 0;
12639 
12640 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12641 }
12642 
12643 static bool sanitize_needed(u8 opcode)
12644 {
12645 	return opcode == BPF_ADD || opcode == BPF_SUB;
12646 }
12647 
12648 struct bpf_sanitize_info {
12649 	struct bpf_insn_aux_data aux;
12650 	bool mask_to_left;
12651 };
12652 
12653 static struct bpf_verifier_state *
12654 sanitize_speculative_path(struct bpf_verifier_env *env,
12655 			  const struct bpf_insn *insn,
12656 			  u32 next_idx, u32 curr_idx)
12657 {
12658 	struct bpf_verifier_state *branch;
12659 	struct bpf_reg_state *regs;
12660 
12661 	branch = push_stack(env, next_idx, curr_idx, true);
12662 	if (branch && insn) {
12663 		regs = branch->frame[branch->curframe]->regs;
12664 		if (BPF_SRC(insn->code) == BPF_K) {
12665 			mark_reg_unknown(env, regs, insn->dst_reg);
12666 		} else if (BPF_SRC(insn->code) == BPF_X) {
12667 			mark_reg_unknown(env, regs, insn->dst_reg);
12668 			mark_reg_unknown(env, regs, insn->src_reg);
12669 		}
12670 	}
12671 	return branch;
12672 }
12673 
12674 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12675 			    struct bpf_insn *insn,
12676 			    const struct bpf_reg_state *ptr_reg,
12677 			    const struct bpf_reg_state *off_reg,
12678 			    struct bpf_reg_state *dst_reg,
12679 			    struct bpf_sanitize_info *info,
12680 			    const bool commit_window)
12681 {
12682 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12683 	struct bpf_verifier_state *vstate = env->cur_state;
12684 	bool off_is_imm = tnum_is_const(off_reg->var_off);
12685 	bool off_is_neg = off_reg->smin_value < 0;
12686 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12687 	u8 opcode = BPF_OP(insn->code);
12688 	u32 alu_state, alu_limit;
12689 	struct bpf_reg_state tmp;
12690 	bool ret;
12691 	int err;
12692 
12693 	if (can_skip_alu_sanitation(env, insn))
12694 		return 0;
12695 
12696 	/* We already marked aux for masking from non-speculative
12697 	 * paths, thus we got here in the first place. We only care
12698 	 * to explore bad access from here.
12699 	 */
12700 	if (vstate->speculative)
12701 		goto do_sim;
12702 
12703 	if (!commit_window) {
12704 		if (!tnum_is_const(off_reg->var_off) &&
12705 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12706 			return REASON_BOUNDS;
12707 
12708 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12709 				     (opcode == BPF_SUB && !off_is_neg);
12710 	}
12711 
12712 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12713 	if (err < 0)
12714 		return err;
12715 
12716 	if (commit_window) {
12717 		/* In commit phase we narrow the masking window based on
12718 		 * the observed pointer move after the simulated operation.
12719 		 */
12720 		alu_state = info->aux.alu_state;
12721 		alu_limit = abs(info->aux.alu_limit - alu_limit);
12722 	} else {
12723 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12724 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12725 		alu_state |= ptr_is_dst_reg ?
12726 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12727 
12728 		/* Limit pruning on unknown scalars to enable deep search for
12729 		 * potential masking differences from other program paths.
12730 		 */
12731 		if (!off_is_imm)
12732 			env->explore_alu_limits = true;
12733 	}
12734 
12735 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12736 	if (err < 0)
12737 		return err;
12738 do_sim:
12739 	/* If we're in commit phase, we're done here given we already
12740 	 * pushed the truncated dst_reg into the speculative verification
12741 	 * stack.
12742 	 *
12743 	 * Also, when register is a known constant, we rewrite register-based
12744 	 * operation to immediate-based, and thus do not need masking (and as
12745 	 * a consequence, do not need to simulate the zero-truncation either).
12746 	 */
12747 	if (commit_window || off_is_imm)
12748 		return 0;
12749 
12750 	/* Simulate and find potential out-of-bounds access under
12751 	 * speculative execution from truncation as a result of
12752 	 * masking when off was not within expected range. If off
12753 	 * sits in dst, then we temporarily need to move ptr there
12754 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12755 	 * for cases where we use K-based arithmetic in one direction
12756 	 * and truncated reg-based in the other in order to explore
12757 	 * bad access.
12758 	 */
12759 	if (!ptr_is_dst_reg) {
12760 		tmp = *dst_reg;
12761 		copy_register_state(dst_reg, ptr_reg);
12762 	}
12763 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12764 					env->insn_idx);
12765 	if (!ptr_is_dst_reg && ret)
12766 		*dst_reg = tmp;
12767 	return !ret ? REASON_STACK : 0;
12768 }
12769 
12770 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12771 {
12772 	struct bpf_verifier_state *vstate = env->cur_state;
12773 
12774 	/* If we simulate paths under speculation, we don't update the
12775 	 * insn as 'seen' such that when we verify unreachable paths in
12776 	 * the non-speculative domain, sanitize_dead_code() can still
12777 	 * rewrite/sanitize them.
12778 	 */
12779 	if (!vstate->speculative)
12780 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12781 }
12782 
12783 static int sanitize_err(struct bpf_verifier_env *env,
12784 			const struct bpf_insn *insn, int reason,
12785 			const struct bpf_reg_state *off_reg,
12786 			const struct bpf_reg_state *dst_reg)
12787 {
12788 	static const char *err = "pointer arithmetic with it prohibited for !root";
12789 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12790 	u32 dst = insn->dst_reg, src = insn->src_reg;
12791 
12792 	switch (reason) {
12793 	case REASON_BOUNDS:
12794 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12795 			off_reg == dst_reg ? dst : src, err);
12796 		break;
12797 	case REASON_TYPE:
12798 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12799 			off_reg == dst_reg ? src : dst, err);
12800 		break;
12801 	case REASON_PATHS:
12802 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12803 			dst, op, err);
12804 		break;
12805 	case REASON_LIMIT:
12806 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12807 			dst, op, err);
12808 		break;
12809 	case REASON_STACK:
12810 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12811 			dst, err);
12812 		break;
12813 	default:
12814 		verbose(env, "verifier internal error: unknown reason (%d)\n",
12815 			reason);
12816 		break;
12817 	}
12818 
12819 	return -EACCES;
12820 }
12821 
12822 /* check that stack access falls within stack limits and that 'reg' doesn't
12823  * have a variable offset.
12824  *
12825  * Variable offset is prohibited for unprivileged mode for simplicity since it
12826  * requires corresponding support in Spectre masking for stack ALU.  See also
12827  * retrieve_ptr_limit().
12828  *
12829  *
12830  * 'off' includes 'reg->off'.
12831  */
12832 static int check_stack_access_for_ptr_arithmetic(
12833 				struct bpf_verifier_env *env,
12834 				int regno,
12835 				const struct bpf_reg_state *reg,
12836 				int off)
12837 {
12838 	if (!tnum_is_const(reg->var_off)) {
12839 		char tn_buf[48];
12840 
12841 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12842 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12843 			regno, tn_buf, off);
12844 		return -EACCES;
12845 	}
12846 
12847 	if (off >= 0 || off < -MAX_BPF_STACK) {
12848 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
12849 			"prohibited for !root; off=%d\n", regno, off);
12850 		return -EACCES;
12851 	}
12852 
12853 	return 0;
12854 }
12855 
12856 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12857 				 const struct bpf_insn *insn,
12858 				 const struct bpf_reg_state *dst_reg)
12859 {
12860 	u32 dst = insn->dst_reg;
12861 
12862 	/* For unprivileged we require that resulting offset must be in bounds
12863 	 * in order to be able to sanitize access later on.
12864 	 */
12865 	if (env->bypass_spec_v1)
12866 		return 0;
12867 
12868 	switch (dst_reg->type) {
12869 	case PTR_TO_STACK:
12870 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12871 					dst_reg->off + dst_reg->var_off.value))
12872 			return -EACCES;
12873 		break;
12874 	case PTR_TO_MAP_VALUE:
12875 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12876 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12877 				"prohibited for !root\n", dst);
12878 			return -EACCES;
12879 		}
12880 		break;
12881 	default:
12882 		break;
12883 	}
12884 
12885 	return 0;
12886 }
12887 
12888 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12889  * Caller should also handle BPF_MOV case separately.
12890  * If we return -EACCES, caller may want to try again treating pointer as a
12891  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12892  */
12893 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12894 				   struct bpf_insn *insn,
12895 				   const struct bpf_reg_state *ptr_reg,
12896 				   const struct bpf_reg_state *off_reg)
12897 {
12898 	struct bpf_verifier_state *vstate = env->cur_state;
12899 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12900 	struct bpf_reg_state *regs = state->regs, *dst_reg;
12901 	bool known = tnum_is_const(off_reg->var_off);
12902 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12903 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12904 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12905 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12906 	struct bpf_sanitize_info info = {};
12907 	u8 opcode = BPF_OP(insn->code);
12908 	u32 dst = insn->dst_reg;
12909 	int ret;
12910 
12911 	dst_reg = &regs[dst];
12912 
12913 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12914 	    smin_val > smax_val || umin_val > umax_val) {
12915 		/* Taint dst register if offset had invalid bounds derived from
12916 		 * e.g. dead branches.
12917 		 */
12918 		__mark_reg_unknown(env, dst_reg);
12919 		return 0;
12920 	}
12921 
12922 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
12923 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
12924 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12925 			__mark_reg_unknown(env, dst_reg);
12926 			return 0;
12927 		}
12928 
12929 		verbose(env,
12930 			"R%d 32-bit pointer arithmetic prohibited\n",
12931 			dst);
12932 		return -EACCES;
12933 	}
12934 
12935 	if (ptr_reg->type & PTR_MAYBE_NULL) {
12936 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12937 			dst, reg_type_str(env, ptr_reg->type));
12938 		return -EACCES;
12939 	}
12940 
12941 	switch (base_type(ptr_reg->type)) {
12942 	case PTR_TO_CTX:
12943 	case PTR_TO_MAP_VALUE:
12944 	case PTR_TO_MAP_KEY:
12945 	case PTR_TO_STACK:
12946 	case PTR_TO_PACKET_META:
12947 	case PTR_TO_PACKET:
12948 	case PTR_TO_TP_BUFFER:
12949 	case PTR_TO_BTF_ID:
12950 	case PTR_TO_MEM:
12951 	case PTR_TO_BUF:
12952 	case PTR_TO_FUNC:
12953 	case CONST_PTR_TO_DYNPTR:
12954 		break;
12955 	case PTR_TO_FLOW_KEYS:
12956 		if (known)
12957 			break;
12958 		fallthrough;
12959 	case CONST_PTR_TO_MAP:
12960 		/* smin_val represents the known value */
12961 		if (known && smin_val == 0 && opcode == BPF_ADD)
12962 			break;
12963 		fallthrough;
12964 	default:
12965 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12966 			dst, reg_type_str(env, ptr_reg->type));
12967 		return -EACCES;
12968 	}
12969 
12970 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12971 	 * The id may be overwritten later if we create a new variable offset.
12972 	 */
12973 	dst_reg->type = ptr_reg->type;
12974 	dst_reg->id = ptr_reg->id;
12975 
12976 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12977 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12978 		return -EINVAL;
12979 
12980 	/* pointer types do not carry 32-bit bounds at the moment. */
12981 	__mark_reg32_unbounded(dst_reg);
12982 
12983 	if (sanitize_needed(opcode)) {
12984 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12985 				       &info, false);
12986 		if (ret < 0)
12987 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12988 	}
12989 
12990 	switch (opcode) {
12991 	case BPF_ADD:
12992 		/* We can take a fixed offset as long as it doesn't overflow
12993 		 * the s32 'off' field
12994 		 */
12995 		if (known && (ptr_reg->off + smin_val ==
12996 			      (s64)(s32)(ptr_reg->off + smin_val))) {
12997 			/* pointer += K.  Accumulate it into fixed offset */
12998 			dst_reg->smin_value = smin_ptr;
12999 			dst_reg->smax_value = smax_ptr;
13000 			dst_reg->umin_value = umin_ptr;
13001 			dst_reg->umax_value = umax_ptr;
13002 			dst_reg->var_off = ptr_reg->var_off;
13003 			dst_reg->off = ptr_reg->off + smin_val;
13004 			dst_reg->raw = ptr_reg->raw;
13005 			break;
13006 		}
13007 		/* A new variable offset is created.  Note that off_reg->off
13008 		 * == 0, since it's a scalar.
13009 		 * dst_reg gets the pointer type and since some positive
13010 		 * integer value was added to the pointer, give it a new 'id'
13011 		 * if it's a PTR_TO_PACKET.
13012 		 * this creates a new 'base' pointer, off_reg (variable) gets
13013 		 * added into the variable offset, and we copy the fixed offset
13014 		 * from ptr_reg.
13015 		 */
13016 		if (signed_add_overflows(smin_ptr, smin_val) ||
13017 		    signed_add_overflows(smax_ptr, smax_val)) {
13018 			dst_reg->smin_value = S64_MIN;
13019 			dst_reg->smax_value = S64_MAX;
13020 		} else {
13021 			dst_reg->smin_value = smin_ptr + smin_val;
13022 			dst_reg->smax_value = smax_ptr + smax_val;
13023 		}
13024 		if (umin_ptr + umin_val < umin_ptr ||
13025 		    umax_ptr + umax_val < umax_ptr) {
13026 			dst_reg->umin_value = 0;
13027 			dst_reg->umax_value = U64_MAX;
13028 		} else {
13029 			dst_reg->umin_value = umin_ptr + umin_val;
13030 			dst_reg->umax_value = umax_ptr + umax_val;
13031 		}
13032 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
13033 		dst_reg->off = ptr_reg->off;
13034 		dst_reg->raw = ptr_reg->raw;
13035 		if (reg_is_pkt_pointer(ptr_reg)) {
13036 			dst_reg->id = ++env->id_gen;
13037 			/* something was added to pkt_ptr, set range to zero */
13038 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13039 		}
13040 		break;
13041 	case BPF_SUB:
13042 		if (dst_reg == off_reg) {
13043 			/* scalar -= pointer.  Creates an unknown scalar */
13044 			verbose(env, "R%d tried to subtract pointer from scalar\n",
13045 				dst);
13046 			return -EACCES;
13047 		}
13048 		/* We don't allow subtraction from FP, because (according to
13049 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
13050 		 * be able to deal with it.
13051 		 */
13052 		if (ptr_reg->type == PTR_TO_STACK) {
13053 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
13054 				dst);
13055 			return -EACCES;
13056 		}
13057 		if (known && (ptr_reg->off - smin_val ==
13058 			      (s64)(s32)(ptr_reg->off - smin_val))) {
13059 			/* pointer -= K.  Subtract it from fixed offset */
13060 			dst_reg->smin_value = smin_ptr;
13061 			dst_reg->smax_value = smax_ptr;
13062 			dst_reg->umin_value = umin_ptr;
13063 			dst_reg->umax_value = umax_ptr;
13064 			dst_reg->var_off = ptr_reg->var_off;
13065 			dst_reg->id = ptr_reg->id;
13066 			dst_reg->off = ptr_reg->off - smin_val;
13067 			dst_reg->raw = ptr_reg->raw;
13068 			break;
13069 		}
13070 		/* A new variable offset is created.  If the subtrahend is known
13071 		 * nonnegative, then any reg->range we had before is still good.
13072 		 */
13073 		if (signed_sub_overflows(smin_ptr, smax_val) ||
13074 		    signed_sub_overflows(smax_ptr, smin_val)) {
13075 			/* Overflow possible, we know nothing */
13076 			dst_reg->smin_value = S64_MIN;
13077 			dst_reg->smax_value = S64_MAX;
13078 		} else {
13079 			dst_reg->smin_value = smin_ptr - smax_val;
13080 			dst_reg->smax_value = smax_ptr - smin_val;
13081 		}
13082 		if (umin_ptr < umax_val) {
13083 			/* Overflow possible, we know nothing */
13084 			dst_reg->umin_value = 0;
13085 			dst_reg->umax_value = U64_MAX;
13086 		} else {
13087 			/* Cannot overflow (as long as bounds are consistent) */
13088 			dst_reg->umin_value = umin_ptr - umax_val;
13089 			dst_reg->umax_value = umax_ptr - umin_val;
13090 		}
13091 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
13092 		dst_reg->off = ptr_reg->off;
13093 		dst_reg->raw = ptr_reg->raw;
13094 		if (reg_is_pkt_pointer(ptr_reg)) {
13095 			dst_reg->id = ++env->id_gen;
13096 			/* something was added to pkt_ptr, set range to zero */
13097 			if (smin_val < 0)
13098 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13099 		}
13100 		break;
13101 	case BPF_AND:
13102 	case BPF_OR:
13103 	case BPF_XOR:
13104 		/* bitwise ops on pointers are troublesome, prohibit. */
13105 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
13106 			dst, bpf_alu_string[opcode >> 4]);
13107 		return -EACCES;
13108 	default:
13109 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
13110 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
13111 			dst, bpf_alu_string[opcode >> 4]);
13112 		return -EACCES;
13113 	}
13114 
13115 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
13116 		return -EINVAL;
13117 	reg_bounds_sync(dst_reg);
13118 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
13119 		return -EACCES;
13120 	if (sanitize_needed(opcode)) {
13121 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
13122 				       &info, true);
13123 		if (ret < 0)
13124 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13125 	}
13126 
13127 	return 0;
13128 }
13129 
13130 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
13131 				 struct bpf_reg_state *src_reg)
13132 {
13133 	s32 smin_val = src_reg->s32_min_value;
13134 	s32 smax_val = src_reg->s32_max_value;
13135 	u32 umin_val = src_reg->u32_min_value;
13136 	u32 umax_val = src_reg->u32_max_value;
13137 
13138 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
13139 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
13140 		dst_reg->s32_min_value = S32_MIN;
13141 		dst_reg->s32_max_value = S32_MAX;
13142 	} else {
13143 		dst_reg->s32_min_value += smin_val;
13144 		dst_reg->s32_max_value += smax_val;
13145 	}
13146 	if (dst_reg->u32_min_value + umin_val < umin_val ||
13147 	    dst_reg->u32_max_value + umax_val < umax_val) {
13148 		dst_reg->u32_min_value = 0;
13149 		dst_reg->u32_max_value = U32_MAX;
13150 	} else {
13151 		dst_reg->u32_min_value += umin_val;
13152 		dst_reg->u32_max_value += umax_val;
13153 	}
13154 }
13155 
13156 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
13157 			       struct bpf_reg_state *src_reg)
13158 {
13159 	s64 smin_val = src_reg->smin_value;
13160 	s64 smax_val = src_reg->smax_value;
13161 	u64 umin_val = src_reg->umin_value;
13162 	u64 umax_val = src_reg->umax_value;
13163 
13164 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
13165 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
13166 		dst_reg->smin_value = S64_MIN;
13167 		dst_reg->smax_value = S64_MAX;
13168 	} else {
13169 		dst_reg->smin_value += smin_val;
13170 		dst_reg->smax_value += smax_val;
13171 	}
13172 	if (dst_reg->umin_value + umin_val < umin_val ||
13173 	    dst_reg->umax_value + umax_val < umax_val) {
13174 		dst_reg->umin_value = 0;
13175 		dst_reg->umax_value = U64_MAX;
13176 	} else {
13177 		dst_reg->umin_value += umin_val;
13178 		dst_reg->umax_value += umax_val;
13179 	}
13180 }
13181 
13182 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
13183 				 struct bpf_reg_state *src_reg)
13184 {
13185 	s32 smin_val = src_reg->s32_min_value;
13186 	s32 smax_val = src_reg->s32_max_value;
13187 	u32 umin_val = src_reg->u32_min_value;
13188 	u32 umax_val = src_reg->u32_max_value;
13189 
13190 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
13191 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
13192 		/* Overflow possible, we know nothing */
13193 		dst_reg->s32_min_value = S32_MIN;
13194 		dst_reg->s32_max_value = S32_MAX;
13195 	} else {
13196 		dst_reg->s32_min_value -= smax_val;
13197 		dst_reg->s32_max_value -= smin_val;
13198 	}
13199 	if (dst_reg->u32_min_value < umax_val) {
13200 		/* Overflow possible, we know nothing */
13201 		dst_reg->u32_min_value = 0;
13202 		dst_reg->u32_max_value = U32_MAX;
13203 	} else {
13204 		/* Cannot overflow (as long as bounds are consistent) */
13205 		dst_reg->u32_min_value -= umax_val;
13206 		dst_reg->u32_max_value -= umin_val;
13207 	}
13208 }
13209 
13210 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
13211 			       struct bpf_reg_state *src_reg)
13212 {
13213 	s64 smin_val = src_reg->smin_value;
13214 	s64 smax_val = src_reg->smax_value;
13215 	u64 umin_val = src_reg->umin_value;
13216 	u64 umax_val = src_reg->umax_value;
13217 
13218 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
13219 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
13220 		/* Overflow possible, we know nothing */
13221 		dst_reg->smin_value = S64_MIN;
13222 		dst_reg->smax_value = S64_MAX;
13223 	} else {
13224 		dst_reg->smin_value -= smax_val;
13225 		dst_reg->smax_value -= smin_val;
13226 	}
13227 	if (dst_reg->umin_value < umax_val) {
13228 		/* Overflow possible, we know nothing */
13229 		dst_reg->umin_value = 0;
13230 		dst_reg->umax_value = U64_MAX;
13231 	} else {
13232 		/* Cannot overflow (as long as bounds are consistent) */
13233 		dst_reg->umin_value -= umax_val;
13234 		dst_reg->umax_value -= umin_val;
13235 	}
13236 }
13237 
13238 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13239 				 struct bpf_reg_state *src_reg)
13240 {
13241 	s32 smin_val = src_reg->s32_min_value;
13242 	u32 umin_val = src_reg->u32_min_value;
13243 	u32 umax_val = src_reg->u32_max_value;
13244 
13245 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
13246 		/* Ain't nobody got time to multiply that sign */
13247 		__mark_reg32_unbounded(dst_reg);
13248 		return;
13249 	}
13250 	/* Both values are positive, so we can work with unsigned and
13251 	 * copy the result to signed (unless it exceeds S32_MAX).
13252 	 */
13253 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
13254 		/* Potential overflow, we know nothing */
13255 		__mark_reg32_unbounded(dst_reg);
13256 		return;
13257 	}
13258 	dst_reg->u32_min_value *= umin_val;
13259 	dst_reg->u32_max_value *= umax_val;
13260 	if (dst_reg->u32_max_value > S32_MAX) {
13261 		/* Overflow possible, we know nothing */
13262 		dst_reg->s32_min_value = S32_MIN;
13263 		dst_reg->s32_max_value = S32_MAX;
13264 	} else {
13265 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13266 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13267 	}
13268 }
13269 
13270 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13271 			       struct bpf_reg_state *src_reg)
13272 {
13273 	s64 smin_val = src_reg->smin_value;
13274 	u64 umin_val = src_reg->umin_value;
13275 	u64 umax_val = src_reg->umax_value;
13276 
13277 	if (smin_val < 0 || dst_reg->smin_value < 0) {
13278 		/* Ain't nobody got time to multiply that sign */
13279 		__mark_reg64_unbounded(dst_reg);
13280 		return;
13281 	}
13282 	/* Both values are positive, so we can work with unsigned and
13283 	 * copy the result to signed (unless it exceeds S64_MAX).
13284 	 */
13285 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
13286 		/* Potential overflow, we know nothing */
13287 		__mark_reg64_unbounded(dst_reg);
13288 		return;
13289 	}
13290 	dst_reg->umin_value *= umin_val;
13291 	dst_reg->umax_value *= umax_val;
13292 	if (dst_reg->umax_value > S64_MAX) {
13293 		/* Overflow possible, we know nothing */
13294 		dst_reg->smin_value = S64_MIN;
13295 		dst_reg->smax_value = S64_MAX;
13296 	} else {
13297 		dst_reg->smin_value = dst_reg->umin_value;
13298 		dst_reg->smax_value = dst_reg->umax_value;
13299 	}
13300 }
13301 
13302 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13303 				 struct bpf_reg_state *src_reg)
13304 {
13305 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13306 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13307 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13308 	s32 smin_val = src_reg->s32_min_value;
13309 	u32 umax_val = src_reg->u32_max_value;
13310 
13311 	if (src_known && dst_known) {
13312 		__mark_reg32_known(dst_reg, var32_off.value);
13313 		return;
13314 	}
13315 
13316 	/* We get our minimum from the var_off, since that's inherently
13317 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13318 	 */
13319 	dst_reg->u32_min_value = var32_off.value;
13320 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13321 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13322 		/* Lose signed bounds when ANDing negative numbers,
13323 		 * ain't nobody got time for that.
13324 		 */
13325 		dst_reg->s32_min_value = S32_MIN;
13326 		dst_reg->s32_max_value = S32_MAX;
13327 	} else {
13328 		/* ANDing two positives gives a positive, so safe to
13329 		 * cast result into s64.
13330 		 */
13331 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13332 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13333 	}
13334 }
13335 
13336 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
13337 			       struct bpf_reg_state *src_reg)
13338 {
13339 	bool src_known = tnum_is_const(src_reg->var_off);
13340 	bool dst_known = tnum_is_const(dst_reg->var_off);
13341 	s64 smin_val = src_reg->smin_value;
13342 	u64 umax_val = src_reg->umax_value;
13343 
13344 	if (src_known && dst_known) {
13345 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13346 		return;
13347 	}
13348 
13349 	/* We get our minimum from the var_off, since that's inherently
13350 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13351 	 */
13352 	dst_reg->umin_value = dst_reg->var_off.value;
13353 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13354 	if (dst_reg->smin_value < 0 || smin_val < 0) {
13355 		/* Lose signed bounds when ANDing negative numbers,
13356 		 * ain't nobody got time for that.
13357 		 */
13358 		dst_reg->smin_value = S64_MIN;
13359 		dst_reg->smax_value = S64_MAX;
13360 	} else {
13361 		/* ANDing two positives gives a positive, so safe to
13362 		 * cast result into s64.
13363 		 */
13364 		dst_reg->smin_value = dst_reg->umin_value;
13365 		dst_reg->smax_value = dst_reg->umax_value;
13366 	}
13367 	/* We may learn something more from the var_off */
13368 	__update_reg_bounds(dst_reg);
13369 }
13370 
13371 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13372 				struct bpf_reg_state *src_reg)
13373 {
13374 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13375 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13376 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13377 	s32 smin_val = src_reg->s32_min_value;
13378 	u32 umin_val = src_reg->u32_min_value;
13379 
13380 	if (src_known && dst_known) {
13381 		__mark_reg32_known(dst_reg, var32_off.value);
13382 		return;
13383 	}
13384 
13385 	/* We get our maximum from the var_off, and our minimum is the
13386 	 * maximum of the operands' minima
13387 	 */
13388 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13389 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13390 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13391 		/* Lose signed bounds when ORing negative numbers,
13392 		 * ain't nobody got time for that.
13393 		 */
13394 		dst_reg->s32_min_value = S32_MIN;
13395 		dst_reg->s32_max_value = S32_MAX;
13396 	} else {
13397 		/* ORing two positives gives a positive, so safe to
13398 		 * cast result into s64.
13399 		 */
13400 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13401 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13402 	}
13403 }
13404 
13405 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13406 			      struct bpf_reg_state *src_reg)
13407 {
13408 	bool src_known = tnum_is_const(src_reg->var_off);
13409 	bool dst_known = tnum_is_const(dst_reg->var_off);
13410 	s64 smin_val = src_reg->smin_value;
13411 	u64 umin_val = src_reg->umin_value;
13412 
13413 	if (src_known && dst_known) {
13414 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13415 		return;
13416 	}
13417 
13418 	/* We get our maximum from the var_off, and our minimum is the
13419 	 * maximum of the operands' minima
13420 	 */
13421 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13422 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13423 	if (dst_reg->smin_value < 0 || smin_val < 0) {
13424 		/* Lose signed bounds when ORing negative numbers,
13425 		 * ain't nobody got time for that.
13426 		 */
13427 		dst_reg->smin_value = S64_MIN;
13428 		dst_reg->smax_value = S64_MAX;
13429 	} else {
13430 		/* ORing two positives gives a positive, so safe to
13431 		 * cast result into s64.
13432 		 */
13433 		dst_reg->smin_value = dst_reg->umin_value;
13434 		dst_reg->smax_value = dst_reg->umax_value;
13435 	}
13436 	/* We may learn something more from the var_off */
13437 	__update_reg_bounds(dst_reg);
13438 }
13439 
13440 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13441 				 struct bpf_reg_state *src_reg)
13442 {
13443 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13444 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13445 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13446 	s32 smin_val = src_reg->s32_min_value;
13447 
13448 	if (src_known && dst_known) {
13449 		__mark_reg32_known(dst_reg, var32_off.value);
13450 		return;
13451 	}
13452 
13453 	/* We get both minimum and maximum from the var32_off. */
13454 	dst_reg->u32_min_value = var32_off.value;
13455 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13456 
13457 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13458 		/* XORing two positive sign numbers gives a positive,
13459 		 * so safe to cast u32 result into s32.
13460 		 */
13461 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13462 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13463 	} else {
13464 		dst_reg->s32_min_value = S32_MIN;
13465 		dst_reg->s32_max_value = S32_MAX;
13466 	}
13467 }
13468 
13469 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13470 			       struct bpf_reg_state *src_reg)
13471 {
13472 	bool src_known = tnum_is_const(src_reg->var_off);
13473 	bool dst_known = tnum_is_const(dst_reg->var_off);
13474 	s64 smin_val = src_reg->smin_value;
13475 
13476 	if (src_known && dst_known) {
13477 		/* dst_reg->var_off.value has been updated earlier */
13478 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13479 		return;
13480 	}
13481 
13482 	/* We get both minimum and maximum from the var_off. */
13483 	dst_reg->umin_value = dst_reg->var_off.value;
13484 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13485 
13486 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13487 		/* XORing two positive sign numbers gives a positive,
13488 		 * so safe to cast u64 result into s64.
13489 		 */
13490 		dst_reg->smin_value = dst_reg->umin_value;
13491 		dst_reg->smax_value = dst_reg->umax_value;
13492 	} else {
13493 		dst_reg->smin_value = S64_MIN;
13494 		dst_reg->smax_value = S64_MAX;
13495 	}
13496 
13497 	__update_reg_bounds(dst_reg);
13498 }
13499 
13500 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13501 				   u64 umin_val, u64 umax_val)
13502 {
13503 	/* We lose all sign bit information (except what we can pick
13504 	 * up from var_off)
13505 	 */
13506 	dst_reg->s32_min_value = S32_MIN;
13507 	dst_reg->s32_max_value = S32_MAX;
13508 	/* If we might shift our top bit out, then we know nothing */
13509 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13510 		dst_reg->u32_min_value = 0;
13511 		dst_reg->u32_max_value = U32_MAX;
13512 	} else {
13513 		dst_reg->u32_min_value <<= umin_val;
13514 		dst_reg->u32_max_value <<= umax_val;
13515 	}
13516 }
13517 
13518 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13519 				 struct bpf_reg_state *src_reg)
13520 {
13521 	u32 umax_val = src_reg->u32_max_value;
13522 	u32 umin_val = src_reg->u32_min_value;
13523 	/* u32 alu operation will zext upper bits */
13524 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13525 
13526 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13527 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13528 	/* Not required but being careful mark reg64 bounds as unknown so
13529 	 * that we are forced to pick them up from tnum and zext later and
13530 	 * if some path skips this step we are still safe.
13531 	 */
13532 	__mark_reg64_unbounded(dst_reg);
13533 	__update_reg32_bounds(dst_reg);
13534 }
13535 
13536 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13537 				   u64 umin_val, u64 umax_val)
13538 {
13539 	/* Special case <<32 because it is a common compiler pattern to sign
13540 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13541 	 * positive we know this shift will also be positive so we can track
13542 	 * bounds correctly. Otherwise we lose all sign bit information except
13543 	 * what we can pick up from var_off. Perhaps we can generalize this
13544 	 * later to shifts of any length.
13545 	 */
13546 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13547 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13548 	else
13549 		dst_reg->smax_value = S64_MAX;
13550 
13551 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13552 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13553 	else
13554 		dst_reg->smin_value = S64_MIN;
13555 
13556 	/* If we might shift our top bit out, then we know nothing */
13557 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13558 		dst_reg->umin_value = 0;
13559 		dst_reg->umax_value = U64_MAX;
13560 	} else {
13561 		dst_reg->umin_value <<= umin_val;
13562 		dst_reg->umax_value <<= umax_val;
13563 	}
13564 }
13565 
13566 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13567 			       struct bpf_reg_state *src_reg)
13568 {
13569 	u64 umax_val = src_reg->umax_value;
13570 	u64 umin_val = src_reg->umin_value;
13571 
13572 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13573 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13574 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13575 
13576 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13577 	/* We may learn something more from the var_off */
13578 	__update_reg_bounds(dst_reg);
13579 }
13580 
13581 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13582 				 struct bpf_reg_state *src_reg)
13583 {
13584 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13585 	u32 umax_val = src_reg->u32_max_value;
13586 	u32 umin_val = src_reg->u32_min_value;
13587 
13588 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13589 	 * be negative, then either:
13590 	 * 1) src_reg might be zero, so the sign bit of the result is
13591 	 *    unknown, so we lose our signed bounds
13592 	 * 2) it's known negative, thus the unsigned bounds capture the
13593 	 *    signed bounds
13594 	 * 3) the signed bounds cross zero, so they tell us nothing
13595 	 *    about the result
13596 	 * If the value in dst_reg is known nonnegative, then again the
13597 	 * unsigned bounds capture the signed bounds.
13598 	 * Thus, in all cases it suffices to blow away our signed bounds
13599 	 * and rely on inferring new ones from the unsigned bounds and
13600 	 * var_off of the result.
13601 	 */
13602 	dst_reg->s32_min_value = S32_MIN;
13603 	dst_reg->s32_max_value = S32_MAX;
13604 
13605 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13606 	dst_reg->u32_min_value >>= umax_val;
13607 	dst_reg->u32_max_value >>= umin_val;
13608 
13609 	__mark_reg64_unbounded(dst_reg);
13610 	__update_reg32_bounds(dst_reg);
13611 }
13612 
13613 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13614 			       struct bpf_reg_state *src_reg)
13615 {
13616 	u64 umax_val = src_reg->umax_value;
13617 	u64 umin_val = src_reg->umin_value;
13618 
13619 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13620 	 * be negative, then either:
13621 	 * 1) src_reg might be zero, so the sign bit of the result is
13622 	 *    unknown, so we lose our signed bounds
13623 	 * 2) it's known negative, thus the unsigned bounds capture the
13624 	 *    signed bounds
13625 	 * 3) the signed bounds cross zero, so they tell us nothing
13626 	 *    about the result
13627 	 * If the value in dst_reg is known nonnegative, then again the
13628 	 * unsigned bounds capture the signed bounds.
13629 	 * Thus, in all cases it suffices to blow away our signed bounds
13630 	 * and rely on inferring new ones from the unsigned bounds and
13631 	 * var_off of the result.
13632 	 */
13633 	dst_reg->smin_value = S64_MIN;
13634 	dst_reg->smax_value = S64_MAX;
13635 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13636 	dst_reg->umin_value >>= umax_val;
13637 	dst_reg->umax_value >>= umin_val;
13638 
13639 	/* Its not easy to operate on alu32 bounds here because it depends
13640 	 * on bits being shifted in. Take easy way out and mark unbounded
13641 	 * so we can recalculate later from tnum.
13642 	 */
13643 	__mark_reg32_unbounded(dst_reg);
13644 	__update_reg_bounds(dst_reg);
13645 }
13646 
13647 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13648 				  struct bpf_reg_state *src_reg)
13649 {
13650 	u64 umin_val = src_reg->u32_min_value;
13651 
13652 	/* Upon reaching here, src_known is true and
13653 	 * umax_val is equal to umin_val.
13654 	 */
13655 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13656 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13657 
13658 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13659 
13660 	/* blow away the dst_reg umin_value/umax_value and rely on
13661 	 * dst_reg var_off to refine the result.
13662 	 */
13663 	dst_reg->u32_min_value = 0;
13664 	dst_reg->u32_max_value = U32_MAX;
13665 
13666 	__mark_reg64_unbounded(dst_reg);
13667 	__update_reg32_bounds(dst_reg);
13668 }
13669 
13670 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13671 				struct bpf_reg_state *src_reg)
13672 {
13673 	u64 umin_val = src_reg->umin_value;
13674 
13675 	/* Upon reaching here, src_known is true and umax_val is equal
13676 	 * to umin_val.
13677 	 */
13678 	dst_reg->smin_value >>= umin_val;
13679 	dst_reg->smax_value >>= umin_val;
13680 
13681 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13682 
13683 	/* blow away the dst_reg umin_value/umax_value and rely on
13684 	 * dst_reg var_off to refine the result.
13685 	 */
13686 	dst_reg->umin_value = 0;
13687 	dst_reg->umax_value = U64_MAX;
13688 
13689 	/* Its not easy to operate on alu32 bounds here because it depends
13690 	 * on bits being shifted in from upper 32-bits. Take easy way out
13691 	 * and mark unbounded so we can recalculate later from tnum.
13692 	 */
13693 	__mark_reg32_unbounded(dst_reg);
13694 	__update_reg_bounds(dst_reg);
13695 }
13696 
13697 /* WARNING: This function does calculations on 64-bit values, but the actual
13698  * execution may occur on 32-bit values. Therefore, things like bitshifts
13699  * need extra checks in the 32-bit case.
13700  */
13701 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13702 				      struct bpf_insn *insn,
13703 				      struct bpf_reg_state *dst_reg,
13704 				      struct bpf_reg_state src_reg)
13705 {
13706 	struct bpf_reg_state *regs = cur_regs(env);
13707 	u8 opcode = BPF_OP(insn->code);
13708 	bool src_known;
13709 	s64 smin_val, smax_val;
13710 	u64 umin_val, umax_val;
13711 	s32 s32_min_val, s32_max_val;
13712 	u32 u32_min_val, u32_max_val;
13713 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13714 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13715 	int ret;
13716 
13717 	smin_val = src_reg.smin_value;
13718 	smax_val = src_reg.smax_value;
13719 	umin_val = src_reg.umin_value;
13720 	umax_val = src_reg.umax_value;
13721 
13722 	s32_min_val = src_reg.s32_min_value;
13723 	s32_max_val = src_reg.s32_max_value;
13724 	u32_min_val = src_reg.u32_min_value;
13725 	u32_max_val = src_reg.u32_max_value;
13726 
13727 	if (alu32) {
13728 		src_known = tnum_subreg_is_const(src_reg.var_off);
13729 		if ((src_known &&
13730 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13731 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13732 			/* Taint dst register if offset had invalid bounds
13733 			 * derived from e.g. dead branches.
13734 			 */
13735 			__mark_reg_unknown(env, dst_reg);
13736 			return 0;
13737 		}
13738 	} else {
13739 		src_known = tnum_is_const(src_reg.var_off);
13740 		if ((src_known &&
13741 		     (smin_val != smax_val || umin_val != umax_val)) ||
13742 		    smin_val > smax_val || umin_val > umax_val) {
13743 			/* Taint dst register if offset had invalid bounds
13744 			 * derived from e.g. dead branches.
13745 			 */
13746 			__mark_reg_unknown(env, dst_reg);
13747 			return 0;
13748 		}
13749 	}
13750 
13751 	if (!src_known &&
13752 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13753 		__mark_reg_unknown(env, dst_reg);
13754 		return 0;
13755 	}
13756 
13757 	if (sanitize_needed(opcode)) {
13758 		ret = sanitize_val_alu(env, insn);
13759 		if (ret < 0)
13760 			return sanitize_err(env, insn, ret, NULL, NULL);
13761 	}
13762 
13763 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13764 	 * There are two classes of instructions: The first class we track both
13765 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13766 	 * greatest amount of precision when alu operations are mixed with jmp32
13767 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13768 	 * and BPF_OR. This is possible because these ops have fairly easy to
13769 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13770 	 * See alu32 verifier tests for examples. The second class of
13771 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13772 	 * with regards to tracking sign/unsigned bounds because the bits may
13773 	 * cross subreg boundaries in the alu64 case. When this happens we mark
13774 	 * the reg unbounded in the subreg bound space and use the resulting
13775 	 * tnum to calculate an approximation of the sign/unsigned bounds.
13776 	 */
13777 	switch (opcode) {
13778 	case BPF_ADD:
13779 		scalar32_min_max_add(dst_reg, &src_reg);
13780 		scalar_min_max_add(dst_reg, &src_reg);
13781 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13782 		break;
13783 	case BPF_SUB:
13784 		scalar32_min_max_sub(dst_reg, &src_reg);
13785 		scalar_min_max_sub(dst_reg, &src_reg);
13786 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13787 		break;
13788 	case BPF_MUL:
13789 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13790 		scalar32_min_max_mul(dst_reg, &src_reg);
13791 		scalar_min_max_mul(dst_reg, &src_reg);
13792 		break;
13793 	case BPF_AND:
13794 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13795 		scalar32_min_max_and(dst_reg, &src_reg);
13796 		scalar_min_max_and(dst_reg, &src_reg);
13797 		break;
13798 	case BPF_OR:
13799 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13800 		scalar32_min_max_or(dst_reg, &src_reg);
13801 		scalar_min_max_or(dst_reg, &src_reg);
13802 		break;
13803 	case BPF_XOR:
13804 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13805 		scalar32_min_max_xor(dst_reg, &src_reg);
13806 		scalar_min_max_xor(dst_reg, &src_reg);
13807 		break;
13808 	case BPF_LSH:
13809 		if (umax_val >= insn_bitness) {
13810 			/* Shifts greater than 31 or 63 are undefined.
13811 			 * This includes shifts by a negative number.
13812 			 */
13813 			mark_reg_unknown(env, regs, insn->dst_reg);
13814 			break;
13815 		}
13816 		if (alu32)
13817 			scalar32_min_max_lsh(dst_reg, &src_reg);
13818 		else
13819 			scalar_min_max_lsh(dst_reg, &src_reg);
13820 		break;
13821 	case BPF_RSH:
13822 		if (umax_val >= insn_bitness) {
13823 			/* Shifts greater than 31 or 63 are undefined.
13824 			 * This includes shifts by a negative number.
13825 			 */
13826 			mark_reg_unknown(env, regs, insn->dst_reg);
13827 			break;
13828 		}
13829 		if (alu32)
13830 			scalar32_min_max_rsh(dst_reg, &src_reg);
13831 		else
13832 			scalar_min_max_rsh(dst_reg, &src_reg);
13833 		break;
13834 	case BPF_ARSH:
13835 		if (umax_val >= insn_bitness) {
13836 			/* Shifts greater than 31 or 63 are undefined.
13837 			 * This includes shifts by a negative number.
13838 			 */
13839 			mark_reg_unknown(env, regs, insn->dst_reg);
13840 			break;
13841 		}
13842 		if (alu32)
13843 			scalar32_min_max_arsh(dst_reg, &src_reg);
13844 		else
13845 			scalar_min_max_arsh(dst_reg, &src_reg);
13846 		break;
13847 	default:
13848 		mark_reg_unknown(env, regs, insn->dst_reg);
13849 		break;
13850 	}
13851 
13852 	/* ALU32 ops are zero extended into 64bit register */
13853 	if (alu32)
13854 		zext_32_to_64(dst_reg);
13855 	reg_bounds_sync(dst_reg);
13856 	return 0;
13857 }
13858 
13859 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13860  * and var_off.
13861  */
13862 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13863 				   struct bpf_insn *insn)
13864 {
13865 	struct bpf_verifier_state *vstate = env->cur_state;
13866 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13867 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13868 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13869 	u8 opcode = BPF_OP(insn->code);
13870 	int err;
13871 
13872 	dst_reg = &regs[insn->dst_reg];
13873 	src_reg = NULL;
13874 
13875 	if (dst_reg->type == PTR_TO_ARENA) {
13876 		struct bpf_insn_aux_data *aux = cur_aux(env);
13877 
13878 		if (BPF_CLASS(insn->code) == BPF_ALU64)
13879 			/*
13880 			 * 32-bit operations zero upper bits automatically.
13881 			 * 64-bit operations need to be converted to 32.
13882 			 */
13883 			aux->needs_zext = true;
13884 
13885 		/* Any arithmetic operations are allowed on arena pointers */
13886 		return 0;
13887 	}
13888 
13889 	if (dst_reg->type != SCALAR_VALUE)
13890 		ptr_reg = dst_reg;
13891 	else
13892 		/* Make sure ID is cleared otherwise dst_reg min/max could be
13893 		 * incorrectly propagated into other registers by find_equal_scalars()
13894 		 */
13895 		dst_reg->id = 0;
13896 	if (BPF_SRC(insn->code) == BPF_X) {
13897 		src_reg = &regs[insn->src_reg];
13898 		if (src_reg->type != SCALAR_VALUE) {
13899 			if (dst_reg->type != SCALAR_VALUE) {
13900 				/* Combining two pointers by any ALU op yields
13901 				 * an arbitrary scalar. Disallow all math except
13902 				 * pointer subtraction
13903 				 */
13904 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13905 					mark_reg_unknown(env, regs, insn->dst_reg);
13906 					return 0;
13907 				}
13908 				verbose(env, "R%d pointer %s pointer prohibited\n",
13909 					insn->dst_reg,
13910 					bpf_alu_string[opcode >> 4]);
13911 				return -EACCES;
13912 			} else {
13913 				/* scalar += pointer
13914 				 * This is legal, but we have to reverse our
13915 				 * src/dest handling in computing the range
13916 				 */
13917 				err = mark_chain_precision(env, insn->dst_reg);
13918 				if (err)
13919 					return err;
13920 				return adjust_ptr_min_max_vals(env, insn,
13921 							       src_reg, dst_reg);
13922 			}
13923 		} else if (ptr_reg) {
13924 			/* pointer += scalar */
13925 			err = mark_chain_precision(env, insn->src_reg);
13926 			if (err)
13927 				return err;
13928 			return adjust_ptr_min_max_vals(env, insn,
13929 						       dst_reg, src_reg);
13930 		} else if (dst_reg->precise) {
13931 			/* if dst_reg is precise, src_reg should be precise as well */
13932 			err = mark_chain_precision(env, insn->src_reg);
13933 			if (err)
13934 				return err;
13935 		}
13936 	} else {
13937 		/* Pretend the src is a reg with a known value, since we only
13938 		 * need to be able to read from this state.
13939 		 */
13940 		off_reg.type = SCALAR_VALUE;
13941 		__mark_reg_known(&off_reg, insn->imm);
13942 		src_reg = &off_reg;
13943 		if (ptr_reg) /* pointer += K */
13944 			return adjust_ptr_min_max_vals(env, insn,
13945 						       ptr_reg, src_reg);
13946 	}
13947 
13948 	/* Got here implies adding two SCALAR_VALUEs */
13949 	if (WARN_ON_ONCE(ptr_reg)) {
13950 		print_verifier_state(env, state, true);
13951 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
13952 		return -EINVAL;
13953 	}
13954 	if (WARN_ON(!src_reg)) {
13955 		print_verifier_state(env, state, true);
13956 		verbose(env, "verifier internal error: no src_reg\n");
13957 		return -EINVAL;
13958 	}
13959 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13960 }
13961 
13962 /* check validity of 32-bit and 64-bit arithmetic operations */
13963 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13964 {
13965 	struct bpf_reg_state *regs = cur_regs(env);
13966 	u8 opcode = BPF_OP(insn->code);
13967 	int err;
13968 
13969 	if (opcode == BPF_END || opcode == BPF_NEG) {
13970 		if (opcode == BPF_NEG) {
13971 			if (BPF_SRC(insn->code) != BPF_K ||
13972 			    insn->src_reg != BPF_REG_0 ||
13973 			    insn->off != 0 || insn->imm != 0) {
13974 				verbose(env, "BPF_NEG uses reserved fields\n");
13975 				return -EINVAL;
13976 			}
13977 		} else {
13978 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13979 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13980 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
13981 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
13982 				verbose(env, "BPF_END uses reserved fields\n");
13983 				return -EINVAL;
13984 			}
13985 		}
13986 
13987 		/* check src operand */
13988 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13989 		if (err)
13990 			return err;
13991 
13992 		if (is_pointer_value(env, insn->dst_reg)) {
13993 			verbose(env, "R%d pointer arithmetic prohibited\n",
13994 				insn->dst_reg);
13995 			return -EACCES;
13996 		}
13997 
13998 		/* check dest operand */
13999 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
14000 		if (err)
14001 			return err;
14002 
14003 	} else if (opcode == BPF_MOV) {
14004 
14005 		if (BPF_SRC(insn->code) == BPF_X) {
14006 			if (BPF_CLASS(insn->code) == BPF_ALU) {
14007 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
14008 				    insn->imm) {
14009 					verbose(env, "BPF_MOV uses reserved fields\n");
14010 					return -EINVAL;
14011 				}
14012 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
14013 				if (insn->imm != 1 && insn->imm != 1u << 16) {
14014 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
14015 					return -EINVAL;
14016 				}
14017 			} else {
14018 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
14019 				     insn->off != 32) || insn->imm) {
14020 					verbose(env, "BPF_MOV uses reserved fields\n");
14021 					return -EINVAL;
14022 				}
14023 			}
14024 
14025 			/* check src operand */
14026 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14027 			if (err)
14028 				return err;
14029 		} else {
14030 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
14031 				verbose(env, "BPF_MOV uses reserved fields\n");
14032 				return -EINVAL;
14033 			}
14034 		}
14035 
14036 		/* check dest operand, mark as required later */
14037 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14038 		if (err)
14039 			return err;
14040 
14041 		if (BPF_SRC(insn->code) == BPF_X) {
14042 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
14043 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
14044 
14045 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
14046 				if (insn->imm) {
14047 					/* off == BPF_ADDR_SPACE_CAST */
14048 					mark_reg_unknown(env, regs, insn->dst_reg);
14049 					if (insn->imm == 1) /* cast from as(1) to as(0) */
14050 						dst_reg->type = PTR_TO_ARENA;
14051 				} else if (insn->off == 0) {
14052 					/* case: R1 = R2
14053 					 * copy register state to dest reg
14054 					 */
14055 					assign_scalar_id_before_mov(env, src_reg);
14056 					copy_register_state(dst_reg, src_reg);
14057 					dst_reg->live |= REG_LIVE_WRITTEN;
14058 					dst_reg->subreg_def = DEF_NOT_SUBREG;
14059 				} else {
14060 					/* case: R1 = (s8, s16 s32)R2 */
14061 					if (is_pointer_value(env, insn->src_reg)) {
14062 						verbose(env,
14063 							"R%d sign-extension part of pointer\n",
14064 							insn->src_reg);
14065 						return -EACCES;
14066 					} else if (src_reg->type == SCALAR_VALUE) {
14067 						bool no_sext;
14068 
14069 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14070 						if (no_sext)
14071 							assign_scalar_id_before_mov(env, src_reg);
14072 						copy_register_state(dst_reg, src_reg);
14073 						if (!no_sext)
14074 							dst_reg->id = 0;
14075 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
14076 						dst_reg->live |= REG_LIVE_WRITTEN;
14077 						dst_reg->subreg_def = DEF_NOT_SUBREG;
14078 					} else {
14079 						mark_reg_unknown(env, regs, insn->dst_reg);
14080 					}
14081 				}
14082 			} else {
14083 				/* R1 = (u32) R2 */
14084 				if (is_pointer_value(env, insn->src_reg)) {
14085 					verbose(env,
14086 						"R%d partial copy of pointer\n",
14087 						insn->src_reg);
14088 					return -EACCES;
14089 				} else if (src_reg->type == SCALAR_VALUE) {
14090 					if (insn->off == 0) {
14091 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
14092 
14093 						if (is_src_reg_u32)
14094 							assign_scalar_id_before_mov(env, src_reg);
14095 						copy_register_state(dst_reg, src_reg);
14096 						/* Make sure ID is cleared if src_reg is not in u32
14097 						 * range otherwise dst_reg min/max could be incorrectly
14098 						 * propagated into src_reg by find_equal_scalars()
14099 						 */
14100 						if (!is_src_reg_u32)
14101 							dst_reg->id = 0;
14102 						dst_reg->live |= REG_LIVE_WRITTEN;
14103 						dst_reg->subreg_def = env->insn_idx + 1;
14104 					} else {
14105 						/* case: W1 = (s8, s16)W2 */
14106 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14107 
14108 						if (no_sext)
14109 							assign_scalar_id_before_mov(env, src_reg);
14110 						copy_register_state(dst_reg, src_reg);
14111 						if (!no_sext)
14112 							dst_reg->id = 0;
14113 						dst_reg->live |= REG_LIVE_WRITTEN;
14114 						dst_reg->subreg_def = env->insn_idx + 1;
14115 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
14116 					}
14117 				} else {
14118 					mark_reg_unknown(env, regs,
14119 							 insn->dst_reg);
14120 				}
14121 				zext_32_to_64(dst_reg);
14122 				reg_bounds_sync(dst_reg);
14123 			}
14124 		} else {
14125 			/* case: R = imm
14126 			 * remember the value we stored into this reg
14127 			 */
14128 			/* clear any state __mark_reg_known doesn't set */
14129 			mark_reg_unknown(env, regs, insn->dst_reg);
14130 			regs[insn->dst_reg].type = SCALAR_VALUE;
14131 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
14132 				__mark_reg_known(regs + insn->dst_reg,
14133 						 insn->imm);
14134 			} else {
14135 				__mark_reg_known(regs + insn->dst_reg,
14136 						 (u32)insn->imm);
14137 			}
14138 		}
14139 
14140 	} else if (opcode > BPF_END) {
14141 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
14142 		return -EINVAL;
14143 
14144 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
14145 
14146 		if (BPF_SRC(insn->code) == BPF_X) {
14147 			if (insn->imm != 0 || insn->off > 1 ||
14148 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14149 				verbose(env, "BPF_ALU uses reserved fields\n");
14150 				return -EINVAL;
14151 			}
14152 			/* check src1 operand */
14153 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14154 			if (err)
14155 				return err;
14156 		} else {
14157 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
14158 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14159 				verbose(env, "BPF_ALU uses reserved fields\n");
14160 				return -EINVAL;
14161 			}
14162 		}
14163 
14164 		/* check src2 operand */
14165 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14166 		if (err)
14167 			return err;
14168 
14169 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
14170 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
14171 			verbose(env, "div by zero\n");
14172 			return -EINVAL;
14173 		}
14174 
14175 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
14176 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
14177 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
14178 
14179 			if (insn->imm < 0 || insn->imm >= size) {
14180 				verbose(env, "invalid shift %d\n", insn->imm);
14181 				return -EINVAL;
14182 			}
14183 		}
14184 
14185 		/* check dest operand */
14186 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14187 		err = err ?: adjust_reg_min_max_vals(env, insn);
14188 		if (err)
14189 			return err;
14190 	}
14191 
14192 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
14193 }
14194 
14195 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
14196 				   struct bpf_reg_state *dst_reg,
14197 				   enum bpf_reg_type type,
14198 				   bool range_right_open)
14199 {
14200 	struct bpf_func_state *state;
14201 	struct bpf_reg_state *reg;
14202 	int new_range;
14203 
14204 	if (dst_reg->off < 0 ||
14205 	    (dst_reg->off == 0 && range_right_open))
14206 		/* This doesn't give us any range */
14207 		return;
14208 
14209 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
14210 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
14211 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
14212 		 * than pkt_end, but that's because it's also less than pkt.
14213 		 */
14214 		return;
14215 
14216 	new_range = dst_reg->off;
14217 	if (range_right_open)
14218 		new_range++;
14219 
14220 	/* Examples for register markings:
14221 	 *
14222 	 * pkt_data in dst register:
14223 	 *
14224 	 *   r2 = r3;
14225 	 *   r2 += 8;
14226 	 *   if (r2 > pkt_end) goto <handle exception>
14227 	 *   <access okay>
14228 	 *
14229 	 *   r2 = r3;
14230 	 *   r2 += 8;
14231 	 *   if (r2 < pkt_end) goto <access okay>
14232 	 *   <handle exception>
14233 	 *
14234 	 *   Where:
14235 	 *     r2 == dst_reg, pkt_end == src_reg
14236 	 *     r2=pkt(id=n,off=8,r=0)
14237 	 *     r3=pkt(id=n,off=0,r=0)
14238 	 *
14239 	 * pkt_data in src register:
14240 	 *
14241 	 *   r2 = r3;
14242 	 *   r2 += 8;
14243 	 *   if (pkt_end >= r2) goto <access okay>
14244 	 *   <handle exception>
14245 	 *
14246 	 *   r2 = r3;
14247 	 *   r2 += 8;
14248 	 *   if (pkt_end <= r2) goto <handle exception>
14249 	 *   <access okay>
14250 	 *
14251 	 *   Where:
14252 	 *     pkt_end == dst_reg, r2 == src_reg
14253 	 *     r2=pkt(id=n,off=8,r=0)
14254 	 *     r3=pkt(id=n,off=0,r=0)
14255 	 *
14256 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
14257 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
14258 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
14259 	 * the check.
14260 	 */
14261 
14262 	/* If our ids match, then we must have the same max_value.  And we
14263 	 * don't care about the other reg's fixed offset, since if it's too big
14264 	 * the range won't allow anything.
14265 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
14266 	 */
14267 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14268 		if (reg->type == type && reg->id == dst_reg->id)
14269 			/* keep the maximum range already checked */
14270 			reg->range = max(reg->range, new_range);
14271 	}));
14272 }
14273 
14274 /*
14275  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
14276  */
14277 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14278 				  u8 opcode, bool is_jmp32)
14279 {
14280 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
14281 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
14282 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
14283 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
14284 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
14285 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
14286 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
14287 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
14288 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
14289 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
14290 
14291 	switch (opcode) {
14292 	case BPF_JEQ:
14293 		/* constants, umin/umax and smin/smax checks would be
14294 		 * redundant in this case because they all should match
14295 		 */
14296 		if (tnum_is_const(t1) && tnum_is_const(t2))
14297 			return t1.value == t2.value;
14298 		/* non-overlapping ranges */
14299 		if (umin1 > umax2 || umax1 < umin2)
14300 			return 0;
14301 		if (smin1 > smax2 || smax1 < smin2)
14302 			return 0;
14303 		if (!is_jmp32) {
14304 			/* if 64-bit ranges are inconclusive, see if we can
14305 			 * utilize 32-bit subrange knowledge to eliminate
14306 			 * branches that can't be taken a priori
14307 			 */
14308 			if (reg1->u32_min_value > reg2->u32_max_value ||
14309 			    reg1->u32_max_value < reg2->u32_min_value)
14310 				return 0;
14311 			if (reg1->s32_min_value > reg2->s32_max_value ||
14312 			    reg1->s32_max_value < reg2->s32_min_value)
14313 				return 0;
14314 		}
14315 		break;
14316 	case BPF_JNE:
14317 		/* constants, umin/umax and smin/smax checks would be
14318 		 * redundant in this case because they all should match
14319 		 */
14320 		if (tnum_is_const(t1) && tnum_is_const(t2))
14321 			return t1.value != t2.value;
14322 		/* non-overlapping ranges */
14323 		if (umin1 > umax2 || umax1 < umin2)
14324 			return 1;
14325 		if (smin1 > smax2 || smax1 < smin2)
14326 			return 1;
14327 		if (!is_jmp32) {
14328 			/* if 64-bit ranges are inconclusive, see if we can
14329 			 * utilize 32-bit subrange knowledge to eliminate
14330 			 * branches that can't be taken a priori
14331 			 */
14332 			if (reg1->u32_min_value > reg2->u32_max_value ||
14333 			    reg1->u32_max_value < reg2->u32_min_value)
14334 				return 1;
14335 			if (reg1->s32_min_value > reg2->s32_max_value ||
14336 			    reg1->s32_max_value < reg2->s32_min_value)
14337 				return 1;
14338 		}
14339 		break;
14340 	case BPF_JSET:
14341 		if (!is_reg_const(reg2, is_jmp32)) {
14342 			swap(reg1, reg2);
14343 			swap(t1, t2);
14344 		}
14345 		if (!is_reg_const(reg2, is_jmp32))
14346 			return -1;
14347 		if ((~t1.mask & t1.value) & t2.value)
14348 			return 1;
14349 		if (!((t1.mask | t1.value) & t2.value))
14350 			return 0;
14351 		break;
14352 	case BPF_JGT:
14353 		if (umin1 > umax2)
14354 			return 1;
14355 		else if (umax1 <= umin2)
14356 			return 0;
14357 		break;
14358 	case BPF_JSGT:
14359 		if (smin1 > smax2)
14360 			return 1;
14361 		else if (smax1 <= smin2)
14362 			return 0;
14363 		break;
14364 	case BPF_JLT:
14365 		if (umax1 < umin2)
14366 			return 1;
14367 		else if (umin1 >= umax2)
14368 			return 0;
14369 		break;
14370 	case BPF_JSLT:
14371 		if (smax1 < smin2)
14372 			return 1;
14373 		else if (smin1 >= smax2)
14374 			return 0;
14375 		break;
14376 	case BPF_JGE:
14377 		if (umin1 >= umax2)
14378 			return 1;
14379 		else if (umax1 < umin2)
14380 			return 0;
14381 		break;
14382 	case BPF_JSGE:
14383 		if (smin1 >= smax2)
14384 			return 1;
14385 		else if (smax1 < smin2)
14386 			return 0;
14387 		break;
14388 	case BPF_JLE:
14389 		if (umax1 <= umin2)
14390 			return 1;
14391 		else if (umin1 > umax2)
14392 			return 0;
14393 		break;
14394 	case BPF_JSLE:
14395 		if (smax1 <= smin2)
14396 			return 1;
14397 		else if (smin1 > smax2)
14398 			return 0;
14399 		break;
14400 	}
14401 
14402 	return -1;
14403 }
14404 
14405 static int flip_opcode(u32 opcode)
14406 {
14407 	/* How can we transform "a <op> b" into "b <op> a"? */
14408 	static const u8 opcode_flip[16] = {
14409 		/* these stay the same */
14410 		[BPF_JEQ  >> 4] = BPF_JEQ,
14411 		[BPF_JNE  >> 4] = BPF_JNE,
14412 		[BPF_JSET >> 4] = BPF_JSET,
14413 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14414 		[BPF_JGE  >> 4] = BPF_JLE,
14415 		[BPF_JGT  >> 4] = BPF_JLT,
14416 		[BPF_JLE  >> 4] = BPF_JGE,
14417 		[BPF_JLT  >> 4] = BPF_JGT,
14418 		[BPF_JSGE >> 4] = BPF_JSLE,
14419 		[BPF_JSGT >> 4] = BPF_JSLT,
14420 		[BPF_JSLE >> 4] = BPF_JSGE,
14421 		[BPF_JSLT >> 4] = BPF_JSGT
14422 	};
14423 	return opcode_flip[opcode >> 4];
14424 }
14425 
14426 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14427 				   struct bpf_reg_state *src_reg,
14428 				   u8 opcode)
14429 {
14430 	struct bpf_reg_state *pkt;
14431 
14432 	if (src_reg->type == PTR_TO_PACKET_END) {
14433 		pkt = dst_reg;
14434 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14435 		pkt = src_reg;
14436 		opcode = flip_opcode(opcode);
14437 	} else {
14438 		return -1;
14439 	}
14440 
14441 	if (pkt->range >= 0)
14442 		return -1;
14443 
14444 	switch (opcode) {
14445 	case BPF_JLE:
14446 		/* pkt <= pkt_end */
14447 		fallthrough;
14448 	case BPF_JGT:
14449 		/* pkt > pkt_end */
14450 		if (pkt->range == BEYOND_PKT_END)
14451 			/* pkt has at last one extra byte beyond pkt_end */
14452 			return opcode == BPF_JGT;
14453 		break;
14454 	case BPF_JLT:
14455 		/* pkt < pkt_end */
14456 		fallthrough;
14457 	case BPF_JGE:
14458 		/* pkt >= pkt_end */
14459 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14460 			return opcode == BPF_JGE;
14461 		break;
14462 	}
14463 	return -1;
14464 }
14465 
14466 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
14467  * and return:
14468  *  1 - branch will be taken and "goto target" will be executed
14469  *  0 - branch will not be taken and fall-through to next insn
14470  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
14471  *      range [0,10]
14472  */
14473 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14474 			   u8 opcode, bool is_jmp32)
14475 {
14476 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
14477 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
14478 
14479 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
14480 		u64 val;
14481 
14482 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
14483 		if (!is_reg_const(reg2, is_jmp32)) {
14484 			opcode = flip_opcode(opcode);
14485 			swap(reg1, reg2);
14486 		}
14487 		/* and ensure that reg2 is a constant */
14488 		if (!is_reg_const(reg2, is_jmp32))
14489 			return -1;
14490 
14491 		if (!reg_not_null(reg1))
14492 			return -1;
14493 
14494 		/* If pointer is valid tests against zero will fail so we can
14495 		 * use this to direct branch taken.
14496 		 */
14497 		val = reg_const_value(reg2, is_jmp32);
14498 		if (val != 0)
14499 			return -1;
14500 
14501 		switch (opcode) {
14502 		case BPF_JEQ:
14503 			return 0;
14504 		case BPF_JNE:
14505 			return 1;
14506 		default:
14507 			return -1;
14508 		}
14509 	}
14510 
14511 	/* now deal with two scalars, but not necessarily constants */
14512 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
14513 }
14514 
14515 /* Opcode that corresponds to a *false* branch condition.
14516  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
14517  */
14518 static u8 rev_opcode(u8 opcode)
14519 {
14520 	switch (opcode) {
14521 	case BPF_JEQ:		return BPF_JNE;
14522 	case BPF_JNE:		return BPF_JEQ;
14523 	/* JSET doesn't have it's reverse opcode in BPF, so add
14524 	 * BPF_X flag to denote the reverse of that operation
14525 	 */
14526 	case BPF_JSET:		return BPF_JSET | BPF_X;
14527 	case BPF_JSET | BPF_X:	return BPF_JSET;
14528 	case BPF_JGE:		return BPF_JLT;
14529 	case BPF_JGT:		return BPF_JLE;
14530 	case BPF_JLE:		return BPF_JGT;
14531 	case BPF_JLT:		return BPF_JGE;
14532 	case BPF_JSGE:		return BPF_JSLT;
14533 	case BPF_JSGT:		return BPF_JSLE;
14534 	case BPF_JSLE:		return BPF_JSGT;
14535 	case BPF_JSLT:		return BPF_JSGE;
14536 	default:		return 0;
14537 	}
14538 }
14539 
14540 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
14541 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14542 				u8 opcode, bool is_jmp32)
14543 {
14544 	struct tnum t;
14545 	u64 val;
14546 
14547 again:
14548 	switch (opcode) {
14549 	case BPF_JEQ:
14550 		if (is_jmp32) {
14551 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14552 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14553 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14554 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14555 			reg2->u32_min_value = reg1->u32_min_value;
14556 			reg2->u32_max_value = reg1->u32_max_value;
14557 			reg2->s32_min_value = reg1->s32_min_value;
14558 			reg2->s32_max_value = reg1->s32_max_value;
14559 
14560 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
14561 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14562 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
14563 		} else {
14564 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
14565 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14566 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
14567 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14568 			reg2->umin_value = reg1->umin_value;
14569 			reg2->umax_value = reg1->umax_value;
14570 			reg2->smin_value = reg1->smin_value;
14571 			reg2->smax_value = reg1->smax_value;
14572 
14573 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
14574 			reg2->var_off = reg1->var_off;
14575 		}
14576 		break;
14577 	case BPF_JNE:
14578 		if (!is_reg_const(reg2, is_jmp32))
14579 			swap(reg1, reg2);
14580 		if (!is_reg_const(reg2, is_jmp32))
14581 			break;
14582 
14583 		/* try to recompute the bound of reg1 if reg2 is a const and
14584 		 * is exactly the edge of reg1.
14585 		 */
14586 		val = reg_const_value(reg2, is_jmp32);
14587 		if (is_jmp32) {
14588 			/* u32_min_value is not equal to 0xffffffff at this point,
14589 			 * because otherwise u32_max_value is 0xffffffff as well,
14590 			 * in such a case both reg1 and reg2 would be constants,
14591 			 * jump would be predicted and reg_set_min_max() won't
14592 			 * be called.
14593 			 *
14594 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
14595 			 * below.
14596 			 */
14597 			if (reg1->u32_min_value == (u32)val)
14598 				reg1->u32_min_value++;
14599 			if (reg1->u32_max_value == (u32)val)
14600 				reg1->u32_max_value--;
14601 			if (reg1->s32_min_value == (s32)val)
14602 				reg1->s32_min_value++;
14603 			if (reg1->s32_max_value == (s32)val)
14604 				reg1->s32_max_value--;
14605 		} else {
14606 			if (reg1->umin_value == (u64)val)
14607 				reg1->umin_value++;
14608 			if (reg1->umax_value == (u64)val)
14609 				reg1->umax_value--;
14610 			if (reg1->smin_value == (s64)val)
14611 				reg1->smin_value++;
14612 			if (reg1->smax_value == (s64)val)
14613 				reg1->smax_value--;
14614 		}
14615 		break;
14616 	case BPF_JSET:
14617 		if (!is_reg_const(reg2, is_jmp32))
14618 			swap(reg1, reg2);
14619 		if (!is_reg_const(reg2, is_jmp32))
14620 			break;
14621 		val = reg_const_value(reg2, is_jmp32);
14622 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
14623 		 * requires single bit to learn something useful. E.g., if we
14624 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
14625 		 * are actually set? We can learn something definite only if
14626 		 * it's a single-bit value to begin with.
14627 		 *
14628 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
14629 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
14630 		 * bit 1 is set, which we can readily use in adjustments.
14631 		 */
14632 		if (!is_power_of_2(val))
14633 			break;
14634 		if (is_jmp32) {
14635 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
14636 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14637 		} else {
14638 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
14639 		}
14640 		break;
14641 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
14642 		if (!is_reg_const(reg2, is_jmp32))
14643 			swap(reg1, reg2);
14644 		if (!is_reg_const(reg2, is_jmp32))
14645 			break;
14646 		val = reg_const_value(reg2, is_jmp32);
14647 		if (is_jmp32) {
14648 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
14649 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14650 		} else {
14651 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
14652 		}
14653 		break;
14654 	case BPF_JLE:
14655 		if (is_jmp32) {
14656 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14657 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14658 		} else {
14659 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14660 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
14661 		}
14662 		break;
14663 	case BPF_JLT:
14664 		if (is_jmp32) {
14665 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
14666 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
14667 		} else {
14668 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
14669 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
14670 		}
14671 		break;
14672 	case BPF_JSLE:
14673 		if (is_jmp32) {
14674 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14675 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14676 		} else {
14677 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14678 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
14679 		}
14680 		break;
14681 	case BPF_JSLT:
14682 		if (is_jmp32) {
14683 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
14684 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
14685 		} else {
14686 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
14687 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
14688 		}
14689 		break;
14690 	case BPF_JGE:
14691 	case BPF_JGT:
14692 	case BPF_JSGE:
14693 	case BPF_JSGT:
14694 		/* just reuse LE/LT logic above */
14695 		opcode = flip_opcode(opcode);
14696 		swap(reg1, reg2);
14697 		goto again;
14698 	default:
14699 		return;
14700 	}
14701 }
14702 
14703 /* Adjusts the register min/max values in the case that the dst_reg and
14704  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
14705  * check, in which case we havea fake SCALAR_VALUE representing insn->imm).
14706  * Technically we can do similar adjustments for pointers to the same object,
14707  * but we don't support that right now.
14708  */
14709 static int reg_set_min_max(struct bpf_verifier_env *env,
14710 			   struct bpf_reg_state *true_reg1,
14711 			   struct bpf_reg_state *true_reg2,
14712 			   struct bpf_reg_state *false_reg1,
14713 			   struct bpf_reg_state *false_reg2,
14714 			   u8 opcode, bool is_jmp32)
14715 {
14716 	int err;
14717 
14718 	/* If either register is a pointer, we can't learn anything about its
14719 	 * variable offset from the compare (unless they were a pointer into
14720 	 * the same object, but we don't bother with that).
14721 	 */
14722 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
14723 		return 0;
14724 
14725 	/* fallthrough (FALSE) branch */
14726 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
14727 	reg_bounds_sync(false_reg1);
14728 	reg_bounds_sync(false_reg2);
14729 
14730 	/* jump (TRUE) branch */
14731 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
14732 	reg_bounds_sync(true_reg1);
14733 	reg_bounds_sync(true_reg2);
14734 
14735 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
14736 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
14737 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
14738 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
14739 	return err;
14740 }
14741 
14742 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14743 				 struct bpf_reg_state *reg, u32 id,
14744 				 bool is_null)
14745 {
14746 	if (type_may_be_null(reg->type) && reg->id == id &&
14747 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14748 		/* Old offset (both fixed and variable parts) should have been
14749 		 * known-zero, because we don't allow pointer arithmetic on
14750 		 * pointers that might be NULL. If we see this happening, don't
14751 		 * convert the register.
14752 		 *
14753 		 * But in some cases, some helpers that return local kptrs
14754 		 * advance offset for the returned pointer. In those cases, it
14755 		 * is fine to expect to see reg->off.
14756 		 */
14757 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14758 			return;
14759 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14760 		    WARN_ON_ONCE(reg->off))
14761 			return;
14762 
14763 		if (is_null) {
14764 			reg->type = SCALAR_VALUE;
14765 			/* We don't need id and ref_obj_id from this point
14766 			 * onwards anymore, thus we should better reset it,
14767 			 * so that state pruning has chances to take effect.
14768 			 */
14769 			reg->id = 0;
14770 			reg->ref_obj_id = 0;
14771 
14772 			return;
14773 		}
14774 
14775 		mark_ptr_not_null_reg(reg);
14776 
14777 		if (!reg_may_point_to_spin_lock(reg)) {
14778 			/* For not-NULL ptr, reg->ref_obj_id will be reset
14779 			 * in release_reference().
14780 			 *
14781 			 * reg->id is still used by spin_lock ptr. Other
14782 			 * than spin_lock ptr type, reg->id can be reset.
14783 			 */
14784 			reg->id = 0;
14785 		}
14786 	}
14787 }
14788 
14789 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14790  * be folded together at some point.
14791  */
14792 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14793 				  bool is_null)
14794 {
14795 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14796 	struct bpf_reg_state *regs = state->regs, *reg;
14797 	u32 ref_obj_id = regs[regno].ref_obj_id;
14798 	u32 id = regs[regno].id;
14799 
14800 	if (ref_obj_id && ref_obj_id == id && is_null)
14801 		/* regs[regno] is in the " == NULL" branch.
14802 		 * No one could have freed the reference state before
14803 		 * doing the NULL check.
14804 		 */
14805 		WARN_ON_ONCE(release_reference_state(state, id));
14806 
14807 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14808 		mark_ptr_or_null_reg(state, reg, id, is_null);
14809 	}));
14810 }
14811 
14812 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14813 				   struct bpf_reg_state *dst_reg,
14814 				   struct bpf_reg_state *src_reg,
14815 				   struct bpf_verifier_state *this_branch,
14816 				   struct bpf_verifier_state *other_branch)
14817 {
14818 	if (BPF_SRC(insn->code) != BPF_X)
14819 		return false;
14820 
14821 	/* Pointers are always 64-bit. */
14822 	if (BPF_CLASS(insn->code) == BPF_JMP32)
14823 		return false;
14824 
14825 	switch (BPF_OP(insn->code)) {
14826 	case BPF_JGT:
14827 		if ((dst_reg->type == PTR_TO_PACKET &&
14828 		     src_reg->type == PTR_TO_PACKET_END) ||
14829 		    (dst_reg->type == PTR_TO_PACKET_META &&
14830 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14831 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14832 			find_good_pkt_pointers(this_branch, dst_reg,
14833 					       dst_reg->type, false);
14834 			mark_pkt_end(other_branch, insn->dst_reg, true);
14835 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14836 			    src_reg->type == PTR_TO_PACKET) ||
14837 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14838 			    src_reg->type == PTR_TO_PACKET_META)) {
14839 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
14840 			find_good_pkt_pointers(other_branch, src_reg,
14841 					       src_reg->type, true);
14842 			mark_pkt_end(this_branch, insn->src_reg, false);
14843 		} else {
14844 			return false;
14845 		}
14846 		break;
14847 	case BPF_JLT:
14848 		if ((dst_reg->type == PTR_TO_PACKET &&
14849 		     src_reg->type == PTR_TO_PACKET_END) ||
14850 		    (dst_reg->type == PTR_TO_PACKET_META &&
14851 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14852 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14853 			find_good_pkt_pointers(other_branch, dst_reg,
14854 					       dst_reg->type, true);
14855 			mark_pkt_end(this_branch, insn->dst_reg, false);
14856 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14857 			    src_reg->type == PTR_TO_PACKET) ||
14858 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14859 			    src_reg->type == PTR_TO_PACKET_META)) {
14860 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
14861 			find_good_pkt_pointers(this_branch, src_reg,
14862 					       src_reg->type, false);
14863 			mark_pkt_end(other_branch, insn->src_reg, true);
14864 		} else {
14865 			return false;
14866 		}
14867 		break;
14868 	case BPF_JGE:
14869 		if ((dst_reg->type == PTR_TO_PACKET &&
14870 		     src_reg->type == PTR_TO_PACKET_END) ||
14871 		    (dst_reg->type == PTR_TO_PACKET_META &&
14872 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14873 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14874 			find_good_pkt_pointers(this_branch, dst_reg,
14875 					       dst_reg->type, true);
14876 			mark_pkt_end(other_branch, insn->dst_reg, false);
14877 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14878 			    src_reg->type == PTR_TO_PACKET) ||
14879 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14880 			    src_reg->type == PTR_TO_PACKET_META)) {
14881 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14882 			find_good_pkt_pointers(other_branch, src_reg,
14883 					       src_reg->type, false);
14884 			mark_pkt_end(this_branch, insn->src_reg, true);
14885 		} else {
14886 			return false;
14887 		}
14888 		break;
14889 	case BPF_JLE:
14890 		if ((dst_reg->type == PTR_TO_PACKET &&
14891 		     src_reg->type == PTR_TO_PACKET_END) ||
14892 		    (dst_reg->type == PTR_TO_PACKET_META &&
14893 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14894 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14895 			find_good_pkt_pointers(other_branch, dst_reg,
14896 					       dst_reg->type, false);
14897 			mark_pkt_end(this_branch, insn->dst_reg, true);
14898 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14899 			    src_reg->type == PTR_TO_PACKET) ||
14900 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14901 			    src_reg->type == PTR_TO_PACKET_META)) {
14902 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14903 			find_good_pkt_pointers(this_branch, src_reg,
14904 					       src_reg->type, true);
14905 			mark_pkt_end(other_branch, insn->src_reg, false);
14906 		} else {
14907 			return false;
14908 		}
14909 		break;
14910 	default:
14911 		return false;
14912 	}
14913 
14914 	return true;
14915 }
14916 
14917 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14918 			       struct bpf_reg_state *known_reg)
14919 {
14920 	struct bpf_func_state *state;
14921 	struct bpf_reg_state *reg;
14922 
14923 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14924 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14925 			copy_register_state(reg, known_reg);
14926 	}));
14927 }
14928 
14929 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14930 			     struct bpf_insn *insn, int *insn_idx)
14931 {
14932 	struct bpf_verifier_state *this_branch = env->cur_state;
14933 	struct bpf_verifier_state *other_branch;
14934 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14935 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14936 	struct bpf_reg_state *eq_branch_regs;
14937 	struct bpf_reg_state fake_reg = {};
14938 	u8 opcode = BPF_OP(insn->code);
14939 	bool is_jmp32;
14940 	int pred = -1;
14941 	int err;
14942 
14943 	/* Only conditional jumps are expected to reach here. */
14944 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
14945 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14946 		return -EINVAL;
14947 	}
14948 
14949 	if (opcode == BPF_JCOND) {
14950 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
14951 		int idx = *insn_idx;
14952 
14953 		if (insn->code != (BPF_JMP | BPF_JCOND) ||
14954 		    insn->src_reg != BPF_MAY_GOTO ||
14955 		    insn->dst_reg || insn->imm || insn->off == 0) {
14956 			verbose(env, "invalid may_goto off %d imm %d\n",
14957 				insn->off, insn->imm);
14958 			return -EINVAL;
14959 		}
14960 		prev_st = find_prev_entry(env, cur_st->parent, idx);
14961 
14962 		/* branch out 'fallthrough' insn as a new state to explore */
14963 		queued_st = push_stack(env, idx + 1, idx, false);
14964 		if (!queued_st)
14965 			return -ENOMEM;
14966 
14967 		queued_st->may_goto_depth++;
14968 		if (prev_st)
14969 			widen_imprecise_scalars(env, prev_st, queued_st);
14970 		*insn_idx += insn->off;
14971 		return 0;
14972 	}
14973 
14974 	/* check src2 operand */
14975 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14976 	if (err)
14977 		return err;
14978 
14979 	dst_reg = &regs[insn->dst_reg];
14980 	if (BPF_SRC(insn->code) == BPF_X) {
14981 		if (insn->imm != 0) {
14982 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14983 			return -EINVAL;
14984 		}
14985 
14986 		/* check src1 operand */
14987 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14988 		if (err)
14989 			return err;
14990 
14991 		src_reg = &regs[insn->src_reg];
14992 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14993 		    is_pointer_value(env, insn->src_reg)) {
14994 			verbose(env, "R%d pointer comparison prohibited\n",
14995 				insn->src_reg);
14996 			return -EACCES;
14997 		}
14998 	} else {
14999 		if (insn->src_reg != BPF_REG_0) {
15000 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
15001 			return -EINVAL;
15002 		}
15003 		src_reg = &fake_reg;
15004 		src_reg->type = SCALAR_VALUE;
15005 		__mark_reg_known(src_reg, insn->imm);
15006 	}
15007 
15008 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
15009 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
15010 	if (pred >= 0) {
15011 		/* If we get here with a dst_reg pointer type it is because
15012 		 * above is_branch_taken() special cased the 0 comparison.
15013 		 */
15014 		if (!__is_pointer_value(false, dst_reg))
15015 			err = mark_chain_precision(env, insn->dst_reg);
15016 		if (BPF_SRC(insn->code) == BPF_X && !err &&
15017 		    !__is_pointer_value(false, src_reg))
15018 			err = mark_chain_precision(env, insn->src_reg);
15019 		if (err)
15020 			return err;
15021 	}
15022 
15023 	if (pred == 1) {
15024 		/* Only follow the goto, ignore fall-through. If needed, push
15025 		 * the fall-through branch for simulation under speculative
15026 		 * execution.
15027 		 */
15028 		if (!env->bypass_spec_v1 &&
15029 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
15030 					       *insn_idx))
15031 			return -EFAULT;
15032 		if (env->log.level & BPF_LOG_LEVEL)
15033 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
15034 		*insn_idx += insn->off;
15035 		return 0;
15036 	} else if (pred == 0) {
15037 		/* Only follow the fall-through branch, since that's where the
15038 		 * program will go. If needed, push the goto branch for
15039 		 * simulation under speculative execution.
15040 		 */
15041 		if (!env->bypass_spec_v1 &&
15042 		    !sanitize_speculative_path(env, insn,
15043 					       *insn_idx + insn->off + 1,
15044 					       *insn_idx))
15045 			return -EFAULT;
15046 		if (env->log.level & BPF_LOG_LEVEL)
15047 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
15048 		return 0;
15049 	}
15050 
15051 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
15052 				  false);
15053 	if (!other_branch)
15054 		return -EFAULT;
15055 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
15056 
15057 	if (BPF_SRC(insn->code) == BPF_X) {
15058 		err = reg_set_min_max(env,
15059 				      &other_branch_regs[insn->dst_reg],
15060 				      &other_branch_regs[insn->src_reg],
15061 				      dst_reg, src_reg, opcode, is_jmp32);
15062 	} else /* BPF_SRC(insn->code) == BPF_K */ {
15063 		err = reg_set_min_max(env,
15064 				      &other_branch_regs[insn->dst_reg],
15065 				      src_reg /* fake one */,
15066 				      dst_reg, src_reg /* same fake one */,
15067 				      opcode, is_jmp32);
15068 	}
15069 	if (err)
15070 		return err;
15071 
15072 	if (BPF_SRC(insn->code) == BPF_X &&
15073 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
15074 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
15075 		find_equal_scalars(this_branch, src_reg);
15076 		find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
15077 	}
15078 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
15079 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
15080 		find_equal_scalars(this_branch, dst_reg);
15081 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
15082 	}
15083 
15084 	/* if one pointer register is compared to another pointer
15085 	 * register check if PTR_MAYBE_NULL could be lifted.
15086 	 * E.g. register A - maybe null
15087 	 *      register B - not null
15088 	 * for JNE A, B, ... - A is not null in the false branch;
15089 	 * for JEQ A, B, ... - A is not null in the true branch.
15090 	 *
15091 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
15092 	 * not need to be null checked by the BPF program, i.e.,
15093 	 * could be null even without PTR_MAYBE_NULL marking, so
15094 	 * only propagate nullness when neither reg is that type.
15095 	 */
15096 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
15097 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
15098 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
15099 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
15100 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
15101 		eq_branch_regs = NULL;
15102 		switch (opcode) {
15103 		case BPF_JEQ:
15104 			eq_branch_regs = other_branch_regs;
15105 			break;
15106 		case BPF_JNE:
15107 			eq_branch_regs = regs;
15108 			break;
15109 		default:
15110 			/* do nothing */
15111 			break;
15112 		}
15113 		if (eq_branch_regs) {
15114 			if (type_may_be_null(src_reg->type))
15115 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
15116 			else
15117 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
15118 		}
15119 	}
15120 
15121 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
15122 	 * NOTE: these optimizations below are related with pointer comparison
15123 	 *       which will never be JMP32.
15124 	 */
15125 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
15126 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
15127 	    type_may_be_null(dst_reg->type)) {
15128 		/* Mark all identical registers in each branch as either
15129 		 * safe or unknown depending R == 0 or R != 0 conditional.
15130 		 */
15131 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
15132 				      opcode == BPF_JNE);
15133 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
15134 				      opcode == BPF_JEQ);
15135 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
15136 					   this_branch, other_branch) &&
15137 		   is_pointer_value(env, insn->dst_reg)) {
15138 		verbose(env, "R%d pointer comparison prohibited\n",
15139 			insn->dst_reg);
15140 		return -EACCES;
15141 	}
15142 	if (env->log.level & BPF_LOG_LEVEL)
15143 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
15144 	return 0;
15145 }
15146 
15147 /* verify BPF_LD_IMM64 instruction */
15148 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
15149 {
15150 	struct bpf_insn_aux_data *aux = cur_aux(env);
15151 	struct bpf_reg_state *regs = cur_regs(env);
15152 	struct bpf_reg_state *dst_reg;
15153 	struct bpf_map *map;
15154 	int err;
15155 
15156 	if (BPF_SIZE(insn->code) != BPF_DW) {
15157 		verbose(env, "invalid BPF_LD_IMM insn\n");
15158 		return -EINVAL;
15159 	}
15160 	if (insn->off != 0) {
15161 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
15162 		return -EINVAL;
15163 	}
15164 
15165 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
15166 	if (err)
15167 		return err;
15168 
15169 	dst_reg = &regs[insn->dst_reg];
15170 	if (insn->src_reg == 0) {
15171 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
15172 
15173 		dst_reg->type = SCALAR_VALUE;
15174 		__mark_reg_known(&regs[insn->dst_reg], imm);
15175 		return 0;
15176 	}
15177 
15178 	/* All special src_reg cases are listed below. From this point onwards
15179 	 * we either succeed and assign a corresponding dst_reg->type after
15180 	 * zeroing the offset, or fail and reject the program.
15181 	 */
15182 	mark_reg_known_zero(env, regs, insn->dst_reg);
15183 
15184 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
15185 		dst_reg->type = aux->btf_var.reg_type;
15186 		switch (base_type(dst_reg->type)) {
15187 		case PTR_TO_MEM:
15188 			dst_reg->mem_size = aux->btf_var.mem_size;
15189 			break;
15190 		case PTR_TO_BTF_ID:
15191 			dst_reg->btf = aux->btf_var.btf;
15192 			dst_reg->btf_id = aux->btf_var.btf_id;
15193 			break;
15194 		default:
15195 			verbose(env, "bpf verifier is misconfigured\n");
15196 			return -EFAULT;
15197 		}
15198 		return 0;
15199 	}
15200 
15201 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
15202 		struct bpf_prog_aux *aux = env->prog->aux;
15203 		u32 subprogno = find_subprog(env,
15204 					     env->insn_idx + insn->imm + 1);
15205 
15206 		if (!aux->func_info) {
15207 			verbose(env, "missing btf func_info\n");
15208 			return -EINVAL;
15209 		}
15210 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
15211 			verbose(env, "callback function not static\n");
15212 			return -EINVAL;
15213 		}
15214 
15215 		dst_reg->type = PTR_TO_FUNC;
15216 		dst_reg->subprogno = subprogno;
15217 		return 0;
15218 	}
15219 
15220 	map = env->used_maps[aux->map_index];
15221 	dst_reg->map_ptr = map;
15222 
15223 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
15224 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
15225 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
15226 			__mark_reg_unknown(env, dst_reg);
15227 			return 0;
15228 		}
15229 		dst_reg->type = PTR_TO_MAP_VALUE;
15230 		dst_reg->off = aux->map_off;
15231 		WARN_ON_ONCE(map->max_entries != 1);
15232 		/* We want reg->id to be same (0) as map_value is not distinct */
15233 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
15234 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
15235 		dst_reg->type = CONST_PTR_TO_MAP;
15236 	} else {
15237 		verbose(env, "bpf verifier is misconfigured\n");
15238 		return -EINVAL;
15239 	}
15240 
15241 	return 0;
15242 }
15243 
15244 static bool may_access_skb(enum bpf_prog_type type)
15245 {
15246 	switch (type) {
15247 	case BPF_PROG_TYPE_SOCKET_FILTER:
15248 	case BPF_PROG_TYPE_SCHED_CLS:
15249 	case BPF_PROG_TYPE_SCHED_ACT:
15250 		return true;
15251 	default:
15252 		return false;
15253 	}
15254 }
15255 
15256 /* verify safety of LD_ABS|LD_IND instructions:
15257  * - they can only appear in the programs where ctx == skb
15258  * - since they are wrappers of function calls, they scratch R1-R5 registers,
15259  *   preserve R6-R9, and store return value into R0
15260  *
15261  * Implicit input:
15262  *   ctx == skb == R6 == CTX
15263  *
15264  * Explicit input:
15265  *   SRC == any register
15266  *   IMM == 32-bit immediate
15267  *
15268  * Output:
15269  *   R0 - 8/16/32-bit skb data converted to cpu endianness
15270  */
15271 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
15272 {
15273 	struct bpf_reg_state *regs = cur_regs(env);
15274 	static const int ctx_reg = BPF_REG_6;
15275 	u8 mode = BPF_MODE(insn->code);
15276 	int i, err;
15277 
15278 	if (!may_access_skb(resolve_prog_type(env->prog))) {
15279 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
15280 		return -EINVAL;
15281 	}
15282 
15283 	if (!env->ops->gen_ld_abs) {
15284 		verbose(env, "bpf verifier is misconfigured\n");
15285 		return -EINVAL;
15286 	}
15287 
15288 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
15289 	    BPF_SIZE(insn->code) == BPF_DW ||
15290 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
15291 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
15292 		return -EINVAL;
15293 	}
15294 
15295 	/* check whether implicit source operand (register R6) is readable */
15296 	err = check_reg_arg(env, ctx_reg, SRC_OP);
15297 	if (err)
15298 		return err;
15299 
15300 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
15301 	 * gen_ld_abs() may terminate the program at runtime, leading to
15302 	 * reference leak.
15303 	 */
15304 	err = check_reference_leak(env, false);
15305 	if (err) {
15306 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
15307 		return err;
15308 	}
15309 
15310 	if (env->cur_state->active_lock.ptr) {
15311 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
15312 		return -EINVAL;
15313 	}
15314 
15315 	if (env->cur_state->active_rcu_lock) {
15316 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
15317 		return -EINVAL;
15318 	}
15319 
15320 	if (regs[ctx_reg].type != PTR_TO_CTX) {
15321 		verbose(env,
15322 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
15323 		return -EINVAL;
15324 	}
15325 
15326 	if (mode == BPF_IND) {
15327 		/* check explicit source operand */
15328 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
15329 		if (err)
15330 			return err;
15331 	}
15332 
15333 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
15334 	if (err < 0)
15335 		return err;
15336 
15337 	/* reset caller saved regs to unreadable */
15338 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
15339 		mark_reg_not_init(env, regs, caller_saved[i]);
15340 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
15341 	}
15342 
15343 	/* mark destination R0 register as readable, since it contains
15344 	 * the value fetched from the packet.
15345 	 * Already marked as written above.
15346 	 */
15347 	mark_reg_unknown(env, regs, BPF_REG_0);
15348 	/* ld_abs load up to 32-bit skb data. */
15349 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
15350 	return 0;
15351 }
15352 
15353 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
15354 {
15355 	const char *exit_ctx = "At program exit";
15356 	struct tnum enforce_attach_type_range = tnum_unknown;
15357 	const struct bpf_prog *prog = env->prog;
15358 	struct bpf_reg_state *reg;
15359 	struct bpf_retval_range range = retval_range(0, 1);
15360 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15361 	int err;
15362 	struct bpf_func_state *frame = env->cur_state->frame[0];
15363 	const bool is_subprog = frame->subprogno;
15364 
15365 	/* LSM and struct_ops func-ptr's return type could be "void" */
15366 	if (!is_subprog || frame->in_exception_callback_fn) {
15367 		switch (prog_type) {
15368 		case BPF_PROG_TYPE_LSM:
15369 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
15370 				/* See below, can be 0 or 0-1 depending on hook. */
15371 				break;
15372 			fallthrough;
15373 		case BPF_PROG_TYPE_STRUCT_OPS:
15374 			if (!prog->aux->attach_func_proto->type)
15375 				return 0;
15376 			break;
15377 		default:
15378 			break;
15379 		}
15380 	}
15381 
15382 	/* eBPF calling convention is such that R0 is used
15383 	 * to return the value from eBPF program.
15384 	 * Make sure that it's readable at this time
15385 	 * of bpf_exit, which means that program wrote
15386 	 * something into it earlier
15387 	 */
15388 	err = check_reg_arg(env, regno, SRC_OP);
15389 	if (err)
15390 		return err;
15391 
15392 	if (is_pointer_value(env, regno)) {
15393 		verbose(env, "R%d leaks addr as return value\n", regno);
15394 		return -EACCES;
15395 	}
15396 
15397 	reg = cur_regs(env) + regno;
15398 
15399 	if (frame->in_async_callback_fn) {
15400 		/* enforce return zero from async callbacks like timer */
15401 		exit_ctx = "At async callback return";
15402 		range = retval_range(0, 0);
15403 		goto enforce_retval;
15404 	}
15405 
15406 	if (is_subprog && !frame->in_exception_callback_fn) {
15407 		if (reg->type != SCALAR_VALUE) {
15408 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
15409 				regno, reg_type_str(env, reg->type));
15410 			return -EINVAL;
15411 		}
15412 		return 0;
15413 	}
15414 
15415 	switch (prog_type) {
15416 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15417 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15418 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15419 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
15420 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15421 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15422 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
15423 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15424 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
15425 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
15426 			range = retval_range(1, 1);
15427 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15428 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15429 			range = retval_range(0, 3);
15430 		break;
15431 	case BPF_PROG_TYPE_CGROUP_SKB:
15432 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15433 			range = retval_range(0, 3);
15434 			enforce_attach_type_range = tnum_range(2, 3);
15435 		}
15436 		break;
15437 	case BPF_PROG_TYPE_CGROUP_SOCK:
15438 	case BPF_PROG_TYPE_SOCK_OPS:
15439 	case BPF_PROG_TYPE_CGROUP_DEVICE:
15440 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15441 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15442 		break;
15443 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15444 		if (!env->prog->aux->attach_btf_id)
15445 			return 0;
15446 		range = retval_range(0, 0);
15447 		break;
15448 	case BPF_PROG_TYPE_TRACING:
15449 		switch (env->prog->expected_attach_type) {
15450 		case BPF_TRACE_FENTRY:
15451 		case BPF_TRACE_FEXIT:
15452 			range = retval_range(0, 0);
15453 			break;
15454 		case BPF_TRACE_RAW_TP:
15455 		case BPF_MODIFY_RETURN:
15456 			return 0;
15457 		case BPF_TRACE_ITER:
15458 			break;
15459 		default:
15460 			return -ENOTSUPP;
15461 		}
15462 		break;
15463 	case BPF_PROG_TYPE_SK_LOOKUP:
15464 		range = retval_range(SK_DROP, SK_PASS);
15465 		break;
15466 
15467 	case BPF_PROG_TYPE_LSM:
15468 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15469 			/* Regular BPF_PROG_TYPE_LSM programs can return
15470 			 * any value.
15471 			 */
15472 			return 0;
15473 		}
15474 		if (!env->prog->aux->attach_func_proto->type) {
15475 			/* Make sure programs that attach to void
15476 			 * hooks don't try to modify return value.
15477 			 */
15478 			range = retval_range(1, 1);
15479 		}
15480 		break;
15481 
15482 	case BPF_PROG_TYPE_NETFILTER:
15483 		range = retval_range(NF_DROP, NF_ACCEPT);
15484 		break;
15485 	case BPF_PROG_TYPE_EXT:
15486 		/* freplace program can return anything as its return value
15487 		 * depends on the to-be-replaced kernel func or bpf program.
15488 		 */
15489 	default:
15490 		return 0;
15491 	}
15492 
15493 enforce_retval:
15494 	if (reg->type != SCALAR_VALUE) {
15495 		verbose(env, "%s the register R%d is not a known value (%s)\n",
15496 			exit_ctx, regno, reg_type_str(env, reg->type));
15497 		return -EINVAL;
15498 	}
15499 
15500 	err = mark_chain_precision(env, regno);
15501 	if (err)
15502 		return err;
15503 
15504 	if (!retval_range_within(range, reg)) {
15505 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
15506 		if (!is_subprog &&
15507 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
15508 		    prog_type == BPF_PROG_TYPE_LSM &&
15509 		    !prog->aux->attach_func_proto->type)
15510 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15511 		return -EINVAL;
15512 	}
15513 
15514 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15515 	    tnum_in(enforce_attach_type_range, reg->var_off))
15516 		env->prog->enforce_expected_attach_type = 1;
15517 	return 0;
15518 }
15519 
15520 /* non-recursive DFS pseudo code
15521  * 1  procedure DFS-iterative(G,v):
15522  * 2      label v as discovered
15523  * 3      let S be a stack
15524  * 4      S.push(v)
15525  * 5      while S is not empty
15526  * 6            t <- S.peek()
15527  * 7            if t is what we're looking for:
15528  * 8                return t
15529  * 9            for all edges e in G.adjacentEdges(t) do
15530  * 10               if edge e is already labelled
15531  * 11                   continue with the next edge
15532  * 12               w <- G.adjacentVertex(t,e)
15533  * 13               if vertex w is not discovered and not explored
15534  * 14                   label e as tree-edge
15535  * 15                   label w as discovered
15536  * 16                   S.push(w)
15537  * 17                   continue at 5
15538  * 18               else if vertex w is discovered
15539  * 19                   label e as back-edge
15540  * 20               else
15541  * 21                   // vertex w is explored
15542  * 22                   label e as forward- or cross-edge
15543  * 23           label t as explored
15544  * 24           S.pop()
15545  *
15546  * convention:
15547  * 0x10 - discovered
15548  * 0x11 - discovered and fall-through edge labelled
15549  * 0x12 - discovered and fall-through and branch edges labelled
15550  * 0x20 - explored
15551  */
15552 
15553 enum {
15554 	DISCOVERED = 0x10,
15555 	EXPLORED = 0x20,
15556 	FALLTHROUGH = 1,
15557 	BRANCH = 2,
15558 };
15559 
15560 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15561 {
15562 	env->insn_aux_data[idx].prune_point = true;
15563 }
15564 
15565 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15566 {
15567 	return env->insn_aux_data[insn_idx].prune_point;
15568 }
15569 
15570 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15571 {
15572 	env->insn_aux_data[idx].force_checkpoint = true;
15573 }
15574 
15575 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15576 {
15577 	return env->insn_aux_data[insn_idx].force_checkpoint;
15578 }
15579 
15580 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15581 {
15582 	env->insn_aux_data[idx].calls_callback = true;
15583 }
15584 
15585 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15586 {
15587 	return env->insn_aux_data[insn_idx].calls_callback;
15588 }
15589 
15590 enum {
15591 	DONE_EXPLORING = 0,
15592 	KEEP_EXPLORING = 1,
15593 };
15594 
15595 /* t, w, e - match pseudo-code above:
15596  * t - index of current instruction
15597  * w - next instruction
15598  * e - edge
15599  */
15600 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15601 {
15602 	int *insn_stack = env->cfg.insn_stack;
15603 	int *insn_state = env->cfg.insn_state;
15604 
15605 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15606 		return DONE_EXPLORING;
15607 
15608 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15609 		return DONE_EXPLORING;
15610 
15611 	if (w < 0 || w >= env->prog->len) {
15612 		verbose_linfo(env, t, "%d: ", t);
15613 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15614 		return -EINVAL;
15615 	}
15616 
15617 	if (e == BRANCH) {
15618 		/* mark branch target for state pruning */
15619 		mark_prune_point(env, w);
15620 		mark_jmp_point(env, w);
15621 	}
15622 
15623 	if (insn_state[w] == 0) {
15624 		/* tree-edge */
15625 		insn_state[t] = DISCOVERED | e;
15626 		insn_state[w] = DISCOVERED;
15627 		if (env->cfg.cur_stack >= env->prog->len)
15628 			return -E2BIG;
15629 		insn_stack[env->cfg.cur_stack++] = w;
15630 		return KEEP_EXPLORING;
15631 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15632 		if (env->bpf_capable)
15633 			return DONE_EXPLORING;
15634 		verbose_linfo(env, t, "%d: ", t);
15635 		verbose_linfo(env, w, "%d: ", w);
15636 		verbose(env, "back-edge from insn %d to %d\n", t, w);
15637 		return -EINVAL;
15638 	} else if (insn_state[w] == EXPLORED) {
15639 		/* forward- or cross-edge */
15640 		insn_state[t] = DISCOVERED | e;
15641 	} else {
15642 		verbose(env, "insn state internal bug\n");
15643 		return -EFAULT;
15644 	}
15645 	return DONE_EXPLORING;
15646 }
15647 
15648 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15649 				struct bpf_verifier_env *env,
15650 				bool visit_callee)
15651 {
15652 	int ret, insn_sz;
15653 
15654 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15655 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15656 	if (ret)
15657 		return ret;
15658 
15659 	mark_prune_point(env, t + insn_sz);
15660 	/* when we exit from subprog, we need to record non-linear history */
15661 	mark_jmp_point(env, t + insn_sz);
15662 
15663 	if (visit_callee) {
15664 		mark_prune_point(env, t);
15665 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15666 	}
15667 	return ret;
15668 }
15669 
15670 /* Visits the instruction at index t and returns one of the following:
15671  *  < 0 - an error occurred
15672  *  DONE_EXPLORING - the instruction was fully explored
15673  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15674  */
15675 static int visit_insn(int t, struct bpf_verifier_env *env)
15676 {
15677 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15678 	int ret, off, insn_sz;
15679 
15680 	if (bpf_pseudo_func(insn))
15681 		return visit_func_call_insn(t, insns, env, true);
15682 
15683 	/* All non-branch instructions have a single fall-through edge. */
15684 	if (BPF_CLASS(insn->code) != BPF_JMP &&
15685 	    BPF_CLASS(insn->code) != BPF_JMP32) {
15686 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15687 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15688 	}
15689 
15690 	switch (BPF_OP(insn->code)) {
15691 	case BPF_EXIT:
15692 		return DONE_EXPLORING;
15693 
15694 	case BPF_CALL:
15695 		if (is_async_callback_calling_insn(insn))
15696 			/* Mark this call insn as a prune point to trigger
15697 			 * is_state_visited() check before call itself is
15698 			 * processed by __check_func_call(). Otherwise new
15699 			 * async state will be pushed for further exploration.
15700 			 */
15701 			mark_prune_point(env, t);
15702 		/* For functions that invoke callbacks it is not known how many times
15703 		 * callback would be called. Verifier models callback calling functions
15704 		 * by repeatedly visiting callback bodies and returning to origin call
15705 		 * instruction.
15706 		 * In order to stop such iteration verifier needs to identify when a
15707 		 * state identical some state from a previous iteration is reached.
15708 		 * Check below forces creation of checkpoint before callback calling
15709 		 * instruction to allow search for such identical states.
15710 		 */
15711 		if (is_sync_callback_calling_insn(insn)) {
15712 			mark_calls_callback(env, t);
15713 			mark_force_checkpoint(env, t);
15714 			mark_prune_point(env, t);
15715 			mark_jmp_point(env, t);
15716 		}
15717 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15718 			struct bpf_kfunc_call_arg_meta meta;
15719 
15720 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15721 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15722 				mark_prune_point(env, t);
15723 				/* Checking and saving state checkpoints at iter_next() call
15724 				 * is crucial for fast convergence of open-coded iterator loop
15725 				 * logic, so we need to force it. If we don't do that,
15726 				 * is_state_visited() might skip saving a checkpoint, causing
15727 				 * unnecessarily long sequence of not checkpointed
15728 				 * instructions and jumps, leading to exhaustion of jump
15729 				 * history buffer, and potentially other undesired outcomes.
15730 				 * It is expected that with correct open-coded iterators
15731 				 * convergence will happen quickly, so we don't run a risk of
15732 				 * exhausting memory.
15733 				 */
15734 				mark_force_checkpoint(env, t);
15735 			}
15736 		}
15737 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15738 
15739 	case BPF_JA:
15740 		if (BPF_SRC(insn->code) != BPF_K)
15741 			return -EINVAL;
15742 
15743 		if (BPF_CLASS(insn->code) == BPF_JMP)
15744 			off = insn->off;
15745 		else
15746 			off = insn->imm;
15747 
15748 		/* unconditional jump with single edge */
15749 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15750 		if (ret)
15751 			return ret;
15752 
15753 		mark_prune_point(env, t + off + 1);
15754 		mark_jmp_point(env, t + off + 1);
15755 
15756 		return ret;
15757 
15758 	default:
15759 		/* conditional jump with two edges */
15760 		mark_prune_point(env, t);
15761 		if (is_may_goto_insn(insn))
15762 			mark_force_checkpoint(env, t);
15763 
15764 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15765 		if (ret)
15766 			return ret;
15767 
15768 		return push_insn(t, t + insn->off + 1, BRANCH, env);
15769 	}
15770 }
15771 
15772 /* non-recursive depth-first-search to detect loops in BPF program
15773  * loop == back-edge in directed graph
15774  */
15775 static int check_cfg(struct bpf_verifier_env *env)
15776 {
15777 	int insn_cnt = env->prog->len;
15778 	int *insn_stack, *insn_state;
15779 	int ex_insn_beg, i, ret = 0;
15780 	bool ex_done = false;
15781 
15782 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15783 	if (!insn_state)
15784 		return -ENOMEM;
15785 
15786 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15787 	if (!insn_stack) {
15788 		kvfree(insn_state);
15789 		return -ENOMEM;
15790 	}
15791 
15792 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15793 	insn_stack[0] = 0; /* 0 is the first instruction */
15794 	env->cfg.cur_stack = 1;
15795 
15796 walk_cfg:
15797 	while (env->cfg.cur_stack > 0) {
15798 		int t = insn_stack[env->cfg.cur_stack - 1];
15799 
15800 		ret = visit_insn(t, env);
15801 		switch (ret) {
15802 		case DONE_EXPLORING:
15803 			insn_state[t] = EXPLORED;
15804 			env->cfg.cur_stack--;
15805 			break;
15806 		case KEEP_EXPLORING:
15807 			break;
15808 		default:
15809 			if (ret > 0) {
15810 				verbose(env, "visit_insn internal bug\n");
15811 				ret = -EFAULT;
15812 			}
15813 			goto err_free;
15814 		}
15815 	}
15816 
15817 	if (env->cfg.cur_stack < 0) {
15818 		verbose(env, "pop stack internal bug\n");
15819 		ret = -EFAULT;
15820 		goto err_free;
15821 	}
15822 
15823 	if (env->exception_callback_subprog && !ex_done) {
15824 		ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
15825 
15826 		insn_state[ex_insn_beg] = DISCOVERED;
15827 		insn_stack[0] = ex_insn_beg;
15828 		env->cfg.cur_stack = 1;
15829 		ex_done = true;
15830 		goto walk_cfg;
15831 	}
15832 
15833 	for (i = 0; i < insn_cnt; i++) {
15834 		struct bpf_insn *insn = &env->prog->insnsi[i];
15835 
15836 		if (insn_state[i] != EXPLORED) {
15837 			verbose(env, "unreachable insn %d\n", i);
15838 			ret = -EINVAL;
15839 			goto err_free;
15840 		}
15841 		if (bpf_is_ldimm64(insn)) {
15842 			if (insn_state[i + 1] != 0) {
15843 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15844 				ret = -EINVAL;
15845 				goto err_free;
15846 			}
15847 			i++; /* skip second half of ldimm64 */
15848 		}
15849 	}
15850 	ret = 0; /* cfg looks good */
15851 
15852 err_free:
15853 	kvfree(insn_state);
15854 	kvfree(insn_stack);
15855 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
15856 	return ret;
15857 }
15858 
15859 static int check_abnormal_return(struct bpf_verifier_env *env)
15860 {
15861 	int i;
15862 
15863 	for (i = 1; i < env->subprog_cnt; i++) {
15864 		if (env->subprog_info[i].has_ld_abs) {
15865 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15866 			return -EINVAL;
15867 		}
15868 		if (env->subprog_info[i].has_tail_call) {
15869 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15870 			return -EINVAL;
15871 		}
15872 	}
15873 	return 0;
15874 }
15875 
15876 /* The minimum supported BTF func info size */
15877 #define MIN_BPF_FUNCINFO_SIZE	8
15878 #define MAX_FUNCINFO_REC_SIZE	252
15879 
15880 static int check_btf_func_early(struct bpf_verifier_env *env,
15881 				const union bpf_attr *attr,
15882 				bpfptr_t uattr)
15883 {
15884 	u32 krec_size = sizeof(struct bpf_func_info);
15885 	const struct btf_type *type, *func_proto;
15886 	u32 i, nfuncs, urec_size, min_size;
15887 	struct bpf_func_info *krecord;
15888 	struct bpf_prog *prog;
15889 	const struct btf *btf;
15890 	u32 prev_offset = 0;
15891 	bpfptr_t urecord;
15892 	int ret = -ENOMEM;
15893 
15894 	nfuncs = attr->func_info_cnt;
15895 	if (!nfuncs) {
15896 		if (check_abnormal_return(env))
15897 			return -EINVAL;
15898 		return 0;
15899 	}
15900 
15901 	urec_size = attr->func_info_rec_size;
15902 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15903 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
15904 	    urec_size % sizeof(u32)) {
15905 		verbose(env, "invalid func info rec size %u\n", urec_size);
15906 		return -EINVAL;
15907 	}
15908 
15909 	prog = env->prog;
15910 	btf = prog->aux->btf;
15911 
15912 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15913 	min_size = min_t(u32, krec_size, urec_size);
15914 
15915 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15916 	if (!krecord)
15917 		return -ENOMEM;
15918 
15919 	for (i = 0; i < nfuncs; i++) {
15920 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15921 		if (ret) {
15922 			if (ret == -E2BIG) {
15923 				verbose(env, "nonzero tailing record in func info");
15924 				/* set the size kernel expects so loader can zero
15925 				 * out the rest of the record.
15926 				 */
15927 				if (copy_to_bpfptr_offset(uattr,
15928 							  offsetof(union bpf_attr, func_info_rec_size),
15929 							  &min_size, sizeof(min_size)))
15930 					ret = -EFAULT;
15931 			}
15932 			goto err_free;
15933 		}
15934 
15935 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15936 			ret = -EFAULT;
15937 			goto err_free;
15938 		}
15939 
15940 		/* check insn_off */
15941 		ret = -EINVAL;
15942 		if (i == 0) {
15943 			if (krecord[i].insn_off) {
15944 				verbose(env,
15945 					"nonzero insn_off %u for the first func info record",
15946 					krecord[i].insn_off);
15947 				goto err_free;
15948 			}
15949 		} else if (krecord[i].insn_off <= prev_offset) {
15950 			verbose(env,
15951 				"same or smaller insn offset (%u) than previous func info record (%u)",
15952 				krecord[i].insn_off, prev_offset);
15953 			goto err_free;
15954 		}
15955 
15956 		/* check type_id */
15957 		type = btf_type_by_id(btf, krecord[i].type_id);
15958 		if (!type || !btf_type_is_func(type)) {
15959 			verbose(env, "invalid type id %d in func info",
15960 				krecord[i].type_id);
15961 			goto err_free;
15962 		}
15963 
15964 		func_proto = btf_type_by_id(btf, type->type);
15965 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15966 			/* btf_func_check() already verified it during BTF load */
15967 			goto err_free;
15968 
15969 		prev_offset = krecord[i].insn_off;
15970 		bpfptr_add(&urecord, urec_size);
15971 	}
15972 
15973 	prog->aux->func_info = krecord;
15974 	prog->aux->func_info_cnt = nfuncs;
15975 	return 0;
15976 
15977 err_free:
15978 	kvfree(krecord);
15979 	return ret;
15980 }
15981 
15982 static int check_btf_func(struct bpf_verifier_env *env,
15983 			  const union bpf_attr *attr,
15984 			  bpfptr_t uattr)
15985 {
15986 	const struct btf_type *type, *func_proto, *ret_type;
15987 	u32 i, nfuncs, urec_size;
15988 	struct bpf_func_info *krecord;
15989 	struct bpf_func_info_aux *info_aux = NULL;
15990 	struct bpf_prog *prog;
15991 	const struct btf *btf;
15992 	bpfptr_t urecord;
15993 	bool scalar_return;
15994 	int ret = -ENOMEM;
15995 
15996 	nfuncs = attr->func_info_cnt;
15997 	if (!nfuncs) {
15998 		if (check_abnormal_return(env))
15999 			return -EINVAL;
16000 		return 0;
16001 	}
16002 	if (nfuncs != env->subprog_cnt) {
16003 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
16004 		return -EINVAL;
16005 	}
16006 
16007 	urec_size = attr->func_info_rec_size;
16008 
16009 	prog = env->prog;
16010 	btf = prog->aux->btf;
16011 
16012 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
16013 
16014 	krecord = prog->aux->func_info;
16015 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
16016 	if (!info_aux)
16017 		return -ENOMEM;
16018 
16019 	for (i = 0; i < nfuncs; i++) {
16020 		/* check insn_off */
16021 		ret = -EINVAL;
16022 
16023 		if (env->subprog_info[i].start != krecord[i].insn_off) {
16024 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
16025 			goto err_free;
16026 		}
16027 
16028 		/* Already checked type_id */
16029 		type = btf_type_by_id(btf, krecord[i].type_id);
16030 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
16031 		/* Already checked func_proto */
16032 		func_proto = btf_type_by_id(btf, type->type);
16033 
16034 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
16035 		scalar_return =
16036 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
16037 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
16038 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
16039 			goto err_free;
16040 		}
16041 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
16042 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
16043 			goto err_free;
16044 		}
16045 
16046 		bpfptr_add(&urecord, urec_size);
16047 	}
16048 
16049 	prog->aux->func_info_aux = info_aux;
16050 	return 0;
16051 
16052 err_free:
16053 	kfree(info_aux);
16054 	return ret;
16055 }
16056 
16057 static void adjust_btf_func(struct bpf_verifier_env *env)
16058 {
16059 	struct bpf_prog_aux *aux = env->prog->aux;
16060 	int i;
16061 
16062 	if (!aux->func_info)
16063 		return;
16064 
16065 	/* func_info is not available for hidden subprogs */
16066 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
16067 		aux->func_info[i].insn_off = env->subprog_info[i].start;
16068 }
16069 
16070 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
16071 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
16072 
16073 static int check_btf_line(struct bpf_verifier_env *env,
16074 			  const union bpf_attr *attr,
16075 			  bpfptr_t uattr)
16076 {
16077 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
16078 	struct bpf_subprog_info *sub;
16079 	struct bpf_line_info *linfo;
16080 	struct bpf_prog *prog;
16081 	const struct btf *btf;
16082 	bpfptr_t ulinfo;
16083 	int err;
16084 
16085 	nr_linfo = attr->line_info_cnt;
16086 	if (!nr_linfo)
16087 		return 0;
16088 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
16089 		return -EINVAL;
16090 
16091 	rec_size = attr->line_info_rec_size;
16092 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
16093 	    rec_size > MAX_LINEINFO_REC_SIZE ||
16094 	    rec_size & (sizeof(u32) - 1))
16095 		return -EINVAL;
16096 
16097 	/* Need to zero it in case the userspace may
16098 	 * pass in a smaller bpf_line_info object.
16099 	 */
16100 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
16101 			 GFP_KERNEL | __GFP_NOWARN);
16102 	if (!linfo)
16103 		return -ENOMEM;
16104 
16105 	prog = env->prog;
16106 	btf = prog->aux->btf;
16107 
16108 	s = 0;
16109 	sub = env->subprog_info;
16110 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
16111 	expected_size = sizeof(struct bpf_line_info);
16112 	ncopy = min_t(u32, expected_size, rec_size);
16113 	for (i = 0; i < nr_linfo; i++) {
16114 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
16115 		if (err) {
16116 			if (err == -E2BIG) {
16117 				verbose(env, "nonzero tailing record in line_info");
16118 				if (copy_to_bpfptr_offset(uattr,
16119 							  offsetof(union bpf_attr, line_info_rec_size),
16120 							  &expected_size, sizeof(expected_size)))
16121 					err = -EFAULT;
16122 			}
16123 			goto err_free;
16124 		}
16125 
16126 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
16127 			err = -EFAULT;
16128 			goto err_free;
16129 		}
16130 
16131 		/*
16132 		 * Check insn_off to ensure
16133 		 * 1) strictly increasing AND
16134 		 * 2) bounded by prog->len
16135 		 *
16136 		 * The linfo[0].insn_off == 0 check logically falls into
16137 		 * the later "missing bpf_line_info for func..." case
16138 		 * because the first linfo[0].insn_off must be the
16139 		 * first sub also and the first sub must have
16140 		 * subprog_info[0].start == 0.
16141 		 */
16142 		if ((i && linfo[i].insn_off <= prev_offset) ||
16143 		    linfo[i].insn_off >= prog->len) {
16144 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
16145 				i, linfo[i].insn_off, prev_offset,
16146 				prog->len);
16147 			err = -EINVAL;
16148 			goto err_free;
16149 		}
16150 
16151 		if (!prog->insnsi[linfo[i].insn_off].code) {
16152 			verbose(env,
16153 				"Invalid insn code at line_info[%u].insn_off\n",
16154 				i);
16155 			err = -EINVAL;
16156 			goto err_free;
16157 		}
16158 
16159 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
16160 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
16161 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
16162 			err = -EINVAL;
16163 			goto err_free;
16164 		}
16165 
16166 		if (s != env->subprog_cnt) {
16167 			if (linfo[i].insn_off == sub[s].start) {
16168 				sub[s].linfo_idx = i;
16169 				s++;
16170 			} else if (sub[s].start < linfo[i].insn_off) {
16171 				verbose(env, "missing bpf_line_info for func#%u\n", s);
16172 				err = -EINVAL;
16173 				goto err_free;
16174 			}
16175 		}
16176 
16177 		prev_offset = linfo[i].insn_off;
16178 		bpfptr_add(&ulinfo, rec_size);
16179 	}
16180 
16181 	if (s != env->subprog_cnt) {
16182 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
16183 			env->subprog_cnt - s, s);
16184 		err = -EINVAL;
16185 		goto err_free;
16186 	}
16187 
16188 	prog->aux->linfo = linfo;
16189 	prog->aux->nr_linfo = nr_linfo;
16190 
16191 	return 0;
16192 
16193 err_free:
16194 	kvfree(linfo);
16195 	return err;
16196 }
16197 
16198 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
16199 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
16200 
16201 static int check_core_relo(struct bpf_verifier_env *env,
16202 			   const union bpf_attr *attr,
16203 			   bpfptr_t uattr)
16204 {
16205 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
16206 	struct bpf_core_relo core_relo = {};
16207 	struct bpf_prog *prog = env->prog;
16208 	const struct btf *btf = prog->aux->btf;
16209 	struct bpf_core_ctx ctx = {
16210 		.log = &env->log,
16211 		.btf = btf,
16212 	};
16213 	bpfptr_t u_core_relo;
16214 	int err;
16215 
16216 	nr_core_relo = attr->core_relo_cnt;
16217 	if (!nr_core_relo)
16218 		return 0;
16219 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
16220 		return -EINVAL;
16221 
16222 	rec_size = attr->core_relo_rec_size;
16223 	if (rec_size < MIN_CORE_RELO_SIZE ||
16224 	    rec_size > MAX_CORE_RELO_SIZE ||
16225 	    rec_size % sizeof(u32))
16226 		return -EINVAL;
16227 
16228 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
16229 	expected_size = sizeof(struct bpf_core_relo);
16230 	ncopy = min_t(u32, expected_size, rec_size);
16231 
16232 	/* Unlike func_info and line_info, copy and apply each CO-RE
16233 	 * relocation record one at a time.
16234 	 */
16235 	for (i = 0; i < nr_core_relo; i++) {
16236 		/* future proofing when sizeof(bpf_core_relo) changes */
16237 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
16238 		if (err) {
16239 			if (err == -E2BIG) {
16240 				verbose(env, "nonzero tailing record in core_relo");
16241 				if (copy_to_bpfptr_offset(uattr,
16242 							  offsetof(union bpf_attr, core_relo_rec_size),
16243 							  &expected_size, sizeof(expected_size)))
16244 					err = -EFAULT;
16245 			}
16246 			break;
16247 		}
16248 
16249 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
16250 			err = -EFAULT;
16251 			break;
16252 		}
16253 
16254 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
16255 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
16256 				i, core_relo.insn_off, prog->len);
16257 			err = -EINVAL;
16258 			break;
16259 		}
16260 
16261 		err = bpf_core_apply(&ctx, &core_relo, i,
16262 				     &prog->insnsi[core_relo.insn_off / 8]);
16263 		if (err)
16264 			break;
16265 		bpfptr_add(&u_core_relo, rec_size);
16266 	}
16267 	return err;
16268 }
16269 
16270 static int check_btf_info_early(struct bpf_verifier_env *env,
16271 				const union bpf_attr *attr,
16272 				bpfptr_t uattr)
16273 {
16274 	struct btf *btf;
16275 	int err;
16276 
16277 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
16278 		if (check_abnormal_return(env))
16279 			return -EINVAL;
16280 		return 0;
16281 	}
16282 
16283 	btf = btf_get_by_fd(attr->prog_btf_fd);
16284 	if (IS_ERR(btf))
16285 		return PTR_ERR(btf);
16286 	if (btf_is_kernel(btf)) {
16287 		btf_put(btf);
16288 		return -EACCES;
16289 	}
16290 	env->prog->aux->btf = btf;
16291 
16292 	err = check_btf_func_early(env, attr, uattr);
16293 	if (err)
16294 		return err;
16295 	return 0;
16296 }
16297 
16298 static int check_btf_info(struct bpf_verifier_env *env,
16299 			  const union bpf_attr *attr,
16300 			  bpfptr_t uattr)
16301 {
16302 	int err;
16303 
16304 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
16305 		if (check_abnormal_return(env))
16306 			return -EINVAL;
16307 		return 0;
16308 	}
16309 
16310 	err = check_btf_func(env, attr, uattr);
16311 	if (err)
16312 		return err;
16313 
16314 	err = check_btf_line(env, attr, uattr);
16315 	if (err)
16316 		return err;
16317 
16318 	err = check_core_relo(env, attr, uattr);
16319 	if (err)
16320 		return err;
16321 
16322 	return 0;
16323 }
16324 
16325 /* check %cur's range satisfies %old's */
16326 static bool range_within(const struct bpf_reg_state *old,
16327 			 const struct bpf_reg_state *cur)
16328 {
16329 	return old->umin_value <= cur->umin_value &&
16330 	       old->umax_value >= cur->umax_value &&
16331 	       old->smin_value <= cur->smin_value &&
16332 	       old->smax_value >= cur->smax_value &&
16333 	       old->u32_min_value <= cur->u32_min_value &&
16334 	       old->u32_max_value >= cur->u32_max_value &&
16335 	       old->s32_min_value <= cur->s32_min_value &&
16336 	       old->s32_max_value >= cur->s32_max_value;
16337 }
16338 
16339 /* If in the old state two registers had the same id, then they need to have
16340  * the same id in the new state as well.  But that id could be different from
16341  * the old state, so we need to track the mapping from old to new ids.
16342  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
16343  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
16344  * regs with a different old id could still have new id 9, we don't care about
16345  * that.
16346  * So we look through our idmap to see if this old id has been seen before.  If
16347  * so, we require the new id to match; otherwise, we add the id pair to the map.
16348  */
16349 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16350 {
16351 	struct bpf_id_pair *map = idmap->map;
16352 	unsigned int i;
16353 
16354 	/* either both IDs should be set or both should be zero */
16355 	if (!!old_id != !!cur_id)
16356 		return false;
16357 
16358 	if (old_id == 0) /* cur_id == 0 as well */
16359 		return true;
16360 
16361 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
16362 		if (!map[i].old) {
16363 			/* Reached an empty slot; haven't seen this id before */
16364 			map[i].old = old_id;
16365 			map[i].cur = cur_id;
16366 			return true;
16367 		}
16368 		if (map[i].old == old_id)
16369 			return map[i].cur == cur_id;
16370 		if (map[i].cur == cur_id)
16371 			return false;
16372 	}
16373 	/* We ran out of idmap slots, which should be impossible */
16374 	WARN_ON_ONCE(1);
16375 	return false;
16376 }
16377 
16378 /* Similar to check_ids(), but allocate a unique temporary ID
16379  * for 'old_id' or 'cur_id' of zero.
16380  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
16381  */
16382 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16383 {
16384 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
16385 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
16386 
16387 	return check_ids(old_id, cur_id, idmap);
16388 }
16389 
16390 static void clean_func_state(struct bpf_verifier_env *env,
16391 			     struct bpf_func_state *st)
16392 {
16393 	enum bpf_reg_liveness live;
16394 	int i, j;
16395 
16396 	for (i = 0; i < BPF_REG_FP; i++) {
16397 		live = st->regs[i].live;
16398 		/* liveness must not touch this register anymore */
16399 		st->regs[i].live |= REG_LIVE_DONE;
16400 		if (!(live & REG_LIVE_READ))
16401 			/* since the register is unused, clear its state
16402 			 * to make further comparison simpler
16403 			 */
16404 			__mark_reg_not_init(env, &st->regs[i]);
16405 	}
16406 
16407 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
16408 		live = st->stack[i].spilled_ptr.live;
16409 		/* liveness must not touch this stack slot anymore */
16410 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
16411 		if (!(live & REG_LIVE_READ)) {
16412 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
16413 			for (j = 0; j < BPF_REG_SIZE; j++)
16414 				st->stack[i].slot_type[j] = STACK_INVALID;
16415 		}
16416 	}
16417 }
16418 
16419 static void clean_verifier_state(struct bpf_verifier_env *env,
16420 				 struct bpf_verifier_state *st)
16421 {
16422 	int i;
16423 
16424 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
16425 		/* all regs in this state in all frames were already marked */
16426 		return;
16427 
16428 	for (i = 0; i <= st->curframe; i++)
16429 		clean_func_state(env, st->frame[i]);
16430 }
16431 
16432 /* the parentage chains form a tree.
16433  * the verifier states are added to state lists at given insn and
16434  * pushed into state stack for future exploration.
16435  * when the verifier reaches bpf_exit insn some of the verifer states
16436  * stored in the state lists have their final liveness state already,
16437  * but a lot of states will get revised from liveness point of view when
16438  * the verifier explores other branches.
16439  * Example:
16440  * 1: r0 = 1
16441  * 2: if r1 == 100 goto pc+1
16442  * 3: r0 = 2
16443  * 4: exit
16444  * when the verifier reaches exit insn the register r0 in the state list of
16445  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
16446  * of insn 2 and goes exploring further. At the insn 4 it will walk the
16447  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
16448  *
16449  * Since the verifier pushes the branch states as it sees them while exploring
16450  * the program the condition of walking the branch instruction for the second
16451  * time means that all states below this branch were already explored and
16452  * their final liveness marks are already propagated.
16453  * Hence when the verifier completes the search of state list in is_state_visited()
16454  * we can call this clean_live_states() function to mark all liveness states
16455  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
16456  * will not be used.
16457  * This function also clears the registers and stack for states that !READ
16458  * to simplify state merging.
16459  *
16460  * Important note here that walking the same branch instruction in the callee
16461  * doesn't meant that the states are DONE. The verifier has to compare
16462  * the callsites
16463  */
16464 static void clean_live_states(struct bpf_verifier_env *env, int insn,
16465 			      struct bpf_verifier_state *cur)
16466 {
16467 	struct bpf_verifier_state_list *sl;
16468 
16469 	sl = *explored_state(env, insn);
16470 	while (sl) {
16471 		if (sl->state.branches)
16472 			goto next;
16473 		if (sl->state.insn_idx != insn ||
16474 		    !same_callsites(&sl->state, cur))
16475 			goto next;
16476 		clean_verifier_state(env, &sl->state);
16477 next:
16478 		sl = sl->next;
16479 	}
16480 }
16481 
16482 static bool regs_exact(const struct bpf_reg_state *rold,
16483 		       const struct bpf_reg_state *rcur,
16484 		       struct bpf_idmap *idmap)
16485 {
16486 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16487 	       check_ids(rold->id, rcur->id, idmap) &&
16488 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16489 }
16490 
16491 enum exact_level {
16492 	NOT_EXACT,
16493 	EXACT,
16494 	RANGE_WITHIN
16495 };
16496 
16497 /* Returns true if (rold safe implies rcur safe) */
16498 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
16499 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
16500 		    enum exact_level exact)
16501 {
16502 	if (exact == EXACT)
16503 		return regs_exact(rold, rcur, idmap);
16504 
16505 	if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT)
16506 		/* explored state didn't use this */
16507 		return true;
16508 	if (rold->type == NOT_INIT) {
16509 		if (exact == NOT_EXACT || rcur->type == NOT_INIT)
16510 			/* explored state can't have used this */
16511 			return true;
16512 	}
16513 
16514 	/* Enforce that register types have to match exactly, including their
16515 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16516 	 * rule.
16517 	 *
16518 	 * One can make a point that using a pointer register as unbounded
16519 	 * SCALAR would be technically acceptable, but this could lead to
16520 	 * pointer leaks because scalars are allowed to leak while pointers
16521 	 * are not. We could make this safe in special cases if root is
16522 	 * calling us, but it's probably not worth the hassle.
16523 	 *
16524 	 * Also, register types that are *not* MAYBE_NULL could technically be
16525 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16526 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16527 	 * to the same map).
16528 	 * However, if the old MAYBE_NULL register then got NULL checked,
16529 	 * doing so could have affected others with the same id, and we can't
16530 	 * check for that because we lost the id when we converted to
16531 	 * a non-MAYBE_NULL variant.
16532 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
16533 	 * non-MAYBE_NULL registers as well.
16534 	 */
16535 	if (rold->type != rcur->type)
16536 		return false;
16537 
16538 	switch (base_type(rold->type)) {
16539 	case SCALAR_VALUE:
16540 		if (env->explore_alu_limits) {
16541 			/* explore_alu_limits disables tnum_in() and range_within()
16542 			 * logic and requires everything to be strict
16543 			 */
16544 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16545 			       check_scalar_ids(rold->id, rcur->id, idmap);
16546 		}
16547 		if (!rold->precise && exact == NOT_EXACT)
16548 			return true;
16549 		/* Why check_ids() for scalar registers?
16550 		 *
16551 		 * Consider the following BPF code:
16552 		 *   1: r6 = ... unbound scalar, ID=a ...
16553 		 *   2: r7 = ... unbound scalar, ID=b ...
16554 		 *   3: if (r6 > r7) goto +1
16555 		 *   4: r6 = r7
16556 		 *   5: if (r6 > X) goto ...
16557 		 *   6: ... memory operation using r7 ...
16558 		 *
16559 		 * First verification path is [1-6]:
16560 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16561 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16562 		 *   r7 <= X, because r6 and r7 share same id.
16563 		 * Next verification path is [1-4, 6].
16564 		 *
16565 		 * Instruction (6) would be reached in two states:
16566 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16567 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16568 		 *
16569 		 * Use check_ids() to distinguish these states.
16570 		 * ---
16571 		 * Also verify that new value satisfies old value range knowledge.
16572 		 */
16573 		return range_within(rold, rcur) &&
16574 		       tnum_in(rold->var_off, rcur->var_off) &&
16575 		       check_scalar_ids(rold->id, rcur->id, idmap);
16576 	case PTR_TO_MAP_KEY:
16577 	case PTR_TO_MAP_VALUE:
16578 	case PTR_TO_MEM:
16579 	case PTR_TO_BUF:
16580 	case PTR_TO_TP_BUFFER:
16581 		/* If the new min/max/var_off satisfy the old ones and
16582 		 * everything else matches, we are OK.
16583 		 */
16584 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16585 		       range_within(rold, rcur) &&
16586 		       tnum_in(rold->var_off, rcur->var_off) &&
16587 		       check_ids(rold->id, rcur->id, idmap) &&
16588 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16589 	case PTR_TO_PACKET_META:
16590 	case PTR_TO_PACKET:
16591 		/* We must have at least as much range as the old ptr
16592 		 * did, so that any accesses which were safe before are
16593 		 * still safe.  This is true even if old range < old off,
16594 		 * since someone could have accessed through (ptr - k), or
16595 		 * even done ptr -= k in a register, to get a safe access.
16596 		 */
16597 		if (rold->range > rcur->range)
16598 			return false;
16599 		/* If the offsets don't match, we can't trust our alignment;
16600 		 * nor can we be sure that we won't fall out of range.
16601 		 */
16602 		if (rold->off != rcur->off)
16603 			return false;
16604 		/* id relations must be preserved */
16605 		if (!check_ids(rold->id, rcur->id, idmap))
16606 			return false;
16607 		/* new val must satisfy old val knowledge */
16608 		return range_within(rold, rcur) &&
16609 		       tnum_in(rold->var_off, rcur->var_off);
16610 	case PTR_TO_STACK:
16611 		/* two stack pointers are equal only if they're pointing to
16612 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16613 		 */
16614 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16615 	case PTR_TO_ARENA:
16616 		return true;
16617 	default:
16618 		return regs_exact(rold, rcur, idmap);
16619 	}
16620 }
16621 
16622 static struct bpf_reg_state unbound_reg;
16623 
16624 static __init int unbound_reg_init(void)
16625 {
16626 	__mark_reg_unknown_imprecise(&unbound_reg);
16627 	unbound_reg.live |= REG_LIVE_READ;
16628 	return 0;
16629 }
16630 late_initcall(unbound_reg_init);
16631 
16632 static bool is_stack_all_misc(struct bpf_verifier_env *env,
16633 			      struct bpf_stack_state *stack)
16634 {
16635 	u32 i;
16636 
16637 	for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
16638 		if ((stack->slot_type[i] == STACK_MISC) ||
16639 		    (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
16640 			continue;
16641 		return false;
16642 	}
16643 
16644 	return true;
16645 }
16646 
16647 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
16648 						  struct bpf_stack_state *stack)
16649 {
16650 	if (is_spilled_scalar_reg64(stack))
16651 		return &stack->spilled_ptr;
16652 
16653 	if (is_stack_all_misc(env, stack))
16654 		return &unbound_reg;
16655 
16656 	return NULL;
16657 }
16658 
16659 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16660 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
16661 		      enum exact_level exact)
16662 {
16663 	int i, spi;
16664 
16665 	/* walk slots of the explored stack and ignore any additional
16666 	 * slots in the current stack, since explored(safe) state
16667 	 * didn't use them
16668 	 */
16669 	for (i = 0; i < old->allocated_stack; i++) {
16670 		struct bpf_reg_state *old_reg, *cur_reg;
16671 
16672 		spi = i / BPF_REG_SIZE;
16673 
16674 		if (exact != NOT_EXACT &&
16675 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16676 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16677 			return false;
16678 
16679 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)
16680 		    && exact == NOT_EXACT) {
16681 			i += BPF_REG_SIZE - 1;
16682 			/* explored state didn't use this */
16683 			continue;
16684 		}
16685 
16686 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16687 			continue;
16688 
16689 		if (env->allow_uninit_stack &&
16690 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16691 			continue;
16692 
16693 		/* explored stack has more populated slots than current stack
16694 		 * and these slots were used
16695 		 */
16696 		if (i >= cur->allocated_stack)
16697 			return false;
16698 
16699 		/* 64-bit scalar spill vs all slots MISC and vice versa.
16700 		 * Load from all slots MISC produces unbound scalar.
16701 		 * Construct a fake register for such stack and call
16702 		 * regsafe() to ensure scalar ids are compared.
16703 		 */
16704 		old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
16705 		cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
16706 		if (old_reg && cur_reg) {
16707 			if (!regsafe(env, old_reg, cur_reg, idmap, exact))
16708 				return false;
16709 			i += BPF_REG_SIZE - 1;
16710 			continue;
16711 		}
16712 
16713 		/* if old state was safe with misc data in the stack
16714 		 * it will be safe with zero-initialized stack.
16715 		 * The opposite is not true
16716 		 */
16717 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16718 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16719 			continue;
16720 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16721 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16722 			/* Ex: old explored (safe) state has STACK_SPILL in
16723 			 * this stack slot, but current has STACK_MISC ->
16724 			 * this verifier states are not equivalent,
16725 			 * return false to continue verification of this path
16726 			 */
16727 			return false;
16728 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16729 			continue;
16730 		/* Both old and cur are having same slot_type */
16731 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16732 		case STACK_SPILL:
16733 			/* when explored and current stack slot are both storing
16734 			 * spilled registers, check that stored pointers types
16735 			 * are the same as well.
16736 			 * Ex: explored safe path could have stored
16737 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16738 			 * but current path has stored:
16739 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16740 			 * such verifier states are not equivalent.
16741 			 * return false to continue verification of this path
16742 			 */
16743 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16744 				     &cur->stack[spi].spilled_ptr, idmap, exact))
16745 				return false;
16746 			break;
16747 		case STACK_DYNPTR:
16748 			old_reg = &old->stack[spi].spilled_ptr;
16749 			cur_reg = &cur->stack[spi].spilled_ptr;
16750 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16751 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16752 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16753 				return false;
16754 			break;
16755 		case STACK_ITER:
16756 			old_reg = &old->stack[spi].spilled_ptr;
16757 			cur_reg = &cur->stack[spi].spilled_ptr;
16758 			/* iter.depth is not compared between states as it
16759 			 * doesn't matter for correctness and would otherwise
16760 			 * prevent convergence; we maintain it only to prevent
16761 			 * infinite loop check triggering, see
16762 			 * iter_active_depths_differ()
16763 			 */
16764 			if (old_reg->iter.btf != cur_reg->iter.btf ||
16765 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16766 			    old_reg->iter.state != cur_reg->iter.state ||
16767 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16768 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16769 				return false;
16770 			break;
16771 		case STACK_MISC:
16772 		case STACK_ZERO:
16773 		case STACK_INVALID:
16774 			continue;
16775 		/* Ensure that new unhandled slot types return false by default */
16776 		default:
16777 			return false;
16778 		}
16779 	}
16780 	return true;
16781 }
16782 
16783 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16784 		    struct bpf_idmap *idmap)
16785 {
16786 	int i;
16787 
16788 	if (old->acquired_refs != cur->acquired_refs)
16789 		return false;
16790 
16791 	for (i = 0; i < old->acquired_refs; i++) {
16792 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16793 			return false;
16794 	}
16795 
16796 	return true;
16797 }
16798 
16799 /* compare two verifier states
16800  *
16801  * all states stored in state_list are known to be valid, since
16802  * verifier reached 'bpf_exit' instruction through them
16803  *
16804  * this function is called when verifier exploring different branches of
16805  * execution popped from the state stack. If it sees an old state that has
16806  * more strict register state and more strict stack state then this execution
16807  * branch doesn't need to be explored further, since verifier already
16808  * concluded that more strict state leads to valid finish.
16809  *
16810  * Therefore two states are equivalent if register state is more conservative
16811  * and explored stack state is more conservative than the current one.
16812  * Example:
16813  *       explored                   current
16814  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16815  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16816  *
16817  * In other words if current stack state (one being explored) has more
16818  * valid slots than old one that already passed validation, it means
16819  * the verifier can stop exploring and conclude that current state is valid too
16820  *
16821  * Similarly with registers. If explored state has register type as invalid
16822  * whereas register type in current state is meaningful, it means that
16823  * the current state will reach 'bpf_exit' instruction safely
16824  */
16825 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16826 			      struct bpf_func_state *cur, enum exact_level exact)
16827 {
16828 	int i;
16829 
16830 	if (old->callback_depth > cur->callback_depth)
16831 		return false;
16832 
16833 	for (i = 0; i < MAX_BPF_REG; i++)
16834 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
16835 			     &env->idmap_scratch, exact))
16836 			return false;
16837 
16838 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16839 		return false;
16840 
16841 	if (!refsafe(old, cur, &env->idmap_scratch))
16842 		return false;
16843 
16844 	return true;
16845 }
16846 
16847 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16848 {
16849 	env->idmap_scratch.tmp_id_gen = env->id_gen;
16850 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16851 }
16852 
16853 static bool states_equal(struct bpf_verifier_env *env,
16854 			 struct bpf_verifier_state *old,
16855 			 struct bpf_verifier_state *cur,
16856 			 enum exact_level exact)
16857 {
16858 	int i;
16859 
16860 	if (old->curframe != cur->curframe)
16861 		return false;
16862 
16863 	reset_idmap_scratch(env);
16864 
16865 	/* Verification state from speculative execution simulation
16866 	 * must never prune a non-speculative execution one.
16867 	 */
16868 	if (old->speculative && !cur->speculative)
16869 		return false;
16870 
16871 	if (old->active_lock.ptr != cur->active_lock.ptr)
16872 		return false;
16873 
16874 	/* Old and cur active_lock's have to be either both present
16875 	 * or both absent.
16876 	 */
16877 	if (!!old->active_lock.id != !!cur->active_lock.id)
16878 		return false;
16879 
16880 	if (old->active_lock.id &&
16881 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16882 		return false;
16883 
16884 	if (old->active_rcu_lock != cur->active_rcu_lock)
16885 		return false;
16886 
16887 	/* for states to be equal callsites have to be the same
16888 	 * and all frame states need to be equivalent
16889 	 */
16890 	for (i = 0; i <= old->curframe; i++) {
16891 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
16892 			return false;
16893 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16894 			return false;
16895 	}
16896 	return true;
16897 }
16898 
16899 /* Return 0 if no propagation happened. Return negative error code if error
16900  * happened. Otherwise, return the propagated bit.
16901  */
16902 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16903 				  struct bpf_reg_state *reg,
16904 				  struct bpf_reg_state *parent_reg)
16905 {
16906 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16907 	u8 flag = reg->live & REG_LIVE_READ;
16908 	int err;
16909 
16910 	/* When comes here, read flags of PARENT_REG or REG could be any of
16911 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16912 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16913 	 */
16914 	if (parent_flag == REG_LIVE_READ64 ||
16915 	    /* Or if there is no read flag from REG. */
16916 	    !flag ||
16917 	    /* Or if the read flag from REG is the same as PARENT_REG. */
16918 	    parent_flag == flag)
16919 		return 0;
16920 
16921 	err = mark_reg_read(env, reg, parent_reg, flag);
16922 	if (err)
16923 		return err;
16924 
16925 	return flag;
16926 }
16927 
16928 /* A write screens off any subsequent reads; but write marks come from the
16929  * straight-line code between a state and its parent.  When we arrive at an
16930  * equivalent state (jump target or such) we didn't arrive by the straight-line
16931  * code, so read marks in the state must propagate to the parent regardless
16932  * of the state's write marks. That's what 'parent == state->parent' comparison
16933  * in mark_reg_read() is for.
16934  */
16935 static int propagate_liveness(struct bpf_verifier_env *env,
16936 			      const struct bpf_verifier_state *vstate,
16937 			      struct bpf_verifier_state *vparent)
16938 {
16939 	struct bpf_reg_state *state_reg, *parent_reg;
16940 	struct bpf_func_state *state, *parent;
16941 	int i, frame, err = 0;
16942 
16943 	if (vparent->curframe != vstate->curframe) {
16944 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
16945 		     vparent->curframe, vstate->curframe);
16946 		return -EFAULT;
16947 	}
16948 	/* Propagate read liveness of registers... */
16949 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16950 	for (frame = 0; frame <= vstate->curframe; frame++) {
16951 		parent = vparent->frame[frame];
16952 		state = vstate->frame[frame];
16953 		parent_reg = parent->regs;
16954 		state_reg = state->regs;
16955 		/* We don't need to worry about FP liveness, it's read-only */
16956 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16957 			err = propagate_liveness_reg(env, &state_reg[i],
16958 						     &parent_reg[i]);
16959 			if (err < 0)
16960 				return err;
16961 			if (err == REG_LIVE_READ64)
16962 				mark_insn_zext(env, &parent_reg[i]);
16963 		}
16964 
16965 		/* Propagate stack slots. */
16966 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16967 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16968 			parent_reg = &parent->stack[i].spilled_ptr;
16969 			state_reg = &state->stack[i].spilled_ptr;
16970 			err = propagate_liveness_reg(env, state_reg,
16971 						     parent_reg);
16972 			if (err < 0)
16973 				return err;
16974 		}
16975 	}
16976 	return 0;
16977 }
16978 
16979 /* find precise scalars in the previous equivalent state and
16980  * propagate them into the current state
16981  */
16982 static int propagate_precision(struct bpf_verifier_env *env,
16983 			       const struct bpf_verifier_state *old)
16984 {
16985 	struct bpf_reg_state *state_reg;
16986 	struct bpf_func_state *state;
16987 	int i, err = 0, fr;
16988 	bool first;
16989 
16990 	for (fr = old->curframe; fr >= 0; fr--) {
16991 		state = old->frame[fr];
16992 		state_reg = state->regs;
16993 		first = true;
16994 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16995 			if (state_reg->type != SCALAR_VALUE ||
16996 			    !state_reg->precise ||
16997 			    !(state_reg->live & REG_LIVE_READ))
16998 				continue;
16999 			if (env->log.level & BPF_LOG_LEVEL2) {
17000 				if (first)
17001 					verbose(env, "frame %d: propagating r%d", fr, i);
17002 				else
17003 					verbose(env, ",r%d", i);
17004 			}
17005 			bt_set_frame_reg(&env->bt, fr, i);
17006 			first = false;
17007 		}
17008 
17009 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17010 			if (!is_spilled_reg(&state->stack[i]))
17011 				continue;
17012 			state_reg = &state->stack[i].spilled_ptr;
17013 			if (state_reg->type != SCALAR_VALUE ||
17014 			    !state_reg->precise ||
17015 			    !(state_reg->live & REG_LIVE_READ))
17016 				continue;
17017 			if (env->log.level & BPF_LOG_LEVEL2) {
17018 				if (first)
17019 					verbose(env, "frame %d: propagating fp%d",
17020 						fr, (-i - 1) * BPF_REG_SIZE);
17021 				else
17022 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
17023 			}
17024 			bt_set_frame_slot(&env->bt, fr, i);
17025 			first = false;
17026 		}
17027 		if (!first)
17028 			verbose(env, "\n");
17029 	}
17030 
17031 	err = mark_chain_precision_batch(env);
17032 	if (err < 0)
17033 		return err;
17034 
17035 	return 0;
17036 }
17037 
17038 static bool states_maybe_looping(struct bpf_verifier_state *old,
17039 				 struct bpf_verifier_state *cur)
17040 {
17041 	struct bpf_func_state *fold, *fcur;
17042 	int i, fr = cur->curframe;
17043 
17044 	if (old->curframe != fr)
17045 		return false;
17046 
17047 	fold = old->frame[fr];
17048 	fcur = cur->frame[fr];
17049 	for (i = 0; i < MAX_BPF_REG; i++)
17050 		if (memcmp(&fold->regs[i], &fcur->regs[i],
17051 			   offsetof(struct bpf_reg_state, parent)))
17052 			return false;
17053 	return true;
17054 }
17055 
17056 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
17057 {
17058 	return env->insn_aux_data[insn_idx].is_iter_next;
17059 }
17060 
17061 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
17062  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
17063  * states to match, which otherwise would look like an infinite loop. So while
17064  * iter_next() calls are taken care of, we still need to be careful and
17065  * prevent erroneous and too eager declaration of "ininite loop", when
17066  * iterators are involved.
17067  *
17068  * Here's a situation in pseudo-BPF assembly form:
17069  *
17070  *   0: again:                          ; set up iter_next() call args
17071  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
17072  *   2:   call bpf_iter_num_next        ; this is iter_next() call
17073  *   3:   if r0 == 0 goto done
17074  *   4:   ... something useful here ...
17075  *   5:   goto again                    ; another iteration
17076  *   6: done:
17077  *   7:   r1 = &it
17078  *   8:   call bpf_iter_num_destroy     ; clean up iter state
17079  *   9:   exit
17080  *
17081  * This is a typical loop. Let's assume that we have a prune point at 1:,
17082  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
17083  * again`, assuming other heuristics don't get in a way).
17084  *
17085  * When we first time come to 1:, let's say we have some state X. We proceed
17086  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
17087  * Now we come back to validate that forked ACTIVE state. We proceed through
17088  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
17089  * are converging. But the problem is that we don't know that yet, as this
17090  * convergence has to happen at iter_next() call site only. So if nothing is
17091  * done, at 1: verifier will use bounded loop logic and declare infinite
17092  * looping (and would be *technically* correct, if not for iterator's
17093  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
17094  * don't want that. So what we do in process_iter_next_call() when we go on
17095  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
17096  * a different iteration. So when we suspect an infinite loop, we additionally
17097  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
17098  * pretend we are not looping and wait for next iter_next() call.
17099  *
17100  * This only applies to ACTIVE state. In DRAINED state we don't expect to
17101  * loop, because that would actually mean infinite loop, as DRAINED state is
17102  * "sticky", and so we'll keep returning into the same instruction with the
17103  * same state (at least in one of possible code paths).
17104  *
17105  * This approach allows to keep infinite loop heuristic even in the face of
17106  * active iterator. E.g., C snippet below is and will be detected as
17107  * inifintely looping:
17108  *
17109  *   struct bpf_iter_num it;
17110  *   int *p, x;
17111  *
17112  *   bpf_iter_num_new(&it, 0, 10);
17113  *   while ((p = bpf_iter_num_next(&t))) {
17114  *       x = p;
17115  *       while (x--) {} // <<-- infinite loop here
17116  *   }
17117  *
17118  */
17119 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
17120 {
17121 	struct bpf_reg_state *slot, *cur_slot;
17122 	struct bpf_func_state *state;
17123 	int i, fr;
17124 
17125 	for (fr = old->curframe; fr >= 0; fr--) {
17126 		state = old->frame[fr];
17127 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17128 			if (state->stack[i].slot_type[0] != STACK_ITER)
17129 				continue;
17130 
17131 			slot = &state->stack[i].spilled_ptr;
17132 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
17133 				continue;
17134 
17135 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
17136 			if (cur_slot->iter.depth != slot->iter.depth)
17137 				return true;
17138 		}
17139 	}
17140 	return false;
17141 }
17142 
17143 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
17144 {
17145 	struct bpf_verifier_state_list *new_sl;
17146 	struct bpf_verifier_state_list *sl, **pprev;
17147 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
17148 	int i, j, n, err, states_cnt = 0;
17149 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
17150 	bool add_new_state = force_new_state;
17151 	bool force_exact;
17152 
17153 	/* bpf progs typically have pruning point every 4 instructions
17154 	 * http://vger.kernel.org/bpfconf2019.html#session-1
17155 	 * Do not add new state for future pruning if the verifier hasn't seen
17156 	 * at least 2 jumps and at least 8 instructions.
17157 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
17158 	 * In tests that amounts to up to 50% reduction into total verifier
17159 	 * memory consumption and 20% verifier time speedup.
17160 	 */
17161 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
17162 	    env->insn_processed - env->prev_insn_processed >= 8)
17163 		add_new_state = true;
17164 
17165 	pprev = explored_state(env, insn_idx);
17166 	sl = *pprev;
17167 
17168 	clean_live_states(env, insn_idx, cur);
17169 
17170 	while (sl) {
17171 		states_cnt++;
17172 		if (sl->state.insn_idx != insn_idx)
17173 			goto next;
17174 
17175 		if (sl->state.branches) {
17176 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
17177 
17178 			if (frame->in_async_callback_fn &&
17179 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
17180 				/* Different async_entry_cnt means that the verifier is
17181 				 * processing another entry into async callback.
17182 				 * Seeing the same state is not an indication of infinite
17183 				 * loop or infinite recursion.
17184 				 * But finding the same state doesn't mean that it's safe
17185 				 * to stop processing the current state. The previous state
17186 				 * hasn't yet reached bpf_exit, since state.branches > 0.
17187 				 * Checking in_async_callback_fn alone is not enough either.
17188 				 * Since the verifier still needs to catch infinite loops
17189 				 * inside async callbacks.
17190 				 */
17191 				goto skip_inf_loop_check;
17192 			}
17193 			/* BPF open-coded iterators loop detection is special.
17194 			 * states_maybe_looping() logic is too simplistic in detecting
17195 			 * states that *might* be equivalent, because it doesn't know
17196 			 * about ID remapping, so don't even perform it.
17197 			 * See process_iter_next_call() and iter_active_depths_differ()
17198 			 * for overview of the logic. When current and one of parent
17199 			 * states are detected as equivalent, it's a good thing: we prove
17200 			 * convergence and can stop simulating further iterations.
17201 			 * It's safe to assume that iterator loop will finish, taking into
17202 			 * account iter_next() contract of eventually returning
17203 			 * sticky NULL result.
17204 			 *
17205 			 * Note, that states have to be compared exactly in this case because
17206 			 * read and precision marks might not be finalized inside the loop.
17207 			 * E.g. as in the program below:
17208 			 *
17209 			 *     1. r7 = -16
17210 			 *     2. r6 = bpf_get_prandom_u32()
17211 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
17212 			 *     4.   if (r6 != 42) {
17213 			 *     5.     r7 = -32
17214 			 *     6.     r6 = bpf_get_prandom_u32()
17215 			 *     7.     continue
17216 			 *     8.   }
17217 			 *     9.   r0 = r10
17218 			 *    10.   r0 += r7
17219 			 *    11.   r8 = *(u64 *)(r0 + 0)
17220 			 *    12.   r6 = bpf_get_prandom_u32()
17221 			 *    13. }
17222 			 *
17223 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
17224 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
17225 			 * not have read or precision mark for r7 yet, thus inexact states
17226 			 * comparison would discard current state with r7=-32
17227 			 * => unsafe memory access at 11 would not be caught.
17228 			 */
17229 			if (is_iter_next_insn(env, insn_idx)) {
17230 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
17231 					struct bpf_func_state *cur_frame;
17232 					struct bpf_reg_state *iter_state, *iter_reg;
17233 					int spi;
17234 
17235 					cur_frame = cur->frame[cur->curframe];
17236 					/* btf_check_iter_kfuncs() enforces that
17237 					 * iter state pointer is always the first arg
17238 					 */
17239 					iter_reg = &cur_frame->regs[BPF_REG_1];
17240 					/* current state is valid due to states_equal(),
17241 					 * so we can assume valid iter and reg state,
17242 					 * no need for extra (re-)validations
17243 					 */
17244 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
17245 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
17246 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
17247 						update_loop_entry(cur, &sl->state);
17248 						goto hit;
17249 					}
17250 				}
17251 				goto skip_inf_loop_check;
17252 			}
17253 			if (is_may_goto_insn_at(env, insn_idx)) {
17254 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
17255 					update_loop_entry(cur, &sl->state);
17256 					goto hit;
17257 				}
17258 				goto skip_inf_loop_check;
17259 			}
17260 			if (calls_callback(env, insn_idx)) {
17261 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
17262 					goto hit;
17263 				goto skip_inf_loop_check;
17264 			}
17265 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
17266 			if (states_maybe_looping(&sl->state, cur) &&
17267 			    states_equal(env, &sl->state, cur, EXACT) &&
17268 			    !iter_active_depths_differ(&sl->state, cur) &&
17269 			    sl->state.may_goto_depth == cur->may_goto_depth &&
17270 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
17271 				verbose_linfo(env, insn_idx, "; ");
17272 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
17273 				verbose(env, "cur state:");
17274 				print_verifier_state(env, cur->frame[cur->curframe], true);
17275 				verbose(env, "old state:");
17276 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
17277 				return -EINVAL;
17278 			}
17279 			/* if the verifier is processing a loop, avoid adding new state
17280 			 * too often, since different loop iterations have distinct
17281 			 * states and may not help future pruning.
17282 			 * This threshold shouldn't be too low to make sure that
17283 			 * a loop with large bound will be rejected quickly.
17284 			 * The most abusive loop will be:
17285 			 * r1 += 1
17286 			 * if r1 < 1000000 goto pc-2
17287 			 * 1M insn_procssed limit / 100 == 10k peak states.
17288 			 * This threshold shouldn't be too high either, since states
17289 			 * at the end of the loop are likely to be useful in pruning.
17290 			 */
17291 skip_inf_loop_check:
17292 			if (!force_new_state &&
17293 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
17294 			    env->insn_processed - env->prev_insn_processed < 100)
17295 				add_new_state = false;
17296 			goto miss;
17297 		}
17298 		/* If sl->state is a part of a loop and this loop's entry is a part of
17299 		 * current verification path then states have to be compared exactly.
17300 		 * 'force_exact' is needed to catch the following case:
17301 		 *
17302 		 *                initial     Here state 'succ' was processed first,
17303 		 *                  |         it was eventually tracked to produce a
17304 		 *                  V         state identical to 'hdr'.
17305 		 *     .---------> hdr        All branches from 'succ' had been explored
17306 		 *     |            |         and thus 'succ' has its .branches == 0.
17307 		 *     |            V
17308 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
17309 		 *     |    |       |         to the same instruction + callsites.
17310 		 *     |    V       V         In such case it is necessary to check
17311 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
17312 		 *     |    |       |         If 'succ' and 'cur' are a part of the
17313 		 *     |    V       V         same loop exact flag has to be set.
17314 		 *     |   succ <- cur        To check if that is the case, verify
17315 		 *     |    |                 if loop entry of 'succ' is in current
17316 		 *     |    V                 DFS path.
17317 		 *     |   ...
17318 		 *     |    |
17319 		 *     '----'
17320 		 *
17321 		 * Additional details are in the comment before get_loop_entry().
17322 		 */
17323 		loop_entry = get_loop_entry(&sl->state);
17324 		force_exact = loop_entry && loop_entry->branches > 0;
17325 		if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) {
17326 			if (force_exact)
17327 				update_loop_entry(cur, loop_entry);
17328 hit:
17329 			sl->hit_cnt++;
17330 			/* reached equivalent register/stack state,
17331 			 * prune the search.
17332 			 * Registers read by the continuation are read by us.
17333 			 * If we have any write marks in env->cur_state, they
17334 			 * will prevent corresponding reads in the continuation
17335 			 * from reaching our parent (an explored_state).  Our
17336 			 * own state will get the read marks recorded, but
17337 			 * they'll be immediately forgotten as we're pruning
17338 			 * this state and will pop a new one.
17339 			 */
17340 			err = propagate_liveness(env, &sl->state, cur);
17341 
17342 			/* if previous state reached the exit with precision and
17343 			 * current state is equivalent to it (except precsion marks)
17344 			 * the precision needs to be propagated back in
17345 			 * the current state.
17346 			 */
17347 			if (is_jmp_point(env, env->insn_idx))
17348 				err = err ? : push_jmp_history(env, cur, 0);
17349 			err = err ? : propagate_precision(env, &sl->state);
17350 			if (err)
17351 				return err;
17352 			return 1;
17353 		}
17354 miss:
17355 		/* when new state is not going to be added do not increase miss count.
17356 		 * Otherwise several loop iterations will remove the state
17357 		 * recorded earlier. The goal of these heuristics is to have
17358 		 * states from some iterations of the loop (some in the beginning
17359 		 * and some at the end) to help pruning.
17360 		 */
17361 		if (add_new_state)
17362 			sl->miss_cnt++;
17363 		/* heuristic to determine whether this state is beneficial
17364 		 * to keep checking from state equivalence point of view.
17365 		 * Higher numbers increase max_states_per_insn and verification time,
17366 		 * but do not meaningfully decrease insn_processed.
17367 		 * 'n' controls how many times state could miss before eviction.
17368 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
17369 		 * too early would hinder iterator convergence.
17370 		 */
17371 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
17372 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
17373 			/* the state is unlikely to be useful. Remove it to
17374 			 * speed up verification
17375 			 */
17376 			*pprev = sl->next;
17377 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
17378 			    !sl->state.used_as_loop_entry) {
17379 				u32 br = sl->state.branches;
17380 
17381 				WARN_ONCE(br,
17382 					  "BUG live_done but branches_to_explore %d\n",
17383 					  br);
17384 				free_verifier_state(&sl->state, false);
17385 				kfree(sl);
17386 				env->peak_states--;
17387 			} else {
17388 				/* cannot free this state, since parentage chain may
17389 				 * walk it later. Add it for free_list instead to
17390 				 * be freed at the end of verification
17391 				 */
17392 				sl->next = env->free_list;
17393 				env->free_list = sl;
17394 			}
17395 			sl = *pprev;
17396 			continue;
17397 		}
17398 next:
17399 		pprev = &sl->next;
17400 		sl = *pprev;
17401 	}
17402 
17403 	if (env->max_states_per_insn < states_cnt)
17404 		env->max_states_per_insn = states_cnt;
17405 
17406 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
17407 		return 0;
17408 
17409 	if (!add_new_state)
17410 		return 0;
17411 
17412 	/* There were no equivalent states, remember the current one.
17413 	 * Technically the current state is not proven to be safe yet,
17414 	 * but it will either reach outer most bpf_exit (which means it's safe)
17415 	 * or it will be rejected. When there are no loops the verifier won't be
17416 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
17417 	 * again on the way to bpf_exit.
17418 	 * When looping the sl->state.branches will be > 0 and this state
17419 	 * will not be considered for equivalence until branches == 0.
17420 	 */
17421 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
17422 	if (!new_sl)
17423 		return -ENOMEM;
17424 	env->total_states++;
17425 	env->peak_states++;
17426 	env->prev_jmps_processed = env->jmps_processed;
17427 	env->prev_insn_processed = env->insn_processed;
17428 
17429 	/* forget precise markings we inherited, see __mark_chain_precision */
17430 	if (env->bpf_capable)
17431 		mark_all_scalars_imprecise(env, cur);
17432 
17433 	/* add new state to the head of linked list */
17434 	new = &new_sl->state;
17435 	err = copy_verifier_state(new, cur);
17436 	if (err) {
17437 		free_verifier_state(new, false);
17438 		kfree(new_sl);
17439 		return err;
17440 	}
17441 	new->insn_idx = insn_idx;
17442 	WARN_ONCE(new->branches != 1,
17443 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
17444 
17445 	cur->parent = new;
17446 	cur->first_insn_idx = insn_idx;
17447 	cur->dfs_depth = new->dfs_depth + 1;
17448 	clear_jmp_history(cur);
17449 	new_sl->next = *explored_state(env, insn_idx);
17450 	*explored_state(env, insn_idx) = new_sl;
17451 	/* connect new state to parentage chain. Current frame needs all
17452 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
17453 	 * to the stack implicitly by JITs) so in callers' frames connect just
17454 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
17455 	 * the state of the call instruction (with WRITTEN set), and r0 comes
17456 	 * from callee with its full parentage chain, anyway.
17457 	 */
17458 	/* clear write marks in current state: the writes we did are not writes
17459 	 * our child did, so they don't screen off its reads from us.
17460 	 * (There are no read marks in current state, because reads always mark
17461 	 * their parent and current state never has children yet.  Only
17462 	 * explored_states can get read marks.)
17463 	 */
17464 	for (j = 0; j <= cur->curframe; j++) {
17465 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
17466 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
17467 		for (i = 0; i < BPF_REG_FP; i++)
17468 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
17469 	}
17470 
17471 	/* all stack frames are accessible from callee, clear them all */
17472 	for (j = 0; j <= cur->curframe; j++) {
17473 		struct bpf_func_state *frame = cur->frame[j];
17474 		struct bpf_func_state *newframe = new->frame[j];
17475 
17476 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
17477 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
17478 			frame->stack[i].spilled_ptr.parent =
17479 						&newframe->stack[i].spilled_ptr;
17480 		}
17481 	}
17482 	return 0;
17483 }
17484 
17485 /* Return true if it's OK to have the same insn return a different type. */
17486 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
17487 {
17488 	switch (base_type(type)) {
17489 	case PTR_TO_CTX:
17490 	case PTR_TO_SOCKET:
17491 	case PTR_TO_SOCK_COMMON:
17492 	case PTR_TO_TCP_SOCK:
17493 	case PTR_TO_XDP_SOCK:
17494 	case PTR_TO_BTF_ID:
17495 	case PTR_TO_ARENA:
17496 		return false;
17497 	default:
17498 		return true;
17499 	}
17500 }
17501 
17502 /* If an instruction was previously used with particular pointer types, then we
17503  * need to be careful to avoid cases such as the below, where it may be ok
17504  * for one branch accessing the pointer, but not ok for the other branch:
17505  *
17506  * R1 = sock_ptr
17507  * goto X;
17508  * ...
17509  * R1 = some_other_valid_ptr;
17510  * goto X;
17511  * ...
17512  * R2 = *(u32 *)(R1 + 0);
17513  */
17514 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17515 {
17516 	return src != prev && (!reg_type_mismatch_ok(src) ||
17517 			       !reg_type_mismatch_ok(prev));
17518 }
17519 
17520 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17521 			     bool allow_trust_missmatch)
17522 {
17523 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17524 
17525 	if (*prev_type == NOT_INIT) {
17526 		/* Saw a valid insn
17527 		 * dst_reg = *(u32 *)(src_reg + off)
17528 		 * save type to validate intersecting paths
17529 		 */
17530 		*prev_type = type;
17531 	} else if (reg_type_mismatch(type, *prev_type)) {
17532 		/* Abuser program is trying to use the same insn
17533 		 * dst_reg = *(u32*) (src_reg + off)
17534 		 * with different pointer types:
17535 		 * src_reg == ctx in one branch and
17536 		 * src_reg == stack|map in some other branch.
17537 		 * Reject it.
17538 		 */
17539 		if (allow_trust_missmatch &&
17540 		    base_type(type) == PTR_TO_BTF_ID &&
17541 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
17542 			/*
17543 			 * Have to support a use case when one path through
17544 			 * the program yields TRUSTED pointer while another
17545 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
17546 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
17547 			 */
17548 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
17549 		} else {
17550 			verbose(env, "same insn cannot be used with different pointers\n");
17551 			return -EINVAL;
17552 		}
17553 	}
17554 
17555 	return 0;
17556 }
17557 
17558 static int do_check(struct bpf_verifier_env *env)
17559 {
17560 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17561 	struct bpf_verifier_state *state = env->cur_state;
17562 	struct bpf_insn *insns = env->prog->insnsi;
17563 	struct bpf_reg_state *regs;
17564 	int insn_cnt = env->prog->len;
17565 	bool do_print_state = false;
17566 	int prev_insn_idx = -1;
17567 
17568 	for (;;) {
17569 		bool exception_exit = false;
17570 		struct bpf_insn *insn;
17571 		u8 class;
17572 		int err;
17573 
17574 		/* reset current history entry on each new instruction */
17575 		env->cur_hist_ent = NULL;
17576 
17577 		env->prev_insn_idx = prev_insn_idx;
17578 		if (env->insn_idx >= insn_cnt) {
17579 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
17580 				env->insn_idx, insn_cnt);
17581 			return -EFAULT;
17582 		}
17583 
17584 		insn = &insns[env->insn_idx];
17585 		class = BPF_CLASS(insn->code);
17586 
17587 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17588 			verbose(env,
17589 				"BPF program is too large. Processed %d insn\n",
17590 				env->insn_processed);
17591 			return -E2BIG;
17592 		}
17593 
17594 		state->last_insn_idx = env->prev_insn_idx;
17595 
17596 		if (is_prune_point(env, env->insn_idx)) {
17597 			err = is_state_visited(env, env->insn_idx);
17598 			if (err < 0)
17599 				return err;
17600 			if (err == 1) {
17601 				/* found equivalent state, can prune the search */
17602 				if (env->log.level & BPF_LOG_LEVEL) {
17603 					if (do_print_state)
17604 						verbose(env, "\nfrom %d to %d%s: safe\n",
17605 							env->prev_insn_idx, env->insn_idx,
17606 							env->cur_state->speculative ?
17607 							" (speculative execution)" : "");
17608 					else
17609 						verbose(env, "%d: safe\n", env->insn_idx);
17610 				}
17611 				goto process_bpf_exit;
17612 			}
17613 		}
17614 
17615 		if (is_jmp_point(env, env->insn_idx)) {
17616 			err = push_jmp_history(env, state, 0);
17617 			if (err)
17618 				return err;
17619 		}
17620 
17621 		if (signal_pending(current))
17622 			return -EAGAIN;
17623 
17624 		if (need_resched())
17625 			cond_resched();
17626 
17627 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17628 			verbose(env, "\nfrom %d to %d%s:",
17629 				env->prev_insn_idx, env->insn_idx,
17630 				env->cur_state->speculative ?
17631 				" (speculative execution)" : "");
17632 			print_verifier_state(env, state->frame[state->curframe], true);
17633 			do_print_state = false;
17634 		}
17635 
17636 		if (env->log.level & BPF_LOG_LEVEL) {
17637 			const struct bpf_insn_cbs cbs = {
17638 				.cb_call	= disasm_kfunc_name,
17639 				.cb_print	= verbose,
17640 				.private_data	= env,
17641 			};
17642 
17643 			if (verifier_state_scratched(env))
17644 				print_insn_state(env, state->frame[state->curframe]);
17645 
17646 			verbose_linfo(env, env->insn_idx, "; ");
17647 			env->prev_log_pos = env->log.end_pos;
17648 			verbose(env, "%d: ", env->insn_idx);
17649 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17650 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17651 			env->prev_log_pos = env->log.end_pos;
17652 		}
17653 
17654 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17655 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17656 							   env->prev_insn_idx);
17657 			if (err)
17658 				return err;
17659 		}
17660 
17661 		regs = cur_regs(env);
17662 		sanitize_mark_insn_seen(env);
17663 		prev_insn_idx = env->insn_idx;
17664 
17665 		if (class == BPF_ALU || class == BPF_ALU64) {
17666 			err = check_alu_op(env, insn);
17667 			if (err)
17668 				return err;
17669 
17670 		} else if (class == BPF_LDX) {
17671 			enum bpf_reg_type src_reg_type;
17672 
17673 			/* check for reserved fields is already done */
17674 
17675 			/* check src operand */
17676 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17677 			if (err)
17678 				return err;
17679 
17680 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17681 			if (err)
17682 				return err;
17683 
17684 			src_reg_type = regs[insn->src_reg].type;
17685 
17686 			/* check that memory (src_reg + off) is readable,
17687 			 * the state of dst_reg will be updated by this func
17688 			 */
17689 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17690 					       insn->off, BPF_SIZE(insn->code),
17691 					       BPF_READ, insn->dst_reg, false,
17692 					       BPF_MODE(insn->code) == BPF_MEMSX);
17693 			err = err ?: save_aux_ptr_type(env, src_reg_type, true);
17694 			err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], "ldx");
17695 			if (err)
17696 				return err;
17697 		} else if (class == BPF_STX) {
17698 			enum bpf_reg_type dst_reg_type;
17699 
17700 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17701 				err = check_atomic(env, env->insn_idx, insn);
17702 				if (err)
17703 					return err;
17704 				env->insn_idx++;
17705 				continue;
17706 			}
17707 
17708 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17709 				verbose(env, "BPF_STX uses reserved fields\n");
17710 				return -EINVAL;
17711 			}
17712 
17713 			/* check src1 operand */
17714 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17715 			if (err)
17716 				return err;
17717 			/* check src2 operand */
17718 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17719 			if (err)
17720 				return err;
17721 
17722 			dst_reg_type = regs[insn->dst_reg].type;
17723 
17724 			/* check that memory (dst_reg + off) is writeable */
17725 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17726 					       insn->off, BPF_SIZE(insn->code),
17727 					       BPF_WRITE, insn->src_reg, false, false);
17728 			if (err)
17729 				return err;
17730 
17731 			err = save_aux_ptr_type(env, dst_reg_type, false);
17732 			if (err)
17733 				return err;
17734 		} else if (class == BPF_ST) {
17735 			enum bpf_reg_type dst_reg_type;
17736 
17737 			if (BPF_MODE(insn->code) != BPF_MEM ||
17738 			    insn->src_reg != BPF_REG_0) {
17739 				verbose(env, "BPF_ST uses reserved fields\n");
17740 				return -EINVAL;
17741 			}
17742 			/* check src operand */
17743 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17744 			if (err)
17745 				return err;
17746 
17747 			dst_reg_type = regs[insn->dst_reg].type;
17748 
17749 			/* check that memory (dst_reg + off) is writeable */
17750 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17751 					       insn->off, BPF_SIZE(insn->code),
17752 					       BPF_WRITE, -1, false, false);
17753 			if (err)
17754 				return err;
17755 
17756 			err = save_aux_ptr_type(env, dst_reg_type, false);
17757 			if (err)
17758 				return err;
17759 		} else if (class == BPF_JMP || class == BPF_JMP32) {
17760 			u8 opcode = BPF_OP(insn->code);
17761 
17762 			env->jmps_processed++;
17763 			if (opcode == BPF_CALL) {
17764 				if (BPF_SRC(insn->code) != BPF_K ||
17765 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17766 				     && insn->off != 0) ||
17767 				    (insn->src_reg != BPF_REG_0 &&
17768 				     insn->src_reg != BPF_PSEUDO_CALL &&
17769 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17770 				    insn->dst_reg != BPF_REG_0 ||
17771 				    class == BPF_JMP32) {
17772 					verbose(env, "BPF_CALL uses reserved fields\n");
17773 					return -EINVAL;
17774 				}
17775 
17776 				if (env->cur_state->active_lock.ptr) {
17777 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17778 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17779 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17780 						verbose(env, "function calls are not allowed while holding a lock\n");
17781 						return -EINVAL;
17782 					}
17783 				}
17784 				if (insn->src_reg == BPF_PSEUDO_CALL) {
17785 					err = check_func_call(env, insn, &env->insn_idx);
17786 				} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17787 					err = check_kfunc_call(env, insn, &env->insn_idx);
17788 					if (!err && is_bpf_throw_kfunc(insn)) {
17789 						exception_exit = true;
17790 						goto process_bpf_exit_full;
17791 					}
17792 				} else {
17793 					err = check_helper_call(env, insn, &env->insn_idx);
17794 				}
17795 				if (err)
17796 					return err;
17797 
17798 				mark_reg_scratched(env, BPF_REG_0);
17799 			} else if (opcode == BPF_JA) {
17800 				if (BPF_SRC(insn->code) != BPF_K ||
17801 				    insn->src_reg != BPF_REG_0 ||
17802 				    insn->dst_reg != BPF_REG_0 ||
17803 				    (class == BPF_JMP && insn->imm != 0) ||
17804 				    (class == BPF_JMP32 && insn->off != 0)) {
17805 					verbose(env, "BPF_JA uses reserved fields\n");
17806 					return -EINVAL;
17807 				}
17808 
17809 				if (class == BPF_JMP)
17810 					env->insn_idx += insn->off + 1;
17811 				else
17812 					env->insn_idx += insn->imm + 1;
17813 				continue;
17814 
17815 			} else if (opcode == BPF_EXIT) {
17816 				if (BPF_SRC(insn->code) != BPF_K ||
17817 				    insn->imm != 0 ||
17818 				    insn->src_reg != BPF_REG_0 ||
17819 				    insn->dst_reg != BPF_REG_0 ||
17820 				    class == BPF_JMP32) {
17821 					verbose(env, "BPF_EXIT uses reserved fields\n");
17822 					return -EINVAL;
17823 				}
17824 process_bpf_exit_full:
17825 				if (env->cur_state->active_lock.ptr && !env->cur_state->curframe) {
17826 					verbose(env, "bpf_spin_unlock is missing\n");
17827 					return -EINVAL;
17828 				}
17829 
17830 				if (env->cur_state->active_rcu_lock && !env->cur_state->curframe) {
17831 					verbose(env, "bpf_rcu_read_unlock is missing\n");
17832 					return -EINVAL;
17833 				}
17834 
17835 				/* We must do check_reference_leak here before
17836 				 * prepare_func_exit to handle the case when
17837 				 * state->curframe > 0, it may be a callback
17838 				 * function, for which reference_state must
17839 				 * match caller reference state when it exits.
17840 				 */
17841 				err = check_reference_leak(env, exception_exit);
17842 				if (err)
17843 					return err;
17844 
17845 				/* The side effect of the prepare_func_exit
17846 				 * which is being skipped is that it frees
17847 				 * bpf_func_state. Typically, process_bpf_exit
17848 				 * will only be hit with outermost exit.
17849 				 * copy_verifier_state in pop_stack will handle
17850 				 * freeing of any extra bpf_func_state left over
17851 				 * from not processing all nested function
17852 				 * exits. We also skip return code checks as
17853 				 * they are not needed for exceptional exits.
17854 				 */
17855 				if (exception_exit)
17856 					goto process_bpf_exit;
17857 
17858 				if (state->curframe) {
17859 					/* exit from nested function */
17860 					err = prepare_func_exit(env, &env->insn_idx);
17861 					if (err)
17862 						return err;
17863 					do_print_state = true;
17864 					continue;
17865 				}
17866 
17867 				err = check_return_code(env, BPF_REG_0, "R0");
17868 				if (err)
17869 					return err;
17870 process_bpf_exit:
17871 				mark_verifier_state_scratched(env);
17872 				update_branch_counts(env, env->cur_state);
17873 				err = pop_stack(env, &prev_insn_idx,
17874 						&env->insn_idx, pop_log);
17875 				if (err < 0) {
17876 					if (err != -ENOENT)
17877 						return err;
17878 					break;
17879 				} else {
17880 					do_print_state = true;
17881 					continue;
17882 				}
17883 			} else {
17884 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
17885 				if (err)
17886 					return err;
17887 			}
17888 		} else if (class == BPF_LD) {
17889 			u8 mode = BPF_MODE(insn->code);
17890 
17891 			if (mode == BPF_ABS || mode == BPF_IND) {
17892 				err = check_ld_abs(env, insn);
17893 				if (err)
17894 					return err;
17895 
17896 			} else if (mode == BPF_IMM) {
17897 				err = check_ld_imm(env, insn);
17898 				if (err)
17899 					return err;
17900 
17901 				env->insn_idx++;
17902 				sanitize_mark_insn_seen(env);
17903 			} else {
17904 				verbose(env, "invalid BPF_LD mode\n");
17905 				return -EINVAL;
17906 			}
17907 		} else {
17908 			verbose(env, "unknown insn class %d\n", class);
17909 			return -EINVAL;
17910 		}
17911 
17912 		env->insn_idx++;
17913 	}
17914 
17915 	return 0;
17916 }
17917 
17918 static int find_btf_percpu_datasec(struct btf *btf)
17919 {
17920 	const struct btf_type *t;
17921 	const char *tname;
17922 	int i, n;
17923 
17924 	/*
17925 	 * Both vmlinux and module each have their own ".data..percpu"
17926 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17927 	 * types to look at only module's own BTF types.
17928 	 */
17929 	n = btf_nr_types(btf);
17930 	if (btf_is_module(btf))
17931 		i = btf_nr_types(btf_vmlinux);
17932 	else
17933 		i = 1;
17934 
17935 	for(; i < n; i++) {
17936 		t = btf_type_by_id(btf, i);
17937 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17938 			continue;
17939 
17940 		tname = btf_name_by_offset(btf, t->name_off);
17941 		if (!strcmp(tname, ".data..percpu"))
17942 			return i;
17943 	}
17944 
17945 	return -ENOENT;
17946 }
17947 
17948 /* replace pseudo btf_id with kernel symbol address */
17949 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17950 			       struct bpf_insn *insn,
17951 			       struct bpf_insn_aux_data *aux)
17952 {
17953 	const struct btf_var_secinfo *vsi;
17954 	const struct btf_type *datasec;
17955 	struct btf_mod_pair *btf_mod;
17956 	const struct btf_type *t;
17957 	const char *sym_name;
17958 	bool percpu = false;
17959 	u32 type, id = insn->imm;
17960 	struct btf *btf;
17961 	s32 datasec_id;
17962 	u64 addr;
17963 	int i, btf_fd, err;
17964 
17965 	btf_fd = insn[1].imm;
17966 	if (btf_fd) {
17967 		btf = btf_get_by_fd(btf_fd);
17968 		if (IS_ERR(btf)) {
17969 			verbose(env, "invalid module BTF object FD specified.\n");
17970 			return -EINVAL;
17971 		}
17972 	} else {
17973 		if (!btf_vmlinux) {
17974 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17975 			return -EINVAL;
17976 		}
17977 		btf = btf_vmlinux;
17978 		btf_get(btf);
17979 	}
17980 
17981 	t = btf_type_by_id(btf, id);
17982 	if (!t) {
17983 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17984 		err = -ENOENT;
17985 		goto err_put;
17986 	}
17987 
17988 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17989 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17990 		err = -EINVAL;
17991 		goto err_put;
17992 	}
17993 
17994 	sym_name = btf_name_by_offset(btf, t->name_off);
17995 	addr = kallsyms_lookup_name(sym_name);
17996 	if (!addr) {
17997 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17998 			sym_name);
17999 		err = -ENOENT;
18000 		goto err_put;
18001 	}
18002 	insn[0].imm = (u32)addr;
18003 	insn[1].imm = addr >> 32;
18004 
18005 	if (btf_type_is_func(t)) {
18006 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18007 		aux->btf_var.mem_size = 0;
18008 		goto check_btf;
18009 	}
18010 
18011 	datasec_id = find_btf_percpu_datasec(btf);
18012 	if (datasec_id > 0) {
18013 		datasec = btf_type_by_id(btf, datasec_id);
18014 		for_each_vsi(i, datasec, vsi) {
18015 			if (vsi->type == id) {
18016 				percpu = true;
18017 				break;
18018 			}
18019 		}
18020 	}
18021 
18022 	type = t->type;
18023 	t = btf_type_skip_modifiers(btf, type, NULL);
18024 	if (percpu) {
18025 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
18026 		aux->btf_var.btf = btf;
18027 		aux->btf_var.btf_id = type;
18028 	} else if (!btf_type_is_struct(t)) {
18029 		const struct btf_type *ret;
18030 		const char *tname;
18031 		u32 tsize;
18032 
18033 		/* resolve the type size of ksym. */
18034 		ret = btf_resolve_size(btf, t, &tsize);
18035 		if (IS_ERR(ret)) {
18036 			tname = btf_name_by_offset(btf, t->name_off);
18037 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
18038 				tname, PTR_ERR(ret));
18039 			err = -EINVAL;
18040 			goto err_put;
18041 		}
18042 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18043 		aux->btf_var.mem_size = tsize;
18044 	} else {
18045 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
18046 		aux->btf_var.btf = btf;
18047 		aux->btf_var.btf_id = type;
18048 	}
18049 check_btf:
18050 	/* check whether we recorded this BTF (and maybe module) already */
18051 	for (i = 0; i < env->used_btf_cnt; i++) {
18052 		if (env->used_btfs[i].btf == btf) {
18053 			btf_put(btf);
18054 			return 0;
18055 		}
18056 	}
18057 
18058 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
18059 		err = -E2BIG;
18060 		goto err_put;
18061 	}
18062 
18063 	btf_mod = &env->used_btfs[env->used_btf_cnt];
18064 	btf_mod->btf = btf;
18065 	btf_mod->module = NULL;
18066 
18067 	/* if we reference variables from kernel module, bump its refcount */
18068 	if (btf_is_module(btf)) {
18069 		btf_mod->module = btf_try_get_module(btf);
18070 		if (!btf_mod->module) {
18071 			err = -ENXIO;
18072 			goto err_put;
18073 		}
18074 	}
18075 
18076 	env->used_btf_cnt++;
18077 
18078 	return 0;
18079 err_put:
18080 	btf_put(btf);
18081 	return err;
18082 }
18083 
18084 static bool is_tracing_prog_type(enum bpf_prog_type type)
18085 {
18086 	switch (type) {
18087 	case BPF_PROG_TYPE_KPROBE:
18088 	case BPF_PROG_TYPE_TRACEPOINT:
18089 	case BPF_PROG_TYPE_PERF_EVENT:
18090 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
18091 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
18092 		return true;
18093 	default:
18094 		return false;
18095 	}
18096 }
18097 
18098 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
18099 					struct bpf_map *map,
18100 					struct bpf_prog *prog)
18101 
18102 {
18103 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18104 
18105 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
18106 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
18107 		if (is_tracing_prog_type(prog_type)) {
18108 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
18109 			return -EINVAL;
18110 		}
18111 	}
18112 
18113 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
18114 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
18115 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
18116 			return -EINVAL;
18117 		}
18118 
18119 		if (is_tracing_prog_type(prog_type)) {
18120 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
18121 			return -EINVAL;
18122 		}
18123 	}
18124 
18125 	if (btf_record_has_field(map->record, BPF_TIMER)) {
18126 		if (is_tracing_prog_type(prog_type)) {
18127 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
18128 			return -EINVAL;
18129 		}
18130 	}
18131 
18132 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
18133 	    !bpf_offload_prog_map_match(prog, map)) {
18134 		verbose(env, "offload device mismatch between prog and map\n");
18135 		return -EINVAL;
18136 	}
18137 
18138 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
18139 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
18140 		return -EINVAL;
18141 	}
18142 
18143 	if (prog->sleepable)
18144 		switch (map->map_type) {
18145 		case BPF_MAP_TYPE_HASH:
18146 		case BPF_MAP_TYPE_LRU_HASH:
18147 		case BPF_MAP_TYPE_ARRAY:
18148 		case BPF_MAP_TYPE_PERCPU_HASH:
18149 		case BPF_MAP_TYPE_PERCPU_ARRAY:
18150 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
18151 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
18152 		case BPF_MAP_TYPE_HASH_OF_MAPS:
18153 		case BPF_MAP_TYPE_RINGBUF:
18154 		case BPF_MAP_TYPE_USER_RINGBUF:
18155 		case BPF_MAP_TYPE_INODE_STORAGE:
18156 		case BPF_MAP_TYPE_SK_STORAGE:
18157 		case BPF_MAP_TYPE_TASK_STORAGE:
18158 		case BPF_MAP_TYPE_CGRP_STORAGE:
18159 		case BPF_MAP_TYPE_QUEUE:
18160 		case BPF_MAP_TYPE_STACK:
18161 		case BPF_MAP_TYPE_ARENA:
18162 			break;
18163 		default:
18164 			verbose(env,
18165 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
18166 			return -EINVAL;
18167 		}
18168 
18169 	return 0;
18170 }
18171 
18172 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
18173 {
18174 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
18175 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
18176 }
18177 
18178 /* find and rewrite pseudo imm in ld_imm64 instructions:
18179  *
18180  * 1. if it accesses map FD, replace it with actual map pointer.
18181  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
18182  *
18183  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
18184  */
18185 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
18186 {
18187 	struct bpf_insn *insn = env->prog->insnsi;
18188 	int insn_cnt = env->prog->len;
18189 	int i, j, err;
18190 
18191 	err = bpf_prog_calc_tag(env->prog);
18192 	if (err)
18193 		return err;
18194 
18195 	for (i = 0; i < insn_cnt; i++, insn++) {
18196 		if (BPF_CLASS(insn->code) == BPF_LDX &&
18197 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
18198 		    insn->imm != 0)) {
18199 			verbose(env, "BPF_LDX uses reserved fields\n");
18200 			return -EINVAL;
18201 		}
18202 
18203 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
18204 			struct bpf_insn_aux_data *aux;
18205 			struct bpf_map *map;
18206 			struct fd f;
18207 			u64 addr;
18208 			u32 fd;
18209 
18210 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
18211 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
18212 			    insn[1].off != 0) {
18213 				verbose(env, "invalid bpf_ld_imm64 insn\n");
18214 				return -EINVAL;
18215 			}
18216 
18217 			if (insn[0].src_reg == 0)
18218 				/* valid generic load 64-bit imm */
18219 				goto next_insn;
18220 
18221 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
18222 				aux = &env->insn_aux_data[i];
18223 				err = check_pseudo_btf_id(env, insn, aux);
18224 				if (err)
18225 					return err;
18226 				goto next_insn;
18227 			}
18228 
18229 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
18230 				aux = &env->insn_aux_data[i];
18231 				aux->ptr_type = PTR_TO_FUNC;
18232 				goto next_insn;
18233 			}
18234 
18235 			/* In final convert_pseudo_ld_imm64() step, this is
18236 			 * converted into regular 64-bit imm load insn.
18237 			 */
18238 			switch (insn[0].src_reg) {
18239 			case BPF_PSEUDO_MAP_VALUE:
18240 			case BPF_PSEUDO_MAP_IDX_VALUE:
18241 				break;
18242 			case BPF_PSEUDO_MAP_FD:
18243 			case BPF_PSEUDO_MAP_IDX:
18244 				if (insn[1].imm == 0)
18245 					break;
18246 				fallthrough;
18247 			default:
18248 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
18249 				return -EINVAL;
18250 			}
18251 
18252 			switch (insn[0].src_reg) {
18253 			case BPF_PSEUDO_MAP_IDX_VALUE:
18254 			case BPF_PSEUDO_MAP_IDX:
18255 				if (bpfptr_is_null(env->fd_array)) {
18256 					verbose(env, "fd_idx without fd_array is invalid\n");
18257 					return -EPROTO;
18258 				}
18259 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
18260 							    insn[0].imm * sizeof(fd),
18261 							    sizeof(fd)))
18262 					return -EFAULT;
18263 				break;
18264 			default:
18265 				fd = insn[0].imm;
18266 				break;
18267 			}
18268 
18269 			f = fdget(fd);
18270 			map = __bpf_map_get(f);
18271 			if (IS_ERR(map)) {
18272 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
18273 					insn[0].imm);
18274 				return PTR_ERR(map);
18275 			}
18276 
18277 			err = check_map_prog_compatibility(env, map, env->prog);
18278 			if (err) {
18279 				fdput(f);
18280 				return err;
18281 			}
18282 
18283 			aux = &env->insn_aux_data[i];
18284 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
18285 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
18286 				addr = (unsigned long)map;
18287 			} else {
18288 				u32 off = insn[1].imm;
18289 
18290 				if (off >= BPF_MAX_VAR_OFF) {
18291 					verbose(env, "direct value offset of %u is not allowed\n", off);
18292 					fdput(f);
18293 					return -EINVAL;
18294 				}
18295 
18296 				if (!map->ops->map_direct_value_addr) {
18297 					verbose(env, "no direct value access support for this map type\n");
18298 					fdput(f);
18299 					return -EINVAL;
18300 				}
18301 
18302 				err = map->ops->map_direct_value_addr(map, &addr, off);
18303 				if (err) {
18304 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
18305 						map->value_size, off);
18306 					fdput(f);
18307 					return err;
18308 				}
18309 
18310 				aux->map_off = off;
18311 				addr += off;
18312 			}
18313 
18314 			insn[0].imm = (u32)addr;
18315 			insn[1].imm = addr >> 32;
18316 
18317 			/* check whether we recorded this map already */
18318 			for (j = 0; j < env->used_map_cnt; j++) {
18319 				if (env->used_maps[j] == map) {
18320 					aux->map_index = j;
18321 					fdput(f);
18322 					goto next_insn;
18323 				}
18324 			}
18325 
18326 			if (env->used_map_cnt >= MAX_USED_MAPS) {
18327 				fdput(f);
18328 				return -E2BIG;
18329 			}
18330 
18331 			if (env->prog->sleepable)
18332 				atomic64_inc(&map->sleepable_refcnt);
18333 			/* hold the map. If the program is rejected by verifier,
18334 			 * the map will be released by release_maps() or it
18335 			 * will be used by the valid program until it's unloaded
18336 			 * and all maps are released in bpf_free_used_maps()
18337 			 */
18338 			bpf_map_inc(map);
18339 
18340 			aux->map_index = env->used_map_cnt;
18341 			env->used_maps[env->used_map_cnt++] = map;
18342 
18343 			if (bpf_map_is_cgroup_storage(map) &&
18344 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
18345 				verbose(env, "only one cgroup storage of each type is allowed\n");
18346 				fdput(f);
18347 				return -EBUSY;
18348 			}
18349 			if (map->map_type == BPF_MAP_TYPE_ARENA) {
18350 				if (env->prog->aux->arena) {
18351 					verbose(env, "Only one arena per program\n");
18352 					fdput(f);
18353 					return -EBUSY;
18354 				}
18355 				if (!env->allow_ptr_leaks || !env->bpf_capable) {
18356 					verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
18357 					fdput(f);
18358 					return -EPERM;
18359 				}
18360 				if (!env->prog->jit_requested) {
18361 					verbose(env, "JIT is required to use arena\n");
18362 					return -EOPNOTSUPP;
18363 				}
18364 				if (!bpf_jit_supports_arena()) {
18365 					verbose(env, "JIT doesn't support arena\n");
18366 					return -EOPNOTSUPP;
18367 				}
18368 				env->prog->aux->arena = (void *)map;
18369 				if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
18370 					verbose(env, "arena's user address must be set via map_extra or mmap()\n");
18371 					return -EINVAL;
18372 				}
18373 			}
18374 
18375 			fdput(f);
18376 next_insn:
18377 			insn++;
18378 			i++;
18379 			continue;
18380 		}
18381 
18382 		/* Basic sanity check before we invest more work here. */
18383 		if (!bpf_opcode_in_insntable(insn->code)) {
18384 			verbose(env, "unknown opcode %02x\n", insn->code);
18385 			return -EINVAL;
18386 		}
18387 	}
18388 
18389 	/* now all pseudo BPF_LD_IMM64 instructions load valid
18390 	 * 'struct bpf_map *' into a register instead of user map_fd.
18391 	 * These pointers will be used later by verifier to validate map access.
18392 	 */
18393 	return 0;
18394 }
18395 
18396 /* drop refcnt of maps used by the rejected program */
18397 static void release_maps(struct bpf_verifier_env *env)
18398 {
18399 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
18400 			     env->used_map_cnt);
18401 }
18402 
18403 /* drop refcnt of maps used by the rejected program */
18404 static void release_btfs(struct bpf_verifier_env *env)
18405 {
18406 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
18407 			     env->used_btf_cnt);
18408 }
18409 
18410 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
18411 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
18412 {
18413 	struct bpf_insn *insn = env->prog->insnsi;
18414 	int insn_cnt = env->prog->len;
18415 	int i;
18416 
18417 	for (i = 0; i < insn_cnt; i++, insn++) {
18418 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
18419 			continue;
18420 		if (insn->src_reg == BPF_PSEUDO_FUNC)
18421 			continue;
18422 		insn->src_reg = 0;
18423 	}
18424 }
18425 
18426 /* single env->prog->insni[off] instruction was replaced with the range
18427  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
18428  * [0, off) and [off, end) to new locations, so the patched range stays zero
18429  */
18430 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
18431 				 struct bpf_insn_aux_data *new_data,
18432 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
18433 {
18434 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
18435 	struct bpf_insn *insn = new_prog->insnsi;
18436 	u32 old_seen = old_data[off].seen;
18437 	u32 prog_len;
18438 	int i;
18439 
18440 	/* aux info at OFF always needs adjustment, no matter fast path
18441 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
18442 	 * original insn at old prog.
18443 	 */
18444 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
18445 
18446 	if (cnt == 1)
18447 		return;
18448 	prog_len = new_prog->len;
18449 
18450 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
18451 	memcpy(new_data + off + cnt - 1, old_data + off,
18452 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
18453 	for (i = off; i < off + cnt - 1; i++) {
18454 		/* Expand insni[off]'s seen count to the patched range. */
18455 		new_data[i].seen = old_seen;
18456 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
18457 	}
18458 	env->insn_aux_data = new_data;
18459 	vfree(old_data);
18460 }
18461 
18462 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
18463 {
18464 	int i;
18465 
18466 	if (len == 1)
18467 		return;
18468 	/* NOTE: fake 'exit' subprog should be updated as well. */
18469 	for (i = 0; i <= env->subprog_cnt; i++) {
18470 		if (env->subprog_info[i].start <= off)
18471 			continue;
18472 		env->subprog_info[i].start += len - 1;
18473 	}
18474 }
18475 
18476 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
18477 {
18478 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
18479 	int i, sz = prog->aux->size_poke_tab;
18480 	struct bpf_jit_poke_descriptor *desc;
18481 
18482 	for (i = 0; i < sz; i++) {
18483 		desc = &tab[i];
18484 		if (desc->insn_idx <= off)
18485 			continue;
18486 		desc->insn_idx += len - 1;
18487 	}
18488 }
18489 
18490 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
18491 					    const struct bpf_insn *patch, u32 len)
18492 {
18493 	struct bpf_prog *new_prog;
18494 	struct bpf_insn_aux_data *new_data = NULL;
18495 
18496 	if (len > 1) {
18497 		new_data = vzalloc(array_size(env->prog->len + len - 1,
18498 					      sizeof(struct bpf_insn_aux_data)));
18499 		if (!new_data)
18500 			return NULL;
18501 	}
18502 
18503 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
18504 	if (IS_ERR(new_prog)) {
18505 		if (PTR_ERR(new_prog) == -ERANGE)
18506 			verbose(env,
18507 				"insn %d cannot be patched due to 16-bit range\n",
18508 				env->insn_aux_data[off].orig_idx);
18509 		vfree(new_data);
18510 		return NULL;
18511 	}
18512 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
18513 	adjust_subprog_starts(env, off, len);
18514 	adjust_poke_descs(new_prog, off, len);
18515 	return new_prog;
18516 }
18517 
18518 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
18519 					      u32 off, u32 cnt)
18520 {
18521 	int i, j;
18522 
18523 	/* find first prog starting at or after off (first to remove) */
18524 	for (i = 0; i < env->subprog_cnt; i++)
18525 		if (env->subprog_info[i].start >= off)
18526 			break;
18527 	/* find first prog starting at or after off + cnt (first to stay) */
18528 	for (j = i; j < env->subprog_cnt; j++)
18529 		if (env->subprog_info[j].start >= off + cnt)
18530 			break;
18531 	/* if j doesn't start exactly at off + cnt, we are just removing
18532 	 * the front of previous prog
18533 	 */
18534 	if (env->subprog_info[j].start != off + cnt)
18535 		j--;
18536 
18537 	if (j > i) {
18538 		struct bpf_prog_aux *aux = env->prog->aux;
18539 		int move;
18540 
18541 		/* move fake 'exit' subprog as well */
18542 		move = env->subprog_cnt + 1 - j;
18543 
18544 		memmove(env->subprog_info + i,
18545 			env->subprog_info + j,
18546 			sizeof(*env->subprog_info) * move);
18547 		env->subprog_cnt -= j - i;
18548 
18549 		/* remove func_info */
18550 		if (aux->func_info) {
18551 			move = aux->func_info_cnt - j;
18552 
18553 			memmove(aux->func_info + i,
18554 				aux->func_info + j,
18555 				sizeof(*aux->func_info) * move);
18556 			aux->func_info_cnt -= j - i;
18557 			/* func_info->insn_off is set after all code rewrites,
18558 			 * in adjust_btf_func() - no need to adjust
18559 			 */
18560 		}
18561 	} else {
18562 		/* convert i from "first prog to remove" to "first to adjust" */
18563 		if (env->subprog_info[i].start == off)
18564 			i++;
18565 	}
18566 
18567 	/* update fake 'exit' subprog as well */
18568 	for (; i <= env->subprog_cnt; i++)
18569 		env->subprog_info[i].start -= cnt;
18570 
18571 	return 0;
18572 }
18573 
18574 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
18575 				      u32 cnt)
18576 {
18577 	struct bpf_prog *prog = env->prog;
18578 	u32 i, l_off, l_cnt, nr_linfo;
18579 	struct bpf_line_info *linfo;
18580 
18581 	nr_linfo = prog->aux->nr_linfo;
18582 	if (!nr_linfo)
18583 		return 0;
18584 
18585 	linfo = prog->aux->linfo;
18586 
18587 	/* find first line info to remove, count lines to be removed */
18588 	for (i = 0; i < nr_linfo; i++)
18589 		if (linfo[i].insn_off >= off)
18590 			break;
18591 
18592 	l_off = i;
18593 	l_cnt = 0;
18594 	for (; i < nr_linfo; i++)
18595 		if (linfo[i].insn_off < off + cnt)
18596 			l_cnt++;
18597 		else
18598 			break;
18599 
18600 	/* First live insn doesn't match first live linfo, it needs to "inherit"
18601 	 * last removed linfo.  prog is already modified, so prog->len == off
18602 	 * means no live instructions after (tail of the program was removed).
18603 	 */
18604 	if (prog->len != off && l_cnt &&
18605 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
18606 		l_cnt--;
18607 		linfo[--i].insn_off = off + cnt;
18608 	}
18609 
18610 	/* remove the line info which refer to the removed instructions */
18611 	if (l_cnt) {
18612 		memmove(linfo + l_off, linfo + i,
18613 			sizeof(*linfo) * (nr_linfo - i));
18614 
18615 		prog->aux->nr_linfo -= l_cnt;
18616 		nr_linfo = prog->aux->nr_linfo;
18617 	}
18618 
18619 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
18620 	for (i = l_off; i < nr_linfo; i++)
18621 		linfo[i].insn_off -= cnt;
18622 
18623 	/* fix up all subprogs (incl. 'exit') which start >= off */
18624 	for (i = 0; i <= env->subprog_cnt; i++)
18625 		if (env->subprog_info[i].linfo_idx > l_off) {
18626 			/* program may have started in the removed region but
18627 			 * may not be fully removed
18628 			 */
18629 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18630 				env->subprog_info[i].linfo_idx -= l_cnt;
18631 			else
18632 				env->subprog_info[i].linfo_idx = l_off;
18633 		}
18634 
18635 	return 0;
18636 }
18637 
18638 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18639 {
18640 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18641 	unsigned int orig_prog_len = env->prog->len;
18642 	int err;
18643 
18644 	if (bpf_prog_is_offloaded(env->prog->aux))
18645 		bpf_prog_offload_remove_insns(env, off, cnt);
18646 
18647 	err = bpf_remove_insns(env->prog, off, cnt);
18648 	if (err)
18649 		return err;
18650 
18651 	err = adjust_subprog_starts_after_remove(env, off, cnt);
18652 	if (err)
18653 		return err;
18654 
18655 	err = bpf_adj_linfo_after_remove(env, off, cnt);
18656 	if (err)
18657 		return err;
18658 
18659 	memmove(aux_data + off,	aux_data + off + cnt,
18660 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18661 
18662 	return 0;
18663 }
18664 
18665 /* The verifier does more data flow analysis than llvm and will not
18666  * explore branches that are dead at run time. Malicious programs can
18667  * have dead code too. Therefore replace all dead at-run-time code
18668  * with 'ja -1'.
18669  *
18670  * Just nops are not optimal, e.g. if they would sit at the end of the
18671  * program and through another bug we would manage to jump there, then
18672  * we'd execute beyond program memory otherwise. Returning exception
18673  * code also wouldn't work since we can have subprogs where the dead
18674  * code could be located.
18675  */
18676 static void sanitize_dead_code(struct bpf_verifier_env *env)
18677 {
18678 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18679 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18680 	struct bpf_insn *insn = env->prog->insnsi;
18681 	const int insn_cnt = env->prog->len;
18682 	int i;
18683 
18684 	for (i = 0; i < insn_cnt; i++) {
18685 		if (aux_data[i].seen)
18686 			continue;
18687 		memcpy(insn + i, &trap, sizeof(trap));
18688 		aux_data[i].zext_dst = false;
18689 	}
18690 }
18691 
18692 static bool insn_is_cond_jump(u8 code)
18693 {
18694 	u8 op;
18695 
18696 	op = BPF_OP(code);
18697 	if (BPF_CLASS(code) == BPF_JMP32)
18698 		return op != BPF_JA;
18699 
18700 	if (BPF_CLASS(code) != BPF_JMP)
18701 		return false;
18702 
18703 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18704 }
18705 
18706 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18707 {
18708 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18709 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18710 	struct bpf_insn *insn = env->prog->insnsi;
18711 	const int insn_cnt = env->prog->len;
18712 	int i;
18713 
18714 	for (i = 0; i < insn_cnt; i++, insn++) {
18715 		if (!insn_is_cond_jump(insn->code))
18716 			continue;
18717 
18718 		if (!aux_data[i + 1].seen)
18719 			ja.off = insn->off;
18720 		else if (!aux_data[i + 1 + insn->off].seen)
18721 			ja.off = 0;
18722 		else
18723 			continue;
18724 
18725 		if (bpf_prog_is_offloaded(env->prog->aux))
18726 			bpf_prog_offload_replace_insn(env, i, &ja);
18727 
18728 		memcpy(insn, &ja, sizeof(ja));
18729 	}
18730 }
18731 
18732 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18733 {
18734 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18735 	int insn_cnt = env->prog->len;
18736 	int i, err;
18737 
18738 	for (i = 0; i < insn_cnt; i++) {
18739 		int j;
18740 
18741 		j = 0;
18742 		while (i + j < insn_cnt && !aux_data[i + j].seen)
18743 			j++;
18744 		if (!j)
18745 			continue;
18746 
18747 		err = verifier_remove_insns(env, i, j);
18748 		if (err)
18749 			return err;
18750 		insn_cnt = env->prog->len;
18751 	}
18752 
18753 	return 0;
18754 }
18755 
18756 static int opt_remove_nops(struct bpf_verifier_env *env)
18757 {
18758 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18759 	struct bpf_insn *insn = env->prog->insnsi;
18760 	int insn_cnt = env->prog->len;
18761 	int i, err;
18762 
18763 	for (i = 0; i < insn_cnt; i++) {
18764 		if (memcmp(&insn[i], &ja, sizeof(ja)))
18765 			continue;
18766 
18767 		err = verifier_remove_insns(env, i, 1);
18768 		if (err)
18769 			return err;
18770 		insn_cnt--;
18771 		i--;
18772 	}
18773 
18774 	return 0;
18775 }
18776 
18777 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18778 					 const union bpf_attr *attr)
18779 {
18780 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18781 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18782 	int i, patch_len, delta = 0, len = env->prog->len;
18783 	struct bpf_insn *insns = env->prog->insnsi;
18784 	struct bpf_prog *new_prog;
18785 	bool rnd_hi32;
18786 
18787 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18788 	zext_patch[1] = BPF_ZEXT_REG(0);
18789 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18790 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18791 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18792 	for (i = 0; i < len; i++) {
18793 		int adj_idx = i + delta;
18794 		struct bpf_insn insn;
18795 		int load_reg;
18796 
18797 		insn = insns[adj_idx];
18798 		load_reg = insn_def_regno(&insn);
18799 		if (!aux[adj_idx].zext_dst) {
18800 			u8 code, class;
18801 			u32 imm_rnd;
18802 
18803 			if (!rnd_hi32)
18804 				continue;
18805 
18806 			code = insn.code;
18807 			class = BPF_CLASS(code);
18808 			if (load_reg == -1)
18809 				continue;
18810 
18811 			/* NOTE: arg "reg" (the fourth one) is only used for
18812 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
18813 			 *       here.
18814 			 */
18815 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18816 				if (class == BPF_LD &&
18817 				    BPF_MODE(code) == BPF_IMM)
18818 					i++;
18819 				continue;
18820 			}
18821 
18822 			/* ctx load could be transformed into wider load. */
18823 			if (class == BPF_LDX &&
18824 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
18825 				continue;
18826 
18827 			imm_rnd = get_random_u32();
18828 			rnd_hi32_patch[0] = insn;
18829 			rnd_hi32_patch[1].imm = imm_rnd;
18830 			rnd_hi32_patch[3].dst_reg = load_reg;
18831 			patch = rnd_hi32_patch;
18832 			patch_len = 4;
18833 			goto apply_patch_buffer;
18834 		}
18835 
18836 		/* Add in an zero-extend instruction if a) the JIT has requested
18837 		 * it or b) it's a CMPXCHG.
18838 		 *
18839 		 * The latter is because: BPF_CMPXCHG always loads a value into
18840 		 * R0, therefore always zero-extends. However some archs'
18841 		 * equivalent instruction only does this load when the
18842 		 * comparison is successful. This detail of CMPXCHG is
18843 		 * orthogonal to the general zero-extension behaviour of the
18844 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
18845 		 */
18846 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18847 			continue;
18848 
18849 		/* Zero-extension is done by the caller. */
18850 		if (bpf_pseudo_kfunc_call(&insn))
18851 			continue;
18852 
18853 		if (WARN_ON(load_reg == -1)) {
18854 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18855 			return -EFAULT;
18856 		}
18857 
18858 		zext_patch[0] = insn;
18859 		zext_patch[1].dst_reg = load_reg;
18860 		zext_patch[1].src_reg = load_reg;
18861 		patch = zext_patch;
18862 		patch_len = 2;
18863 apply_patch_buffer:
18864 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18865 		if (!new_prog)
18866 			return -ENOMEM;
18867 		env->prog = new_prog;
18868 		insns = new_prog->insnsi;
18869 		aux = env->insn_aux_data;
18870 		delta += patch_len - 1;
18871 	}
18872 
18873 	return 0;
18874 }
18875 
18876 /* convert load instructions that access fields of a context type into a
18877  * sequence of instructions that access fields of the underlying structure:
18878  *     struct __sk_buff    -> struct sk_buff
18879  *     struct bpf_sock_ops -> struct sock
18880  */
18881 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18882 {
18883 	const struct bpf_verifier_ops *ops = env->ops;
18884 	int i, cnt, size, ctx_field_size, delta = 0;
18885 	const int insn_cnt = env->prog->len;
18886 	struct bpf_insn insn_buf[16], *insn;
18887 	u32 target_size, size_default, off;
18888 	struct bpf_prog *new_prog;
18889 	enum bpf_access_type type;
18890 	bool is_narrower_load;
18891 
18892 	if (ops->gen_prologue || env->seen_direct_write) {
18893 		if (!ops->gen_prologue) {
18894 			verbose(env, "bpf verifier is misconfigured\n");
18895 			return -EINVAL;
18896 		}
18897 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18898 					env->prog);
18899 		if (cnt >= ARRAY_SIZE(insn_buf)) {
18900 			verbose(env, "bpf verifier is misconfigured\n");
18901 			return -EINVAL;
18902 		} else if (cnt) {
18903 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18904 			if (!new_prog)
18905 				return -ENOMEM;
18906 
18907 			env->prog = new_prog;
18908 			delta += cnt - 1;
18909 		}
18910 	}
18911 
18912 	if (bpf_prog_is_offloaded(env->prog->aux))
18913 		return 0;
18914 
18915 	insn = env->prog->insnsi + delta;
18916 
18917 	for (i = 0; i < insn_cnt; i++, insn++) {
18918 		bpf_convert_ctx_access_t convert_ctx_access;
18919 		u8 mode;
18920 
18921 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18922 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18923 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18924 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18925 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18926 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18927 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18928 			type = BPF_READ;
18929 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18930 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18931 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18932 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18933 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18934 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18935 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18936 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18937 			type = BPF_WRITE;
18938 		} else {
18939 			continue;
18940 		}
18941 
18942 		if (type == BPF_WRITE &&
18943 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
18944 			struct bpf_insn patch[] = {
18945 				*insn,
18946 				BPF_ST_NOSPEC(),
18947 			};
18948 
18949 			cnt = ARRAY_SIZE(patch);
18950 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18951 			if (!new_prog)
18952 				return -ENOMEM;
18953 
18954 			delta    += cnt - 1;
18955 			env->prog = new_prog;
18956 			insn      = new_prog->insnsi + i + delta;
18957 			continue;
18958 		}
18959 
18960 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18961 		case PTR_TO_CTX:
18962 			if (!ops->convert_ctx_access)
18963 				continue;
18964 			convert_ctx_access = ops->convert_ctx_access;
18965 			break;
18966 		case PTR_TO_SOCKET:
18967 		case PTR_TO_SOCK_COMMON:
18968 			convert_ctx_access = bpf_sock_convert_ctx_access;
18969 			break;
18970 		case PTR_TO_TCP_SOCK:
18971 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18972 			break;
18973 		case PTR_TO_XDP_SOCK:
18974 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18975 			break;
18976 		case PTR_TO_BTF_ID:
18977 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18978 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18979 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18980 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18981 		 * any faults for loads into such types. BPF_WRITE is disallowed
18982 		 * for this case.
18983 		 */
18984 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18985 			if (type == BPF_READ) {
18986 				if (BPF_MODE(insn->code) == BPF_MEM)
18987 					insn->code = BPF_LDX | BPF_PROBE_MEM |
18988 						     BPF_SIZE((insn)->code);
18989 				else
18990 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18991 						     BPF_SIZE((insn)->code);
18992 				env->prog->aux->num_exentries++;
18993 			}
18994 			continue;
18995 		case PTR_TO_ARENA:
18996 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
18997 				verbose(env, "sign extending loads from arena are not supported yet\n");
18998 				return -EOPNOTSUPP;
18999 			}
19000 			insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
19001 			env->prog->aux->num_exentries++;
19002 			continue;
19003 		default:
19004 			continue;
19005 		}
19006 
19007 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
19008 		size = BPF_LDST_BYTES(insn);
19009 		mode = BPF_MODE(insn->code);
19010 
19011 		/* If the read access is a narrower load of the field,
19012 		 * convert to a 4/8-byte load, to minimum program type specific
19013 		 * convert_ctx_access changes. If conversion is successful,
19014 		 * we will apply proper mask to the result.
19015 		 */
19016 		is_narrower_load = size < ctx_field_size;
19017 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
19018 		off = insn->off;
19019 		if (is_narrower_load) {
19020 			u8 size_code;
19021 
19022 			if (type == BPF_WRITE) {
19023 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
19024 				return -EINVAL;
19025 			}
19026 
19027 			size_code = BPF_H;
19028 			if (ctx_field_size == 4)
19029 				size_code = BPF_W;
19030 			else if (ctx_field_size == 8)
19031 				size_code = BPF_DW;
19032 
19033 			insn->off = off & ~(size_default - 1);
19034 			insn->code = BPF_LDX | BPF_MEM | size_code;
19035 		}
19036 
19037 		target_size = 0;
19038 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
19039 					 &target_size);
19040 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
19041 		    (ctx_field_size && !target_size)) {
19042 			verbose(env, "bpf verifier is misconfigured\n");
19043 			return -EINVAL;
19044 		}
19045 
19046 		if (is_narrower_load && size < target_size) {
19047 			u8 shift = bpf_ctx_narrow_access_offset(
19048 				off, size, size_default) * 8;
19049 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
19050 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
19051 				return -EINVAL;
19052 			}
19053 			if (ctx_field_size <= 4) {
19054 				if (shift)
19055 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
19056 									insn->dst_reg,
19057 									shift);
19058 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
19059 								(1 << size * 8) - 1);
19060 			} else {
19061 				if (shift)
19062 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
19063 									insn->dst_reg,
19064 									shift);
19065 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
19066 								(1ULL << size * 8) - 1);
19067 			}
19068 		}
19069 		if (mode == BPF_MEMSX)
19070 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
19071 						       insn->dst_reg, insn->dst_reg,
19072 						       size * 8, 0);
19073 
19074 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19075 		if (!new_prog)
19076 			return -ENOMEM;
19077 
19078 		delta += cnt - 1;
19079 
19080 		/* keep walking new program and skip insns we just inserted */
19081 		env->prog = new_prog;
19082 		insn      = new_prog->insnsi + i + delta;
19083 	}
19084 
19085 	return 0;
19086 }
19087 
19088 static int jit_subprogs(struct bpf_verifier_env *env)
19089 {
19090 	struct bpf_prog *prog = env->prog, **func, *tmp;
19091 	int i, j, subprog_start, subprog_end = 0, len, subprog;
19092 	struct bpf_map *map_ptr;
19093 	struct bpf_insn *insn;
19094 	void *old_bpf_func;
19095 	int err, num_exentries;
19096 
19097 	if (env->subprog_cnt <= 1)
19098 		return 0;
19099 
19100 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19101 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
19102 			continue;
19103 
19104 		/* Upon error here we cannot fall back to interpreter but
19105 		 * need a hard reject of the program. Thus -EFAULT is
19106 		 * propagated in any case.
19107 		 */
19108 		subprog = find_subprog(env, i + insn->imm + 1);
19109 		if (subprog < 0) {
19110 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
19111 				  i + insn->imm + 1);
19112 			return -EFAULT;
19113 		}
19114 		/* temporarily remember subprog id inside insn instead of
19115 		 * aux_data, since next loop will split up all insns into funcs
19116 		 */
19117 		insn->off = subprog;
19118 		/* remember original imm in case JIT fails and fallback
19119 		 * to interpreter will be needed
19120 		 */
19121 		env->insn_aux_data[i].call_imm = insn->imm;
19122 		/* point imm to __bpf_call_base+1 from JITs point of view */
19123 		insn->imm = 1;
19124 		if (bpf_pseudo_func(insn))
19125 			/* jit (e.g. x86_64) may emit fewer instructions
19126 			 * if it learns a u32 imm is the same as a u64 imm.
19127 			 * Force a non zero here.
19128 			 */
19129 			insn[1].imm = 1;
19130 	}
19131 
19132 	err = bpf_prog_alloc_jited_linfo(prog);
19133 	if (err)
19134 		goto out_undo_insn;
19135 
19136 	err = -ENOMEM;
19137 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
19138 	if (!func)
19139 		goto out_undo_insn;
19140 
19141 	for (i = 0; i < env->subprog_cnt; i++) {
19142 		subprog_start = subprog_end;
19143 		subprog_end = env->subprog_info[i + 1].start;
19144 
19145 		len = subprog_end - subprog_start;
19146 		/* bpf_prog_run() doesn't call subprogs directly,
19147 		 * hence main prog stats include the runtime of subprogs.
19148 		 * subprogs don't have IDs and not reachable via prog_get_next_id
19149 		 * func[i]->stats will never be accessed and stays NULL
19150 		 */
19151 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
19152 		if (!func[i])
19153 			goto out_free;
19154 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
19155 		       len * sizeof(struct bpf_insn));
19156 		func[i]->type = prog->type;
19157 		func[i]->len = len;
19158 		if (bpf_prog_calc_tag(func[i]))
19159 			goto out_free;
19160 		func[i]->is_func = 1;
19161 		func[i]->aux->func_idx = i;
19162 		/* Below members will be freed only at prog->aux */
19163 		func[i]->aux->btf = prog->aux->btf;
19164 		func[i]->aux->func_info = prog->aux->func_info;
19165 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
19166 		func[i]->aux->poke_tab = prog->aux->poke_tab;
19167 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
19168 
19169 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
19170 			struct bpf_jit_poke_descriptor *poke;
19171 
19172 			poke = &prog->aux->poke_tab[j];
19173 			if (poke->insn_idx < subprog_end &&
19174 			    poke->insn_idx >= subprog_start)
19175 				poke->aux = func[i]->aux;
19176 		}
19177 
19178 		func[i]->aux->name[0] = 'F';
19179 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
19180 		func[i]->jit_requested = 1;
19181 		func[i]->blinding_requested = prog->blinding_requested;
19182 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
19183 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
19184 		func[i]->aux->linfo = prog->aux->linfo;
19185 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
19186 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
19187 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
19188 		func[i]->aux->arena = prog->aux->arena;
19189 		num_exentries = 0;
19190 		insn = func[i]->insnsi;
19191 		for (j = 0; j < func[i]->len; j++, insn++) {
19192 			if (BPF_CLASS(insn->code) == BPF_LDX &&
19193 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
19194 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
19195 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
19196 				num_exentries++;
19197 			if ((BPF_CLASS(insn->code) == BPF_STX ||
19198 			     BPF_CLASS(insn->code) == BPF_ST) &&
19199 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
19200 				num_exentries++;
19201 		}
19202 		func[i]->aux->num_exentries = num_exentries;
19203 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
19204 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
19205 		if (!i)
19206 			func[i]->aux->exception_boundary = env->seen_exception;
19207 		func[i] = bpf_int_jit_compile(func[i]);
19208 		if (!func[i]->jited) {
19209 			err = -ENOTSUPP;
19210 			goto out_free;
19211 		}
19212 		cond_resched();
19213 	}
19214 
19215 	/* at this point all bpf functions were successfully JITed
19216 	 * now populate all bpf_calls with correct addresses and
19217 	 * run last pass of JIT
19218 	 */
19219 	for (i = 0; i < env->subprog_cnt; i++) {
19220 		insn = func[i]->insnsi;
19221 		for (j = 0; j < func[i]->len; j++, insn++) {
19222 			if (bpf_pseudo_func(insn)) {
19223 				subprog = insn->off;
19224 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
19225 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
19226 				continue;
19227 			}
19228 			if (!bpf_pseudo_call(insn))
19229 				continue;
19230 			subprog = insn->off;
19231 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
19232 		}
19233 
19234 		/* we use the aux data to keep a list of the start addresses
19235 		 * of the JITed images for each function in the program
19236 		 *
19237 		 * for some architectures, such as powerpc64, the imm field
19238 		 * might not be large enough to hold the offset of the start
19239 		 * address of the callee's JITed image from __bpf_call_base
19240 		 *
19241 		 * in such cases, we can lookup the start address of a callee
19242 		 * by using its subprog id, available from the off field of
19243 		 * the call instruction, as an index for this list
19244 		 */
19245 		func[i]->aux->func = func;
19246 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19247 		func[i]->aux->real_func_cnt = env->subprog_cnt;
19248 	}
19249 	for (i = 0; i < env->subprog_cnt; i++) {
19250 		old_bpf_func = func[i]->bpf_func;
19251 		tmp = bpf_int_jit_compile(func[i]);
19252 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
19253 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
19254 			err = -ENOTSUPP;
19255 			goto out_free;
19256 		}
19257 		cond_resched();
19258 	}
19259 
19260 	/* finally lock prog and jit images for all functions and
19261 	 * populate kallsysm. Begin at the first subprogram, since
19262 	 * bpf_prog_load will add the kallsyms for the main program.
19263 	 */
19264 	for (i = 1; i < env->subprog_cnt; i++) {
19265 		bpf_prog_lock_ro(func[i]);
19266 		bpf_prog_kallsyms_add(func[i]);
19267 	}
19268 
19269 	/* Last step: make now unused interpreter insns from main
19270 	 * prog consistent for later dump requests, so they can
19271 	 * later look the same as if they were interpreted only.
19272 	 */
19273 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19274 		if (bpf_pseudo_func(insn)) {
19275 			insn[0].imm = env->insn_aux_data[i].call_imm;
19276 			insn[1].imm = insn->off;
19277 			insn->off = 0;
19278 			continue;
19279 		}
19280 		if (!bpf_pseudo_call(insn))
19281 			continue;
19282 		insn->off = env->insn_aux_data[i].call_imm;
19283 		subprog = find_subprog(env, i + insn->off + 1);
19284 		insn->imm = subprog;
19285 	}
19286 
19287 	prog->jited = 1;
19288 	prog->bpf_func = func[0]->bpf_func;
19289 	prog->jited_len = func[0]->jited_len;
19290 	prog->aux->extable = func[0]->aux->extable;
19291 	prog->aux->num_exentries = func[0]->aux->num_exentries;
19292 	prog->aux->func = func;
19293 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19294 	prog->aux->real_func_cnt = env->subprog_cnt;
19295 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
19296 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
19297 	bpf_prog_jit_attempt_done(prog);
19298 	return 0;
19299 out_free:
19300 	/* We failed JIT'ing, so at this point we need to unregister poke
19301 	 * descriptors from subprogs, so that kernel is not attempting to
19302 	 * patch it anymore as we're freeing the subprog JIT memory.
19303 	 */
19304 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19305 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19306 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
19307 	}
19308 	/* At this point we're guaranteed that poke descriptors are not
19309 	 * live anymore. We can just unlink its descriptor table as it's
19310 	 * released with the main prog.
19311 	 */
19312 	for (i = 0; i < env->subprog_cnt; i++) {
19313 		if (!func[i])
19314 			continue;
19315 		func[i]->aux->poke_tab = NULL;
19316 		bpf_jit_free(func[i]);
19317 	}
19318 	kfree(func);
19319 out_undo_insn:
19320 	/* cleanup main prog to be interpreted */
19321 	prog->jit_requested = 0;
19322 	prog->blinding_requested = 0;
19323 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19324 		if (!bpf_pseudo_call(insn))
19325 			continue;
19326 		insn->off = 0;
19327 		insn->imm = env->insn_aux_data[i].call_imm;
19328 	}
19329 	bpf_prog_jit_attempt_done(prog);
19330 	return err;
19331 }
19332 
19333 static int fixup_call_args(struct bpf_verifier_env *env)
19334 {
19335 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19336 	struct bpf_prog *prog = env->prog;
19337 	struct bpf_insn *insn = prog->insnsi;
19338 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
19339 	int i, depth;
19340 #endif
19341 	int err = 0;
19342 
19343 	if (env->prog->jit_requested &&
19344 	    !bpf_prog_is_offloaded(env->prog->aux)) {
19345 		err = jit_subprogs(env);
19346 		if (err == 0)
19347 			return 0;
19348 		if (err == -EFAULT)
19349 			return err;
19350 	}
19351 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19352 	if (has_kfunc_call) {
19353 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
19354 		return -EINVAL;
19355 	}
19356 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
19357 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
19358 		 * have to be rejected, since interpreter doesn't support them yet.
19359 		 */
19360 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
19361 		return -EINVAL;
19362 	}
19363 	for (i = 0; i < prog->len; i++, insn++) {
19364 		if (bpf_pseudo_func(insn)) {
19365 			/* When JIT fails the progs with callback calls
19366 			 * have to be rejected, since interpreter doesn't support them yet.
19367 			 */
19368 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
19369 			return -EINVAL;
19370 		}
19371 
19372 		if (!bpf_pseudo_call(insn))
19373 			continue;
19374 		depth = get_callee_stack_depth(env, insn, i);
19375 		if (depth < 0)
19376 			return depth;
19377 		bpf_patch_call_args(insn, depth);
19378 	}
19379 	err = 0;
19380 #endif
19381 	return err;
19382 }
19383 
19384 /* replace a generic kfunc with a specialized version if necessary */
19385 static void specialize_kfunc(struct bpf_verifier_env *env,
19386 			     u32 func_id, u16 offset, unsigned long *addr)
19387 {
19388 	struct bpf_prog *prog = env->prog;
19389 	bool seen_direct_write;
19390 	void *xdp_kfunc;
19391 	bool is_rdonly;
19392 
19393 	if (bpf_dev_bound_kfunc_id(func_id)) {
19394 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
19395 		if (xdp_kfunc) {
19396 			*addr = (unsigned long)xdp_kfunc;
19397 			return;
19398 		}
19399 		/* fallback to default kfunc when not supported by netdev */
19400 	}
19401 
19402 	if (offset)
19403 		return;
19404 
19405 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
19406 		seen_direct_write = env->seen_direct_write;
19407 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
19408 
19409 		if (is_rdonly)
19410 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
19411 
19412 		/* restore env->seen_direct_write to its original value, since
19413 		 * may_access_direct_pkt_data mutates it
19414 		 */
19415 		env->seen_direct_write = seen_direct_write;
19416 	}
19417 }
19418 
19419 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
19420 					    u16 struct_meta_reg,
19421 					    u16 node_offset_reg,
19422 					    struct bpf_insn *insn,
19423 					    struct bpf_insn *insn_buf,
19424 					    int *cnt)
19425 {
19426 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
19427 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
19428 
19429 	insn_buf[0] = addr[0];
19430 	insn_buf[1] = addr[1];
19431 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
19432 	insn_buf[3] = *insn;
19433 	*cnt = 4;
19434 }
19435 
19436 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
19437 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
19438 {
19439 	const struct bpf_kfunc_desc *desc;
19440 
19441 	if (!insn->imm) {
19442 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
19443 		return -EINVAL;
19444 	}
19445 
19446 	*cnt = 0;
19447 
19448 	/* insn->imm has the btf func_id. Replace it with an offset relative to
19449 	 * __bpf_call_base, unless the JIT needs to call functions that are
19450 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
19451 	 */
19452 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
19453 	if (!desc) {
19454 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
19455 			insn->imm);
19456 		return -EFAULT;
19457 	}
19458 
19459 	if (!bpf_jit_supports_far_kfunc_call())
19460 		insn->imm = BPF_CALL_IMM(desc->addr);
19461 	if (insn->off)
19462 		return 0;
19463 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
19464 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
19465 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19466 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19467 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
19468 
19469 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
19470 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19471 				insn_idx);
19472 			return -EFAULT;
19473 		}
19474 
19475 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
19476 		insn_buf[1] = addr[0];
19477 		insn_buf[2] = addr[1];
19478 		insn_buf[3] = *insn;
19479 		*cnt = 4;
19480 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
19481 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
19482 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
19483 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19484 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19485 
19486 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
19487 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19488 				insn_idx);
19489 			return -EFAULT;
19490 		}
19491 
19492 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
19493 		    !kptr_struct_meta) {
19494 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19495 				insn_idx);
19496 			return -EFAULT;
19497 		}
19498 
19499 		insn_buf[0] = addr[0];
19500 		insn_buf[1] = addr[1];
19501 		insn_buf[2] = *insn;
19502 		*cnt = 3;
19503 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
19504 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
19505 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19506 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19507 		int struct_meta_reg = BPF_REG_3;
19508 		int node_offset_reg = BPF_REG_4;
19509 
19510 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
19511 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19512 			struct_meta_reg = BPF_REG_4;
19513 			node_offset_reg = BPF_REG_5;
19514 		}
19515 
19516 		if (!kptr_struct_meta) {
19517 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19518 				insn_idx);
19519 			return -EFAULT;
19520 		}
19521 
19522 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
19523 						node_offset_reg, insn, insn_buf, cnt);
19524 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
19525 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
19526 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
19527 		*cnt = 1;
19528 	}
19529 	return 0;
19530 }
19531 
19532 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
19533 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
19534 {
19535 	struct bpf_subprog_info *info = env->subprog_info;
19536 	int cnt = env->subprog_cnt;
19537 	struct bpf_prog *prog;
19538 
19539 	/* We only reserve one slot for hidden subprogs in subprog_info. */
19540 	if (env->hidden_subprog_cnt) {
19541 		verbose(env, "verifier internal error: only one hidden subprog supported\n");
19542 		return -EFAULT;
19543 	}
19544 	/* We're not patching any existing instruction, just appending the new
19545 	 * ones for the hidden subprog. Hence all of the adjustment operations
19546 	 * in bpf_patch_insn_data are no-ops.
19547 	 */
19548 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
19549 	if (!prog)
19550 		return -ENOMEM;
19551 	env->prog = prog;
19552 	info[cnt + 1].start = info[cnt].start;
19553 	info[cnt].start = prog->len - len + 1;
19554 	env->subprog_cnt++;
19555 	env->hidden_subprog_cnt++;
19556 	return 0;
19557 }
19558 
19559 /* Do various post-verification rewrites in a single program pass.
19560  * These rewrites simplify JIT and interpreter implementations.
19561  */
19562 static int do_misc_fixups(struct bpf_verifier_env *env)
19563 {
19564 	struct bpf_prog *prog = env->prog;
19565 	enum bpf_attach_type eatype = prog->expected_attach_type;
19566 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
19567 	struct bpf_insn *insn = prog->insnsi;
19568 	const struct bpf_func_proto *fn;
19569 	const int insn_cnt = prog->len;
19570 	const struct bpf_map_ops *ops;
19571 	struct bpf_insn_aux_data *aux;
19572 	struct bpf_insn insn_buf[16];
19573 	struct bpf_prog *new_prog;
19574 	struct bpf_map *map_ptr;
19575 	int i, ret, cnt, delta = 0, cur_subprog = 0;
19576 	struct bpf_subprog_info *subprogs = env->subprog_info;
19577 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
19578 	u16 stack_depth_extra = 0;
19579 
19580 	if (env->seen_exception && !env->exception_callback_subprog) {
19581 		struct bpf_insn patch[] = {
19582 			env->prog->insnsi[insn_cnt - 1],
19583 			BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
19584 			BPF_EXIT_INSN(),
19585 		};
19586 
19587 		ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
19588 		if (ret < 0)
19589 			return ret;
19590 		prog = env->prog;
19591 		insn = prog->insnsi;
19592 
19593 		env->exception_callback_subprog = env->subprog_cnt - 1;
19594 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
19595 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
19596 	}
19597 
19598 	for (i = 0; i < insn_cnt;) {
19599 		if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
19600 			if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
19601 			    (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
19602 				/* convert to 32-bit mov that clears upper 32-bit */
19603 				insn->code = BPF_ALU | BPF_MOV | BPF_X;
19604 				/* clear off, so it's a normal 'wX = wY' from JIT pov */
19605 				insn->off = 0;
19606 			} /* cast from as(0) to as(1) should be handled by JIT */
19607 			goto next_insn;
19608 		}
19609 
19610 		if (env->insn_aux_data[i + delta].needs_zext)
19611 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
19612 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
19613 
19614 		/* Make divide-by-zero exceptions impossible. */
19615 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
19616 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
19617 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
19618 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
19619 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
19620 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
19621 			struct bpf_insn *patchlet;
19622 			struct bpf_insn chk_and_div[] = {
19623 				/* [R,W]x div 0 -> 0 */
19624 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19625 					     BPF_JNE | BPF_K, insn->src_reg,
19626 					     0, 2, 0),
19627 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
19628 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19629 				*insn,
19630 			};
19631 			struct bpf_insn chk_and_mod[] = {
19632 				/* [R,W]x mod 0 -> [R,W]x */
19633 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19634 					     BPF_JEQ | BPF_K, insn->src_reg,
19635 					     0, 1 + (is64 ? 0 : 1), 0),
19636 				*insn,
19637 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19638 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
19639 			};
19640 
19641 			patchlet = isdiv ? chk_and_div : chk_and_mod;
19642 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
19643 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
19644 
19645 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
19646 			if (!new_prog)
19647 				return -ENOMEM;
19648 
19649 			delta    += cnt - 1;
19650 			env->prog = prog = new_prog;
19651 			insn      = new_prog->insnsi + i + delta;
19652 			goto next_insn;
19653 		}
19654 
19655 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
19656 		if (BPF_CLASS(insn->code) == BPF_LD &&
19657 		    (BPF_MODE(insn->code) == BPF_ABS ||
19658 		     BPF_MODE(insn->code) == BPF_IND)) {
19659 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
19660 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19661 				verbose(env, "bpf verifier is misconfigured\n");
19662 				return -EINVAL;
19663 			}
19664 
19665 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19666 			if (!new_prog)
19667 				return -ENOMEM;
19668 
19669 			delta    += cnt - 1;
19670 			env->prog = prog = new_prog;
19671 			insn      = new_prog->insnsi + i + delta;
19672 			goto next_insn;
19673 		}
19674 
19675 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
19676 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
19677 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
19678 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
19679 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
19680 			struct bpf_insn *patch = &insn_buf[0];
19681 			bool issrc, isneg, isimm;
19682 			u32 off_reg;
19683 
19684 			aux = &env->insn_aux_data[i + delta];
19685 			if (!aux->alu_state ||
19686 			    aux->alu_state == BPF_ALU_NON_POINTER)
19687 				goto next_insn;
19688 
19689 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
19690 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
19691 				BPF_ALU_SANITIZE_SRC;
19692 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
19693 
19694 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
19695 			if (isimm) {
19696 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19697 			} else {
19698 				if (isneg)
19699 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19700 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19701 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
19702 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
19703 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
19704 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
19705 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
19706 			}
19707 			if (!issrc)
19708 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
19709 			insn->src_reg = BPF_REG_AX;
19710 			if (isneg)
19711 				insn->code = insn->code == code_add ?
19712 					     code_sub : code_add;
19713 			*patch++ = *insn;
19714 			if (issrc && isneg && !isimm)
19715 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19716 			cnt = patch - insn_buf;
19717 
19718 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19719 			if (!new_prog)
19720 				return -ENOMEM;
19721 
19722 			delta    += cnt - 1;
19723 			env->prog = prog = new_prog;
19724 			insn      = new_prog->insnsi + i + delta;
19725 			goto next_insn;
19726 		}
19727 
19728 		if (is_may_goto_insn(insn)) {
19729 			int stack_off = -stack_depth - 8;
19730 
19731 			stack_depth_extra = 8;
19732 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
19733 			insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
19734 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
19735 			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
19736 			cnt = 4;
19737 
19738 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19739 			if (!new_prog)
19740 				return -ENOMEM;
19741 
19742 			delta += cnt - 1;
19743 			env->prog = prog = new_prog;
19744 			insn = new_prog->insnsi + i + delta;
19745 			goto next_insn;
19746 		}
19747 
19748 		if (insn->code != (BPF_JMP | BPF_CALL))
19749 			goto next_insn;
19750 		if (insn->src_reg == BPF_PSEUDO_CALL)
19751 			goto next_insn;
19752 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19753 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19754 			if (ret)
19755 				return ret;
19756 			if (cnt == 0)
19757 				goto next_insn;
19758 
19759 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19760 			if (!new_prog)
19761 				return -ENOMEM;
19762 
19763 			delta	 += cnt - 1;
19764 			env->prog = prog = new_prog;
19765 			insn	  = new_prog->insnsi + i + delta;
19766 			goto next_insn;
19767 		}
19768 
19769 		if (insn->imm == BPF_FUNC_get_route_realm)
19770 			prog->dst_needed = 1;
19771 		if (insn->imm == BPF_FUNC_get_prandom_u32)
19772 			bpf_user_rnd_init_once();
19773 		if (insn->imm == BPF_FUNC_override_return)
19774 			prog->kprobe_override = 1;
19775 		if (insn->imm == BPF_FUNC_tail_call) {
19776 			/* If we tail call into other programs, we
19777 			 * cannot make any assumptions since they can
19778 			 * be replaced dynamically during runtime in
19779 			 * the program array.
19780 			 */
19781 			prog->cb_access = 1;
19782 			if (!allow_tail_call_in_subprogs(env))
19783 				prog->aux->stack_depth = MAX_BPF_STACK;
19784 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19785 
19786 			/* mark bpf_tail_call as different opcode to avoid
19787 			 * conditional branch in the interpreter for every normal
19788 			 * call and to prevent accidental JITing by JIT compiler
19789 			 * that doesn't support bpf_tail_call yet
19790 			 */
19791 			insn->imm = 0;
19792 			insn->code = BPF_JMP | BPF_TAIL_CALL;
19793 
19794 			aux = &env->insn_aux_data[i + delta];
19795 			if (env->bpf_capable && !prog->blinding_requested &&
19796 			    prog->jit_requested &&
19797 			    !bpf_map_key_poisoned(aux) &&
19798 			    !bpf_map_ptr_poisoned(aux) &&
19799 			    !bpf_map_ptr_unpriv(aux)) {
19800 				struct bpf_jit_poke_descriptor desc = {
19801 					.reason = BPF_POKE_REASON_TAIL_CALL,
19802 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19803 					.tail_call.key = bpf_map_key_immediate(aux),
19804 					.insn_idx = i + delta,
19805 				};
19806 
19807 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
19808 				if (ret < 0) {
19809 					verbose(env, "adding tail call poke descriptor failed\n");
19810 					return ret;
19811 				}
19812 
19813 				insn->imm = ret + 1;
19814 				goto next_insn;
19815 			}
19816 
19817 			if (!bpf_map_ptr_unpriv(aux))
19818 				goto next_insn;
19819 
19820 			/* instead of changing every JIT dealing with tail_call
19821 			 * emit two extra insns:
19822 			 * if (index >= max_entries) goto out;
19823 			 * index &= array->index_mask;
19824 			 * to avoid out-of-bounds cpu speculation
19825 			 */
19826 			if (bpf_map_ptr_poisoned(aux)) {
19827 				verbose(env, "tail_call abusing map_ptr\n");
19828 				return -EINVAL;
19829 			}
19830 
19831 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19832 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19833 						  map_ptr->max_entries, 2);
19834 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19835 						    container_of(map_ptr,
19836 								 struct bpf_array,
19837 								 map)->index_mask);
19838 			insn_buf[2] = *insn;
19839 			cnt = 3;
19840 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19841 			if (!new_prog)
19842 				return -ENOMEM;
19843 
19844 			delta    += cnt - 1;
19845 			env->prog = prog = new_prog;
19846 			insn      = new_prog->insnsi + i + delta;
19847 			goto next_insn;
19848 		}
19849 
19850 		if (insn->imm == BPF_FUNC_timer_set_callback) {
19851 			/* The verifier will process callback_fn as many times as necessary
19852 			 * with different maps and the register states prepared by
19853 			 * set_timer_callback_state will be accurate.
19854 			 *
19855 			 * The following use case is valid:
19856 			 *   map1 is shared by prog1, prog2, prog3.
19857 			 *   prog1 calls bpf_timer_init for some map1 elements
19858 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
19859 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
19860 			 *   prog3 calls bpf_timer_start for some map1 elements.
19861 			 *     Those that were not both bpf_timer_init-ed and
19862 			 *     bpf_timer_set_callback-ed will return -EINVAL.
19863 			 */
19864 			struct bpf_insn ld_addrs[2] = {
19865 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19866 			};
19867 
19868 			insn_buf[0] = ld_addrs[0];
19869 			insn_buf[1] = ld_addrs[1];
19870 			insn_buf[2] = *insn;
19871 			cnt = 3;
19872 
19873 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19874 			if (!new_prog)
19875 				return -ENOMEM;
19876 
19877 			delta    += cnt - 1;
19878 			env->prog = prog = new_prog;
19879 			insn      = new_prog->insnsi + i + delta;
19880 			goto patch_call_imm;
19881 		}
19882 
19883 		if (is_storage_get_function(insn->imm)) {
19884 			if (!in_sleepable(env) ||
19885 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
19886 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19887 			else
19888 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19889 			insn_buf[1] = *insn;
19890 			cnt = 2;
19891 
19892 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19893 			if (!new_prog)
19894 				return -ENOMEM;
19895 
19896 			delta += cnt - 1;
19897 			env->prog = prog = new_prog;
19898 			insn = new_prog->insnsi + i + delta;
19899 			goto patch_call_imm;
19900 		}
19901 
19902 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
19903 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
19904 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
19905 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
19906 			 */
19907 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
19908 			insn_buf[1] = *insn;
19909 			cnt = 2;
19910 
19911 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19912 			if (!new_prog)
19913 				return -ENOMEM;
19914 
19915 			delta += cnt - 1;
19916 			env->prog = prog = new_prog;
19917 			insn = new_prog->insnsi + i + delta;
19918 			goto patch_call_imm;
19919 		}
19920 
19921 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19922 		 * and other inlining handlers are currently limited to 64 bit
19923 		 * only.
19924 		 */
19925 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19926 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
19927 		     insn->imm == BPF_FUNC_map_update_elem ||
19928 		     insn->imm == BPF_FUNC_map_delete_elem ||
19929 		     insn->imm == BPF_FUNC_map_push_elem   ||
19930 		     insn->imm == BPF_FUNC_map_pop_elem    ||
19931 		     insn->imm == BPF_FUNC_map_peek_elem   ||
19932 		     insn->imm == BPF_FUNC_redirect_map    ||
19933 		     insn->imm == BPF_FUNC_for_each_map_elem ||
19934 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19935 			aux = &env->insn_aux_data[i + delta];
19936 			if (bpf_map_ptr_poisoned(aux))
19937 				goto patch_call_imm;
19938 
19939 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19940 			ops = map_ptr->ops;
19941 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
19942 			    ops->map_gen_lookup) {
19943 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19944 				if (cnt == -EOPNOTSUPP)
19945 					goto patch_map_ops_generic;
19946 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19947 					verbose(env, "bpf verifier is misconfigured\n");
19948 					return -EINVAL;
19949 				}
19950 
19951 				new_prog = bpf_patch_insn_data(env, i + delta,
19952 							       insn_buf, cnt);
19953 				if (!new_prog)
19954 					return -ENOMEM;
19955 
19956 				delta    += cnt - 1;
19957 				env->prog = prog = new_prog;
19958 				insn      = new_prog->insnsi + i + delta;
19959 				goto next_insn;
19960 			}
19961 
19962 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19963 				     (void *(*)(struct bpf_map *map, void *key))NULL));
19964 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19965 				     (long (*)(struct bpf_map *map, void *key))NULL));
19966 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19967 				     (long (*)(struct bpf_map *map, void *key, void *value,
19968 					      u64 flags))NULL));
19969 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19970 				     (long (*)(struct bpf_map *map, void *value,
19971 					      u64 flags))NULL));
19972 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19973 				     (long (*)(struct bpf_map *map, void *value))NULL));
19974 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19975 				     (long (*)(struct bpf_map *map, void *value))NULL));
19976 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
19977 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19978 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19979 				     (long (*)(struct bpf_map *map,
19980 					      bpf_callback_t callback_fn,
19981 					      void *callback_ctx,
19982 					      u64 flags))NULL));
19983 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19984 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19985 
19986 patch_map_ops_generic:
19987 			switch (insn->imm) {
19988 			case BPF_FUNC_map_lookup_elem:
19989 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19990 				goto next_insn;
19991 			case BPF_FUNC_map_update_elem:
19992 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19993 				goto next_insn;
19994 			case BPF_FUNC_map_delete_elem:
19995 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19996 				goto next_insn;
19997 			case BPF_FUNC_map_push_elem:
19998 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19999 				goto next_insn;
20000 			case BPF_FUNC_map_pop_elem:
20001 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
20002 				goto next_insn;
20003 			case BPF_FUNC_map_peek_elem:
20004 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
20005 				goto next_insn;
20006 			case BPF_FUNC_redirect_map:
20007 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
20008 				goto next_insn;
20009 			case BPF_FUNC_for_each_map_elem:
20010 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
20011 				goto next_insn;
20012 			case BPF_FUNC_map_lookup_percpu_elem:
20013 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
20014 				goto next_insn;
20015 			}
20016 
20017 			goto patch_call_imm;
20018 		}
20019 
20020 		/* Implement bpf_jiffies64 inline. */
20021 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
20022 		    insn->imm == BPF_FUNC_jiffies64) {
20023 			struct bpf_insn ld_jiffies_addr[2] = {
20024 				BPF_LD_IMM64(BPF_REG_0,
20025 					     (unsigned long)&jiffies),
20026 			};
20027 
20028 			insn_buf[0] = ld_jiffies_addr[0];
20029 			insn_buf[1] = ld_jiffies_addr[1];
20030 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
20031 						  BPF_REG_0, 0);
20032 			cnt = 3;
20033 
20034 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
20035 						       cnt);
20036 			if (!new_prog)
20037 				return -ENOMEM;
20038 
20039 			delta    += cnt - 1;
20040 			env->prog = prog = new_prog;
20041 			insn      = new_prog->insnsi + i + delta;
20042 			goto next_insn;
20043 		}
20044 
20045 		/* Implement bpf_get_func_arg inline. */
20046 		if (prog_type == BPF_PROG_TYPE_TRACING &&
20047 		    insn->imm == BPF_FUNC_get_func_arg) {
20048 			/* Load nr_args from ctx - 8 */
20049 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20050 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
20051 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
20052 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
20053 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
20054 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
20055 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
20056 			insn_buf[7] = BPF_JMP_A(1);
20057 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
20058 			cnt = 9;
20059 
20060 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20061 			if (!new_prog)
20062 				return -ENOMEM;
20063 
20064 			delta    += cnt - 1;
20065 			env->prog = prog = new_prog;
20066 			insn      = new_prog->insnsi + i + delta;
20067 			goto next_insn;
20068 		}
20069 
20070 		/* Implement bpf_get_func_ret inline. */
20071 		if (prog_type == BPF_PROG_TYPE_TRACING &&
20072 		    insn->imm == BPF_FUNC_get_func_ret) {
20073 			if (eatype == BPF_TRACE_FEXIT ||
20074 			    eatype == BPF_MODIFY_RETURN) {
20075 				/* Load nr_args from ctx - 8 */
20076 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20077 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
20078 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
20079 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
20080 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
20081 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
20082 				cnt = 6;
20083 			} else {
20084 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
20085 				cnt = 1;
20086 			}
20087 
20088 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20089 			if (!new_prog)
20090 				return -ENOMEM;
20091 
20092 			delta    += cnt - 1;
20093 			env->prog = prog = new_prog;
20094 			insn      = new_prog->insnsi + i + delta;
20095 			goto next_insn;
20096 		}
20097 
20098 		/* Implement get_func_arg_cnt inline. */
20099 		if (prog_type == BPF_PROG_TYPE_TRACING &&
20100 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
20101 			/* Load nr_args from ctx - 8 */
20102 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20103 
20104 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
20105 			if (!new_prog)
20106 				return -ENOMEM;
20107 
20108 			env->prog = prog = new_prog;
20109 			insn      = new_prog->insnsi + i + delta;
20110 			goto next_insn;
20111 		}
20112 
20113 		/* Implement bpf_get_func_ip inline. */
20114 		if (prog_type == BPF_PROG_TYPE_TRACING &&
20115 		    insn->imm == BPF_FUNC_get_func_ip) {
20116 			/* Load IP address from ctx - 16 */
20117 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
20118 
20119 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
20120 			if (!new_prog)
20121 				return -ENOMEM;
20122 
20123 			env->prog = prog = new_prog;
20124 			insn      = new_prog->insnsi + i + delta;
20125 			goto next_insn;
20126 		}
20127 
20128 		/* Implement bpf_kptr_xchg inline */
20129 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
20130 		    insn->imm == BPF_FUNC_kptr_xchg &&
20131 		    bpf_jit_supports_ptr_xchg()) {
20132 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
20133 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
20134 			cnt = 2;
20135 
20136 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20137 			if (!new_prog)
20138 				return -ENOMEM;
20139 
20140 			delta    += cnt - 1;
20141 			env->prog = prog = new_prog;
20142 			insn      = new_prog->insnsi + i + delta;
20143 			goto next_insn;
20144 		}
20145 patch_call_imm:
20146 		fn = env->ops->get_func_proto(insn->imm, env->prog);
20147 		/* all functions that have prototype and verifier allowed
20148 		 * programs to call them, must be real in-kernel functions
20149 		 */
20150 		if (!fn->func) {
20151 			verbose(env,
20152 				"kernel subsystem misconfigured func %s#%d\n",
20153 				func_id_name(insn->imm), insn->imm);
20154 			return -EFAULT;
20155 		}
20156 		insn->imm = fn->func - __bpf_call_base;
20157 next_insn:
20158 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
20159 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
20160 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
20161 			cur_subprog++;
20162 			stack_depth = subprogs[cur_subprog].stack_depth;
20163 			stack_depth_extra = 0;
20164 		}
20165 		i++;
20166 		insn++;
20167 	}
20168 
20169 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
20170 	for (i = 0; i < env->subprog_cnt; i++) {
20171 		int subprog_start = subprogs[i].start;
20172 		int stack_slots = subprogs[i].stack_extra / 8;
20173 
20174 		if (!stack_slots)
20175 			continue;
20176 		if (stack_slots > 1) {
20177 			verbose(env, "verifier bug: stack_slots supports may_goto only\n");
20178 			return -EFAULT;
20179 		}
20180 
20181 		/* Add ST insn to subprog prologue to init extra stack */
20182 		insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP,
20183 					 -subprogs[i].stack_depth, BPF_MAX_LOOPS);
20184 		/* Copy first actual insn to preserve it */
20185 		insn_buf[1] = env->prog->insnsi[subprog_start];
20186 
20187 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2);
20188 		if (!new_prog)
20189 			return -ENOMEM;
20190 		env->prog = prog = new_prog;
20191 	}
20192 
20193 	/* Since poke tab is now finalized, publish aux to tracker. */
20194 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
20195 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
20196 		if (!map_ptr->ops->map_poke_track ||
20197 		    !map_ptr->ops->map_poke_untrack ||
20198 		    !map_ptr->ops->map_poke_run) {
20199 			verbose(env, "bpf verifier is misconfigured\n");
20200 			return -EINVAL;
20201 		}
20202 
20203 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
20204 		if (ret < 0) {
20205 			verbose(env, "tracking tail call prog failed\n");
20206 			return ret;
20207 		}
20208 	}
20209 
20210 	sort_kfunc_descs_by_imm_off(env->prog);
20211 
20212 	return 0;
20213 }
20214 
20215 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
20216 					int position,
20217 					s32 stack_base,
20218 					u32 callback_subprogno,
20219 					u32 *cnt)
20220 {
20221 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
20222 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
20223 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
20224 	int reg_loop_max = BPF_REG_6;
20225 	int reg_loop_cnt = BPF_REG_7;
20226 	int reg_loop_ctx = BPF_REG_8;
20227 
20228 	struct bpf_prog *new_prog;
20229 	u32 callback_start;
20230 	u32 call_insn_offset;
20231 	s32 callback_offset;
20232 
20233 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
20234 	 * be careful to modify this code in sync.
20235 	 */
20236 	struct bpf_insn insn_buf[] = {
20237 		/* Return error and jump to the end of the patch if
20238 		 * expected number of iterations is too big.
20239 		 */
20240 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
20241 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
20242 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
20243 		/* spill R6, R7, R8 to use these as loop vars */
20244 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
20245 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
20246 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
20247 		/* initialize loop vars */
20248 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
20249 		BPF_MOV32_IMM(reg_loop_cnt, 0),
20250 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
20251 		/* loop header,
20252 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
20253 		 */
20254 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
20255 		/* callback call,
20256 		 * correct callback offset would be set after patching
20257 		 */
20258 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
20259 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
20260 		BPF_CALL_REL(0),
20261 		/* increment loop counter */
20262 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
20263 		/* jump to loop header if callback returned 0 */
20264 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
20265 		/* return value of bpf_loop,
20266 		 * set R0 to the number of iterations
20267 		 */
20268 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
20269 		/* restore original values of R6, R7, R8 */
20270 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
20271 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
20272 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
20273 	};
20274 
20275 	*cnt = ARRAY_SIZE(insn_buf);
20276 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
20277 	if (!new_prog)
20278 		return new_prog;
20279 
20280 	/* callback start is known only after patching */
20281 	callback_start = env->subprog_info[callback_subprogno].start;
20282 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
20283 	call_insn_offset = position + 12;
20284 	callback_offset = callback_start - call_insn_offset - 1;
20285 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
20286 
20287 	return new_prog;
20288 }
20289 
20290 static bool is_bpf_loop_call(struct bpf_insn *insn)
20291 {
20292 	return insn->code == (BPF_JMP | BPF_CALL) &&
20293 		insn->src_reg == 0 &&
20294 		insn->imm == BPF_FUNC_loop;
20295 }
20296 
20297 /* For all sub-programs in the program (including main) check
20298  * insn_aux_data to see if there are bpf_loop calls that require
20299  * inlining. If such calls are found the calls are replaced with a
20300  * sequence of instructions produced by `inline_bpf_loop` function and
20301  * subprog stack_depth is increased by the size of 3 registers.
20302  * This stack space is used to spill values of the R6, R7, R8.  These
20303  * registers are used to store the loop bound, counter and context
20304  * variables.
20305  */
20306 static int optimize_bpf_loop(struct bpf_verifier_env *env)
20307 {
20308 	struct bpf_subprog_info *subprogs = env->subprog_info;
20309 	int i, cur_subprog = 0, cnt, delta = 0;
20310 	struct bpf_insn *insn = env->prog->insnsi;
20311 	int insn_cnt = env->prog->len;
20312 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
20313 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20314 	u16 stack_depth_extra = 0;
20315 
20316 	for (i = 0; i < insn_cnt; i++, insn++) {
20317 		struct bpf_loop_inline_state *inline_state =
20318 			&env->insn_aux_data[i + delta].loop_inline_state;
20319 
20320 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
20321 			struct bpf_prog *new_prog;
20322 
20323 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
20324 			new_prog = inline_bpf_loop(env,
20325 						   i + delta,
20326 						   -(stack_depth + stack_depth_extra),
20327 						   inline_state->callback_subprogno,
20328 						   &cnt);
20329 			if (!new_prog)
20330 				return -ENOMEM;
20331 
20332 			delta     += cnt - 1;
20333 			env->prog  = new_prog;
20334 			insn       = new_prog->insnsi + i + delta;
20335 		}
20336 
20337 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
20338 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
20339 			cur_subprog++;
20340 			stack_depth = subprogs[cur_subprog].stack_depth;
20341 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20342 			stack_depth_extra = 0;
20343 		}
20344 	}
20345 
20346 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20347 
20348 	return 0;
20349 }
20350 
20351 static void free_states(struct bpf_verifier_env *env)
20352 {
20353 	struct bpf_verifier_state_list *sl, *sln;
20354 	int i;
20355 
20356 	sl = env->free_list;
20357 	while (sl) {
20358 		sln = sl->next;
20359 		free_verifier_state(&sl->state, false);
20360 		kfree(sl);
20361 		sl = sln;
20362 	}
20363 	env->free_list = NULL;
20364 
20365 	if (!env->explored_states)
20366 		return;
20367 
20368 	for (i = 0; i < state_htab_size(env); i++) {
20369 		sl = env->explored_states[i];
20370 
20371 		while (sl) {
20372 			sln = sl->next;
20373 			free_verifier_state(&sl->state, false);
20374 			kfree(sl);
20375 			sl = sln;
20376 		}
20377 		env->explored_states[i] = NULL;
20378 	}
20379 }
20380 
20381 static int do_check_common(struct bpf_verifier_env *env, int subprog)
20382 {
20383 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20384 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
20385 	struct bpf_verifier_state *state;
20386 	struct bpf_reg_state *regs;
20387 	int ret, i;
20388 
20389 	env->prev_linfo = NULL;
20390 	env->pass_cnt++;
20391 
20392 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
20393 	if (!state)
20394 		return -ENOMEM;
20395 	state->curframe = 0;
20396 	state->speculative = false;
20397 	state->branches = 1;
20398 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
20399 	if (!state->frame[0]) {
20400 		kfree(state);
20401 		return -ENOMEM;
20402 	}
20403 	env->cur_state = state;
20404 	init_func_state(env, state->frame[0],
20405 			BPF_MAIN_FUNC /* callsite */,
20406 			0 /* frameno */,
20407 			subprog);
20408 	state->first_insn_idx = env->subprog_info[subprog].start;
20409 	state->last_insn_idx = -1;
20410 
20411 	regs = state->frame[state->curframe]->regs;
20412 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
20413 		const char *sub_name = subprog_name(env, subprog);
20414 		struct bpf_subprog_arg_info *arg;
20415 		struct bpf_reg_state *reg;
20416 
20417 		verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
20418 		ret = btf_prepare_func_args(env, subprog);
20419 		if (ret)
20420 			goto out;
20421 
20422 		if (subprog_is_exc_cb(env, subprog)) {
20423 			state->frame[0]->in_exception_callback_fn = true;
20424 			/* We have already ensured that the callback returns an integer, just
20425 			 * like all global subprogs. We need to determine it only has a single
20426 			 * scalar argument.
20427 			 */
20428 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
20429 				verbose(env, "exception cb only supports single integer argument\n");
20430 				ret = -EINVAL;
20431 				goto out;
20432 			}
20433 		}
20434 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
20435 			arg = &sub->args[i - BPF_REG_1];
20436 			reg = &regs[i];
20437 
20438 			if (arg->arg_type == ARG_PTR_TO_CTX) {
20439 				reg->type = PTR_TO_CTX;
20440 				mark_reg_known_zero(env, regs, i);
20441 			} else if (arg->arg_type == ARG_ANYTHING) {
20442 				reg->type = SCALAR_VALUE;
20443 				mark_reg_unknown(env, regs, i);
20444 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
20445 				/* assume unspecial LOCAL dynptr type */
20446 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
20447 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
20448 				reg->type = PTR_TO_MEM;
20449 				if (arg->arg_type & PTR_MAYBE_NULL)
20450 					reg->type |= PTR_MAYBE_NULL;
20451 				mark_reg_known_zero(env, regs, i);
20452 				reg->mem_size = arg->mem_size;
20453 				reg->id = ++env->id_gen;
20454 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
20455 				reg->type = PTR_TO_BTF_ID;
20456 				if (arg->arg_type & PTR_MAYBE_NULL)
20457 					reg->type |= PTR_MAYBE_NULL;
20458 				if (arg->arg_type & PTR_UNTRUSTED)
20459 					reg->type |= PTR_UNTRUSTED;
20460 				if (arg->arg_type & PTR_TRUSTED)
20461 					reg->type |= PTR_TRUSTED;
20462 				mark_reg_known_zero(env, regs, i);
20463 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
20464 				reg->btf_id = arg->btf_id;
20465 				reg->id = ++env->id_gen;
20466 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
20467 				/* caller can pass either PTR_TO_ARENA or SCALAR */
20468 				mark_reg_unknown(env, regs, i);
20469 			} else {
20470 				WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
20471 					  i - BPF_REG_1, arg->arg_type);
20472 				ret = -EFAULT;
20473 				goto out;
20474 			}
20475 		}
20476 	} else {
20477 		/* if main BPF program has associated BTF info, validate that
20478 		 * it's matching expected signature, and otherwise mark BTF
20479 		 * info for main program as unreliable
20480 		 */
20481 		if (env->prog->aux->func_info_aux) {
20482 			ret = btf_prepare_func_args(env, 0);
20483 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
20484 				env->prog->aux->func_info_aux[0].unreliable = true;
20485 		}
20486 
20487 		/* 1st arg to a function */
20488 		regs[BPF_REG_1].type = PTR_TO_CTX;
20489 		mark_reg_known_zero(env, regs, BPF_REG_1);
20490 	}
20491 
20492 	ret = do_check(env);
20493 out:
20494 	/* check for NULL is necessary, since cur_state can be freed inside
20495 	 * do_check() under memory pressure.
20496 	 */
20497 	if (env->cur_state) {
20498 		free_verifier_state(env->cur_state, true);
20499 		env->cur_state = NULL;
20500 	}
20501 	while (!pop_stack(env, NULL, NULL, false));
20502 	if (!ret && pop_log)
20503 		bpf_vlog_reset(&env->log, 0);
20504 	free_states(env);
20505 	return ret;
20506 }
20507 
20508 /* Lazily verify all global functions based on their BTF, if they are called
20509  * from main BPF program or any of subprograms transitively.
20510  * BPF global subprogs called from dead code are not validated.
20511  * All callable global functions must pass verification.
20512  * Otherwise the whole program is rejected.
20513  * Consider:
20514  * int bar(int);
20515  * int foo(int f)
20516  * {
20517  *    return bar(f);
20518  * }
20519  * int bar(int b)
20520  * {
20521  *    ...
20522  * }
20523  * foo() will be verified first for R1=any_scalar_value. During verification it
20524  * will be assumed that bar() already verified successfully and call to bar()
20525  * from foo() will be checked for type match only. Later bar() will be verified
20526  * independently to check that it's safe for R1=any_scalar_value.
20527  */
20528 static int do_check_subprogs(struct bpf_verifier_env *env)
20529 {
20530 	struct bpf_prog_aux *aux = env->prog->aux;
20531 	struct bpf_func_info_aux *sub_aux;
20532 	int i, ret, new_cnt;
20533 
20534 	if (!aux->func_info)
20535 		return 0;
20536 
20537 	/* exception callback is presumed to be always called */
20538 	if (env->exception_callback_subprog)
20539 		subprog_aux(env, env->exception_callback_subprog)->called = true;
20540 
20541 again:
20542 	new_cnt = 0;
20543 	for (i = 1; i < env->subprog_cnt; i++) {
20544 		if (!subprog_is_global(env, i))
20545 			continue;
20546 
20547 		sub_aux = subprog_aux(env, i);
20548 		if (!sub_aux->called || sub_aux->verified)
20549 			continue;
20550 
20551 		env->insn_idx = env->subprog_info[i].start;
20552 		WARN_ON_ONCE(env->insn_idx == 0);
20553 		ret = do_check_common(env, i);
20554 		if (ret) {
20555 			return ret;
20556 		} else if (env->log.level & BPF_LOG_LEVEL) {
20557 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
20558 				i, subprog_name(env, i));
20559 		}
20560 
20561 		/* We verified new global subprog, it might have called some
20562 		 * more global subprogs that we haven't verified yet, so we
20563 		 * need to do another pass over subprogs to verify those.
20564 		 */
20565 		sub_aux->verified = true;
20566 		new_cnt++;
20567 	}
20568 
20569 	/* We can't loop forever as we verify at least one global subprog on
20570 	 * each pass.
20571 	 */
20572 	if (new_cnt)
20573 		goto again;
20574 
20575 	return 0;
20576 }
20577 
20578 static int do_check_main(struct bpf_verifier_env *env)
20579 {
20580 	int ret;
20581 
20582 	env->insn_idx = 0;
20583 	ret = do_check_common(env, 0);
20584 	if (!ret)
20585 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20586 	return ret;
20587 }
20588 
20589 
20590 static void print_verification_stats(struct bpf_verifier_env *env)
20591 {
20592 	int i;
20593 
20594 	if (env->log.level & BPF_LOG_STATS) {
20595 		verbose(env, "verification time %lld usec\n",
20596 			div_u64(env->verification_time, 1000));
20597 		verbose(env, "stack depth ");
20598 		for (i = 0; i < env->subprog_cnt; i++) {
20599 			u32 depth = env->subprog_info[i].stack_depth;
20600 
20601 			verbose(env, "%d", depth);
20602 			if (i + 1 < env->subprog_cnt)
20603 				verbose(env, "+");
20604 		}
20605 		verbose(env, "\n");
20606 	}
20607 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
20608 		"total_states %d peak_states %d mark_read %d\n",
20609 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
20610 		env->max_states_per_insn, env->total_states,
20611 		env->peak_states, env->longest_mark_read_walk);
20612 }
20613 
20614 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
20615 {
20616 	const struct btf_type *t, *func_proto;
20617 	const struct bpf_struct_ops_desc *st_ops_desc;
20618 	const struct bpf_struct_ops *st_ops;
20619 	const struct btf_member *member;
20620 	struct bpf_prog *prog = env->prog;
20621 	u32 btf_id, member_idx;
20622 	struct btf *btf;
20623 	const char *mname;
20624 
20625 	if (!prog->gpl_compatible) {
20626 		verbose(env, "struct ops programs must have a GPL compatible license\n");
20627 		return -EINVAL;
20628 	}
20629 
20630 	if (!prog->aux->attach_btf_id)
20631 		return -ENOTSUPP;
20632 
20633 	btf = prog->aux->attach_btf;
20634 	if (btf_is_module(btf)) {
20635 		/* Make sure st_ops is valid through the lifetime of env */
20636 		env->attach_btf_mod = btf_try_get_module(btf);
20637 		if (!env->attach_btf_mod) {
20638 			verbose(env, "struct_ops module %s is not found\n",
20639 				btf_get_name(btf));
20640 			return -ENOTSUPP;
20641 		}
20642 	}
20643 
20644 	btf_id = prog->aux->attach_btf_id;
20645 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
20646 	if (!st_ops_desc) {
20647 		verbose(env, "attach_btf_id %u is not a supported struct\n",
20648 			btf_id);
20649 		return -ENOTSUPP;
20650 	}
20651 	st_ops = st_ops_desc->st_ops;
20652 
20653 	t = st_ops_desc->type;
20654 	member_idx = prog->expected_attach_type;
20655 	if (member_idx >= btf_type_vlen(t)) {
20656 		verbose(env, "attach to invalid member idx %u of struct %s\n",
20657 			member_idx, st_ops->name);
20658 		return -EINVAL;
20659 	}
20660 
20661 	member = &btf_type_member(t)[member_idx];
20662 	mname = btf_name_by_offset(btf, member->name_off);
20663 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
20664 					       NULL);
20665 	if (!func_proto) {
20666 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
20667 			mname, member_idx, st_ops->name);
20668 		return -EINVAL;
20669 	}
20670 
20671 	if (st_ops->check_member) {
20672 		int err = st_ops->check_member(t, member, prog);
20673 
20674 		if (err) {
20675 			verbose(env, "attach to unsupported member %s of struct %s\n",
20676 				mname, st_ops->name);
20677 			return err;
20678 		}
20679 	}
20680 
20681 	/* btf_ctx_access() used this to provide argument type info */
20682 	prog->aux->ctx_arg_info =
20683 		st_ops_desc->arg_info[member_idx].info;
20684 	prog->aux->ctx_arg_info_size =
20685 		st_ops_desc->arg_info[member_idx].cnt;
20686 
20687 	prog->aux->attach_func_proto = func_proto;
20688 	prog->aux->attach_func_name = mname;
20689 	env->ops = st_ops->verifier_ops;
20690 
20691 	return 0;
20692 }
20693 #define SECURITY_PREFIX "security_"
20694 
20695 static int check_attach_modify_return(unsigned long addr, const char *func_name)
20696 {
20697 	if (within_error_injection_list(addr) ||
20698 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
20699 		return 0;
20700 
20701 	return -EINVAL;
20702 }
20703 
20704 /* list of non-sleepable functions that are otherwise on
20705  * ALLOW_ERROR_INJECTION list
20706  */
20707 BTF_SET_START(btf_non_sleepable_error_inject)
20708 /* Three functions below can be called from sleepable and non-sleepable context.
20709  * Assume non-sleepable from bpf safety point of view.
20710  */
20711 BTF_ID(func, __filemap_add_folio)
20712 BTF_ID(func, should_fail_alloc_page)
20713 BTF_ID(func, should_failslab)
20714 BTF_SET_END(btf_non_sleepable_error_inject)
20715 
20716 static int check_non_sleepable_error_inject(u32 btf_id)
20717 {
20718 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
20719 }
20720 
20721 int bpf_check_attach_target(struct bpf_verifier_log *log,
20722 			    const struct bpf_prog *prog,
20723 			    const struct bpf_prog *tgt_prog,
20724 			    u32 btf_id,
20725 			    struct bpf_attach_target_info *tgt_info)
20726 {
20727 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
20728 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
20729 	const char prefix[] = "btf_trace_";
20730 	int ret = 0, subprog = -1, i;
20731 	const struct btf_type *t;
20732 	bool conservative = true;
20733 	const char *tname;
20734 	struct btf *btf;
20735 	long addr = 0;
20736 	struct module *mod = NULL;
20737 
20738 	if (!btf_id) {
20739 		bpf_log(log, "Tracing programs must provide btf_id\n");
20740 		return -EINVAL;
20741 	}
20742 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
20743 	if (!btf) {
20744 		bpf_log(log,
20745 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
20746 		return -EINVAL;
20747 	}
20748 	t = btf_type_by_id(btf, btf_id);
20749 	if (!t) {
20750 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
20751 		return -EINVAL;
20752 	}
20753 	tname = btf_name_by_offset(btf, t->name_off);
20754 	if (!tname) {
20755 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
20756 		return -EINVAL;
20757 	}
20758 	if (tgt_prog) {
20759 		struct bpf_prog_aux *aux = tgt_prog->aux;
20760 
20761 		if (bpf_prog_is_dev_bound(prog->aux) &&
20762 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
20763 			bpf_log(log, "Target program bound device mismatch");
20764 			return -EINVAL;
20765 		}
20766 
20767 		for (i = 0; i < aux->func_info_cnt; i++)
20768 			if (aux->func_info[i].type_id == btf_id) {
20769 				subprog = i;
20770 				break;
20771 			}
20772 		if (subprog == -1) {
20773 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
20774 			return -EINVAL;
20775 		}
20776 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
20777 			bpf_log(log,
20778 				"%s programs cannot attach to exception callback\n",
20779 				prog_extension ? "Extension" : "FENTRY/FEXIT");
20780 			return -EINVAL;
20781 		}
20782 		conservative = aux->func_info_aux[subprog].unreliable;
20783 		if (prog_extension) {
20784 			if (conservative) {
20785 				bpf_log(log,
20786 					"Cannot replace static functions\n");
20787 				return -EINVAL;
20788 			}
20789 			if (!prog->jit_requested) {
20790 				bpf_log(log,
20791 					"Extension programs should be JITed\n");
20792 				return -EINVAL;
20793 			}
20794 		}
20795 		if (!tgt_prog->jited) {
20796 			bpf_log(log, "Can attach to only JITed progs\n");
20797 			return -EINVAL;
20798 		}
20799 		if (prog_tracing) {
20800 			if (aux->attach_tracing_prog) {
20801 				/*
20802 				 * Target program is an fentry/fexit which is already attached
20803 				 * to another tracing program. More levels of nesting
20804 				 * attachment are not allowed.
20805 				 */
20806 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
20807 				return -EINVAL;
20808 			}
20809 		} else if (tgt_prog->type == prog->type) {
20810 			/*
20811 			 * To avoid potential call chain cycles, prevent attaching of a
20812 			 * program extension to another extension. It's ok to attach
20813 			 * fentry/fexit to extension program.
20814 			 */
20815 			bpf_log(log, "Cannot recursively attach\n");
20816 			return -EINVAL;
20817 		}
20818 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
20819 		    prog_extension &&
20820 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
20821 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
20822 			/* Program extensions can extend all program types
20823 			 * except fentry/fexit. The reason is the following.
20824 			 * The fentry/fexit programs are used for performance
20825 			 * analysis, stats and can be attached to any program
20826 			 * type. When extension program is replacing XDP function
20827 			 * it is necessary to allow performance analysis of all
20828 			 * functions. Both original XDP program and its program
20829 			 * extension. Hence attaching fentry/fexit to
20830 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
20831 			 * fentry/fexit was allowed it would be possible to create
20832 			 * long call chain fentry->extension->fentry->extension
20833 			 * beyond reasonable stack size. Hence extending fentry
20834 			 * is not allowed.
20835 			 */
20836 			bpf_log(log, "Cannot extend fentry/fexit\n");
20837 			return -EINVAL;
20838 		}
20839 	} else {
20840 		if (prog_extension) {
20841 			bpf_log(log, "Cannot replace kernel functions\n");
20842 			return -EINVAL;
20843 		}
20844 	}
20845 
20846 	switch (prog->expected_attach_type) {
20847 	case BPF_TRACE_RAW_TP:
20848 		if (tgt_prog) {
20849 			bpf_log(log,
20850 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
20851 			return -EINVAL;
20852 		}
20853 		if (!btf_type_is_typedef(t)) {
20854 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
20855 				btf_id);
20856 			return -EINVAL;
20857 		}
20858 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
20859 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
20860 				btf_id, tname);
20861 			return -EINVAL;
20862 		}
20863 		tname += sizeof(prefix) - 1;
20864 		t = btf_type_by_id(btf, t->type);
20865 		if (!btf_type_is_ptr(t))
20866 			/* should never happen in valid vmlinux build */
20867 			return -EINVAL;
20868 		t = btf_type_by_id(btf, t->type);
20869 		if (!btf_type_is_func_proto(t))
20870 			/* should never happen in valid vmlinux build */
20871 			return -EINVAL;
20872 
20873 		break;
20874 	case BPF_TRACE_ITER:
20875 		if (!btf_type_is_func(t)) {
20876 			bpf_log(log, "attach_btf_id %u is not a function\n",
20877 				btf_id);
20878 			return -EINVAL;
20879 		}
20880 		t = btf_type_by_id(btf, t->type);
20881 		if (!btf_type_is_func_proto(t))
20882 			return -EINVAL;
20883 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20884 		if (ret)
20885 			return ret;
20886 		break;
20887 	default:
20888 		if (!prog_extension)
20889 			return -EINVAL;
20890 		fallthrough;
20891 	case BPF_MODIFY_RETURN:
20892 	case BPF_LSM_MAC:
20893 	case BPF_LSM_CGROUP:
20894 	case BPF_TRACE_FENTRY:
20895 	case BPF_TRACE_FEXIT:
20896 		if (!btf_type_is_func(t)) {
20897 			bpf_log(log, "attach_btf_id %u is not a function\n",
20898 				btf_id);
20899 			return -EINVAL;
20900 		}
20901 		if (prog_extension &&
20902 		    btf_check_type_match(log, prog, btf, t))
20903 			return -EINVAL;
20904 		t = btf_type_by_id(btf, t->type);
20905 		if (!btf_type_is_func_proto(t))
20906 			return -EINVAL;
20907 
20908 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
20909 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
20910 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
20911 			return -EINVAL;
20912 
20913 		if (tgt_prog && conservative)
20914 			t = NULL;
20915 
20916 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20917 		if (ret < 0)
20918 			return ret;
20919 
20920 		if (tgt_prog) {
20921 			if (subprog == 0)
20922 				addr = (long) tgt_prog->bpf_func;
20923 			else
20924 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20925 		} else {
20926 			if (btf_is_module(btf)) {
20927 				mod = btf_try_get_module(btf);
20928 				if (mod)
20929 					addr = find_kallsyms_symbol_value(mod, tname);
20930 				else
20931 					addr = 0;
20932 			} else {
20933 				addr = kallsyms_lookup_name(tname);
20934 			}
20935 			if (!addr) {
20936 				module_put(mod);
20937 				bpf_log(log,
20938 					"The address of function %s cannot be found\n",
20939 					tname);
20940 				return -ENOENT;
20941 			}
20942 		}
20943 
20944 		if (prog->sleepable) {
20945 			ret = -EINVAL;
20946 			switch (prog->type) {
20947 			case BPF_PROG_TYPE_TRACING:
20948 
20949 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
20950 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20951 				 */
20952 				if (!check_non_sleepable_error_inject(btf_id) &&
20953 				    within_error_injection_list(addr))
20954 					ret = 0;
20955 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
20956 				 * in the fmodret id set with the KF_SLEEPABLE flag.
20957 				 */
20958 				else {
20959 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20960 										prog);
20961 
20962 					if (flags && (*flags & KF_SLEEPABLE))
20963 						ret = 0;
20964 				}
20965 				break;
20966 			case BPF_PROG_TYPE_LSM:
20967 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
20968 				 * Only some of them are sleepable.
20969 				 */
20970 				if (bpf_lsm_is_sleepable_hook(btf_id))
20971 					ret = 0;
20972 				break;
20973 			default:
20974 				break;
20975 			}
20976 			if (ret) {
20977 				module_put(mod);
20978 				bpf_log(log, "%s is not sleepable\n", tname);
20979 				return ret;
20980 			}
20981 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20982 			if (tgt_prog) {
20983 				module_put(mod);
20984 				bpf_log(log, "can't modify return codes of BPF programs\n");
20985 				return -EINVAL;
20986 			}
20987 			ret = -EINVAL;
20988 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20989 			    !check_attach_modify_return(addr, tname))
20990 				ret = 0;
20991 			if (ret) {
20992 				module_put(mod);
20993 				bpf_log(log, "%s() is not modifiable\n", tname);
20994 				return ret;
20995 			}
20996 		}
20997 
20998 		break;
20999 	}
21000 	tgt_info->tgt_addr = addr;
21001 	tgt_info->tgt_name = tname;
21002 	tgt_info->tgt_type = t;
21003 	tgt_info->tgt_mod = mod;
21004 	return 0;
21005 }
21006 
21007 BTF_SET_START(btf_id_deny)
21008 BTF_ID_UNUSED
21009 #ifdef CONFIG_SMP
21010 BTF_ID(func, migrate_disable)
21011 BTF_ID(func, migrate_enable)
21012 #endif
21013 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
21014 BTF_ID(func, rcu_read_unlock_strict)
21015 #endif
21016 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
21017 BTF_ID(func, preempt_count_add)
21018 BTF_ID(func, preempt_count_sub)
21019 #endif
21020 #ifdef CONFIG_PREEMPT_RCU
21021 BTF_ID(func, __rcu_read_lock)
21022 BTF_ID(func, __rcu_read_unlock)
21023 #endif
21024 BTF_SET_END(btf_id_deny)
21025 
21026 static bool can_be_sleepable(struct bpf_prog *prog)
21027 {
21028 	if (prog->type == BPF_PROG_TYPE_TRACING) {
21029 		switch (prog->expected_attach_type) {
21030 		case BPF_TRACE_FENTRY:
21031 		case BPF_TRACE_FEXIT:
21032 		case BPF_MODIFY_RETURN:
21033 		case BPF_TRACE_ITER:
21034 			return true;
21035 		default:
21036 			return false;
21037 		}
21038 	}
21039 	return prog->type == BPF_PROG_TYPE_LSM ||
21040 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
21041 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
21042 }
21043 
21044 static int check_attach_btf_id(struct bpf_verifier_env *env)
21045 {
21046 	struct bpf_prog *prog = env->prog;
21047 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
21048 	struct bpf_attach_target_info tgt_info = {};
21049 	u32 btf_id = prog->aux->attach_btf_id;
21050 	struct bpf_trampoline *tr;
21051 	int ret;
21052 	u64 key;
21053 
21054 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
21055 		if (prog->sleepable)
21056 			/* attach_btf_id checked to be zero already */
21057 			return 0;
21058 		verbose(env, "Syscall programs can only be sleepable\n");
21059 		return -EINVAL;
21060 	}
21061 
21062 	if (prog->sleepable && !can_be_sleepable(prog)) {
21063 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
21064 		return -EINVAL;
21065 	}
21066 
21067 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
21068 		return check_struct_ops_btf_id(env);
21069 
21070 	if (prog->type != BPF_PROG_TYPE_TRACING &&
21071 	    prog->type != BPF_PROG_TYPE_LSM &&
21072 	    prog->type != BPF_PROG_TYPE_EXT)
21073 		return 0;
21074 
21075 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
21076 	if (ret)
21077 		return ret;
21078 
21079 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
21080 		/* to make freplace equivalent to their targets, they need to
21081 		 * inherit env->ops and expected_attach_type for the rest of the
21082 		 * verification
21083 		 */
21084 		env->ops = bpf_verifier_ops[tgt_prog->type];
21085 		prog->expected_attach_type = tgt_prog->expected_attach_type;
21086 	}
21087 
21088 	/* store info about the attachment target that will be used later */
21089 	prog->aux->attach_func_proto = tgt_info.tgt_type;
21090 	prog->aux->attach_func_name = tgt_info.tgt_name;
21091 	prog->aux->mod = tgt_info.tgt_mod;
21092 
21093 	if (tgt_prog) {
21094 		prog->aux->saved_dst_prog_type = tgt_prog->type;
21095 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
21096 	}
21097 
21098 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
21099 		prog->aux->attach_btf_trace = true;
21100 		return 0;
21101 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
21102 		if (!bpf_iter_prog_supported(prog))
21103 			return -EINVAL;
21104 		return 0;
21105 	}
21106 
21107 	if (prog->type == BPF_PROG_TYPE_LSM) {
21108 		ret = bpf_lsm_verify_prog(&env->log, prog);
21109 		if (ret < 0)
21110 			return ret;
21111 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
21112 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
21113 		return -EINVAL;
21114 	}
21115 
21116 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
21117 	tr = bpf_trampoline_get(key, &tgt_info);
21118 	if (!tr)
21119 		return -ENOMEM;
21120 
21121 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
21122 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
21123 
21124 	prog->aux->dst_trampoline = tr;
21125 	return 0;
21126 }
21127 
21128 struct btf *bpf_get_btf_vmlinux(void)
21129 {
21130 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
21131 		mutex_lock(&bpf_verifier_lock);
21132 		if (!btf_vmlinux)
21133 			btf_vmlinux = btf_parse_vmlinux();
21134 		mutex_unlock(&bpf_verifier_lock);
21135 	}
21136 	return btf_vmlinux;
21137 }
21138 
21139 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
21140 {
21141 	u64 start_time = ktime_get_ns();
21142 	struct bpf_verifier_env *env;
21143 	int i, len, ret = -EINVAL, err;
21144 	u32 log_true_size;
21145 	bool is_priv;
21146 
21147 	/* no program is valid */
21148 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
21149 		return -EINVAL;
21150 
21151 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
21152 	 * allocate/free it every time bpf_check() is called
21153 	 */
21154 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
21155 	if (!env)
21156 		return -ENOMEM;
21157 
21158 	env->bt.env = env;
21159 
21160 	len = (*prog)->len;
21161 	env->insn_aux_data =
21162 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
21163 	ret = -ENOMEM;
21164 	if (!env->insn_aux_data)
21165 		goto err_free_env;
21166 	for (i = 0; i < len; i++)
21167 		env->insn_aux_data[i].orig_idx = i;
21168 	env->prog = *prog;
21169 	env->ops = bpf_verifier_ops[env->prog->type];
21170 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
21171 
21172 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
21173 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
21174 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
21175 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
21176 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
21177 
21178 	bpf_get_btf_vmlinux();
21179 
21180 	/* grab the mutex to protect few globals used by verifier */
21181 	if (!is_priv)
21182 		mutex_lock(&bpf_verifier_lock);
21183 
21184 	/* user could have requested verbose verifier output
21185 	 * and supplied buffer to store the verification trace
21186 	 */
21187 	ret = bpf_vlog_init(&env->log, attr->log_level,
21188 			    (char __user *) (unsigned long) attr->log_buf,
21189 			    attr->log_size);
21190 	if (ret)
21191 		goto err_unlock;
21192 
21193 	mark_verifier_state_clean(env);
21194 
21195 	if (IS_ERR(btf_vmlinux)) {
21196 		/* Either gcc or pahole or kernel are broken. */
21197 		verbose(env, "in-kernel BTF is malformed\n");
21198 		ret = PTR_ERR(btf_vmlinux);
21199 		goto skip_full_check;
21200 	}
21201 
21202 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
21203 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
21204 		env->strict_alignment = true;
21205 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
21206 		env->strict_alignment = false;
21207 
21208 	if (is_priv)
21209 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
21210 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
21211 
21212 	env->explored_states = kvcalloc(state_htab_size(env),
21213 				       sizeof(struct bpf_verifier_state_list *),
21214 				       GFP_USER);
21215 	ret = -ENOMEM;
21216 	if (!env->explored_states)
21217 		goto skip_full_check;
21218 
21219 	ret = check_btf_info_early(env, attr, uattr);
21220 	if (ret < 0)
21221 		goto skip_full_check;
21222 
21223 	ret = add_subprog_and_kfunc(env);
21224 	if (ret < 0)
21225 		goto skip_full_check;
21226 
21227 	ret = check_subprogs(env);
21228 	if (ret < 0)
21229 		goto skip_full_check;
21230 
21231 	ret = check_btf_info(env, attr, uattr);
21232 	if (ret < 0)
21233 		goto skip_full_check;
21234 
21235 	ret = check_attach_btf_id(env);
21236 	if (ret)
21237 		goto skip_full_check;
21238 
21239 	ret = resolve_pseudo_ldimm64(env);
21240 	if (ret < 0)
21241 		goto skip_full_check;
21242 
21243 	if (bpf_prog_is_offloaded(env->prog->aux)) {
21244 		ret = bpf_prog_offload_verifier_prep(env->prog);
21245 		if (ret)
21246 			goto skip_full_check;
21247 	}
21248 
21249 	ret = check_cfg(env);
21250 	if (ret < 0)
21251 		goto skip_full_check;
21252 
21253 	ret = do_check_main(env);
21254 	ret = ret ?: do_check_subprogs(env);
21255 
21256 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
21257 		ret = bpf_prog_offload_finalize(env);
21258 
21259 skip_full_check:
21260 	kvfree(env->explored_states);
21261 
21262 	if (ret == 0)
21263 		ret = check_max_stack_depth(env);
21264 
21265 	/* instruction rewrites happen after this point */
21266 	if (ret == 0)
21267 		ret = optimize_bpf_loop(env);
21268 
21269 	if (is_priv) {
21270 		if (ret == 0)
21271 			opt_hard_wire_dead_code_branches(env);
21272 		if (ret == 0)
21273 			ret = opt_remove_dead_code(env);
21274 		if (ret == 0)
21275 			ret = opt_remove_nops(env);
21276 	} else {
21277 		if (ret == 0)
21278 			sanitize_dead_code(env);
21279 	}
21280 
21281 	if (ret == 0)
21282 		/* program is valid, convert *(u32*)(ctx + off) accesses */
21283 		ret = convert_ctx_accesses(env);
21284 
21285 	if (ret == 0)
21286 		ret = do_misc_fixups(env);
21287 
21288 	/* do 32-bit optimization after insn patching has done so those patched
21289 	 * insns could be handled correctly.
21290 	 */
21291 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
21292 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
21293 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
21294 								     : false;
21295 	}
21296 
21297 	if (ret == 0)
21298 		ret = fixup_call_args(env);
21299 
21300 	env->verification_time = ktime_get_ns() - start_time;
21301 	print_verification_stats(env);
21302 	env->prog->aux->verified_insns = env->insn_processed;
21303 
21304 	/* preserve original error even if log finalization is successful */
21305 	err = bpf_vlog_finalize(&env->log, &log_true_size);
21306 	if (err)
21307 		ret = err;
21308 
21309 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
21310 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
21311 				  &log_true_size, sizeof(log_true_size))) {
21312 		ret = -EFAULT;
21313 		goto err_release_maps;
21314 	}
21315 
21316 	if (ret)
21317 		goto err_release_maps;
21318 
21319 	if (env->used_map_cnt) {
21320 		/* if program passed verifier, update used_maps in bpf_prog_info */
21321 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
21322 							  sizeof(env->used_maps[0]),
21323 							  GFP_KERNEL);
21324 
21325 		if (!env->prog->aux->used_maps) {
21326 			ret = -ENOMEM;
21327 			goto err_release_maps;
21328 		}
21329 
21330 		memcpy(env->prog->aux->used_maps, env->used_maps,
21331 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
21332 		env->prog->aux->used_map_cnt = env->used_map_cnt;
21333 	}
21334 	if (env->used_btf_cnt) {
21335 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
21336 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
21337 							  sizeof(env->used_btfs[0]),
21338 							  GFP_KERNEL);
21339 		if (!env->prog->aux->used_btfs) {
21340 			ret = -ENOMEM;
21341 			goto err_release_maps;
21342 		}
21343 
21344 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
21345 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
21346 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
21347 	}
21348 	if (env->used_map_cnt || env->used_btf_cnt) {
21349 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
21350 		 * bpf_ld_imm64 instructions
21351 		 */
21352 		convert_pseudo_ld_imm64(env);
21353 	}
21354 
21355 	adjust_btf_func(env);
21356 
21357 err_release_maps:
21358 	if (!env->prog->aux->used_maps)
21359 		/* if we didn't copy map pointers into bpf_prog_info, release
21360 		 * them now. Otherwise free_used_maps() will release them.
21361 		 */
21362 		release_maps(env);
21363 	if (!env->prog->aux->used_btfs)
21364 		release_btfs(env);
21365 
21366 	/* extension progs temporarily inherit the attach_type of their targets
21367 	   for verification purposes, so set it back to zero before returning
21368 	 */
21369 	if (env->prog->type == BPF_PROG_TYPE_EXT)
21370 		env->prog->expected_attach_type = 0;
21371 
21372 	*prog = env->prog;
21373 
21374 	module_put(env->attach_btf_mod);
21375 err_unlock:
21376 	if (!is_priv)
21377 		mutex_unlock(&bpf_verifier_lock);
21378 	vfree(env->insn_aux_data);
21379 err_free_env:
21380 	kfree(env);
21381 	return ret;
21382 }
21383