xref: /linux/kernel/bpf/verifier.c (revision 993498e537af9260e697219ce41b41b22b6199cc)
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 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
199 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
200 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
201 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
202 static int ref_set_non_owning(struct bpf_verifier_env *env,
203 			      struct bpf_reg_state *reg);
204 static void specialize_kfunc(struct bpf_verifier_env *env,
205 			     u32 func_id, u16 offset, unsigned long *addr);
206 static bool is_trusted_reg(const struct bpf_reg_state *reg);
207 
208 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
209 {
210 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
211 }
212 
213 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
214 {
215 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
216 }
217 
218 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
219 			      const struct bpf_map *map, bool unpriv)
220 {
221 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
222 	unpriv |= bpf_map_ptr_unpriv(aux);
223 	aux->map_ptr_state = (unsigned long)map |
224 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
225 }
226 
227 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
228 {
229 	return aux->map_key_state & BPF_MAP_KEY_POISON;
230 }
231 
232 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
233 {
234 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
235 }
236 
237 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
238 {
239 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
240 }
241 
242 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
243 {
244 	bool poisoned = bpf_map_key_poisoned(aux);
245 
246 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
247 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
248 }
249 
250 static bool bpf_helper_call(const struct bpf_insn *insn)
251 {
252 	return insn->code == (BPF_JMP | BPF_CALL) &&
253 	       insn->src_reg == 0;
254 }
255 
256 static bool bpf_pseudo_call(const struct bpf_insn *insn)
257 {
258 	return insn->code == (BPF_JMP | BPF_CALL) &&
259 	       insn->src_reg == BPF_PSEUDO_CALL;
260 }
261 
262 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
263 {
264 	return insn->code == (BPF_JMP | BPF_CALL) &&
265 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
266 }
267 
268 struct bpf_call_arg_meta {
269 	struct bpf_map *map_ptr;
270 	bool raw_mode;
271 	bool pkt_access;
272 	u8 release_regno;
273 	int regno;
274 	int access_size;
275 	int mem_size;
276 	u64 msize_max_value;
277 	int ref_obj_id;
278 	int dynptr_id;
279 	int map_uid;
280 	int func_id;
281 	struct btf *btf;
282 	u32 btf_id;
283 	struct btf *ret_btf;
284 	u32 ret_btf_id;
285 	u32 subprogno;
286 	struct btf_field *kptr_field;
287 };
288 
289 struct bpf_kfunc_call_arg_meta {
290 	/* In parameters */
291 	struct btf *btf;
292 	u32 func_id;
293 	u32 kfunc_flags;
294 	const struct btf_type *func_proto;
295 	const char *func_name;
296 	/* Out parameters */
297 	u32 ref_obj_id;
298 	u8 release_regno;
299 	bool r0_rdonly;
300 	u32 ret_btf_id;
301 	u64 r0_size;
302 	u32 subprogno;
303 	struct {
304 		u64 value;
305 		bool found;
306 	} arg_constant;
307 
308 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
309 	 * generally to pass info about user-defined local kptr types to later
310 	 * verification logic
311 	 *   bpf_obj_drop/bpf_percpu_obj_drop
312 	 *     Record the local kptr type to be drop'd
313 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
314 	 *     Record the local kptr type to be refcount_incr'd and use
315 	 *     arg_owning_ref to determine whether refcount_acquire should be
316 	 *     fallible
317 	 */
318 	struct btf *arg_btf;
319 	u32 arg_btf_id;
320 	bool arg_owning_ref;
321 
322 	struct {
323 		struct btf_field *field;
324 	} arg_list_head;
325 	struct {
326 		struct btf_field *field;
327 	} arg_rbtree_root;
328 	struct {
329 		enum bpf_dynptr_type type;
330 		u32 id;
331 		u32 ref_obj_id;
332 	} initialized_dynptr;
333 	struct {
334 		u8 spi;
335 		u8 frameno;
336 	} iter;
337 	u64 mem_size;
338 };
339 
340 struct btf *btf_vmlinux;
341 
342 static const char *btf_type_name(const struct btf *btf, u32 id)
343 {
344 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
345 }
346 
347 static DEFINE_MUTEX(bpf_verifier_lock);
348 static DEFINE_MUTEX(bpf_percpu_ma_lock);
349 
350 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
351 {
352 	struct bpf_verifier_env *env = private_data;
353 	va_list args;
354 
355 	if (!bpf_verifier_log_needed(&env->log))
356 		return;
357 
358 	va_start(args, fmt);
359 	bpf_verifier_vlog(&env->log, fmt, args);
360 	va_end(args);
361 }
362 
363 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
364 				   struct bpf_reg_state *reg,
365 				   struct bpf_retval_range range, const char *ctx,
366 				   const char *reg_name)
367 {
368 	bool unknown = true;
369 
370 	verbose(env, "%s the register %s has", ctx, reg_name);
371 	if (reg->smin_value > S64_MIN) {
372 		verbose(env, " smin=%lld", reg->smin_value);
373 		unknown = false;
374 	}
375 	if (reg->smax_value < S64_MAX) {
376 		verbose(env, " smax=%lld", reg->smax_value);
377 		unknown = false;
378 	}
379 	if (unknown)
380 		verbose(env, " unknown scalar value");
381 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
382 }
383 
384 static bool type_may_be_null(u32 type)
385 {
386 	return type & PTR_MAYBE_NULL;
387 }
388 
389 static bool reg_not_null(const struct bpf_reg_state *reg)
390 {
391 	enum bpf_reg_type type;
392 
393 	type = reg->type;
394 	if (type_may_be_null(type))
395 		return false;
396 
397 	type = base_type(type);
398 	return type == PTR_TO_SOCKET ||
399 		type == PTR_TO_TCP_SOCK ||
400 		type == PTR_TO_MAP_VALUE ||
401 		type == PTR_TO_MAP_KEY ||
402 		type == PTR_TO_SOCK_COMMON ||
403 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
404 		type == PTR_TO_MEM;
405 }
406 
407 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
408 {
409 	struct btf_record *rec = NULL;
410 	struct btf_struct_meta *meta;
411 
412 	if (reg->type == PTR_TO_MAP_VALUE) {
413 		rec = reg->map_ptr->record;
414 	} else if (type_is_ptr_alloc_obj(reg->type)) {
415 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
416 		if (meta)
417 			rec = meta->record;
418 	}
419 	return rec;
420 }
421 
422 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
423 {
424 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
425 
426 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
427 }
428 
429 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
430 {
431 	struct bpf_func_info *info;
432 
433 	if (!env->prog->aux->func_info)
434 		return "";
435 
436 	info = &env->prog->aux->func_info[subprog];
437 	return btf_type_name(env->prog->aux->btf, info->type_id);
438 }
439 
440 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
441 {
442 	struct bpf_subprog_info *info = subprog_info(env, subprog);
443 
444 	info->is_cb = true;
445 	info->is_async_cb = true;
446 	info->is_exception_cb = true;
447 }
448 
449 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
450 {
451 	return subprog_info(env, subprog)->is_exception_cb;
452 }
453 
454 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
455 {
456 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
457 }
458 
459 static bool type_is_rdonly_mem(u32 type)
460 {
461 	return type & MEM_RDONLY;
462 }
463 
464 static bool is_acquire_function(enum bpf_func_id func_id,
465 				const struct bpf_map *map)
466 {
467 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
468 
469 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
470 	    func_id == BPF_FUNC_sk_lookup_udp ||
471 	    func_id == BPF_FUNC_skc_lookup_tcp ||
472 	    func_id == BPF_FUNC_ringbuf_reserve ||
473 	    func_id == BPF_FUNC_kptr_xchg)
474 		return true;
475 
476 	if (func_id == BPF_FUNC_map_lookup_elem &&
477 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
478 	     map_type == BPF_MAP_TYPE_SOCKHASH))
479 		return true;
480 
481 	return false;
482 }
483 
484 static bool is_ptr_cast_function(enum bpf_func_id func_id)
485 {
486 	return func_id == BPF_FUNC_tcp_sock ||
487 		func_id == BPF_FUNC_sk_fullsock ||
488 		func_id == BPF_FUNC_skc_to_tcp_sock ||
489 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
490 		func_id == BPF_FUNC_skc_to_udp6_sock ||
491 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
492 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
493 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
494 }
495 
496 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
497 {
498 	return func_id == BPF_FUNC_dynptr_data;
499 }
500 
501 static bool is_sync_callback_calling_kfunc(u32 btf_id);
502 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
503 
504 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
505 {
506 	return func_id == BPF_FUNC_for_each_map_elem ||
507 	       func_id == BPF_FUNC_find_vma ||
508 	       func_id == BPF_FUNC_loop ||
509 	       func_id == BPF_FUNC_user_ringbuf_drain;
510 }
511 
512 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
513 {
514 	return func_id == BPF_FUNC_timer_set_callback;
515 }
516 
517 static bool is_callback_calling_function(enum bpf_func_id func_id)
518 {
519 	return is_sync_callback_calling_function(func_id) ||
520 	       is_async_callback_calling_function(func_id);
521 }
522 
523 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
524 {
525 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
526 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
527 }
528 
529 static bool is_storage_get_function(enum bpf_func_id func_id)
530 {
531 	return func_id == BPF_FUNC_sk_storage_get ||
532 	       func_id == BPF_FUNC_inode_storage_get ||
533 	       func_id == BPF_FUNC_task_storage_get ||
534 	       func_id == BPF_FUNC_cgrp_storage_get;
535 }
536 
537 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
538 					const struct bpf_map *map)
539 {
540 	int ref_obj_uses = 0;
541 
542 	if (is_ptr_cast_function(func_id))
543 		ref_obj_uses++;
544 	if (is_acquire_function(func_id, map))
545 		ref_obj_uses++;
546 	if (is_dynptr_ref_function(func_id))
547 		ref_obj_uses++;
548 
549 	return ref_obj_uses > 1;
550 }
551 
552 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
553 {
554 	return BPF_CLASS(insn->code) == BPF_STX &&
555 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
556 	       insn->imm == BPF_CMPXCHG;
557 }
558 
559 static int __get_spi(s32 off)
560 {
561 	return (-off - 1) / BPF_REG_SIZE;
562 }
563 
564 static struct bpf_func_state *func(struct bpf_verifier_env *env,
565 				   const struct bpf_reg_state *reg)
566 {
567 	struct bpf_verifier_state *cur = env->cur_state;
568 
569 	return cur->frame[reg->frameno];
570 }
571 
572 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
573 {
574        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
575 
576        /* We need to check that slots between [spi - nr_slots + 1, spi] are
577 	* within [0, allocated_stack).
578 	*
579 	* Please note that the spi grows downwards. For example, a dynptr
580 	* takes the size of two stack slots; the first slot will be at
581 	* spi and the second slot will be at spi - 1.
582 	*/
583        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
584 }
585 
586 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
587 			          const char *obj_kind, int nr_slots)
588 {
589 	int off, spi;
590 
591 	if (!tnum_is_const(reg->var_off)) {
592 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
593 		return -EINVAL;
594 	}
595 
596 	off = reg->off + reg->var_off.value;
597 	if (off % BPF_REG_SIZE) {
598 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
599 		return -EINVAL;
600 	}
601 
602 	spi = __get_spi(off);
603 	if (spi + 1 < nr_slots) {
604 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
605 		return -EINVAL;
606 	}
607 
608 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
609 		return -ERANGE;
610 	return spi;
611 }
612 
613 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
614 {
615 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
616 }
617 
618 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
619 {
620 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
621 }
622 
623 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
624 {
625 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
626 	case DYNPTR_TYPE_LOCAL:
627 		return BPF_DYNPTR_TYPE_LOCAL;
628 	case DYNPTR_TYPE_RINGBUF:
629 		return BPF_DYNPTR_TYPE_RINGBUF;
630 	case DYNPTR_TYPE_SKB:
631 		return BPF_DYNPTR_TYPE_SKB;
632 	case DYNPTR_TYPE_XDP:
633 		return BPF_DYNPTR_TYPE_XDP;
634 	default:
635 		return BPF_DYNPTR_TYPE_INVALID;
636 	}
637 }
638 
639 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
640 {
641 	switch (type) {
642 	case BPF_DYNPTR_TYPE_LOCAL:
643 		return DYNPTR_TYPE_LOCAL;
644 	case BPF_DYNPTR_TYPE_RINGBUF:
645 		return DYNPTR_TYPE_RINGBUF;
646 	case BPF_DYNPTR_TYPE_SKB:
647 		return DYNPTR_TYPE_SKB;
648 	case BPF_DYNPTR_TYPE_XDP:
649 		return DYNPTR_TYPE_XDP;
650 	default:
651 		return 0;
652 	}
653 }
654 
655 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
656 {
657 	return type == BPF_DYNPTR_TYPE_RINGBUF;
658 }
659 
660 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
661 			      enum bpf_dynptr_type type,
662 			      bool first_slot, int dynptr_id);
663 
664 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
665 				struct bpf_reg_state *reg);
666 
667 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
668 				   struct bpf_reg_state *sreg1,
669 				   struct bpf_reg_state *sreg2,
670 				   enum bpf_dynptr_type type)
671 {
672 	int id = ++env->id_gen;
673 
674 	__mark_dynptr_reg(sreg1, type, true, id);
675 	__mark_dynptr_reg(sreg2, type, false, id);
676 }
677 
678 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
679 			       struct bpf_reg_state *reg,
680 			       enum bpf_dynptr_type type)
681 {
682 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
683 }
684 
685 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
686 				        struct bpf_func_state *state, int spi);
687 
688 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
689 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
690 {
691 	struct bpf_func_state *state = func(env, reg);
692 	enum bpf_dynptr_type type;
693 	int spi, i, err;
694 
695 	spi = dynptr_get_spi(env, reg);
696 	if (spi < 0)
697 		return spi;
698 
699 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
700 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
701 	 * to ensure that for the following example:
702 	 *	[d1][d1][d2][d2]
703 	 * spi    3   2   1   0
704 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
705 	 * case they do belong to same dynptr, second call won't see slot_type
706 	 * as STACK_DYNPTR and will simply skip destruction.
707 	 */
708 	err = destroy_if_dynptr_stack_slot(env, state, spi);
709 	if (err)
710 		return err;
711 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
712 	if (err)
713 		return err;
714 
715 	for (i = 0; i < BPF_REG_SIZE; i++) {
716 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
717 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
718 	}
719 
720 	type = arg_to_dynptr_type(arg_type);
721 	if (type == BPF_DYNPTR_TYPE_INVALID)
722 		return -EINVAL;
723 
724 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
725 			       &state->stack[spi - 1].spilled_ptr, type);
726 
727 	if (dynptr_type_refcounted(type)) {
728 		/* The id is used to track proper releasing */
729 		int id;
730 
731 		if (clone_ref_obj_id)
732 			id = clone_ref_obj_id;
733 		else
734 			id = acquire_reference_state(env, insn_idx);
735 
736 		if (id < 0)
737 			return id;
738 
739 		state->stack[spi].spilled_ptr.ref_obj_id = id;
740 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
741 	}
742 
743 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
744 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
745 
746 	return 0;
747 }
748 
749 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
750 {
751 	int i;
752 
753 	for (i = 0; i < BPF_REG_SIZE; i++) {
754 		state->stack[spi].slot_type[i] = STACK_INVALID;
755 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
756 	}
757 
758 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
759 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
760 
761 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
762 	 *
763 	 * While we don't allow reading STACK_INVALID, it is still possible to
764 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
765 	 * helpers or insns can do partial read of that part without failing,
766 	 * but check_stack_range_initialized, check_stack_read_var_off, and
767 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
768 	 * the slot conservatively. Hence we need to prevent those liveness
769 	 * marking walks.
770 	 *
771 	 * This was not a problem before because STACK_INVALID is only set by
772 	 * default (where the default reg state has its reg->parent as NULL), or
773 	 * in clean_live_states after REG_LIVE_DONE (at which point
774 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
775 	 * verifier state exploration (like we did above). Hence, for our case
776 	 * parentage chain will still be live (i.e. reg->parent may be
777 	 * non-NULL), while earlier reg->parent was NULL, so we need
778 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
779 	 * done later on reads or by mark_dynptr_read as well to unnecessary
780 	 * mark registers in verifier state.
781 	 */
782 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
783 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
784 }
785 
786 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
787 {
788 	struct bpf_func_state *state = func(env, reg);
789 	int spi, ref_obj_id, i;
790 
791 	spi = dynptr_get_spi(env, reg);
792 	if (spi < 0)
793 		return spi;
794 
795 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
796 		invalidate_dynptr(env, state, spi);
797 		return 0;
798 	}
799 
800 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
801 
802 	/* If the dynptr has a ref_obj_id, then we need to invalidate
803 	 * two things:
804 	 *
805 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
806 	 * 2) Any slices derived from this dynptr.
807 	 */
808 
809 	/* Invalidate any slices associated with this dynptr */
810 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
811 
812 	/* Invalidate any dynptr clones */
813 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
814 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
815 			continue;
816 
817 		/* it should always be the case that if the ref obj id
818 		 * matches then the stack slot also belongs to a
819 		 * dynptr
820 		 */
821 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
822 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
823 			return -EFAULT;
824 		}
825 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
826 			invalidate_dynptr(env, state, i);
827 	}
828 
829 	return 0;
830 }
831 
832 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
833 			       struct bpf_reg_state *reg);
834 
835 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
836 {
837 	if (!env->allow_ptr_leaks)
838 		__mark_reg_not_init(env, reg);
839 	else
840 		__mark_reg_unknown(env, reg);
841 }
842 
843 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
844 				        struct bpf_func_state *state, int spi)
845 {
846 	struct bpf_func_state *fstate;
847 	struct bpf_reg_state *dreg;
848 	int i, dynptr_id;
849 
850 	/* We always ensure that STACK_DYNPTR is never set partially,
851 	 * hence just checking for slot_type[0] is enough. This is
852 	 * different for STACK_SPILL, where it may be only set for
853 	 * 1 byte, so code has to use is_spilled_reg.
854 	 */
855 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
856 		return 0;
857 
858 	/* Reposition spi to first slot */
859 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
860 		spi = spi + 1;
861 
862 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
863 		verbose(env, "cannot overwrite referenced dynptr\n");
864 		return -EINVAL;
865 	}
866 
867 	mark_stack_slot_scratched(env, spi);
868 	mark_stack_slot_scratched(env, spi - 1);
869 
870 	/* Writing partially to one dynptr stack slot destroys both. */
871 	for (i = 0; i < BPF_REG_SIZE; i++) {
872 		state->stack[spi].slot_type[i] = STACK_INVALID;
873 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
874 	}
875 
876 	dynptr_id = state->stack[spi].spilled_ptr.id;
877 	/* Invalidate any slices associated with this dynptr */
878 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
879 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
880 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
881 			continue;
882 		if (dreg->dynptr_id == dynptr_id)
883 			mark_reg_invalid(env, dreg);
884 	}));
885 
886 	/* Do not release reference state, we are destroying dynptr on stack,
887 	 * not using some helper to release it. Just reset register.
888 	 */
889 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
890 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
891 
892 	/* Same reason as unmark_stack_slots_dynptr above */
893 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
894 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
895 
896 	return 0;
897 }
898 
899 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
900 {
901 	int spi;
902 
903 	if (reg->type == CONST_PTR_TO_DYNPTR)
904 		return false;
905 
906 	spi = dynptr_get_spi(env, reg);
907 
908 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
909 	 * error because this just means the stack state hasn't been updated yet.
910 	 * We will do check_mem_access to check and update stack bounds later.
911 	 */
912 	if (spi < 0 && spi != -ERANGE)
913 		return false;
914 
915 	/* We don't need to check if the stack slots are marked by previous
916 	 * dynptr initializations because we allow overwriting existing unreferenced
917 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
918 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
919 	 * touching are completely destructed before we reinitialize them for a new
920 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
921 	 * instead of delaying it until the end where the user will get "Unreleased
922 	 * reference" error.
923 	 */
924 	return true;
925 }
926 
927 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
928 {
929 	struct bpf_func_state *state = func(env, reg);
930 	int i, spi;
931 
932 	/* This already represents first slot of initialized bpf_dynptr.
933 	 *
934 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
935 	 * check_func_arg_reg_off's logic, so we don't need to check its
936 	 * offset and alignment.
937 	 */
938 	if (reg->type == CONST_PTR_TO_DYNPTR)
939 		return true;
940 
941 	spi = dynptr_get_spi(env, reg);
942 	if (spi < 0)
943 		return false;
944 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
945 		return false;
946 
947 	for (i = 0; i < BPF_REG_SIZE; i++) {
948 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
949 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
950 			return false;
951 	}
952 
953 	return true;
954 }
955 
956 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
957 				    enum bpf_arg_type arg_type)
958 {
959 	struct bpf_func_state *state = func(env, reg);
960 	enum bpf_dynptr_type dynptr_type;
961 	int spi;
962 
963 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
964 	if (arg_type == ARG_PTR_TO_DYNPTR)
965 		return true;
966 
967 	dynptr_type = arg_to_dynptr_type(arg_type);
968 	if (reg->type == CONST_PTR_TO_DYNPTR) {
969 		return reg->dynptr.type == dynptr_type;
970 	} else {
971 		spi = dynptr_get_spi(env, reg);
972 		if (spi < 0)
973 			return false;
974 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
975 	}
976 }
977 
978 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
979 
980 static bool in_rcu_cs(struct bpf_verifier_env *env);
981 
982 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
983 
984 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
985 				 struct bpf_kfunc_call_arg_meta *meta,
986 				 struct bpf_reg_state *reg, int insn_idx,
987 				 struct btf *btf, u32 btf_id, int nr_slots)
988 {
989 	struct bpf_func_state *state = func(env, reg);
990 	int spi, i, j, id;
991 
992 	spi = iter_get_spi(env, reg, nr_slots);
993 	if (spi < 0)
994 		return spi;
995 
996 	id = acquire_reference_state(env, insn_idx);
997 	if (id < 0)
998 		return id;
999 
1000 	for (i = 0; i < nr_slots; i++) {
1001 		struct bpf_stack_state *slot = &state->stack[spi - i];
1002 		struct bpf_reg_state *st = &slot->spilled_ptr;
1003 
1004 		__mark_reg_known_zero(st);
1005 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1006 		if (is_kfunc_rcu_protected(meta)) {
1007 			if (in_rcu_cs(env))
1008 				st->type |= MEM_RCU;
1009 			else
1010 				st->type |= PTR_UNTRUSTED;
1011 		}
1012 		st->live |= REG_LIVE_WRITTEN;
1013 		st->ref_obj_id = i == 0 ? id : 0;
1014 		st->iter.btf = btf;
1015 		st->iter.btf_id = btf_id;
1016 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1017 		st->iter.depth = 0;
1018 
1019 		for (j = 0; j < BPF_REG_SIZE; j++)
1020 			slot->slot_type[j] = STACK_ITER;
1021 
1022 		mark_stack_slot_scratched(env, spi - i);
1023 	}
1024 
1025 	return 0;
1026 }
1027 
1028 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1029 				   struct bpf_reg_state *reg, int nr_slots)
1030 {
1031 	struct bpf_func_state *state = func(env, reg);
1032 	int spi, i, j;
1033 
1034 	spi = iter_get_spi(env, reg, nr_slots);
1035 	if (spi < 0)
1036 		return spi;
1037 
1038 	for (i = 0; i < nr_slots; i++) {
1039 		struct bpf_stack_state *slot = &state->stack[spi - i];
1040 		struct bpf_reg_state *st = &slot->spilled_ptr;
1041 
1042 		if (i == 0)
1043 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1044 
1045 		__mark_reg_not_init(env, st);
1046 
1047 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1048 		st->live |= REG_LIVE_WRITTEN;
1049 
1050 		for (j = 0; j < BPF_REG_SIZE; j++)
1051 			slot->slot_type[j] = STACK_INVALID;
1052 
1053 		mark_stack_slot_scratched(env, spi - i);
1054 	}
1055 
1056 	return 0;
1057 }
1058 
1059 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1060 				     struct bpf_reg_state *reg, int nr_slots)
1061 {
1062 	struct bpf_func_state *state = func(env, reg);
1063 	int spi, i, j;
1064 
1065 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1066 	 * will do check_mem_access to check and update stack bounds later, so
1067 	 * return true for that case.
1068 	 */
1069 	spi = iter_get_spi(env, reg, nr_slots);
1070 	if (spi == -ERANGE)
1071 		return true;
1072 	if (spi < 0)
1073 		return false;
1074 
1075 	for (i = 0; i < nr_slots; i++) {
1076 		struct bpf_stack_state *slot = &state->stack[spi - i];
1077 
1078 		for (j = 0; j < BPF_REG_SIZE; j++)
1079 			if (slot->slot_type[j] == STACK_ITER)
1080 				return false;
1081 	}
1082 
1083 	return true;
1084 }
1085 
1086 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1087 				   struct btf *btf, u32 btf_id, int nr_slots)
1088 {
1089 	struct bpf_func_state *state = func(env, reg);
1090 	int spi, i, j;
1091 
1092 	spi = iter_get_spi(env, reg, nr_slots);
1093 	if (spi < 0)
1094 		return -EINVAL;
1095 
1096 	for (i = 0; i < nr_slots; i++) {
1097 		struct bpf_stack_state *slot = &state->stack[spi - i];
1098 		struct bpf_reg_state *st = &slot->spilled_ptr;
1099 
1100 		if (st->type & PTR_UNTRUSTED)
1101 			return -EPROTO;
1102 		/* only main (first) slot has ref_obj_id set */
1103 		if (i == 0 && !st->ref_obj_id)
1104 			return -EINVAL;
1105 		if (i != 0 && st->ref_obj_id)
1106 			return -EINVAL;
1107 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1108 			return -EINVAL;
1109 
1110 		for (j = 0; j < BPF_REG_SIZE; j++)
1111 			if (slot->slot_type[j] != STACK_ITER)
1112 				return -EINVAL;
1113 	}
1114 
1115 	return 0;
1116 }
1117 
1118 /* Check if given stack slot is "special":
1119  *   - spilled register state (STACK_SPILL);
1120  *   - dynptr state (STACK_DYNPTR);
1121  *   - iter state (STACK_ITER).
1122  */
1123 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1124 {
1125 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1126 
1127 	switch (type) {
1128 	case STACK_SPILL:
1129 	case STACK_DYNPTR:
1130 	case STACK_ITER:
1131 		return true;
1132 	case STACK_INVALID:
1133 	case STACK_MISC:
1134 	case STACK_ZERO:
1135 		return false;
1136 	default:
1137 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1138 		return true;
1139 	}
1140 }
1141 
1142 /* The reg state of a pointer or a bounded scalar was saved when
1143  * it was spilled to the stack.
1144  */
1145 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1146 {
1147 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1148 }
1149 
1150 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1151 {
1152 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1153 	       stack->spilled_ptr.type == SCALAR_VALUE;
1154 }
1155 
1156 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1157  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1158  * more precise STACK_ZERO.
1159  * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take
1160  * env->allow_ptr_leaks into account and force STACK_MISC, if necessary.
1161  */
1162 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1163 {
1164 	if (*stype == STACK_ZERO)
1165 		return;
1166 	if (env->allow_ptr_leaks && *stype == STACK_INVALID)
1167 		return;
1168 	*stype = STACK_MISC;
1169 }
1170 
1171 static void scrub_spilled_slot(u8 *stype)
1172 {
1173 	if (*stype != STACK_INVALID)
1174 		*stype = STACK_MISC;
1175 }
1176 
1177 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1178  * small to hold src. This is different from krealloc since we don't want to preserve
1179  * the contents of dst.
1180  *
1181  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1182  * not be allocated.
1183  */
1184 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1185 {
1186 	size_t alloc_bytes;
1187 	void *orig = dst;
1188 	size_t bytes;
1189 
1190 	if (ZERO_OR_NULL_PTR(src))
1191 		goto out;
1192 
1193 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1194 		return NULL;
1195 
1196 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1197 	dst = krealloc(orig, alloc_bytes, flags);
1198 	if (!dst) {
1199 		kfree(orig);
1200 		return NULL;
1201 	}
1202 
1203 	memcpy(dst, src, bytes);
1204 out:
1205 	return dst ? dst : ZERO_SIZE_PTR;
1206 }
1207 
1208 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1209  * small to hold new_n items. new items are zeroed out if the array grows.
1210  *
1211  * Contrary to krealloc_array, does not free arr if new_n is zero.
1212  */
1213 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1214 {
1215 	size_t alloc_size;
1216 	void *new_arr;
1217 
1218 	if (!new_n || old_n == new_n)
1219 		goto out;
1220 
1221 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1222 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1223 	if (!new_arr) {
1224 		kfree(arr);
1225 		return NULL;
1226 	}
1227 	arr = new_arr;
1228 
1229 	if (new_n > old_n)
1230 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1231 
1232 out:
1233 	return arr ? arr : ZERO_SIZE_PTR;
1234 }
1235 
1236 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1237 {
1238 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1239 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1240 	if (!dst->refs)
1241 		return -ENOMEM;
1242 
1243 	dst->acquired_refs = src->acquired_refs;
1244 	return 0;
1245 }
1246 
1247 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1248 {
1249 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1250 
1251 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1252 				GFP_KERNEL);
1253 	if (!dst->stack)
1254 		return -ENOMEM;
1255 
1256 	dst->allocated_stack = src->allocated_stack;
1257 	return 0;
1258 }
1259 
1260 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1261 {
1262 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1263 				    sizeof(struct bpf_reference_state));
1264 	if (!state->refs)
1265 		return -ENOMEM;
1266 
1267 	state->acquired_refs = n;
1268 	return 0;
1269 }
1270 
1271 /* Possibly update state->allocated_stack to be at least size bytes. Also
1272  * possibly update the function's high-water mark in its bpf_subprog_info.
1273  */
1274 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1275 {
1276 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1277 
1278 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1279 	size = round_up(size, BPF_REG_SIZE);
1280 	n = size / BPF_REG_SIZE;
1281 
1282 	if (old_n >= n)
1283 		return 0;
1284 
1285 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1286 	if (!state->stack)
1287 		return -ENOMEM;
1288 
1289 	state->allocated_stack = size;
1290 
1291 	/* update known max for given subprogram */
1292 	if (env->subprog_info[state->subprogno].stack_depth < size)
1293 		env->subprog_info[state->subprogno].stack_depth = size;
1294 
1295 	return 0;
1296 }
1297 
1298 /* Acquire a pointer id from the env and update the state->refs to include
1299  * this new pointer reference.
1300  * On success, returns a valid pointer id to associate with the register
1301  * On failure, returns a negative errno.
1302  */
1303 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1304 {
1305 	struct bpf_func_state *state = cur_func(env);
1306 	int new_ofs = state->acquired_refs;
1307 	int id, err;
1308 
1309 	err = resize_reference_state(state, state->acquired_refs + 1);
1310 	if (err)
1311 		return err;
1312 	id = ++env->id_gen;
1313 	state->refs[new_ofs].id = id;
1314 	state->refs[new_ofs].insn_idx = insn_idx;
1315 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1316 
1317 	return id;
1318 }
1319 
1320 /* release function corresponding to acquire_reference_state(). Idempotent. */
1321 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1322 {
1323 	int i, last_idx;
1324 
1325 	last_idx = state->acquired_refs - 1;
1326 	for (i = 0; i < state->acquired_refs; i++) {
1327 		if (state->refs[i].id == ptr_id) {
1328 			/* Cannot release caller references in callbacks */
1329 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1330 				return -EINVAL;
1331 			if (last_idx && i != last_idx)
1332 				memcpy(&state->refs[i], &state->refs[last_idx],
1333 				       sizeof(*state->refs));
1334 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1335 			state->acquired_refs--;
1336 			return 0;
1337 		}
1338 	}
1339 	return -EINVAL;
1340 }
1341 
1342 static void free_func_state(struct bpf_func_state *state)
1343 {
1344 	if (!state)
1345 		return;
1346 	kfree(state->refs);
1347 	kfree(state->stack);
1348 	kfree(state);
1349 }
1350 
1351 static void clear_jmp_history(struct bpf_verifier_state *state)
1352 {
1353 	kfree(state->jmp_history);
1354 	state->jmp_history = NULL;
1355 	state->jmp_history_cnt = 0;
1356 }
1357 
1358 static void free_verifier_state(struct bpf_verifier_state *state,
1359 				bool free_self)
1360 {
1361 	int i;
1362 
1363 	for (i = 0; i <= state->curframe; i++) {
1364 		free_func_state(state->frame[i]);
1365 		state->frame[i] = NULL;
1366 	}
1367 	clear_jmp_history(state);
1368 	if (free_self)
1369 		kfree(state);
1370 }
1371 
1372 /* copy verifier state from src to dst growing dst stack space
1373  * when necessary to accommodate larger src stack
1374  */
1375 static int copy_func_state(struct bpf_func_state *dst,
1376 			   const struct bpf_func_state *src)
1377 {
1378 	int err;
1379 
1380 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1381 	err = copy_reference_state(dst, src);
1382 	if (err)
1383 		return err;
1384 	return copy_stack_state(dst, src);
1385 }
1386 
1387 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1388 			       const struct bpf_verifier_state *src)
1389 {
1390 	struct bpf_func_state *dst;
1391 	int i, err;
1392 
1393 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1394 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1395 					  GFP_USER);
1396 	if (!dst_state->jmp_history)
1397 		return -ENOMEM;
1398 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1399 
1400 	/* if dst has more stack frames then src frame, free them, this is also
1401 	 * necessary in case of exceptional exits using bpf_throw.
1402 	 */
1403 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1404 		free_func_state(dst_state->frame[i]);
1405 		dst_state->frame[i] = NULL;
1406 	}
1407 	dst_state->speculative = src->speculative;
1408 	dst_state->active_rcu_lock = src->active_rcu_lock;
1409 	dst_state->curframe = src->curframe;
1410 	dst_state->active_lock.ptr = src->active_lock.ptr;
1411 	dst_state->active_lock.id = src->active_lock.id;
1412 	dst_state->branches = src->branches;
1413 	dst_state->parent = src->parent;
1414 	dst_state->first_insn_idx = src->first_insn_idx;
1415 	dst_state->last_insn_idx = src->last_insn_idx;
1416 	dst_state->dfs_depth = src->dfs_depth;
1417 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1418 	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1419 	for (i = 0; i <= src->curframe; i++) {
1420 		dst = dst_state->frame[i];
1421 		if (!dst) {
1422 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1423 			if (!dst)
1424 				return -ENOMEM;
1425 			dst_state->frame[i] = dst;
1426 		}
1427 		err = copy_func_state(dst, src->frame[i]);
1428 		if (err)
1429 			return err;
1430 	}
1431 	return 0;
1432 }
1433 
1434 static u32 state_htab_size(struct bpf_verifier_env *env)
1435 {
1436 	return env->prog->len;
1437 }
1438 
1439 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1440 {
1441 	struct bpf_verifier_state *cur = env->cur_state;
1442 	struct bpf_func_state *state = cur->frame[cur->curframe];
1443 
1444 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1445 }
1446 
1447 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1448 {
1449 	int fr;
1450 
1451 	if (a->curframe != b->curframe)
1452 		return false;
1453 
1454 	for (fr = a->curframe; fr >= 0; fr--)
1455 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1456 			return false;
1457 
1458 	return true;
1459 }
1460 
1461 /* Open coded iterators allow back-edges in the state graph in order to
1462  * check unbounded loops that iterators.
1463  *
1464  * In is_state_visited() it is necessary to know if explored states are
1465  * part of some loops in order to decide whether non-exact states
1466  * comparison could be used:
1467  * - non-exact states comparison establishes sub-state relation and uses
1468  *   read and precision marks to do so, these marks are propagated from
1469  *   children states and thus are not guaranteed to be final in a loop;
1470  * - exact states comparison just checks if current and explored states
1471  *   are identical (and thus form a back-edge).
1472  *
1473  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1474  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1475  * algorithm for loop structure detection and gives an overview of
1476  * relevant terminology. It also has helpful illustrations.
1477  *
1478  * [1] https://api.semanticscholar.org/CorpusID:15784067
1479  *
1480  * We use a similar algorithm but because loop nested structure is
1481  * irrelevant for verifier ours is significantly simpler and resembles
1482  * strongly connected components algorithm from Sedgewick's textbook.
1483  *
1484  * Define topmost loop entry as a first node of the loop traversed in a
1485  * depth first search starting from initial state. The goal of the loop
1486  * tracking algorithm is to associate topmost loop entries with states
1487  * derived from these entries.
1488  *
1489  * For each step in the DFS states traversal algorithm needs to identify
1490  * the following situations:
1491  *
1492  *          initial                     initial                   initial
1493  *            |                           |                         |
1494  *            V                           V                         V
1495  *           ...                         ...           .---------> hdr
1496  *            |                           |            |            |
1497  *            V                           V            |            V
1498  *           cur                     .-> succ          |    .------...
1499  *            |                      |    |            |    |       |
1500  *            V                      |    V            |    V       V
1501  *           succ                    '-- cur           |   ...     ...
1502  *                                                     |    |       |
1503  *                                                     |    V       V
1504  *                                                     |   succ <- cur
1505  *                                                     |    |
1506  *                                                     |    V
1507  *                                                     |   ...
1508  *                                                     |    |
1509  *                                                     '----'
1510  *
1511  *  (A) successor state of cur   (B) successor state of cur or it's entry
1512  *      not yet traversed            are in current DFS path, thus cur and succ
1513  *                                   are members of the same outermost loop
1514  *
1515  *                      initial                  initial
1516  *                        |                        |
1517  *                        V                        V
1518  *                       ...                      ...
1519  *                        |                        |
1520  *                        V                        V
1521  *                .------...               .------...
1522  *                |       |                |       |
1523  *                V       V                V       V
1524  *           .-> hdr     ...              ...     ...
1525  *           |    |       |                |       |
1526  *           |    V       V                V       V
1527  *           |   succ <- cur              succ <- cur
1528  *           |    |                        |
1529  *           |    V                        V
1530  *           |   ...                      ...
1531  *           |    |                        |
1532  *           '----'                       exit
1533  *
1534  * (C) successor state of cur is a part of some loop but this loop
1535  *     does not include cur or successor state is not in a loop at all.
1536  *
1537  * Algorithm could be described as the following python code:
1538  *
1539  *     traversed = set()   # Set of traversed nodes
1540  *     entries = {}        # Mapping from node to loop entry
1541  *     depths = {}         # Depth level assigned to graph node
1542  *     path = set()        # Current DFS path
1543  *
1544  *     # Find outermost loop entry known for n
1545  *     def get_loop_entry(n):
1546  *         h = entries.get(n, None)
1547  *         while h in entries and entries[h] != h:
1548  *             h = entries[h]
1549  *         return h
1550  *
1551  *     # Update n's loop entry if h's outermost entry comes
1552  *     # before n's outermost entry in current DFS path.
1553  *     def update_loop_entry(n, h):
1554  *         n1 = get_loop_entry(n) or n
1555  *         h1 = get_loop_entry(h) or h
1556  *         if h1 in path and depths[h1] <= depths[n1]:
1557  *             entries[n] = h1
1558  *
1559  *     def dfs(n, depth):
1560  *         traversed.add(n)
1561  *         path.add(n)
1562  *         depths[n] = depth
1563  *         for succ in G.successors(n):
1564  *             if succ not in traversed:
1565  *                 # Case A: explore succ and update cur's loop entry
1566  *                 #         only if succ's entry is in current DFS path.
1567  *                 dfs(succ, depth + 1)
1568  *                 h = get_loop_entry(succ)
1569  *                 update_loop_entry(n, h)
1570  *             else:
1571  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1572  *                 update_loop_entry(n, succ)
1573  *         path.remove(n)
1574  *
1575  * To adapt this algorithm for use with verifier:
1576  * - use st->branch == 0 as a signal that DFS of succ had been finished
1577  *   and cur's loop entry has to be updated (case A), handle this in
1578  *   update_branch_counts();
1579  * - use st->branch > 0 as a signal that st is in the current DFS path;
1580  * - handle cases B and C in is_state_visited();
1581  * - update topmost loop entry for intermediate states in get_loop_entry().
1582  */
1583 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1584 {
1585 	struct bpf_verifier_state *topmost = st->loop_entry, *old;
1586 
1587 	while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1588 		topmost = topmost->loop_entry;
1589 	/* Update loop entries for intermediate states to avoid this
1590 	 * traversal in future get_loop_entry() calls.
1591 	 */
1592 	while (st && st->loop_entry != topmost) {
1593 		old = st->loop_entry;
1594 		st->loop_entry = topmost;
1595 		st = old;
1596 	}
1597 	return topmost;
1598 }
1599 
1600 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1601 {
1602 	struct bpf_verifier_state *cur1, *hdr1;
1603 
1604 	cur1 = get_loop_entry(cur) ?: cur;
1605 	hdr1 = get_loop_entry(hdr) ?: hdr;
1606 	/* The head1->branches check decides between cases B and C in
1607 	 * comment for get_loop_entry(). If hdr1->branches == 0 then
1608 	 * head's topmost loop entry is not in current DFS path,
1609 	 * hence 'cur' and 'hdr' are not in the same loop and there is
1610 	 * no need to update cur->loop_entry.
1611 	 */
1612 	if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1613 		cur->loop_entry = hdr;
1614 		hdr->used_as_loop_entry = true;
1615 	}
1616 }
1617 
1618 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1619 {
1620 	while (st) {
1621 		u32 br = --st->branches;
1622 
1623 		/* br == 0 signals that DFS exploration for 'st' is finished,
1624 		 * thus it is necessary to update parent's loop entry if it
1625 		 * turned out that st is a part of some loop.
1626 		 * This is a part of 'case A' in get_loop_entry() comment.
1627 		 */
1628 		if (br == 0 && st->parent && st->loop_entry)
1629 			update_loop_entry(st->parent, st->loop_entry);
1630 
1631 		/* WARN_ON(br > 1) technically makes sense here,
1632 		 * but see comment in push_stack(), hence:
1633 		 */
1634 		WARN_ONCE((int)br < 0,
1635 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1636 			  br);
1637 		if (br)
1638 			break;
1639 		st = st->parent;
1640 	}
1641 }
1642 
1643 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1644 		     int *insn_idx, bool pop_log)
1645 {
1646 	struct bpf_verifier_state *cur = env->cur_state;
1647 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1648 	int err;
1649 
1650 	if (env->head == NULL)
1651 		return -ENOENT;
1652 
1653 	if (cur) {
1654 		err = copy_verifier_state(cur, &head->st);
1655 		if (err)
1656 			return err;
1657 	}
1658 	if (pop_log)
1659 		bpf_vlog_reset(&env->log, head->log_pos);
1660 	if (insn_idx)
1661 		*insn_idx = head->insn_idx;
1662 	if (prev_insn_idx)
1663 		*prev_insn_idx = head->prev_insn_idx;
1664 	elem = head->next;
1665 	free_verifier_state(&head->st, false);
1666 	kfree(head);
1667 	env->head = elem;
1668 	env->stack_size--;
1669 	return 0;
1670 }
1671 
1672 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1673 					     int insn_idx, int prev_insn_idx,
1674 					     bool speculative)
1675 {
1676 	struct bpf_verifier_state *cur = env->cur_state;
1677 	struct bpf_verifier_stack_elem *elem;
1678 	int err;
1679 
1680 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1681 	if (!elem)
1682 		goto err;
1683 
1684 	elem->insn_idx = insn_idx;
1685 	elem->prev_insn_idx = prev_insn_idx;
1686 	elem->next = env->head;
1687 	elem->log_pos = env->log.end_pos;
1688 	env->head = elem;
1689 	env->stack_size++;
1690 	err = copy_verifier_state(&elem->st, cur);
1691 	if (err)
1692 		goto err;
1693 	elem->st.speculative |= speculative;
1694 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1695 		verbose(env, "The sequence of %d jumps is too complex.\n",
1696 			env->stack_size);
1697 		goto err;
1698 	}
1699 	if (elem->st.parent) {
1700 		++elem->st.parent->branches;
1701 		/* WARN_ON(branches > 2) technically makes sense here,
1702 		 * but
1703 		 * 1. speculative states will bump 'branches' for non-branch
1704 		 * instructions
1705 		 * 2. is_state_visited() heuristics may decide not to create
1706 		 * a new state for a sequence of branches and all such current
1707 		 * and cloned states will be pointing to a single parent state
1708 		 * which might have large 'branches' count.
1709 		 */
1710 	}
1711 	return &elem->st;
1712 err:
1713 	free_verifier_state(env->cur_state, true);
1714 	env->cur_state = NULL;
1715 	/* pop all elements and return */
1716 	while (!pop_stack(env, NULL, NULL, false));
1717 	return NULL;
1718 }
1719 
1720 #define CALLER_SAVED_REGS 6
1721 static const int caller_saved[CALLER_SAVED_REGS] = {
1722 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1723 };
1724 
1725 /* This helper doesn't clear reg->id */
1726 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1727 {
1728 	reg->var_off = tnum_const(imm);
1729 	reg->smin_value = (s64)imm;
1730 	reg->smax_value = (s64)imm;
1731 	reg->umin_value = imm;
1732 	reg->umax_value = imm;
1733 
1734 	reg->s32_min_value = (s32)imm;
1735 	reg->s32_max_value = (s32)imm;
1736 	reg->u32_min_value = (u32)imm;
1737 	reg->u32_max_value = (u32)imm;
1738 }
1739 
1740 /* Mark the unknown part of a register (variable offset or scalar value) as
1741  * known to have the value @imm.
1742  */
1743 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1744 {
1745 	/* Clear off and union(map_ptr, range) */
1746 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1747 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1748 	reg->id = 0;
1749 	reg->ref_obj_id = 0;
1750 	___mark_reg_known(reg, imm);
1751 }
1752 
1753 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1754 {
1755 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1756 	reg->s32_min_value = (s32)imm;
1757 	reg->s32_max_value = (s32)imm;
1758 	reg->u32_min_value = (u32)imm;
1759 	reg->u32_max_value = (u32)imm;
1760 }
1761 
1762 /* Mark the 'variable offset' part of a register as zero.  This should be
1763  * used only on registers holding a pointer type.
1764  */
1765 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1766 {
1767 	__mark_reg_known(reg, 0);
1768 }
1769 
1770 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1771 {
1772 	__mark_reg_known(reg, 0);
1773 	reg->type = SCALAR_VALUE;
1774 	/* all scalars are assumed imprecise initially (unless unprivileged,
1775 	 * in which case everything is forced to be precise)
1776 	 */
1777 	reg->precise = !env->bpf_capable;
1778 }
1779 
1780 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1781 				struct bpf_reg_state *regs, u32 regno)
1782 {
1783 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1784 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1785 		/* Something bad happened, let's kill all regs */
1786 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1787 			__mark_reg_not_init(env, regs + regno);
1788 		return;
1789 	}
1790 	__mark_reg_known_zero(regs + regno);
1791 }
1792 
1793 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1794 			      bool first_slot, int dynptr_id)
1795 {
1796 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1797 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1798 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1799 	 */
1800 	__mark_reg_known_zero(reg);
1801 	reg->type = CONST_PTR_TO_DYNPTR;
1802 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1803 	reg->id = dynptr_id;
1804 	reg->dynptr.type = type;
1805 	reg->dynptr.first_slot = first_slot;
1806 }
1807 
1808 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1809 {
1810 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1811 		const struct bpf_map *map = reg->map_ptr;
1812 
1813 		if (map->inner_map_meta) {
1814 			reg->type = CONST_PTR_TO_MAP;
1815 			reg->map_ptr = map->inner_map_meta;
1816 			/* transfer reg's id which is unique for every map_lookup_elem
1817 			 * as UID of the inner map.
1818 			 */
1819 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1820 				reg->map_uid = reg->id;
1821 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1822 			reg->type = PTR_TO_XDP_SOCK;
1823 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1824 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1825 			reg->type = PTR_TO_SOCKET;
1826 		} else {
1827 			reg->type = PTR_TO_MAP_VALUE;
1828 		}
1829 		return;
1830 	}
1831 
1832 	reg->type &= ~PTR_MAYBE_NULL;
1833 }
1834 
1835 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1836 				struct btf_field_graph_root *ds_head)
1837 {
1838 	__mark_reg_known_zero(&regs[regno]);
1839 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1840 	regs[regno].btf = ds_head->btf;
1841 	regs[regno].btf_id = ds_head->value_btf_id;
1842 	regs[regno].off = ds_head->node_offset;
1843 }
1844 
1845 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1846 {
1847 	return type_is_pkt_pointer(reg->type);
1848 }
1849 
1850 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1851 {
1852 	return reg_is_pkt_pointer(reg) ||
1853 	       reg->type == PTR_TO_PACKET_END;
1854 }
1855 
1856 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1857 {
1858 	return base_type(reg->type) == PTR_TO_MEM &&
1859 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1860 }
1861 
1862 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1863 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1864 				    enum bpf_reg_type which)
1865 {
1866 	/* The register can already have a range from prior markings.
1867 	 * This is fine as long as it hasn't been advanced from its
1868 	 * origin.
1869 	 */
1870 	return reg->type == which &&
1871 	       reg->id == 0 &&
1872 	       reg->off == 0 &&
1873 	       tnum_equals_const(reg->var_off, 0);
1874 }
1875 
1876 /* Reset the min/max bounds of a register */
1877 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1878 {
1879 	reg->smin_value = S64_MIN;
1880 	reg->smax_value = S64_MAX;
1881 	reg->umin_value = 0;
1882 	reg->umax_value = U64_MAX;
1883 
1884 	reg->s32_min_value = S32_MIN;
1885 	reg->s32_max_value = S32_MAX;
1886 	reg->u32_min_value = 0;
1887 	reg->u32_max_value = U32_MAX;
1888 }
1889 
1890 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1891 {
1892 	reg->smin_value = S64_MIN;
1893 	reg->smax_value = S64_MAX;
1894 	reg->umin_value = 0;
1895 	reg->umax_value = U64_MAX;
1896 }
1897 
1898 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1899 {
1900 	reg->s32_min_value = S32_MIN;
1901 	reg->s32_max_value = S32_MAX;
1902 	reg->u32_min_value = 0;
1903 	reg->u32_max_value = U32_MAX;
1904 }
1905 
1906 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1907 {
1908 	struct tnum var32_off = tnum_subreg(reg->var_off);
1909 
1910 	/* min signed is max(sign bit) | min(other bits) */
1911 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1912 			var32_off.value | (var32_off.mask & S32_MIN));
1913 	/* max signed is min(sign bit) | max(other bits) */
1914 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1915 			var32_off.value | (var32_off.mask & S32_MAX));
1916 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1917 	reg->u32_max_value = min(reg->u32_max_value,
1918 				 (u32)(var32_off.value | var32_off.mask));
1919 }
1920 
1921 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1922 {
1923 	/* min signed is max(sign bit) | min(other bits) */
1924 	reg->smin_value = max_t(s64, reg->smin_value,
1925 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1926 	/* max signed is min(sign bit) | max(other bits) */
1927 	reg->smax_value = min_t(s64, reg->smax_value,
1928 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1929 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1930 	reg->umax_value = min(reg->umax_value,
1931 			      reg->var_off.value | reg->var_off.mask);
1932 }
1933 
1934 static void __update_reg_bounds(struct bpf_reg_state *reg)
1935 {
1936 	__update_reg32_bounds(reg);
1937 	__update_reg64_bounds(reg);
1938 }
1939 
1940 /* Uses signed min/max values to inform unsigned, and vice-versa */
1941 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1942 {
1943 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
1944 	 * bits to improve our u32/s32 boundaries.
1945 	 *
1946 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
1947 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
1948 	 * [10, 20] range. But this property holds for any 64-bit range as
1949 	 * long as upper 32 bits in that entire range of values stay the same.
1950 	 *
1951 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
1952 	 * in decimal) has the same upper 32 bits throughout all the values in
1953 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
1954 	 * range.
1955 	 *
1956 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
1957 	 * following the rules outlined below about u64/s64 correspondence
1958 	 * (which equally applies to u32 vs s32 correspondence). In general it
1959 	 * depends on actual hexadecimal values of 32-bit range. They can form
1960 	 * only valid u32, or only valid s32 ranges in some cases.
1961 	 *
1962 	 * So we use all these insights to derive bounds for subregisters here.
1963 	 */
1964 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
1965 		/* u64 to u32 casting preserves validity of low 32 bits as
1966 		 * a range, if upper 32 bits are the same
1967 		 */
1968 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
1969 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
1970 
1971 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
1972 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
1973 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
1974 		}
1975 	}
1976 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
1977 		/* low 32 bits should form a proper u32 range */
1978 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
1979 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
1980 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
1981 		}
1982 		/* low 32 bits should form a proper s32 range */
1983 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
1984 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
1985 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
1986 		}
1987 	}
1988 	/* Special case where upper bits form a small sequence of two
1989 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
1990 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
1991 	 * going from negative numbers to positive numbers. E.g., let's say we
1992 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
1993 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
1994 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
1995 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
1996 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
1997 	 * upper 32 bits. As a random example, s64 range
1998 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
1999 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2000 	 */
2001 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2002 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2003 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2004 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2005 	}
2006 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2007 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
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 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2012 	 * try to learn from that
2013 	 */
2014 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2015 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2016 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2017 	}
2018 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2019 	 * are the same, so combine.  This works even in the negative case, e.g.
2020 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2021 	 */
2022 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2023 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2024 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2025 	}
2026 }
2027 
2028 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2029 {
2030 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2031 	 * try to learn from that. Let's do a bit of ASCII art to see when
2032 	 * this is happening. Let's take u64 range first:
2033 	 *
2034 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2035 	 * |-------------------------------|--------------------------------|
2036 	 *
2037 	 * Valid u64 range is formed when umin and umax are anywhere in the
2038 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2039 	 * straightforward. Let's see how s64 range maps onto the same range
2040 	 * of values, annotated below the line for comparison:
2041 	 *
2042 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2043 	 * |-------------------------------|--------------------------------|
2044 	 * 0                        S64_MAX S64_MIN                        -1
2045 	 *
2046 	 * So s64 values basically start in the middle and they are logically
2047 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2048 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2049 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2050 	 * more visually as mapped to sign-agnostic range of hex values.
2051 	 *
2052 	 *  u64 start                                               u64 end
2053 	 *  _______________________________________________________________
2054 	 * /                                                               \
2055 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2056 	 * |-------------------------------|--------------------------------|
2057 	 * 0                        S64_MAX S64_MIN                        -1
2058 	 *                                / \
2059 	 * >------------------------------   ------------------------------->
2060 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2061 	 *
2062 	 * What this means is that, in general, we can't always derive
2063 	 * something new about u64 from any random s64 range, and vice versa.
2064 	 *
2065 	 * But we can do that in two particular cases. One is when entire
2066 	 * u64/s64 range is *entirely* contained within left half of the above
2067 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2068 	 *
2069 	 * |-------------------------------|--------------------------------|
2070 	 *     ^                   ^            ^                 ^
2071 	 *     A                   B            C                 D
2072 	 *
2073 	 * [A, B] and [C, D] are contained entirely in their respective halves
2074 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2075 	 * will be non-negative both as u64 and s64 (and in fact it will be
2076 	 * identical ranges no matter the signedness). [C, D] treated as s64
2077 	 * will be a range of negative values, while in u64 it will be
2078 	 * non-negative range of values larger than 0x8000000000000000.
2079 	 *
2080 	 * Now, any other range here can't be represented in both u64 and s64
2081 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2082 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2083 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2084 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2085 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2086 	 * ranges as u64. Currently reg_state can't represent two segments per
2087 	 * numeric domain, so in such situations we can only derive maximal
2088 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2089 	 *
2090 	 * So we use these facts to derive umin/umax from smin/smax and vice
2091 	 * versa only if they stay within the same "half". This is equivalent
2092 	 * to checking sign bit: lower half will have sign bit as zero, upper
2093 	 * half have sign bit 1. Below in code we simplify this by just
2094 	 * casting umin/umax as smin/smax and checking if they form valid
2095 	 * range, and vice versa. Those are equivalent checks.
2096 	 */
2097 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2098 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2099 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2100 	}
2101 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2102 	 * are the same, so combine.  This works even in the negative case, e.g.
2103 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2104 	 */
2105 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2106 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2107 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2108 	}
2109 }
2110 
2111 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2112 {
2113 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2114 	 * values on both sides of 64-bit range in hope to have tigher range.
2115 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2116 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2117 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2118 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2119 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2120 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2121 	 * We just need to make sure that derived bounds we are intersecting
2122 	 * with are well-formed ranges in respecitve s64 or u64 domain, just
2123 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2124 	 */
2125 	__u64 new_umin, new_umax;
2126 	__s64 new_smin, new_smax;
2127 
2128 	/* u32 -> u64 tightening, it's always well-formed */
2129 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2130 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2131 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2132 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2133 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2134 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2135 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2136 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2137 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2138 
2139 	/* if s32 can be treated as valid u32 range, we can use it as well */
2140 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2141 		/* s32 -> u64 tightening */
2142 		new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2143 		new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2144 		reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2145 		reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2146 		/* s32 -> s64 tightening */
2147 		new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2148 		new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2149 		reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2150 		reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2151 	}
2152 }
2153 
2154 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2155 {
2156 	__reg32_deduce_bounds(reg);
2157 	__reg64_deduce_bounds(reg);
2158 	__reg_deduce_mixed_bounds(reg);
2159 }
2160 
2161 /* Attempts to improve var_off based on unsigned min/max information */
2162 static void __reg_bound_offset(struct bpf_reg_state *reg)
2163 {
2164 	struct tnum var64_off = tnum_intersect(reg->var_off,
2165 					       tnum_range(reg->umin_value,
2166 							  reg->umax_value));
2167 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2168 					       tnum_range(reg->u32_min_value,
2169 							  reg->u32_max_value));
2170 
2171 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2172 }
2173 
2174 static void reg_bounds_sync(struct bpf_reg_state *reg)
2175 {
2176 	/* We might have learned new bounds from the var_off. */
2177 	__update_reg_bounds(reg);
2178 	/* We might have learned something about the sign bit. */
2179 	__reg_deduce_bounds(reg);
2180 	__reg_deduce_bounds(reg);
2181 	/* We might have learned some bits from the bounds. */
2182 	__reg_bound_offset(reg);
2183 	/* Intersecting with the old var_off might have improved our bounds
2184 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2185 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2186 	 */
2187 	__update_reg_bounds(reg);
2188 }
2189 
2190 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2191 				   struct bpf_reg_state *reg, const char *ctx)
2192 {
2193 	const char *msg;
2194 
2195 	if (reg->umin_value > reg->umax_value ||
2196 	    reg->smin_value > reg->smax_value ||
2197 	    reg->u32_min_value > reg->u32_max_value ||
2198 	    reg->s32_min_value > reg->s32_max_value) {
2199 		    msg = "range bounds violation";
2200 		    goto out;
2201 	}
2202 
2203 	if (tnum_is_const(reg->var_off)) {
2204 		u64 uval = reg->var_off.value;
2205 		s64 sval = (s64)uval;
2206 
2207 		if (reg->umin_value != uval || reg->umax_value != uval ||
2208 		    reg->smin_value != sval || reg->smax_value != sval) {
2209 			msg = "const tnum out of sync with range bounds";
2210 			goto out;
2211 		}
2212 	}
2213 
2214 	if (tnum_subreg_is_const(reg->var_off)) {
2215 		u32 uval32 = tnum_subreg(reg->var_off).value;
2216 		s32 sval32 = (s32)uval32;
2217 
2218 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2219 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2220 			msg = "const subreg tnum out of sync with range bounds";
2221 			goto out;
2222 		}
2223 	}
2224 
2225 	return 0;
2226 out:
2227 	verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2228 		"s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n",
2229 		ctx, msg, reg->umin_value, reg->umax_value,
2230 		reg->smin_value, reg->smax_value,
2231 		reg->u32_min_value, reg->u32_max_value,
2232 		reg->s32_min_value, reg->s32_max_value,
2233 		reg->var_off.value, reg->var_off.mask);
2234 	if (env->test_reg_invariants)
2235 		return -EFAULT;
2236 	__mark_reg_unbounded(reg);
2237 	return 0;
2238 }
2239 
2240 static bool __reg32_bound_s64(s32 a)
2241 {
2242 	return a >= 0 && a <= S32_MAX;
2243 }
2244 
2245 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2246 {
2247 	reg->umin_value = reg->u32_min_value;
2248 	reg->umax_value = reg->u32_max_value;
2249 
2250 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2251 	 * be positive otherwise set to worse case bounds and refine later
2252 	 * from tnum.
2253 	 */
2254 	if (__reg32_bound_s64(reg->s32_min_value) &&
2255 	    __reg32_bound_s64(reg->s32_max_value)) {
2256 		reg->smin_value = reg->s32_min_value;
2257 		reg->smax_value = reg->s32_max_value;
2258 	} else {
2259 		reg->smin_value = 0;
2260 		reg->smax_value = U32_MAX;
2261 	}
2262 }
2263 
2264 /* Mark a register as having a completely unknown (scalar) value. */
2265 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2266 			       struct bpf_reg_state *reg)
2267 {
2268 	/*
2269 	 * Clear type, off, and union(map_ptr, range) and
2270 	 * padding between 'type' and union
2271 	 */
2272 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2273 	reg->type = SCALAR_VALUE;
2274 	reg->id = 0;
2275 	reg->ref_obj_id = 0;
2276 	reg->var_off = tnum_unknown;
2277 	reg->frameno = 0;
2278 	reg->precise = !env->bpf_capable;
2279 	__mark_reg_unbounded(reg);
2280 }
2281 
2282 static void mark_reg_unknown(struct bpf_verifier_env *env,
2283 			     struct bpf_reg_state *regs, u32 regno)
2284 {
2285 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2286 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2287 		/* Something bad happened, let's kill all regs except FP */
2288 		for (regno = 0; regno < BPF_REG_FP; regno++)
2289 			__mark_reg_not_init(env, regs + regno);
2290 		return;
2291 	}
2292 	__mark_reg_unknown(env, regs + regno);
2293 }
2294 
2295 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2296 				struct bpf_reg_state *reg)
2297 {
2298 	__mark_reg_unknown(env, reg);
2299 	reg->type = NOT_INIT;
2300 }
2301 
2302 static void mark_reg_not_init(struct bpf_verifier_env *env,
2303 			      struct bpf_reg_state *regs, u32 regno)
2304 {
2305 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2306 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2307 		/* Something bad happened, let's kill all regs except FP */
2308 		for (regno = 0; regno < BPF_REG_FP; regno++)
2309 			__mark_reg_not_init(env, regs + regno);
2310 		return;
2311 	}
2312 	__mark_reg_not_init(env, regs + regno);
2313 }
2314 
2315 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2316 			    struct bpf_reg_state *regs, u32 regno,
2317 			    enum bpf_reg_type reg_type,
2318 			    struct btf *btf, u32 btf_id,
2319 			    enum bpf_type_flag flag)
2320 {
2321 	if (reg_type == SCALAR_VALUE) {
2322 		mark_reg_unknown(env, regs, regno);
2323 		return;
2324 	}
2325 	mark_reg_known_zero(env, regs, regno);
2326 	regs[regno].type = PTR_TO_BTF_ID | flag;
2327 	regs[regno].btf = btf;
2328 	regs[regno].btf_id = btf_id;
2329 }
2330 
2331 #define DEF_NOT_SUBREG	(0)
2332 static void init_reg_state(struct bpf_verifier_env *env,
2333 			   struct bpf_func_state *state)
2334 {
2335 	struct bpf_reg_state *regs = state->regs;
2336 	int i;
2337 
2338 	for (i = 0; i < MAX_BPF_REG; i++) {
2339 		mark_reg_not_init(env, regs, i);
2340 		regs[i].live = REG_LIVE_NONE;
2341 		regs[i].parent = NULL;
2342 		regs[i].subreg_def = DEF_NOT_SUBREG;
2343 	}
2344 
2345 	/* frame pointer */
2346 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2347 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2348 	regs[BPF_REG_FP].frameno = state->frameno;
2349 }
2350 
2351 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2352 {
2353 	return (struct bpf_retval_range){ minval, maxval };
2354 }
2355 
2356 #define BPF_MAIN_FUNC (-1)
2357 static void init_func_state(struct bpf_verifier_env *env,
2358 			    struct bpf_func_state *state,
2359 			    int callsite, int frameno, int subprogno)
2360 {
2361 	state->callsite = callsite;
2362 	state->frameno = frameno;
2363 	state->subprogno = subprogno;
2364 	state->callback_ret_range = retval_range(0, 0);
2365 	init_reg_state(env, state);
2366 	mark_verifier_state_scratched(env);
2367 }
2368 
2369 /* Similar to push_stack(), but for async callbacks */
2370 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2371 						int insn_idx, int prev_insn_idx,
2372 						int subprog)
2373 {
2374 	struct bpf_verifier_stack_elem *elem;
2375 	struct bpf_func_state *frame;
2376 
2377 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2378 	if (!elem)
2379 		goto err;
2380 
2381 	elem->insn_idx = insn_idx;
2382 	elem->prev_insn_idx = prev_insn_idx;
2383 	elem->next = env->head;
2384 	elem->log_pos = env->log.end_pos;
2385 	env->head = elem;
2386 	env->stack_size++;
2387 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2388 		verbose(env,
2389 			"The sequence of %d jumps is too complex for async cb.\n",
2390 			env->stack_size);
2391 		goto err;
2392 	}
2393 	/* Unlike push_stack() do not copy_verifier_state().
2394 	 * The caller state doesn't matter.
2395 	 * This is async callback. It starts in a fresh stack.
2396 	 * Initialize it similar to do_check_common().
2397 	 */
2398 	elem->st.branches = 1;
2399 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2400 	if (!frame)
2401 		goto err;
2402 	init_func_state(env, frame,
2403 			BPF_MAIN_FUNC /* callsite */,
2404 			0 /* frameno within this callchain */,
2405 			subprog /* subprog number within this prog */);
2406 	elem->st.frame[0] = frame;
2407 	return &elem->st;
2408 err:
2409 	free_verifier_state(env->cur_state, true);
2410 	env->cur_state = NULL;
2411 	/* pop all elements and return */
2412 	while (!pop_stack(env, NULL, NULL, false));
2413 	return NULL;
2414 }
2415 
2416 
2417 enum reg_arg_type {
2418 	SRC_OP,		/* register is used as source operand */
2419 	DST_OP,		/* register is used as destination operand */
2420 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2421 };
2422 
2423 static int cmp_subprogs(const void *a, const void *b)
2424 {
2425 	return ((struct bpf_subprog_info *)a)->start -
2426 	       ((struct bpf_subprog_info *)b)->start;
2427 }
2428 
2429 static int find_subprog(struct bpf_verifier_env *env, int off)
2430 {
2431 	struct bpf_subprog_info *p;
2432 
2433 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2434 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2435 	if (!p)
2436 		return -ENOENT;
2437 	return p - env->subprog_info;
2438 
2439 }
2440 
2441 static int add_subprog(struct bpf_verifier_env *env, int off)
2442 {
2443 	int insn_cnt = env->prog->len;
2444 	int ret;
2445 
2446 	if (off >= insn_cnt || off < 0) {
2447 		verbose(env, "call to invalid destination\n");
2448 		return -EINVAL;
2449 	}
2450 	ret = find_subprog(env, off);
2451 	if (ret >= 0)
2452 		return ret;
2453 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2454 		verbose(env, "too many subprograms\n");
2455 		return -E2BIG;
2456 	}
2457 	/* determine subprog starts. The end is one before the next starts */
2458 	env->subprog_info[env->subprog_cnt++].start = off;
2459 	sort(env->subprog_info, env->subprog_cnt,
2460 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2461 	return env->subprog_cnt - 1;
2462 }
2463 
2464 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2465 {
2466 	struct bpf_prog_aux *aux = env->prog->aux;
2467 	struct btf *btf = aux->btf;
2468 	const struct btf_type *t;
2469 	u32 main_btf_id, id;
2470 	const char *name;
2471 	int ret, i;
2472 
2473 	/* Non-zero func_info_cnt implies valid btf */
2474 	if (!aux->func_info_cnt)
2475 		return 0;
2476 	main_btf_id = aux->func_info[0].type_id;
2477 
2478 	t = btf_type_by_id(btf, main_btf_id);
2479 	if (!t) {
2480 		verbose(env, "invalid btf id for main subprog in func_info\n");
2481 		return -EINVAL;
2482 	}
2483 
2484 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2485 	if (IS_ERR(name)) {
2486 		ret = PTR_ERR(name);
2487 		/* If there is no tag present, there is no exception callback */
2488 		if (ret == -ENOENT)
2489 			ret = 0;
2490 		else if (ret == -EEXIST)
2491 			verbose(env, "multiple exception callback tags for main subprog\n");
2492 		return ret;
2493 	}
2494 
2495 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2496 	if (ret < 0) {
2497 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2498 		return ret;
2499 	}
2500 	id = ret;
2501 	t = btf_type_by_id(btf, id);
2502 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2503 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2504 		return -EINVAL;
2505 	}
2506 	ret = 0;
2507 	for (i = 0; i < aux->func_info_cnt; i++) {
2508 		if (aux->func_info[i].type_id != id)
2509 			continue;
2510 		ret = aux->func_info[i].insn_off;
2511 		/* Further func_info and subprog checks will also happen
2512 		 * later, so assume this is the right insn_off for now.
2513 		 */
2514 		if (!ret) {
2515 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2516 			ret = -EINVAL;
2517 		}
2518 	}
2519 	if (!ret) {
2520 		verbose(env, "exception callback type id not found in func_info\n");
2521 		ret = -EINVAL;
2522 	}
2523 	return ret;
2524 }
2525 
2526 #define MAX_KFUNC_DESCS 256
2527 #define MAX_KFUNC_BTFS	256
2528 
2529 struct bpf_kfunc_desc {
2530 	struct btf_func_model func_model;
2531 	u32 func_id;
2532 	s32 imm;
2533 	u16 offset;
2534 	unsigned long addr;
2535 };
2536 
2537 struct bpf_kfunc_btf {
2538 	struct btf *btf;
2539 	struct module *module;
2540 	u16 offset;
2541 };
2542 
2543 struct bpf_kfunc_desc_tab {
2544 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2545 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2546 	 * available, therefore at the end of verification do_misc_fixups()
2547 	 * sorts this by imm and offset.
2548 	 */
2549 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2550 	u32 nr_descs;
2551 };
2552 
2553 struct bpf_kfunc_btf_tab {
2554 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2555 	u32 nr_descs;
2556 };
2557 
2558 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2559 {
2560 	const struct bpf_kfunc_desc *d0 = a;
2561 	const struct bpf_kfunc_desc *d1 = b;
2562 
2563 	/* func_id is not greater than BTF_MAX_TYPE */
2564 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2565 }
2566 
2567 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2568 {
2569 	const struct bpf_kfunc_btf *d0 = a;
2570 	const struct bpf_kfunc_btf *d1 = b;
2571 
2572 	return d0->offset - d1->offset;
2573 }
2574 
2575 static const struct bpf_kfunc_desc *
2576 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2577 {
2578 	struct bpf_kfunc_desc desc = {
2579 		.func_id = func_id,
2580 		.offset = offset,
2581 	};
2582 	struct bpf_kfunc_desc_tab *tab;
2583 
2584 	tab = prog->aux->kfunc_tab;
2585 	return bsearch(&desc, tab->descs, tab->nr_descs,
2586 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2587 }
2588 
2589 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2590 		       u16 btf_fd_idx, u8 **func_addr)
2591 {
2592 	const struct bpf_kfunc_desc *desc;
2593 
2594 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2595 	if (!desc)
2596 		return -EFAULT;
2597 
2598 	*func_addr = (u8 *)desc->addr;
2599 	return 0;
2600 }
2601 
2602 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2603 					 s16 offset)
2604 {
2605 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2606 	struct bpf_kfunc_btf_tab *tab;
2607 	struct bpf_kfunc_btf *b;
2608 	struct module *mod;
2609 	struct btf *btf;
2610 	int btf_fd;
2611 
2612 	tab = env->prog->aux->kfunc_btf_tab;
2613 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2614 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2615 	if (!b) {
2616 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2617 			verbose(env, "too many different module BTFs\n");
2618 			return ERR_PTR(-E2BIG);
2619 		}
2620 
2621 		if (bpfptr_is_null(env->fd_array)) {
2622 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2623 			return ERR_PTR(-EPROTO);
2624 		}
2625 
2626 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2627 					    offset * sizeof(btf_fd),
2628 					    sizeof(btf_fd)))
2629 			return ERR_PTR(-EFAULT);
2630 
2631 		btf = btf_get_by_fd(btf_fd);
2632 		if (IS_ERR(btf)) {
2633 			verbose(env, "invalid module BTF fd specified\n");
2634 			return btf;
2635 		}
2636 
2637 		if (!btf_is_module(btf)) {
2638 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2639 			btf_put(btf);
2640 			return ERR_PTR(-EINVAL);
2641 		}
2642 
2643 		mod = btf_try_get_module(btf);
2644 		if (!mod) {
2645 			btf_put(btf);
2646 			return ERR_PTR(-ENXIO);
2647 		}
2648 
2649 		b = &tab->descs[tab->nr_descs++];
2650 		b->btf = btf;
2651 		b->module = mod;
2652 		b->offset = offset;
2653 
2654 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2655 		     kfunc_btf_cmp_by_off, NULL);
2656 	}
2657 	return b->btf;
2658 }
2659 
2660 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2661 {
2662 	if (!tab)
2663 		return;
2664 
2665 	while (tab->nr_descs--) {
2666 		module_put(tab->descs[tab->nr_descs].module);
2667 		btf_put(tab->descs[tab->nr_descs].btf);
2668 	}
2669 	kfree(tab);
2670 }
2671 
2672 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2673 {
2674 	if (offset) {
2675 		if (offset < 0) {
2676 			/* In the future, this can be allowed to increase limit
2677 			 * of fd index into fd_array, interpreted as u16.
2678 			 */
2679 			verbose(env, "negative offset disallowed for kernel module function call\n");
2680 			return ERR_PTR(-EINVAL);
2681 		}
2682 
2683 		return __find_kfunc_desc_btf(env, offset);
2684 	}
2685 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2686 }
2687 
2688 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2689 {
2690 	const struct btf_type *func, *func_proto;
2691 	struct bpf_kfunc_btf_tab *btf_tab;
2692 	struct bpf_kfunc_desc_tab *tab;
2693 	struct bpf_prog_aux *prog_aux;
2694 	struct bpf_kfunc_desc *desc;
2695 	const char *func_name;
2696 	struct btf *desc_btf;
2697 	unsigned long call_imm;
2698 	unsigned long addr;
2699 	int err;
2700 
2701 	prog_aux = env->prog->aux;
2702 	tab = prog_aux->kfunc_tab;
2703 	btf_tab = prog_aux->kfunc_btf_tab;
2704 	if (!tab) {
2705 		if (!btf_vmlinux) {
2706 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2707 			return -ENOTSUPP;
2708 		}
2709 
2710 		if (!env->prog->jit_requested) {
2711 			verbose(env, "JIT is required for calling kernel function\n");
2712 			return -ENOTSUPP;
2713 		}
2714 
2715 		if (!bpf_jit_supports_kfunc_call()) {
2716 			verbose(env, "JIT does not support calling kernel function\n");
2717 			return -ENOTSUPP;
2718 		}
2719 
2720 		if (!env->prog->gpl_compatible) {
2721 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2722 			return -EINVAL;
2723 		}
2724 
2725 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2726 		if (!tab)
2727 			return -ENOMEM;
2728 		prog_aux->kfunc_tab = tab;
2729 	}
2730 
2731 	/* func_id == 0 is always invalid, but instead of returning an error, be
2732 	 * conservative and wait until the code elimination pass before returning
2733 	 * error, so that invalid calls that get pruned out can be in BPF programs
2734 	 * loaded from userspace.  It is also required that offset be untouched
2735 	 * for such calls.
2736 	 */
2737 	if (!func_id && !offset)
2738 		return 0;
2739 
2740 	if (!btf_tab && offset) {
2741 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2742 		if (!btf_tab)
2743 			return -ENOMEM;
2744 		prog_aux->kfunc_btf_tab = btf_tab;
2745 	}
2746 
2747 	desc_btf = find_kfunc_desc_btf(env, offset);
2748 	if (IS_ERR(desc_btf)) {
2749 		verbose(env, "failed to find BTF for kernel function\n");
2750 		return PTR_ERR(desc_btf);
2751 	}
2752 
2753 	if (find_kfunc_desc(env->prog, func_id, offset))
2754 		return 0;
2755 
2756 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2757 		verbose(env, "too many different kernel function calls\n");
2758 		return -E2BIG;
2759 	}
2760 
2761 	func = btf_type_by_id(desc_btf, func_id);
2762 	if (!func || !btf_type_is_func(func)) {
2763 		verbose(env, "kernel btf_id %u is not a function\n",
2764 			func_id);
2765 		return -EINVAL;
2766 	}
2767 	func_proto = btf_type_by_id(desc_btf, func->type);
2768 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2769 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2770 			func_id);
2771 		return -EINVAL;
2772 	}
2773 
2774 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2775 	addr = kallsyms_lookup_name(func_name);
2776 	if (!addr) {
2777 		verbose(env, "cannot find address for kernel function %s\n",
2778 			func_name);
2779 		return -EINVAL;
2780 	}
2781 	specialize_kfunc(env, func_id, offset, &addr);
2782 
2783 	if (bpf_jit_supports_far_kfunc_call()) {
2784 		call_imm = func_id;
2785 	} else {
2786 		call_imm = BPF_CALL_IMM(addr);
2787 		/* Check whether the relative offset overflows desc->imm */
2788 		if ((unsigned long)(s32)call_imm != call_imm) {
2789 			verbose(env, "address of kernel function %s is out of range\n",
2790 				func_name);
2791 			return -EINVAL;
2792 		}
2793 	}
2794 
2795 	if (bpf_dev_bound_kfunc_id(func_id)) {
2796 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2797 		if (err)
2798 			return err;
2799 	}
2800 
2801 	desc = &tab->descs[tab->nr_descs++];
2802 	desc->func_id = func_id;
2803 	desc->imm = call_imm;
2804 	desc->offset = offset;
2805 	desc->addr = addr;
2806 	err = btf_distill_func_proto(&env->log, desc_btf,
2807 				     func_proto, func_name,
2808 				     &desc->func_model);
2809 	if (!err)
2810 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2811 		     kfunc_desc_cmp_by_id_off, NULL);
2812 	return err;
2813 }
2814 
2815 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2816 {
2817 	const struct bpf_kfunc_desc *d0 = a;
2818 	const struct bpf_kfunc_desc *d1 = b;
2819 
2820 	if (d0->imm != d1->imm)
2821 		return d0->imm < d1->imm ? -1 : 1;
2822 	if (d0->offset != d1->offset)
2823 		return d0->offset < d1->offset ? -1 : 1;
2824 	return 0;
2825 }
2826 
2827 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2828 {
2829 	struct bpf_kfunc_desc_tab *tab;
2830 
2831 	tab = prog->aux->kfunc_tab;
2832 	if (!tab)
2833 		return;
2834 
2835 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2836 	     kfunc_desc_cmp_by_imm_off, NULL);
2837 }
2838 
2839 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2840 {
2841 	return !!prog->aux->kfunc_tab;
2842 }
2843 
2844 const struct btf_func_model *
2845 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2846 			 const struct bpf_insn *insn)
2847 {
2848 	const struct bpf_kfunc_desc desc = {
2849 		.imm = insn->imm,
2850 		.offset = insn->off,
2851 	};
2852 	const struct bpf_kfunc_desc *res;
2853 	struct bpf_kfunc_desc_tab *tab;
2854 
2855 	tab = prog->aux->kfunc_tab;
2856 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2857 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2858 
2859 	return res ? &res->func_model : NULL;
2860 }
2861 
2862 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2863 {
2864 	struct bpf_subprog_info *subprog = env->subprog_info;
2865 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
2866 	struct bpf_insn *insn = env->prog->insnsi;
2867 
2868 	/* Add entry function. */
2869 	ret = add_subprog(env, 0);
2870 	if (ret)
2871 		return ret;
2872 
2873 	for (i = 0; i < insn_cnt; i++, insn++) {
2874 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2875 		    !bpf_pseudo_kfunc_call(insn))
2876 			continue;
2877 
2878 		if (!env->bpf_capable) {
2879 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2880 			return -EPERM;
2881 		}
2882 
2883 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2884 			ret = add_subprog(env, i + insn->imm + 1);
2885 		else
2886 			ret = add_kfunc_call(env, insn->imm, insn->off);
2887 
2888 		if (ret < 0)
2889 			return ret;
2890 	}
2891 
2892 	ret = bpf_find_exception_callback_insn_off(env);
2893 	if (ret < 0)
2894 		return ret;
2895 	ex_cb_insn = ret;
2896 
2897 	/* If ex_cb_insn > 0, this means that the main program has a subprog
2898 	 * marked using BTF decl tag to serve as the exception callback.
2899 	 */
2900 	if (ex_cb_insn) {
2901 		ret = add_subprog(env, ex_cb_insn);
2902 		if (ret < 0)
2903 			return ret;
2904 		for (i = 1; i < env->subprog_cnt; i++) {
2905 			if (env->subprog_info[i].start != ex_cb_insn)
2906 				continue;
2907 			env->exception_callback_subprog = i;
2908 			mark_subprog_exc_cb(env, i);
2909 			break;
2910 		}
2911 	}
2912 
2913 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2914 	 * logic. 'subprog_cnt' should not be increased.
2915 	 */
2916 	subprog[env->subprog_cnt].start = insn_cnt;
2917 
2918 	if (env->log.level & BPF_LOG_LEVEL2)
2919 		for (i = 0; i < env->subprog_cnt; i++)
2920 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2921 
2922 	return 0;
2923 }
2924 
2925 static int check_subprogs(struct bpf_verifier_env *env)
2926 {
2927 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2928 	struct bpf_subprog_info *subprog = env->subprog_info;
2929 	struct bpf_insn *insn = env->prog->insnsi;
2930 	int insn_cnt = env->prog->len;
2931 
2932 	/* now check that all jumps are within the same subprog */
2933 	subprog_start = subprog[cur_subprog].start;
2934 	subprog_end = subprog[cur_subprog + 1].start;
2935 	for (i = 0; i < insn_cnt; i++) {
2936 		u8 code = insn[i].code;
2937 
2938 		if (code == (BPF_JMP | BPF_CALL) &&
2939 		    insn[i].src_reg == 0 &&
2940 		    insn[i].imm == BPF_FUNC_tail_call)
2941 			subprog[cur_subprog].has_tail_call = true;
2942 		if (BPF_CLASS(code) == BPF_LD &&
2943 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2944 			subprog[cur_subprog].has_ld_abs = true;
2945 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2946 			goto next;
2947 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2948 			goto next;
2949 		if (code == (BPF_JMP32 | BPF_JA))
2950 			off = i + insn[i].imm + 1;
2951 		else
2952 			off = i + insn[i].off + 1;
2953 		if (off < subprog_start || off >= subprog_end) {
2954 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2955 			return -EINVAL;
2956 		}
2957 next:
2958 		if (i == subprog_end - 1) {
2959 			/* to avoid fall-through from one subprog into another
2960 			 * the last insn of the subprog should be either exit
2961 			 * or unconditional jump back or bpf_throw call
2962 			 */
2963 			if (code != (BPF_JMP | BPF_EXIT) &&
2964 			    code != (BPF_JMP32 | BPF_JA) &&
2965 			    code != (BPF_JMP | BPF_JA)) {
2966 				verbose(env, "last insn is not an exit or jmp\n");
2967 				return -EINVAL;
2968 			}
2969 			subprog_start = subprog_end;
2970 			cur_subprog++;
2971 			if (cur_subprog < env->subprog_cnt)
2972 				subprog_end = subprog[cur_subprog + 1].start;
2973 		}
2974 	}
2975 	return 0;
2976 }
2977 
2978 /* Parentage chain of this register (or stack slot) should take care of all
2979  * issues like callee-saved registers, stack slot allocation time, etc.
2980  */
2981 static int mark_reg_read(struct bpf_verifier_env *env,
2982 			 const struct bpf_reg_state *state,
2983 			 struct bpf_reg_state *parent, u8 flag)
2984 {
2985 	bool writes = parent == state->parent; /* Observe write marks */
2986 	int cnt = 0;
2987 
2988 	while (parent) {
2989 		/* if read wasn't screened by an earlier write ... */
2990 		if (writes && state->live & REG_LIVE_WRITTEN)
2991 			break;
2992 		if (parent->live & REG_LIVE_DONE) {
2993 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2994 				reg_type_str(env, parent->type),
2995 				parent->var_off.value, parent->off);
2996 			return -EFAULT;
2997 		}
2998 		/* The first condition is more likely to be true than the
2999 		 * second, checked it first.
3000 		 */
3001 		if ((parent->live & REG_LIVE_READ) == flag ||
3002 		    parent->live & REG_LIVE_READ64)
3003 			/* The parentage chain never changes and
3004 			 * this parent was already marked as LIVE_READ.
3005 			 * There is no need to keep walking the chain again and
3006 			 * keep re-marking all parents as LIVE_READ.
3007 			 * This case happens when the same register is read
3008 			 * multiple times without writes into it in-between.
3009 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3010 			 * then no need to set the weak REG_LIVE_READ32.
3011 			 */
3012 			break;
3013 		/* ... then we depend on parent's value */
3014 		parent->live |= flag;
3015 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3016 		if (flag == REG_LIVE_READ64)
3017 			parent->live &= ~REG_LIVE_READ32;
3018 		state = parent;
3019 		parent = state->parent;
3020 		writes = true;
3021 		cnt++;
3022 	}
3023 
3024 	if (env->longest_mark_read_walk < cnt)
3025 		env->longest_mark_read_walk = cnt;
3026 	return 0;
3027 }
3028 
3029 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3030 {
3031 	struct bpf_func_state *state = func(env, reg);
3032 	int spi, ret;
3033 
3034 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3035 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3036 	 * check_kfunc_call.
3037 	 */
3038 	if (reg->type == CONST_PTR_TO_DYNPTR)
3039 		return 0;
3040 	spi = dynptr_get_spi(env, reg);
3041 	if (spi < 0)
3042 		return spi;
3043 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3044 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3045 	 * read.
3046 	 */
3047 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3048 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3049 	if (ret)
3050 		return ret;
3051 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3052 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3053 }
3054 
3055 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3056 			  int spi, int nr_slots)
3057 {
3058 	struct bpf_func_state *state = func(env, reg);
3059 	int err, i;
3060 
3061 	for (i = 0; i < nr_slots; i++) {
3062 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3063 
3064 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3065 		if (err)
3066 			return err;
3067 
3068 		mark_stack_slot_scratched(env, spi - i);
3069 	}
3070 
3071 	return 0;
3072 }
3073 
3074 /* This function is supposed to be used by the following 32-bit optimization
3075  * code only. It returns TRUE if the source or destination register operates
3076  * on 64-bit, otherwise return FALSE.
3077  */
3078 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3079 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3080 {
3081 	u8 code, class, op;
3082 
3083 	code = insn->code;
3084 	class = BPF_CLASS(code);
3085 	op = BPF_OP(code);
3086 	if (class == BPF_JMP) {
3087 		/* BPF_EXIT for "main" will reach here. Return TRUE
3088 		 * conservatively.
3089 		 */
3090 		if (op == BPF_EXIT)
3091 			return true;
3092 		if (op == BPF_CALL) {
3093 			/* BPF to BPF call will reach here because of marking
3094 			 * caller saved clobber with DST_OP_NO_MARK for which we
3095 			 * don't care the register def because they are anyway
3096 			 * marked as NOT_INIT already.
3097 			 */
3098 			if (insn->src_reg == BPF_PSEUDO_CALL)
3099 				return false;
3100 			/* Helper call will reach here because of arg type
3101 			 * check, conservatively return TRUE.
3102 			 */
3103 			if (t == SRC_OP)
3104 				return true;
3105 
3106 			return false;
3107 		}
3108 	}
3109 
3110 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3111 		return false;
3112 
3113 	if (class == BPF_ALU64 || class == BPF_JMP ||
3114 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3115 		return true;
3116 
3117 	if (class == BPF_ALU || class == BPF_JMP32)
3118 		return false;
3119 
3120 	if (class == BPF_LDX) {
3121 		if (t != SRC_OP)
3122 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3123 		/* LDX source must be ptr. */
3124 		return true;
3125 	}
3126 
3127 	if (class == BPF_STX) {
3128 		/* BPF_STX (including atomic variants) has multiple source
3129 		 * operands, one of which is a ptr. Check whether the caller is
3130 		 * asking about it.
3131 		 */
3132 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3133 			return true;
3134 		return BPF_SIZE(code) == BPF_DW;
3135 	}
3136 
3137 	if (class == BPF_LD) {
3138 		u8 mode = BPF_MODE(code);
3139 
3140 		/* LD_IMM64 */
3141 		if (mode == BPF_IMM)
3142 			return true;
3143 
3144 		/* Both LD_IND and LD_ABS return 32-bit data. */
3145 		if (t != SRC_OP)
3146 			return  false;
3147 
3148 		/* Implicit ctx ptr. */
3149 		if (regno == BPF_REG_6)
3150 			return true;
3151 
3152 		/* Explicit source could be any width. */
3153 		return true;
3154 	}
3155 
3156 	if (class == BPF_ST)
3157 		/* The only source register for BPF_ST is a ptr. */
3158 		return true;
3159 
3160 	/* Conservatively return true at default. */
3161 	return true;
3162 }
3163 
3164 /* Return the regno defined by the insn, or -1. */
3165 static int insn_def_regno(const struct bpf_insn *insn)
3166 {
3167 	switch (BPF_CLASS(insn->code)) {
3168 	case BPF_JMP:
3169 	case BPF_JMP32:
3170 	case BPF_ST:
3171 		return -1;
3172 	case BPF_STX:
3173 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3174 		    (insn->imm & BPF_FETCH)) {
3175 			if (insn->imm == BPF_CMPXCHG)
3176 				return BPF_REG_0;
3177 			else
3178 				return insn->src_reg;
3179 		} else {
3180 			return -1;
3181 		}
3182 	default:
3183 		return insn->dst_reg;
3184 	}
3185 }
3186 
3187 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3188 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3189 {
3190 	int dst_reg = insn_def_regno(insn);
3191 
3192 	if (dst_reg == -1)
3193 		return false;
3194 
3195 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3196 }
3197 
3198 static void mark_insn_zext(struct bpf_verifier_env *env,
3199 			   struct bpf_reg_state *reg)
3200 {
3201 	s32 def_idx = reg->subreg_def;
3202 
3203 	if (def_idx == DEF_NOT_SUBREG)
3204 		return;
3205 
3206 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3207 	/* The dst will be zero extended, so won't be sub-register anymore. */
3208 	reg->subreg_def = DEF_NOT_SUBREG;
3209 }
3210 
3211 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3212 			   enum reg_arg_type t)
3213 {
3214 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3215 	struct bpf_reg_state *reg;
3216 	bool rw64;
3217 
3218 	if (regno >= MAX_BPF_REG) {
3219 		verbose(env, "R%d is invalid\n", regno);
3220 		return -EINVAL;
3221 	}
3222 
3223 	mark_reg_scratched(env, regno);
3224 
3225 	reg = &regs[regno];
3226 	rw64 = is_reg64(env, insn, regno, reg, t);
3227 	if (t == SRC_OP) {
3228 		/* check whether register used as source operand can be read */
3229 		if (reg->type == NOT_INIT) {
3230 			verbose(env, "R%d !read_ok\n", regno);
3231 			return -EACCES;
3232 		}
3233 		/* We don't need to worry about FP liveness because it's read-only */
3234 		if (regno == BPF_REG_FP)
3235 			return 0;
3236 
3237 		if (rw64)
3238 			mark_insn_zext(env, reg);
3239 
3240 		return mark_reg_read(env, reg, reg->parent,
3241 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3242 	} else {
3243 		/* check whether register used as dest operand can be written to */
3244 		if (regno == BPF_REG_FP) {
3245 			verbose(env, "frame pointer is read only\n");
3246 			return -EACCES;
3247 		}
3248 		reg->live |= REG_LIVE_WRITTEN;
3249 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3250 		if (t == DST_OP)
3251 			mark_reg_unknown(env, regs, regno);
3252 	}
3253 	return 0;
3254 }
3255 
3256 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3257 			 enum reg_arg_type t)
3258 {
3259 	struct bpf_verifier_state *vstate = env->cur_state;
3260 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3261 
3262 	return __check_reg_arg(env, state->regs, regno, t);
3263 }
3264 
3265 static int insn_stack_access_flags(int frameno, int spi)
3266 {
3267 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3268 }
3269 
3270 static int insn_stack_access_spi(int insn_flags)
3271 {
3272 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3273 }
3274 
3275 static int insn_stack_access_frameno(int insn_flags)
3276 {
3277 	return insn_flags & INSN_F_FRAMENO_MASK;
3278 }
3279 
3280 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3281 {
3282 	env->insn_aux_data[idx].jmp_point = true;
3283 }
3284 
3285 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3286 {
3287 	return env->insn_aux_data[insn_idx].jmp_point;
3288 }
3289 
3290 /* for any branch, call, exit record the history of jmps in the given state */
3291 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3292 			    int insn_flags)
3293 {
3294 	u32 cnt = cur->jmp_history_cnt;
3295 	struct bpf_jmp_history_entry *p;
3296 	size_t alloc_size;
3297 
3298 	/* combine instruction flags if we already recorded this instruction */
3299 	if (env->cur_hist_ent) {
3300 		/* atomic instructions push insn_flags twice, for READ and
3301 		 * WRITE sides, but they should agree on stack slot
3302 		 */
3303 		WARN_ONCE((env->cur_hist_ent->flags & insn_flags) &&
3304 			  (env->cur_hist_ent->flags & insn_flags) != insn_flags,
3305 			  "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n",
3306 			  env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3307 		env->cur_hist_ent->flags |= insn_flags;
3308 		return 0;
3309 	}
3310 
3311 	cnt++;
3312 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3313 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3314 	if (!p)
3315 		return -ENOMEM;
3316 	cur->jmp_history = p;
3317 
3318 	p = &cur->jmp_history[cnt - 1];
3319 	p->idx = env->insn_idx;
3320 	p->prev_idx = env->prev_insn_idx;
3321 	p->flags = insn_flags;
3322 	cur->jmp_history_cnt = cnt;
3323 	env->cur_hist_ent = p;
3324 
3325 	return 0;
3326 }
3327 
3328 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3329 						        u32 hist_end, int insn_idx)
3330 {
3331 	if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3332 		return &st->jmp_history[hist_end - 1];
3333 	return NULL;
3334 }
3335 
3336 /* Backtrack one insn at a time. If idx is not at the top of recorded
3337  * history then previous instruction came from straight line execution.
3338  * Return -ENOENT if we exhausted all instructions within given state.
3339  *
3340  * It's legal to have a bit of a looping with the same starting and ending
3341  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3342  * instruction index is the same as state's first_idx doesn't mean we are
3343  * done. If there is still some jump history left, we should keep going. We
3344  * need to take into account that we might have a jump history between given
3345  * state's parent and itself, due to checkpointing. In this case, we'll have
3346  * history entry recording a jump from last instruction of parent state and
3347  * first instruction of given state.
3348  */
3349 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3350 			     u32 *history)
3351 {
3352 	u32 cnt = *history;
3353 
3354 	if (i == st->first_insn_idx) {
3355 		if (cnt == 0)
3356 			return -ENOENT;
3357 		if (cnt == 1 && st->jmp_history[0].idx == i)
3358 			return -ENOENT;
3359 	}
3360 
3361 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3362 		i = st->jmp_history[cnt - 1].prev_idx;
3363 		(*history)--;
3364 	} else {
3365 		i--;
3366 	}
3367 	return i;
3368 }
3369 
3370 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3371 {
3372 	const struct btf_type *func;
3373 	struct btf *desc_btf;
3374 
3375 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3376 		return NULL;
3377 
3378 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3379 	if (IS_ERR(desc_btf))
3380 		return "<error>";
3381 
3382 	func = btf_type_by_id(desc_btf, insn->imm);
3383 	return btf_name_by_offset(desc_btf, func->name_off);
3384 }
3385 
3386 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3387 {
3388 	bt->frame = frame;
3389 }
3390 
3391 static inline void bt_reset(struct backtrack_state *bt)
3392 {
3393 	struct bpf_verifier_env *env = bt->env;
3394 
3395 	memset(bt, 0, sizeof(*bt));
3396 	bt->env = env;
3397 }
3398 
3399 static inline u32 bt_empty(struct backtrack_state *bt)
3400 {
3401 	u64 mask = 0;
3402 	int i;
3403 
3404 	for (i = 0; i <= bt->frame; i++)
3405 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3406 
3407 	return mask == 0;
3408 }
3409 
3410 static inline int bt_subprog_enter(struct backtrack_state *bt)
3411 {
3412 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3413 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3414 		WARN_ONCE(1, "verifier backtracking bug");
3415 		return -EFAULT;
3416 	}
3417 	bt->frame++;
3418 	return 0;
3419 }
3420 
3421 static inline int bt_subprog_exit(struct backtrack_state *bt)
3422 {
3423 	if (bt->frame == 0) {
3424 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3425 		WARN_ONCE(1, "verifier backtracking bug");
3426 		return -EFAULT;
3427 	}
3428 	bt->frame--;
3429 	return 0;
3430 }
3431 
3432 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3433 {
3434 	bt->reg_masks[frame] |= 1 << reg;
3435 }
3436 
3437 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3438 {
3439 	bt->reg_masks[frame] &= ~(1 << reg);
3440 }
3441 
3442 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3443 {
3444 	bt_set_frame_reg(bt, bt->frame, reg);
3445 }
3446 
3447 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3448 {
3449 	bt_clear_frame_reg(bt, bt->frame, reg);
3450 }
3451 
3452 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3453 {
3454 	bt->stack_masks[frame] |= 1ull << slot;
3455 }
3456 
3457 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3458 {
3459 	bt->stack_masks[frame] &= ~(1ull << slot);
3460 }
3461 
3462 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3463 {
3464 	return bt->reg_masks[frame];
3465 }
3466 
3467 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3468 {
3469 	return bt->reg_masks[bt->frame];
3470 }
3471 
3472 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3473 {
3474 	return bt->stack_masks[frame];
3475 }
3476 
3477 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3478 {
3479 	return bt->stack_masks[bt->frame];
3480 }
3481 
3482 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3483 {
3484 	return bt->reg_masks[bt->frame] & (1 << reg);
3485 }
3486 
3487 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
3488 {
3489 	return bt->stack_masks[frame] & (1ull << slot);
3490 }
3491 
3492 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3493 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3494 {
3495 	DECLARE_BITMAP(mask, 64);
3496 	bool first = true;
3497 	int i, n;
3498 
3499 	buf[0] = '\0';
3500 
3501 	bitmap_from_u64(mask, reg_mask);
3502 	for_each_set_bit(i, mask, 32) {
3503 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3504 		first = false;
3505 		buf += n;
3506 		buf_sz -= n;
3507 		if (buf_sz < 0)
3508 			break;
3509 	}
3510 }
3511 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3512 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3513 {
3514 	DECLARE_BITMAP(mask, 64);
3515 	bool first = true;
3516 	int i, n;
3517 
3518 	buf[0] = '\0';
3519 
3520 	bitmap_from_u64(mask, stack_mask);
3521 	for_each_set_bit(i, mask, 64) {
3522 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3523 		first = false;
3524 		buf += n;
3525 		buf_sz -= n;
3526 		if (buf_sz < 0)
3527 			break;
3528 	}
3529 }
3530 
3531 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3532 
3533 /* For given verifier state backtrack_insn() is called from the last insn to
3534  * the first insn. Its purpose is to compute a bitmask of registers and
3535  * stack slots that needs precision in the parent verifier state.
3536  *
3537  * @idx is an index of the instruction we are currently processing;
3538  * @subseq_idx is an index of the subsequent instruction that:
3539  *   - *would be* executed next, if jump history is viewed in forward order;
3540  *   - *was* processed previously during backtracking.
3541  */
3542 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3543 			  struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
3544 {
3545 	const struct bpf_insn_cbs cbs = {
3546 		.cb_call	= disasm_kfunc_name,
3547 		.cb_print	= verbose,
3548 		.private_data	= env,
3549 	};
3550 	struct bpf_insn *insn = env->prog->insnsi + idx;
3551 	u8 class = BPF_CLASS(insn->code);
3552 	u8 opcode = BPF_OP(insn->code);
3553 	u8 mode = BPF_MODE(insn->code);
3554 	u32 dreg = insn->dst_reg;
3555 	u32 sreg = insn->src_reg;
3556 	u32 spi, i, fr;
3557 
3558 	if (insn->code == 0)
3559 		return 0;
3560 	if (env->log.level & BPF_LOG_LEVEL2) {
3561 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3562 		verbose(env, "mark_precise: frame%d: regs=%s ",
3563 			bt->frame, env->tmp_str_buf);
3564 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3565 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3566 		verbose(env, "%d: ", idx);
3567 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3568 	}
3569 
3570 	if (class == BPF_ALU || class == BPF_ALU64) {
3571 		if (!bt_is_reg_set(bt, dreg))
3572 			return 0;
3573 		if (opcode == BPF_END || opcode == BPF_NEG) {
3574 			/* sreg is reserved and unused
3575 			 * dreg still need precision before this insn
3576 			 */
3577 			return 0;
3578 		} else if (opcode == BPF_MOV) {
3579 			if (BPF_SRC(insn->code) == BPF_X) {
3580 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3581 				 * dreg needs precision after this insn
3582 				 * sreg needs precision before this insn
3583 				 */
3584 				bt_clear_reg(bt, dreg);
3585 				bt_set_reg(bt, sreg);
3586 			} else {
3587 				/* dreg = K
3588 				 * dreg needs precision after this insn.
3589 				 * Corresponding register is already marked
3590 				 * as precise=true in this verifier state.
3591 				 * No further markings in parent are necessary
3592 				 */
3593 				bt_clear_reg(bt, dreg);
3594 			}
3595 		} else {
3596 			if (BPF_SRC(insn->code) == BPF_X) {
3597 				/* dreg += sreg
3598 				 * both dreg and sreg need precision
3599 				 * before this insn
3600 				 */
3601 				bt_set_reg(bt, sreg);
3602 			} /* else dreg += K
3603 			   * dreg still needs precision before this insn
3604 			   */
3605 		}
3606 	} else if (class == BPF_LDX) {
3607 		if (!bt_is_reg_set(bt, dreg))
3608 			return 0;
3609 		bt_clear_reg(bt, dreg);
3610 
3611 		/* scalars can only be spilled into stack w/o losing precision.
3612 		 * Load from any other memory can be zero extended.
3613 		 * The desire to keep that precision is already indicated
3614 		 * by 'precise' mark in corresponding register of this state.
3615 		 * No further tracking necessary.
3616 		 */
3617 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3618 			return 0;
3619 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3620 		 * that [fp - off] slot contains scalar that needs to be
3621 		 * tracked with precision
3622 		 */
3623 		spi = insn_stack_access_spi(hist->flags);
3624 		fr = insn_stack_access_frameno(hist->flags);
3625 		bt_set_frame_slot(bt, fr, spi);
3626 	} else if (class == BPF_STX || class == BPF_ST) {
3627 		if (bt_is_reg_set(bt, dreg))
3628 			/* stx & st shouldn't be using _scalar_ dst_reg
3629 			 * to access memory. It means backtracking
3630 			 * encountered a case of pointer subtraction.
3631 			 */
3632 			return -ENOTSUPP;
3633 		/* scalars can only be spilled into stack */
3634 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3635 			return 0;
3636 		spi = insn_stack_access_spi(hist->flags);
3637 		fr = insn_stack_access_frameno(hist->flags);
3638 		if (!bt_is_frame_slot_set(bt, fr, spi))
3639 			return 0;
3640 		bt_clear_frame_slot(bt, fr, spi);
3641 		if (class == BPF_STX)
3642 			bt_set_reg(bt, sreg);
3643 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3644 		if (bpf_pseudo_call(insn)) {
3645 			int subprog_insn_idx, subprog;
3646 
3647 			subprog_insn_idx = idx + insn->imm + 1;
3648 			subprog = find_subprog(env, subprog_insn_idx);
3649 			if (subprog < 0)
3650 				return -EFAULT;
3651 
3652 			if (subprog_is_global(env, subprog)) {
3653 				/* check that jump history doesn't have any
3654 				 * extra instructions from subprog; the next
3655 				 * instruction after call to global subprog
3656 				 * should be literally next instruction in
3657 				 * caller program
3658 				 */
3659 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3660 				/* r1-r5 are invalidated after subprog call,
3661 				 * so for global func call it shouldn't be set
3662 				 * anymore
3663 				 */
3664 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3665 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3666 					WARN_ONCE(1, "verifier backtracking bug");
3667 					return -EFAULT;
3668 				}
3669 				/* global subprog always sets R0 */
3670 				bt_clear_reg(bt, BPF_REG_0);
3671 				return 0;
3672 			} else {
3673 				/* static subprog call instruction, which
3674 				 * means that we are exiting current subprog,
3675 				 * so only r1-r5 could be still requested as
3676 				 * precise, r0 and r6-r10 or any stack slot in
3677 				 * the current frame should be zero by now
3678 				 */
3679 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3680 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3681 					WARN_ONCE(1, "verifier backtracking bug");
3682 					return -EFAULT;
3683 				}
3684 				/* we are now tracking register spills correctly,
3685 				 * so any instance of leftover slots is a bug
3686 				 */
3687 				if (bt_stack_mask(bt) != 0) {
3688 					verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3689 					WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)");
3690 					return -EFAULT;
3691 				}
3692 				/* propagate r1-r5 to the caller */
3693 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3694 					if (bt_is_reg_set(bt, i)) {
3695 						bt_clear_reg(bt, i);
3696 						bt_set_frame_reg(bt, bt->frame - 1, i);
3697 					}
3698 				}
3699 				if (bt_subprog_exit(bt))
3700 					return -EFAULT;
3701 				return 0;
3702 			}
3703 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3704 			/* exit from callback subprog to callback-calling helper or
3705 			 * kfunc call. Use idx/subseq_idx check to discern it from
3706 			 * straight line code backtracking.
3707 			 * Unlike the subprog call handling above, we shouldn't
3708 			 * propagate precision of r1-r5 (if any requested), as they are
3709 			 * not actually arguments passed directly to callback subprogs
3710 			 */
3711 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3712 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3713 				WARN_ONCE(1, "verifier backtracking bug");
3714 				return -EFAULT;
3715 			}
3716 			if (bt_stack_mask(bt) != 0) {
3717 				verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3718 				WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)");
3719 				return -EFAULT;
3720 			}
3721 			/* clear r1-r5 in callback subprog's mask */
3722 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3723 				bt_clear_reg(bt, i);
3724 			if (bt_subprog_exit(bt))
3725 				return -EFAULT;
3726 			return 0;
3727 		} else if (opcode == BPF_CALL) {
3728 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3729 			 * catch this error later. Make backtracking conservative
3730 			 * with ENOTSUPP.
3731 			 */
3732 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3733 				return -ENOTSUPP;
3734 			/* regular helper call sets R0 */
3735 			bt_clear_reg(bt, BPF_REG_0);
3736 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3737 				/* if backtracing was looking for registers R1-R5
3738 				 * they should have been found already.
3739 				 */
3740 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3741 				WARN_ONCE(1, "verifier backtracking bug");
3742 				return -EFAULT;
3743 			}
3744 		} else if (opcode == BPF_EXIT) {
3745 			bool r0_precise;
3746 
3747 			/* Backtracking to a nested function call, 'idx' is a part of
3748 			 * the inner frame 'subseq_idx' is a part of the outer frame.
3749 			 * In case of a regular function call, instructions giving
3750 			 * precision to registers R1-R5 should have been found already.
3751 			 * In case of a callback, it is ok to have R1-R5 marked for
3752 			 * backtracking, as these registers are set by the function
3753 			 * invoking callback.
3754 			 */
3755 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3756 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3757 					bt_clear_reg(bt, i);
3758 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3759 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3760 				WARN_ONCE(1, "verifier backtracking bug");
3761 				return -EFAULT;
3762 			}
3763 
3764 			/* BPF_EXIT in subprog or callback always returns
3765 			 * right after the call instruction, so by checking
3766 			 * whether the instruction at subseq_idx-1 is subprog
3767 			 * call or not we can distinguish actual exit from
3768 			 * *subprog* from exit from *callback*. In the former
3769 			 * case, we need to propagate r0 precision, if
3770 			 * necessary. In the former we never do that.
3771 			 */
3772 			r0_precise = subseq_idx - 1 >= 0 &&
3773 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3774 				     bt_is_reg_set(bt, BPF_REG_0);
3775 
3776 			bt_clear_reg(bt, BPF_REG_0);
3777 			if (bt_subprog_enter(bt))
3778 				return -EFAULT;
3779 
3780 			if (r0_precise)
3781 				bt_set_reg(bt, BPF_REG_0);
3782 			/* r6-r9 and stack slots will stay set in caller frame
3783 			 * bitmasks until we return back from callee(s)
3784 			 */
3785 			return 0;
3786 		} else if (BPF_SRC(insn->code) == BPF_X) {
3787 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3788 				return 0;
3789 			/* dreg <cond> sreg
3790 			 * Both dreg and sreg need precision before
3791 			 * this insn. If only sreg was marked precise
3792 			 * before it would be equally necessary to
3793 			 * propagate it to dreg.
3794 			 */
3795 			bt_set_reg(bt, dreg);
3796 			bt_set_reg(bt, sreg);
3797 			 /* else dreg <cond> K
3798 			  * Only dreg still needs precision before
3799 			  * this insn, so for the K-based conditional
3800 			  * there is nothing new to be marked.
3801 			  */
3802 		}
3803 	} else if (class == BPF_LD) {
3804 		if (!bt_is_reg_set(bt, dreg))
3805 			return 0;
3806 		bt_clear_reg(bt, dreg);
3807 		/* It's ld_imm64 or ld_abs or ld_ind.
3808 		 * For ld_imm64 no further tracking of precision
3809 		 * into parent is necessary
3810 		 */
3811 		if (mode == BPF_IND || mode == BPF_ABS)
3812 			/* to be analyzed */
3813 			return -ENOTSUPP;
3814 	}
3815 	return 0;
3816 }
3817 
3818 /* the scalar precision tracking algorithm:
3819  * . at the start all registers have precise=false.
3820  * . scalar ranges are tracked as normal through alu and jmp insns.
3821  * . once precise value of the scalar register is used in:
3822  *   .  ptr + scalar alu
3823  *   . if (scalar cond K|scalar)
3824  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3825  *   backtrack through the verifier states and mark all registers and
3826  *   stack slots with spilled constants that these scalar regisers
3827  *   should be precise.
3828  * . during state pruning two registers (or spilled stack slots)
3829  *   are equivalent if both are not precise.
3830  *
3831  * Note the verifier cannot simply walk register parentage chain,
3832  * since many different registers and stack slots could have been
3833  * used to compute single precise scalar.
3834  *
3835  * The approach of starting with precise=true for all registers and then
3836  * backtrack to mark a register as not precise when the verifier detects
3837  * that program doesn't care about specific value (e.g., when helper
3838  * takes register as ARG_ANYTHING parameter) is not safe.
3839  *
3840  * It's ok to walk single parentage chain of the verifier states.
3841  * It's possible that this backtracking will go all the way till 1st insn.
3842  * All other branches will be explored for needing precision later.
3843  *
3844  * The backtracking needs to deal with cases like:
3845  *   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)
3846  * r9 -= r8
3847  * r5 = r9
3848  * if r5 > 0x79f goto pc+7
3849  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3850  * r5 += 1
3851  * ...
3852  * call bpf_perf_event_output#25
3853  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3854  *
3855  * and this case:
3856  * r6 = 1
3857  * call foo // uses callee's r6 inside to compute r0
3858  * r0 += r6
3859  * if r0 == 0 goto
3860  *
3861  * to track above reg_mask/stack_mask needs to be independent for each frame.
3862  *
3863  * Also if parent's curframe > frame where backtracking started,
3864  * the verifier need to mark registers in both frames, otherwise callees
3865  * may incorrectly prune callers. This is similar to
3866  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3867  *
3868  * For now backtracking falls back into conservative marking.
3869  */
3870 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3871 				     struct bpf_verifier_state *st)
3872 {
3873 	struct bpf_func_state *func;
3874 	struct bpf_reg_state *reg;
3875 	int i, j;
3876 
3877 	if (env->log.level & BPF_LOG_LEVEL2) {
3878 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3879 			st->curframe);
3880 	}
3881 
3882 	/* big hammer: mark all scalars precise in this path.
3883 	 * pop_stack may still get !precise scalars.
3884 	 * We also skip current state and go straight to first parent state,
3885 	 * because precision markings in current non-checkpointed state are
3886 	 * not needed. See why in the comment in __mark_chain_precision below.
3887 	 */
3888 	for (st = st->parent; st; st = st->parent) {
3889 		for (i = 0; i <= st->curframe; i++) {
3890 			func = st->frame[i];
3891 			for (j = 0; j < BPF_REG_FP; j++) {
3892 				reg = &func->regs[j];
3893 				if (reg->type != SCALAR_VALUE || reg->precise)
3894 					continue;
3895 				reg->precise = true;
3896 				if (env->log.level & BPF_LOG_LEVEL2) {
3897 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3898 						i, j);
3899 				}
3900 			}
3901 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3902 				if (!is_spilled_reg(&func->stack[j]))
3903 					continue;
3904 				reg = &func->stack[j].spilled_ptr;
3905 				if (reg->type != SCALAR_VALUE || reg->precise)
3906 					continue;
3907 				reg->precise = true;
3908 				if (env->log.level & BPF_LOG_LEVEL2) {
3909 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3910 						i, -(j + 1) * 8);
3911 				}
3912 			}
3913 		}
3914 	}
3915 }
3916 
3917 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3918 {
3919 	struct bpf_func_state *func;
3920 	struct bpf_reg_state *reg;
3921 	int i, j;
3922 
3923 	for (i = 0; i <= st->curframe; i++) {
3924 		func = st->frame[i];
3925 		for (j = 0; j < BPF_REG_FP; j++) {
3926 			reg = &func->regs[j];
3927 			if (reg->type != SCALAR_VALUE)
3928 				continue;
3929 			reg->precise = false;
3930 		}
3931 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3932 			if (!is_spilled_reg(&func->stack[j]))
3933 				continue;
3934 			reg = &func->stack[j].spilled_ptr;
3935 			if (reg->type != SCALAR_VALUE)
3936 				continue;
3937 			reg->precise = false;
3938 		}
3939 	}
3940 }
3941 
3942 static bool idset_contains(struct bpf_idset *s, u32 id)
3943 {
3944 	u32 i;
3945 
3946 	for (i = 0; i < s->count; ++i)
3947 		if (s->ids[i] == id)
3948 			return true;
3949 
3950 	return false;
3951 }
3952 
3953 static int idset_push(struct bpf_idset *s, u32 id)
3954 {
3955 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3956 		return -EFAULT;
3957 	s->ids[s->count++] = id;
3958 	return 0;
3959 }
3960 
3961 static void idset_reset(struct bpf_idset *s)
3962 {
3963 	s->count = 0;
3964 }
3965 
3966 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3967  * Mark all registers with these IDs as precise.
3968  */
3969 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3970 {
3971 	struct bpf_idset *precise_ids = &env->idset_scratch;
3972 	struct backtrack_state *bt = &env->bt;
3973 	struct bpf_func_state *func;
3974 	struct bpf_reg_state *reg;
3975 	DECLARE_BITMAP(mask, 64);
3976 	int i, fr;
3977 
3978 	idset_reset(precise_ids);
3979 
3980 	for (fr = bt->frame; fr >= 0; fr--) {
3981 		func = st->frame[fr];
3982 
3983 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3984 		for_each_set_bit(i, mask, 32) {
3985 			reg = &func->regs[i];
3986 			if (!reg->id || reg->type != SCALAR_VALUE)
3987 				continue;
3988 			if (idset_push(precise_ids, reg->id))
3989 				return -EFAULT;
3990 		}
3991 
3992 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3993 		for_each_set_bit(i, mask, 64) {
3994 			if (i >= func->allocated_stack / BPF_REG_SIZE)
3995 				break;
3996 			if (!is_spilled_scalar_reg(&func->stack[i]))
3997 				continue;
3998 			reg = &func->stack[i].spilled_ptr;
3999 			if (!reg->id)
4000 				continue;
4001 			if (idset_push(precise_ids, reg->id))
4002 				return -EFAULT;
4003 		}
4004 	}
4005 
4006 	for (fr = 0; fr <= st->curframe; ++fr) {
4007 		func = st->frame[fr];
4008 
4009 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4010 			reg = &func->regs[i];
4011 			if (!reg->id)
4012 				continue;
4013 			if (!idset_contains(precise_ids, reg->id))
4014 				continue;
4015 			bt_set_frame_reg(bt, fr, i);
4016 		}
4017 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4018 			if (!is_spilled_scalar_reg(&func->stack[i]))
4019 				continue;
4020 			reg = &func->stack[i].spilled_ptr;
4021 			if (!reg->id)
4022 				continue;
4023 			if (!idset_contains(precise_ids, reg->id))
4024 				continue;
4025 			bt_set_frame_slot(bt, fr, i);
4026 		}
4027 	}
4028 
4029 	return 0;
4030 }
4031 
4032 /*
4033  * __mark_chain_precision() backtracks BPF program instruction sequence and
4034  * chain of verifier states making sure that register *regno* (if regno >= 0)
4035  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4036  * SCALARS, as well as any other registers and slots that contribute to
4037  * a tracked state of given registers/stack slots, depending on specific BPF
4038  * assembly instructions (see backtrack_insns() for exact instruction handling
4039  * logic). This backtracking relies on recorded jmp_history and is able to
4040  * traverse entire chain of parent states. This process ends only when all the
4041  * necessary registers/slots and their transitive dependencies are marked as
4042  * precise.
4043  *
4044  * One important and subtle aspect is that precise marks *do not matter* in
4045  * the currently verified state (current state). It is important to understand
4046  * why this is the case.
4047  *
4048  * First, note that current state is the state that is not yet "checkpointed",
4049  * i.e., it is not yet put into env->explored_states, and it has no children
4050  * states as well. It's ephemeral, and can end up either a) being discarded if
4051  * compatible explored state is found at some point or BPF_EXIT instruction is
4052  * reached or b) checkpointed and put into env->explored_states, branching out
4053  * into one or more children states.
4054  *
4055  * In the former case, precise markings in current state are completely
4056  * ignored by state comparison code (see regsafe() for details). Only
4057  * checkpointed ("old") state precise markings are important, and if old
4058  * state's register/slot is precise, regsafe() assumes current state's
4059  * register/slot as precise and checks value ranges exactly and precisely. If
4060  * states turn out to be compatible, current state's necessary precise
4061  * markings and any required parent states' precise markings are enforced
4062  * after the fact with propagate_precision() logic, after the fact. But it's
4063  * important to realize that in this case, even after marking current state
4064  * registers/slots as precise, we immediately discard current state. So what
4065  * actually matters is any of the precise markings propagated into current
4066  * state's parent states, which are always checkpointed (due to b) case above).
4067  * As such, for scenario a) it doesn't matter if current state has precise
4068  * markings set or not.
4069  *
4070  * Now, for the scenario b), checkpointing and forking into child(ren)
4071  * state(s). Note that before current state gets to checkpointing step, any
4072  * processed instruction always assumes precise SCALAR register/slot
4073  * knowledge: if precise value or range is useful to prune jump branch, BPF
4074  * verifier takes this opportunity enthusiastically. Similarly, when
4075  * register's value is used to calculate offset or memory address, exact
4076  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4077  * what we mentioned above about state comparison ignoring precise markings
4078  * during state comparison, BPF verifier ignores and also assumes precise
4079  * markings *at will* during instruction verification process. But as verifier
4080  * assumes precision, it also propagates any precision dependencies across
4081  * parent states, which are not yet finalized, so can be further restricted
4082  * based on new knowledge gained from restrictions enforced by their children
4083  * states. This is so that once those parent states are finalized, i.e., when
4084  * they have no more active children state, state comparison logic in
4085  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4086  * required for correctness.
4087  *
4088  * To build a bit more intuition, note also that once a state is checkpointed,
4089  * the path we took to get to that state is not important. This is crucial
4090  * property for state pruning. When state is checkpointed and finalized at
4091  * some instruction index, it can be correctly and safely used to "short
4092  * circuit" any *compatible* state that reaches exactly the same instruction
4093  * index. I.e., if we jumped to that instruction from a completely different
4094  * code path than original finalized state was derived from, it doesn't
4095  * matter, current state can be discarded because from that instruction
4096  * forward having a compatible state will ensure we will safely reach the
4097  * exit. States describe preconditions for further exploration, but completely
4098  * forget the history of how we got here.
4099  *
4100  * This also means that even if we needed precise SCALAR range to get to
4101  * finalized state, but from that point forward *that same* SCALAR register is
4102  * never used in a precise context (i.e., it's precise value is not needed for
4103  * correctness), it's correct and safe to mark such register as "imprecise"
4104  * (i.e., precise marking set to false). This is what we rely on when we do
4105  * not set precise marking in current state. If no child state requires
4106  * precision for any given SCALAR register, it's safe to dictate that it can
4107  * be imprecise. If any child state does require this register to be precise,
4108  * we'll mark it precise later retroactively during precise markings
4109  * propagation from child state to parent states.
4110  *
4111  * Skipping precise marking setting in current state is a mild version of
4112  * relying on the above observation. But we can utilize this property even
4113  * more aggressively by proactively forgetting any precise marking in the
4114  * current state (which we inherited from the parent state), right before we
4115  * checkpoint it and branch off into new child state. This is done by
4116  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4117  * finalized states which help in short circuiting more future states.
4118  */
4119 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4120 {
4121 	struct backtrack_state *bt = &env->bt;
4122 	struct bpf_verifier_state *st = env->cur_state;
4123 	int first_idx = st->first_insn_idx;
4124 	int last_idx = env->insn_idx;
4125 	int subseq_idx = -1;
4126 	struct bpf_func_state *func;
4127 	struct bpf_reg_state *reg;
4128 	bool skip_first = true;
4129 	int i, fr, err;
4130 
4131 	if (!env->bpf_capable)
4132 		return 0;
4133 
4134 	/* set frame number from which we are starting to backtrack */
4135 	bt_init(bt, env->cur_state->curframe);
4136 
4137 	/* Do sanity checks against current state of register and/or stack
4138 	 * slot, but don't set precise flag in current state, as precision
4139 	 * tracking in the current state is unnecessary.
4140 	 */
4141 	func = st->frame[bt->frame];
4142 	if (regno >= 0) {
4143 		reg = &func->regs[regno];
4144 		if (reg->type != SCALAR_VALUE) {
4145 			WARN_ONCE(1, "backtracing misuse");
4146 			return -EFAULT;
4147 		}
4148 		bt_set_reg(bt, regno);
4149 	}
4150 
4151 	if (bt_empty(bt))
4152 		return 0;
4153 
4154 	for (;;) {
4155 		DECLARE_BITMAP(mask, 64);
4156 		u32 history = st->jmp_history_cnt;
4157 		struct bpf_jmp_history_entry *hist;
4158 
4159 		if (env->log.level & BPF_LOG_LEVEL2) {
4160 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4161 				bt->frame, last_idx, first_idx, subseq_idx);
4162 		}
4163 
4164 		/* If some register with scalar ID is marked as precise,
4165 		 * make sure that all registers sharing this ID are also precise.
4166 		 * This is needed to estimate effect of find_equal_scalars().
4167 		 * Do this at the last instruction of each state,
4168 		 * bpf_reg_state::id fields are valid for these instructions.
4169 		 *
4170 		 * Allows to track precision in situation like below:
4171 		 *
4172 		 *     r2 = unknown value
4173 		 *     ...
4174 		 *   --- state #0 ---
4175 		 *     ...
4176 		 *     r1 = r2                 // r1 and r2 now share the same ID
4177 		 *     ...
4178 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4179 		 *     ...
4180 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4181 		 *     ...
4182 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4183 		 *     r3 = r10
4184 		 *     r3 += r1                // need to mark both r1 and r2
4185 		 */
4186 		if (mark_precise_scalar_ids(env, st))
4187 			return -EFAULT;
4188 
4189 		if (last_idx < 0) {
4190 			/* we are at the entry into subprog, which
4191 			 * is expected for global funcs, but only if
4192 			 * requested precise registers are R1-R5
4193 			 * (which are global func's input arguments)
4194 			 */
4195 			if (st->curframe == 0 &&
4196 			    st->frame[0]->subprogno > 0 &&
4197 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4198 			    bt_stack_mask(bt) == 0 &&
4199 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4200 				bitmap_from_u64(mask, bt_reg_mask(bt));
4201 				for_each_set_bit(i, mask, 32) {
4202 					reg = &st->frame[0]->regs[i];
4203 					bt_clear_reg(bt, i);
4204 					if (reg->type == SCALAR_VALUE)
4205 						reg->precise = true;
4206 				}
4207 				return 0;
4208 			}
4209 
4210 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4211 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4212 			WARN_ONCE(1, "verifier backtracking bug");
4213 			return -EFAULT;
4214 		}
4215 
4216 		for (i = last_idx;;) {
4217 			if (skip_first) {
4218 				err = 0;
4219 				skip_first = false;
4220 			} else {
4221 				hist = get_jmp_hist_entry(st, history, i);
4222 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4223 			}
4224 			if (err == -ENOTSUPP) {
4225 				mark_all_scalars_precise(env, env->cur_state);
4226 				bt_reset(bt);
4227 				return 0;
4228 			} else if (err) {
4229 				return err;
4230 			}
4231 			if (bt_empty(bt))
4232 				/* Found assignment(s) into tracked register in this state.
4233 				 * Since this state is already marked, just return.
4234 				 * Nothing to be tracked further in the parent state.
4235 				 */
4236 				return 0;
4237 			subseq_idx = i;
4238 			i = get_prev_insn_idx(st, i, &history);
4239 			if (i == -ENOENT)
4240 				break;
4241 			if (i >= env->prog->len) {
4242 				/* This can happen if backtracking reached insn 0
4243 				 * and there are still reg_mask or stack_mask
4244 				 * to backtrack.
4245 				 * It means the backtracking missed the spot where
4246 				 * particular register was initialized with a constant.
4247 				 */
4248 				verbose(env, "BUG backtracking idx %d\n", i);
4249 				WARN_ONCE(1, "verifier backtracking bug");
4250 				return -EFAULT;
4251 			}
4252 		}
4253 		st = st->parent;
4254 		if (!st)
4255 			break;
4256 
4257 		for (fr = bt->frame; fr >= 0; fr--) {
4258 			func = st->frame[fr];
4259 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4260 			for_each_set_bit(i, mask, 32) {
4261 				reg = &func->regs[i];
4262 				if (reg->type != SCALAR_VALUE) {
4263 					bt_clear_frame_reg(bt, fr, i);
4264 					continue;
4265 				}
4266 				if (reg->precise)
4267 					bt_clear_frame_reg(bt, fr, i);
4268 				else
4269 					reg->precise = true;
4270 			}
4271 
4272 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4273 			for_each_set_bit(i, mask, 64) {
4274 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4275 					verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n",
4276 						i, func->allocated_stack / BPF_REG_SIZE);
4277 					WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)");
4278 					return -EFAULT;
4279 				}
4280 
4281 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4282 					bt_clear_frame_slot(bt, fr, i);
4283 					continue;
4284 				}
4285 				reg = &func->stack[i].spilled_ptr;
4286 				if (reg->precise)
4287 					bt_clear_frame_slot(bt, fr, i);
4288 				else
4289 					reg->precise = true;
4290 			}
4291 			if (env->log.level & BPF_LOG_LEVEL2) {
4292 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4293 					     bt_frame_reg_mask(bt, fr));
4294 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4295 					fr, env->tmp_str_buf);
4296 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4297 					       bt_frame_stack_mask(bt, fr));
4298 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4299 				print_verifier_state(env, func, true);
4300 			}
4301 		}
4302 
4303 		if (bt_empty(bt))
4304 			return 0;
4305 
4306 		subseq_idx = first_idx;
4307 		last_idx = st->last_insn_idx;
4308 		first_idx = st->first_insn_idx;
4309 	}
4310 
4311 	/* if we still have requested precise regs or slots, we missed
4312 	 * something (e.g., stack access through non-r10 register), so
4313 	 * fallback to marking all precise
4314 	 */
4315 	if (!bt_empty(bt)) {
4316 		mark_all_scalars_precise(env, env->cur_state);
4317 		bt_reset(bt);
4318 	}
4319 
4320 	return 0;
4321 }
4322 
4323 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4324 {
4325 	return __mark_chain_precision(env, regno);
4326 }
4327 
4328 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4329  * desired reg and stack masks across all relevant frames
4330  */
4331 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4332 {
4333 	return __mark_chain_precision(env, -1);
4334 }
4335 
4336 static bool is_spillable_regtype(enum bpf_reg_type type)
4337 {
4338 	switch (base_type(type)) {
4339 	case PTR_TO_MAP_VALUE:
4340 	case PTR_TO_STACK:
4341 	case PTR_TO_CTX:
4342 	case PTR_TO_PACKET:
4343 	case PTR_TO_PACKET_META:
4344 	case PTR_TO_PACKET_END:
4345 	case PTR_TO_FLOW_KEYS:
4346 	case CONST_PTR_TO_MAP:
4347 	case PTR_TO_SOCKET:
4348 	case PTR_TO_SOCK_COMMON:
4349 	case PTR_TO_TCP_SOCK:
4350 	case PTR_TO_XDP_SOCK:
4351 	case PTR_TO_BTF_ID:
4352 	case PTR_TO_BUF:
4353 	case PTR_TO_MEM:
4354 	case PTR_TO_FUNC:
4355 	case PTR_TO_MAP_KEY:
4356 		return true;
4357 	default:
4358 		return false;
4359 	}
4360 }
4361 
4362 /* Does this register contain a constant zero? */
4363 static bool register_is_null(struct bpf_reg_state *reg)
4364 {
4365 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4366 }
4367 
4368 /* check if register is a constant scalar value */
4369 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4370 {
4371 	return reg->type == SCALAR_VALUE &&
4372 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4373 }
4374 
4375 /* assuming is_reg_const() is true, return constant value of a register */
4376 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4377 {
4378 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4379 }
4380 
4381 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4382 {
4383 	return tnum_is_unknown(reg->var_off) &&
4384 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4385 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4386 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4387 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4388 }
4389 
4390 static bool register_is_bounded(struct bpf_reg_state *reg)
4391 {
4392 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4393 }
4394 
4395 static bool __is_pointer_value(bool allow_ptr_leaks,
4396 			       const struct bpf_reg_state *reg)
4397 {
4398 	if (allow_ptr_leaks)
4399 		return false;
4400 
4401 	return reg->type != SCALAR_VALUE;
4402 }
4403 
4404 /* Copy src state preserving dst->parent and dst->live fields */
4405 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4406 {
4407 	struct bpf_reg_state *parent = dst->parent;
4408 	enum bpf_reg_liveness live = dst->live;
4409 
4410 	*dst = *src;
4411 	dst->parent = parent;
4412 	dst->live = live;
4413 }
4414 
4415 static void save_register_state(struct bpf_verifier_env *env,
4416 				struct bpf_func_state *state,
4417 				int spi, struct bpf_reg_state *reg,
4418 				int size)
4419 {
4420 	int i;
4421 
4422 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4423 	if (size == BPF_REG_SIZE)
4424 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4425 
4426 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4427 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4428 
4429 	/* size < 8 bytes spill */
4430 	for (; i; i--)
4431 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4432 }
4433 
4434 static bool is_bpf_st_mem(struct bpf_insn *insn)
4435 {
4436 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4437 }
4438 
4439 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4440  * stack boundary and alignment are checked in check_mem_access()
4441  */
4442 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4443 				       /* stack frame we're writing to */
4444 				       struct bpf_func_state *state,
4445 				       int off, int size, int value_regno,
4446 				       int insn_idx)
4447 {
4448 	struct bpf_func_state *cur; /* state of the current function */
4449 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4450 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4451 	struct bpf_reg_state *reg = NULL;
4452 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
4453 
4454 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4455 	 * so it's aligned access and [off, off + size) are within stack limits
4456 	 */
4457 	if (!env->allow_ptr_leaks &&
4458 	    is_spilled_reg(&state->stack[spi]) &&
4459 	    size != BPF_REG_SIZE) {
4460 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4461 		return -EACCES;
4462 	}
4463 
4464 	cur = env->cur_state->frame[env->cur_state->curframe];
4465 	if (value_regno >= 0)
4466 		reg = &cur->regs[value_regno];
4467 	if (!env->bypass_spec_v4) {
4468 		bool sanitize = reg && is_spillable_regtype(reg->type);
4469 
4470 		for (i = 0; i < size; i++) {
4471 			u8 type = state->stack[spi].slot_type[i];
4472 
4473 			if (type != STACK_MISC && type != STACK_ZERO) {
4474 				sanitize = true;
4475 				break;
4476 			}
4477 		}
4478 
4479 		if (sanitize)
4480 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4481 	}
4482 
4483 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4484 	if (err)
4485 		return err;
4486 
4487 	mark_stack_slot_scratched(env, spi);
4488 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && env->bpf_capable) {
4489 		save_register_state(env, state, spi, reg, size);
4490 		/* Break the relation on a narrowing spill. */
4491 		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4492 			state->stack[spi].spilled_ptr.id = 0;
4493 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4494 		   insn->imm != 0 && env->bpf_capable) {
4495 		struct bpf_reg_state fake_reg = {};
4496 
4497 		__mark_reg_known(&fake_reg, insn->imm);
4498 		fake_reg.type = SCALAR_VALUE;
4499 		save_register_state(env, state, spi, &fake_reg, size);
4500 	} else if (reg && is_spillable_regtype(reg->type)) {
4501 		/* register containing pointer is being spilled into stack */
4502 		if (size != BPF_REG_SIZE) {
4503 			verbose_linfo(env, insn_idx, "; ");
4504 			verbose(env, "invalid size of register spill\n");
4505 			return -EACCES;
4506 		}
4507 		if (state != cur && reg->type == PTR_TO_STACK) {
4508 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4509 			return -EINVAL;
4510 		}
4511 		save_register_state(env, state, spi, reg, size);
4512 	} else {
4513 		u8 type = STACK_MISC;
4514 
4515 		/* regular write of data into stack destroys any spilled ptr */
4516 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4517 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4518 		if (is_stack_slot_special(&state->stack[spi]))
4519 			for (i = 0; i < BPF_REG_SIZE; i++)
4520 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4521 
4522 		/* only mark the slot as written if all 8 bytes were written
4523 		 * otherwise read propagation may incorrectly stop too soon
4524 		 * when stack slots are partially written.
4525 		 * This heuristic means that read propagation will be
4526 		 * conservative, since it will add reg_live_read marks
4527 		 * to stack slots all the way to first state when programs
4528 		 * writes+reads less than 8 bytes
4529 		 */
4530 		if (size == BPF_REG_SIZE)
4531 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4532 
4533 		/* when we zero initialize stack slots mark them as such */
4534 		if ((reg && register_is_null(reg)) ||
4535 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4536 			/* STACK_ZERO case happened because register spill
4537 			 * wasn't properly aligned at the stack slot boundary,
4538 			 * so it's not a register spill anymore; force
4539 			 * originating register to be precise to make
4540 			 * STACK_ZERO correct for subsequent states
4541 			 */
4542 			err = mark_chain_precision(env, value_regno);
4543 			if (err)
4544 				return err;
4545 			type = STACK_ZERO;
4546 		}
4547 
4548 		/* Mark slots affected by this stack write. */
4549 		for (i = 0; i < size; i++)
4550 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
4551 		insn_flags = 0; /* not a register spill */
4552 	}
4553 
4554 	if (insn_flags)
4555 		return push_jmp_history(env, env->cur_state, insn_flags);
4556 	return 0;
4557 }
4558 
4559 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4560  * known to contain a variable offset.
4561  * This function checks whether the write is permitted and conservatively
4562  * tracks the effects of the write, considering that each stack slot in the
4563  * dynamic range is potentially written to.
4564  *
4565  * 'off' includes 'regno->off'.
4566  * 'value_regno' can be -1, meaning that an unknown value is being written to
4567  * the stack.
4568  *
4569  * Spilled pointers in range are not marked as written because we don't know
4570  * what's going to be actually written. This means that read propagation for
4571  * future reads cannot be terminated by this write.
4572  *
4573  * For privileged programs, uninitialized stack slots are considered
4574  * initialized by this write (even though we don't know exactly what offsets
4575  * are going to be written to). The idea is that we don't want the verifier to
4576  * reject future reads that access slots written to through variable offsets.
4577  */
4578 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4579 				     /* func where register points to */
4580 				     struct bpf_func_state *state,
4581 				     int ptr_regno, int off, int size,
4582 				     int value_regno, int insn_idx)
4583 {
4584 	struct bpf_func_state *cur; /* state of the current function */
4585 	int min_off, max_off;
4586 	int i, err;
4587 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4588 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4589 	bool writing_zero = false;
4590 	/* set if the fact that we're writing a zero is used to let any
4591 	 * stack slots remain STACK_ZERO
4592 	 */
4593 	bool zero_used = false;
4594 
4595 	cur = env->cur_state->frame[env->cur_state->curframe];
4596 	ptr_reg = &cur->regs[ptr_regno];
4597 	min_off = ptr_reg->smin_value + off;
4598 	max_off = ptr_reg->smax_value + off + size;
4599 	if (value_regno >= 0)
4600 		value_reg = &cur->regs[value_regno];
4601 	if ((value_reg && register_is_null(value_reg)) ||
4602 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4603 		writing_zero = true;
4604 
4605 	for (i = min_off; i < max_off; i++) {
4606 		int spi;
4607 
4608 		spi = __get_spi(i);
4609 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4610 		if (err)
4611 			return err;
4612 	}
4613 
4614 	/* Variable offset writes destroy any spilled pointers in range. */
4615 	for (i = min_off; i < max_off; i++) {
4616 		u8 new_type, *stype;
4617 		int slot, spi;
4618 
4619 		slot = -i - 1;
4620 		spi = slot / BPF_REG_SIZE;
4621 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4622 		mark_stack_slot_scratched(env, spi);
4623 
4624 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4625 			/* Reject the write if range we may write to has not
4626 			 * been initialized beforehand. If we didn't reject
4627 			 * here, the ptr status would be erased below (even
4628 			 * though not all slots are actually overwritten),
4629 			 * possibly opening the door to leaks.
4630 			 *
4631 			 * We do however catch STACK_INVALID case below, and
4632 			 * only allow reading possibly uninitialized memory
4633 			 * later for CAP_PERFMON, as the write may not happen to
4634 			 * that slot.
4635 			 */
4636 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4637 				insn_idx, i);
4638 			return -EINVAL;
4639 		}
4640 
4641 		/* Erase all spilled pointers. */
4642 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4643 
4644 		/* Update the slot type. */
4645 		new_type = STACK_MISC;
4646 		if (writing_zero && *stype == STACK_ZERO) {
4647 			new_type = STACK_ZERO;
4648 			zero_used = true;
4649 		}
4650 		/* If the slot is STACK_INVALID, we check whether it's OK to
4651 		 * pretend that it will be initialized by this write. The slot
4652 		 * might not actually be written to, and so if we mark it as
4653 		 * initialized future reads might leak uninitialized memory.
4654 		 * For privileged programs, we will accept such reads to slots
4655 		 * that may or may not be written because, if we're reject
4656 		 * them, the error would be too confusing.
4657 		 */
4658 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4659 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4660 					insn_idx, i);
4661 			return -EINVAL;
4662 		}
4663 		*stype = new_type;
4664 	}
4665 	if (zero_used) {
4666 		/* backtracking doesn't work for STACK_ZERO yet. */
4667 		err = mark_chain_precision(env, value_regno);
4668 		if (err)
4669 			return err;
4670 	}
4671 	return 0;
4672 }
4673 
4674 /* When register 'dst_regno' is assigned some values from stack[min_off,
4675  * max_off), we set the register's type according to the types of the
4676  * respective stack slots. If all the stack values are known to be zeros, then
4677  * so is the destination reg. Otherwise, the register is considered to be
4678  * SCALAR. This function does not deal with register filling; the caller must
4679  * ensure that all spilled registers in the stack range have been marked as
4680  * read.
4681  */
4682 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4683 				/* func where src register points to */
4684 				struct bpf_func_state *ptr_state,
4685 				int min_off, int max_off, int dst_regno)
4686 {
4687 	struct bpf_verifier_state *vstate = env->cur_state;
4688 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4689 	int i, slot, spi;
4690 	u8 *stype;
4691 	int zeros = 0;
4692 
4693 	for (i = min_off; i < max_off; i++) {
4694 		slot = -i - 1;
4695 		spi = slot / BPF_REG_SIZE;
4696 		mark_stack_slot_scratched(env, spi);
4697 		stype = ptr_state->stack[spi].slot_type;
4698 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4699 			break;
4700 		zeros++;
4701 	}
4702 	if (zeros == max_off - min_off) {
4703 		/* Any access_size read into register is zero extended,
4704 		 * so the whole register == const_zero.
4705 		 */
4706 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
4707 	} else {
4708 		/* have read misc data from the stack */
4709 		mark_reg_unknown(env, state->regs, dst_regno);
4710 	}
4711 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4712 }
4713 
4714 /* Read the stack at 'off' and put the results into the register indicated by
4715  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4716  * spilled reg.
4717  *
4718  * 'dst_regno' can be -1, meaning that the read value is not going to a
4719  * register.
4720  *
4721  * The access is assumed to be within the current stack bounds.
4722  */
4723 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4724 				      /* func where src register points to */
4725 				      struct bpf_func_state *reg_state,
4726 				      int off, int size, int dst_regno)
4727 {
4728 	struct bpf_verifier_state *vstate = env->cur_state;
4729 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4730 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4731 	struct bpf_reg_state *reg;
4732 	u8 *stype, type;
4733 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
4734 
4735 	stype = reg_state->stack[spi].slot_type;
4736 	reg = &reg_state->stack[spi].spilled_ptr;
4737 
4738 	mark_stack_slot_scratched(env, spi);
4739 
4740 	if (is_spilled_reg(&reg_state->stack[spi])) {
4741 		u8 spill_size = 1;
4742 
4743 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4744 			spill_size++;
4745 
4746 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4747 			if (reg->type != SCALAR_VALUE) {
4748 				verbose_linfo(env, env->insn_idx, "; ");
4749 				verbose(env, "invalid size of register fill\n");
4750 				return -EACCES;
4751 			}
4752 
4753 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4754 			if (dst_regno < 0)
4755 				return 0;
4756 
4757 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4758 				/* The earlier check_reg_arg() has decided the
4759 				 * subreg_def for this insn.  Save it first.
4760 				 */
4761 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4762 
4763 				copy_register_state(&state->regs[dst_regno], reg);
4764 				state->regs[dst_regno].subreg_def = subreg_def;
4765 			} else {
4766 				int spill_cnt = 0, zero_cnt = 0;
4767 
4768 				for (i = 0; i < size; i++) {
4769 					type = stype[(slot - i) % BPF_REG_SIZE];
4770 					if (type == STACK_SPILL) {
4771 						spill_cnt++;
4772 						continue;
4773 					}
4774 					if (type == STACK_MISC)
4775 						continue;
4776 					if (type == STACK_ZERO) {
4777 						zero_cnt++;
4778 						continue;
4779 					}
4780 					if (type == STACK_INVALID && env->allow_uninit_stack)
4781 						continue;
4782 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4783 						off, i, size);
4784 					return -EACCES;
4785 				}
4786 
4787 				if (spill_cnt == size &&
4788 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
4789 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4790 					/* this IS register fill, so keep insn_flags */
4791 				} else if (zero_cnt == size) {
4792 					/* similarly to mark_reg_stack_read(), preserve zeroes */
4793 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4794 					insn_flags = 0; /* not restoring original register state */
4795 				} else {
4796 					mark_reg_unknown(env, state->regs, dst_regno);
4797 					insn_flags = 0; /* not restoring original register state */
4798 				}
4799 			}
4800 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4801 		} else if (dst_regno >= 0) {
4802 			/* restore register state from stack */
4803 			copy_register_state(&state->regs[dst_regno], reg);
4804 			/* mark reg as written since spilled pointer state likely
4805 			 * has its liveness marks cleared by is_state_visited()
4806 			 * which resets stack/reg liveness for state transitions
4807 			 */
4808 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4809 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4810 			/* If dst_regno==-1, the caller is asking us whether
4811 			 * it is acceptable to use this value as a SCALAR_VALUE
4812 			 * (e.g. for XADD).
4813 			 * We must not allow unprivileged callers to do that
4814 			 * with spilled pointers.
4815 			 */
4816 			verbose(env, "leaking pointer from stack off %d\n",
4817 				off);
4818 			return -EACCES;
4819 		}
4820 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4821 	} else {
4822 		for (i = 0; i < size; i++) {
4823 			type = stype[(slot - i) % BPF_REG_SIZE];
4824 			if (type == STACK_MISC)
4825 				continue;
4826 			if (type == STACK_ZERO)
4827 				continue;
4828 			if (type == STACK_INVALID && env->allow_uninit_stack)
4829 				continue;
4830 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4831 				off, i, size);
4832 			return -EACCES;
4833 		}
4834 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4835 		if (dst_regno >= 0)
4836 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4837 		insn_flags = 0; /* we are not restoring spilled register */
4838 	}
4839 	if (insn_flags)
4840 		return push_jmp_history(env, env->cur_state, insn_flags);
4841 	return 0;
4842 }
4843 
4844 enum bpf_access_src {
4845 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4846 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4847 };
4848 
4849 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4850 					 int regno, int off, int access_size,
4851 					 bool zero_size_allowed,
4852 					 enum bpf_access_src type,
4853 					 struct bpf_call_arg_meta *meta);
4854 
4855 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4856 {
4857 	return cur_regs(env) + regno;
4858 }
4859 
4860 /* Read the stack at 'ptr_regno + off' and put the result into the register
4861  * 'dst_regno'.
4862  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4863  * but not its variable offset.
4864  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4865  *
4866  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4867  * filling registers (i.e. reads of spilled register cannot be detected when
4868  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4869  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4870  * offset; for a fixed offset check_stack_read_fixed_off should be used
4871  * instead.
4872  */
4873 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4874 				    int ptr_regno, int off, int size, int dst_regno)
4875 {
4876 	/* The state of the source register. */
4877 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4878 	struct bpf_func_state *ptr_state = func(env, reg);
4879 	int err;
4880 	int min_off, max_off;
4881 
4882 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4883 	 */
4884 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4885 					    false, ACCESS_DIRECT, NULL);
4886 	if (err)
4887 		return err;
4888 
4889 	min_off = reg->smin_value + off;
4890 	max_off = reg->smax_value + off;
4891 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4892 	return 0;
4893 }
4894 
4895 /* check_stack_read dispatches to check_stack_read_fixed_off or
4896  * check_stack_read_var_off.
4897  *
4898  * The caller must ensure that the offset falls within the allocated stack
4899  * bounds.
4900  *
4901  * 'dst_regno' is a register which will receive the value from the stack. It
4902  * can be -1, meaning that the read value is not going to a register.
4903  */
4904 static int check_stack_read(struct bpf_verifier_env *env,
4905 			    int ptr_regno, int off, int size,
4906 			    int dst_regno)
4907 {
4908 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4909 	struct bpf_func_state *state = func(env, reg);
4910 	int err;
4911 	/* Some accesses are only permitted with a static offset. */
4912 	bool var_off = !tnum_is_const(reg->var_off);
4913 
4914 	/* The offset is required to be static when reads don't go to a
4915 	 * register, in order to not leak pointers (see
4916 	 * check_stack_read_fixed_off).
4917 	 */
4918 	if (dst_regno < 0 && var_off) {
4919 		char tn_buf[48];
4920 
4921 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4922 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4923 			tn_buf, off, size);
4924 		return -EACCES;
4925 	}
4926 	/* Variable offset is prohibited for unprivileged mode for simplicity
4927 	 * since it requires corresponding support in Spectre masking for stack
4928 	 * ALU. See also retrieve_ptr_limit(). The check in
4929 	 * check_stack_access_for_ptr_arithmetic() called by
4930 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4931 	 * with variable offsets, therefore no check is required here. Further,
4932 	 * just checking it here would be insufficient as speculative stack
4933 	 * writes could still lead to unsafe speculative behaviour.
4934 	 */
4935 	if (!var_off) {
4936 		off += reg->var_off.value;
4937 		err = check_stack_read_fixed_off(env, state, off, size,
4938 						 dst_regno);
4939 	} else {
4940 		/* Variable offset stack reads need more conservative handling
4941 		 * than fixed offset ones. Note that dst_regno >= 0 on this
4942 		 * branch.
4943 		 */
4944 		err = check_stack_read_var_off(env, ptr_regno, off, size,
4945 					       dst_regno);
4946 	}
4947 	return err;
4948 }
4949 
4950 
4951 /* check_stack_write dispatches to check_stack_write_fixed_off or
4952  * check_stack_write_var_off.
4953  *
4954  * 'ptr_regno' is the register used as a pointer into the stack.
4955  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4956  * 'value_regno' is the register whose value we're writing to the stack. It can
4957  * be -1, meaning that we're not writing from a register.
4958  *
4959  * The caller must ensure that the offset falls within the maximum stack size.
4960  */
4961 static int check_stack_write(struct bpf_verifier_env *env,
4962 			     int ptr_regno, int off, int size,
4963 			     int value_regno, int insn_idx)
4964 {
4965 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4966 	struct bpf_func_state *state = func(env, reg);
4967 	int err;
4968 
4969 	if (tnum_is_const(reg->var_off)) {
4970 		off += reg->var_off.value;
4971 		err = check_stack_write_fixed_off(env, state, off, size,
4972 						  value_regno, insn_idx);
4973 	} else {
4974 		/* Variable offset stack reads need more conservative handling
4975 		 * than fixed offset ones.
4976 		 */
4977 		err = check_stack_write_var_off(env, state,
4978 						ptr_regno, off, size,
4979 						value_regno, insn_idx);
4980 	}
4981 	return err;
4982 }
4983 
4984 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4985 				 int off, int size, enum bpf_access_type type)
4986 {
4987 	struct bpf_reg_state *regs = cur_regs(env);
4988 	struct bpf_map *map = regs[regno].map_ptr;
4989 	u32 cap = bpf_map_flags_to_cap(map);
4990 
4991 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4992 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4993 			map->value_size, off, size);
4994 		return -EACCES;
4995 	}
4996 
4997 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4998 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4999 			map->value_size, off, size);
5000 		return -EACCES;
5001 	}
5002 
5003 	return 0;
5004 }
5005 
5006 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5007 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5008 			      int off, int size, u32 mem_size,
5009 			      bool zero_size_allowed)
5010 {
5011 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5012 	struct bpf_reg_state *reg;
5013 
5014 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5015 		return 0;
5016 
5017 	reg = &cur_regs(env)[regno];
5018 	switch (reg->type) {
5019 	case PTR_TO_MAP_KEY:
5020 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5021 			mem_size, off, size);
5022 		break;
5023 	case PTR_TO_MAP_VALUE:
5024 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5025 			mem_size, off, size);
5026 		break;
5027 	case PTR_TO_PACKET:
5028 	case PTR_TO_PACKET_META:
5029 	case PTR_TO_PACKET_END:
5030 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5031 			off, size, regno, reg->id, off, mem_size);
5032 		break;
5033 	case PTR_TO_MEM:
5034 	default:
5035 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5036 			mem_size, off, size);
5037 	}
5038 
5039 	return -EACCES;
5040 }
5041 
5042 /* check read/write into a memory region with possible variable offset */
5043 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5044 				   int off, int size, u32 mem_size,
5045 				   bool zero_size_allowed)
5046 {
5047 	struct bpf_verifier_state *vstate = env->cur_state;
5048 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5049 	struct bpf_reg_state *reg = &state->regs[regno];
5050 	int err;
5051 
5052 	/* We may have adjusted the register pointing to memory region, so we
5053 	 * need to try adding each of min_value and max_value to off
5054 	 * to make sure our theoretical access will be safe.
5055 	 *
5056 	 * The minimum value is only important with signed
5057 	 * comparisons where we can't assume the floor of a
5058 	 * value is 0.  If we are using signed variables for our
5059 	 * index'es we need to make sure that whatever we use
5060 	 * will have a set floor within our range.
5061 	 */
5062 	if (reg->smin_value < 0 &&
5063 	    (reg->smin_value == S64_MIN ||
5064 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5065 	      reg->smin_value + off < 0)) {
5066 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5067 			regno);
5068 		return -EACCES;
5069 	}
5070 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5071 				 mem_size, zero_size_allowed);
5072 	if (err) {
5073 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5074 			regno);
5075 		return err;
5076 	}
5077 
5078 	/* If we haven't set a max value then we need to bail since we can't be
5079 	 * sure we won't do bad things.
5080 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5081 	 */
5082 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5083 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5084 			regno);
5085 		return -EACCES;
5086 	}
5087 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5088 				 mem_size, zero_size_allowed);
5089 	if (err) {
5090 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5091 			regno);
5092 		return err;
5093 	}
5094 
5095 	return 0;
5096 }
5097 
5098 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5099 			       const struct bpf_reg_state *reg, int regno,
5100 			       bool fixed_off_ok)
5101 {
5102 	/* Access to this pointer-typed register or passing it to a helper
5103 	 * is only allowed in its original, unmodified form.
5104 	 */
5105 
5106 	if (reg->off < 0) {
5107 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5108 			reg_type_str(env, reg->type), regno, reg->off);
5109 		return -EACCES;
5110 	}
5111 
5112 	if (!fixed_off_ok && reg->off) {
5113 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5114 			reg_type_str(env, reg->type), regno, reg->off);
5115 		return -EACCES;
5116 	}
5117 
5118 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5119 		char tn_buf[48];
5120 
5121 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5122 		verbose(env, "variable %s access var_off=%s disallowed\n",
5123 			reg_type_str(env, reg->type), tn_buf);
5124 		return -EACCES;
5125 	}
5126 
5127 	return 0;
5128 }
5129 
5130 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5131 		             const struct bpf_reg_state *reg, int regno)
5132 {
5133 	return __check_ptr_off_reg(env, reg, regno, false);
5134 }
5135 
5136 static int map_kptr_match_type(struct bpf_verifier_env *env,
5137 			       struct btf_field *kptr_field,
5138 			       struct bpf_reg_state *reg, u32 regno)
5139 {
5140 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5141 	int perm_flags;
5142 	const char *reg_name = "";
5143 
5144 	if (btf_is_kernel(reg->btf)) {
5145 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5146 
5147 		/* Only unreferenced case accepts untrusted pointers */
5148 		if (kptr_field->type == BPF_KPTR_UNREF)
5149 			perm_flags |= PTR_UNTRUSTED;
5150 	} else {
5151 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5152 		if (kptr_field->type == BPF_KPTR_PERCPU)
5153 			perm_flags |= MEM_PERCPU;
5154 	}
5155 
5156 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5157 		goto bad_type;
5158 
5159 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5160 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5161 
5162 	/* For ref_ptr case, release function check should ensure we get one
5163 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5164 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5165 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5166 	 * reg->off and reg->ref_obj_id are not needed here.
5167 	 */
5168 	if (__check_ptr_off_reg(env, reg, regno, true))
5169 		return -EACCES;
5170 
5171 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5172 	 * we also need to take into account the reg->off.
5173 	 *
5174 	 * We want to support cases like:
5175 	 *
5176 	 * struct foo {
5177 	 *         struct bar br;
5178 	 *         struct baz bz;
5179 	 * };
5180 	 *
5181 	 * struct foo *v;
5182 	 * v = func();	      // PTR_TO_BTF_ID
5183 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5184 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5185 	 *                    // first member type of struct after comparison fails
5186 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5187 	 *                    // to match type
5188 	 *
5189 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5190 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5191 	 * the struct to match type against first member of struct, i.e. reject
5192 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5193 	 * strict mode to true for type match.
5194 	 */
5195 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5196 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5197 				  kptr_field->type != BPF_KPTR_UNREF))
5198 		goto bad_type;
5199 	return 0;
5200 bad_type:
5201 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5202 		reg_type_str(env, reg->type), reg_name);
5203 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5204 	if (kptr_field->type == BPF_KPTR_UNREF)
5205 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5206 			targ_name);
5207 	else
5208 		verbose(env, "\n");
5209 	return -EINVAL;
5210 }
5211 
5212 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5213  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5214  */
5215 static bool in_rcu_cs(struct bpf_verifier_env *env)
5216 {
5217 	return env->cur_state->active_rcu_lock ||
5218 	       env->cur_state->active_lock.ptr ||
5219 	       !env->prog->aux->sleepable;
5220 }
5221 
5222 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5223 BTF_SET_START(rcu_protected_types)
5224 BTF_ID(struct, prog_test_ref_kfunc)
5225 #ifdef CONFIG_CGROUPS
5226 BTF_ID(struct, cgroup)
5227 #endif
5228 BTF_ID(struct, bpf_cpumask)
5229 BTF_ID(struct, task_struct)
5230 BTF_SET_END(rcu_protected_types)
5231 
5232 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5233 {
5234 	if (!btf_is_kernel(btf))
5235 		return true;
5236 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5237 }
5238 
5239 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5240 {
5241 	struct btf_struct_meta *meta;
5242 
5243 	if (btf_is_kernel(kptr_field->kptr.btf))
5244 		return NULL;
5245 
5246 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5247 				    kptr_field->kptr.btf_id);
5248 
5249 	return meta ? meta->record : NULL;
5250 }
5251 
5252 static bool rcu_safe_kptr(const struct btf_field *field)
5253 {
5254 	const struct btf_field_kptr *kptr = &field->kptr;
5255 
5256 	return field->type == BPF_KPTR_PERCPU ||
5257 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5258 }
5259 
5260 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5261 {
5262 	struct btf_record *rec;
5263 	u32 ret;
5264 
5265 	ret = PTR_MAYBE_NULL;
5266 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5267 		ret |= MEM_RCU;
5268 		if (kptr_field->type == BPF_KPTR_PERCPU)
5269 			ret |= MEM_PERCPU;
5270 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5271 			ret |= MEM_ALLOC;
5272 
5273 		rec = kptr_pointee_btf_record(kptr_field);
5274 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5275 			ret |= NON_OWN_REF;
5276 	} else {
5277 		ret |= PTR_UNTRUSTED;
5278 	}
5279 
5280 	return ret;
5281 }
5282 
5283 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5284 				 int value_regno, int insn_idx,
5285 				 struct btf_field *kptr_field)
5286 {
5287 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5288 	int class = BPF_CLASS(insn->code);
5289 	struct bpf_reg_state *val_reg;
5290 
5291 	/* Things we already checked for in check_map_access and caller:
5292 	 *  - Reject cases where variable offset may touch kptr
5293 	 *  - size of access (must be BPF_DW)
5294 	 *  - tnum_is_const(reg->var_off)
5295 	 *  - kptr_field->offset == off + reg->var_off.value
5296 	 */
5297 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5298 	if (BPF_MODE(insn->code) != BPF_MEM) {
5299 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5300 		return -EACCES;
5301 	}
5302 
5303 	/* We only allow loading referenced kptr, since it will be marked as
5304 	 * untrusted, similar to unreferenced kptr.
5305 	 */
5306 	if (class != BPF_LDX &&
5307 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5308 		verbose(env, "store to referenced kptr disallowed\n");
5309 		return -EACCES;
5310 	}
5311 
5312 	if (class == BPF_LDX) {
5313 		val_reg = reg_state(env, value_regno);
5314 		/* We can simply mark the value_regno receiving the pointer
5315 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5316 		 */
5317 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5318 				kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5319 		/* For mark_ptr_or_null_reg */
5320 		val_reg->id = ++env->id_gen;
5321 	} else if (class == BPF_STX) {
5322 		val_reg = reg_state(env, value_regno);
5323 		if (!register_is_null(val_reg) &&
5324 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5325 			return -EACCES;
5326 	} else if (class == BPF_ST) {
5327 		if (insn->imm) {
5328 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5329 				kptr_field->offset);
5330 			return -EACCES;
5331 		}
5332 	} else {
5333 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5334 		return -EACCES;
5335 	}
5336 	return 0;
5337 }
5338 
5339 /* check read/write into a map element with possible variable offset */
5340 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5341 			    int off, int size, bool zero_size_allowed,
5342 			    enum bpf_access_src src)
5343 {
5344 	struct bpf_verifier_state *vstate = env->cur_state;
5345 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5346 	struct bpf_reg_state *reg = &state->regs[regno];
5347 	struct bpf_map *map = reg->map_ptr;
5348 	struct btf_record *rec;
5349 	int err, i;
5350 
5351 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5352 				      zero_size_allowed);
5353 	if (err)
5354 		return err;
5355 
5356 	if (IS_ERR_OR_NULL(map->record))
5357 		return 0;
5358 	rec = map->record;
5359 	for (i = 0; i < rec->cnt; i++) {
5360 		struct btf_field *field = &rec->fields[i];
5361 		u32 p = field->offset;
5362 
5363 		/* If any part of a field  can be touched by load/store, reject
5364 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5365 		 * it is sufficient to check x1 < y2 && y1 < x2.
5366 		 */
5367 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5368 		    p < reg->umax_value + off + size) {
5369 			switch (field->type) {
5370 			case BPF_KPTR_UNREF:
5371 			case BPF_KPTR_REF:
5372 			case BPF_KPTR_PERCPU:
5373 				if (src != ACCESS_DIRECT) {
5374 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5375 					return -EACCES;
5376 				}
5377 				if (!tnum_is_const(reg->var_off)) {
5378 					verbose(env, "kptr access cannot have variable offset\n");
5379 					return -EACCES;
5380 				}
5381 				if (p != off + reg->var_off.value) {
5382 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5383 						p, off + reg->var_off.value);
5384 					return -EACCES;
5385 				}
5386 				if (size != bpf_size_to_bytes(BPF_DW)) {
5387 					verbose(env, "kptr access size must be BPF_DW\n");
5388 					return -EACCES;
5389 				}
5390 				break;
5391 			default:
5392 				verbose(env, "%s cannot be accessed directly by load/store\n",
5393 					btf_field_type_name(field->type));
5394 				return -EACCES;
5395 			}
5396 		}
5397 	}
5398 	return 0;
5399 }
5400 
5401 #define MAX_PACKET_OFF 0xffff
5402 
5403 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5404 				       const struct bpf_call_arg_meta *meta,
5405 				       enum bpf_access_type t)
5406 {
5407 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5408 
5409 	switch (prog_type) {
5410 	/* Program types only with direct read access go here! */
5411 	case BPF_PROG_TYPE_LWT_IN:
5412 	case BPF_PROG_TYPE_LWT_OUT:
5413 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5414 	case BPF_PROG_TYPE_SK_REUSEPORT:
5415 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5416 	case BPF_PROG_TYPE_CGROUP_SKB:
5417 		if (t == BPF_WRITE)
5418 			return false;
5419 		fallthrough;
5420 
5421 	/* Program types with direct read + write access go here! */
5422 	case BPF_PROG_TYPE_SCHED_CLS:
5423 	case BPF_PROG_TYPE_SCHED_ACT:
5424 	case BPF_PROG_TYPE_XDP:
5425 	case BPF_PROG_TYPE_LWT_XMIT:
5426 	case BPF_PROG_TYPE_SK_SKB:
5427 	case BPF_PROG_TYPE_SK_MSG:
5428 		if (meta)
5429 			return meta->pkt_access;
5430 
5431 		env->seen_direct_write = true;
5432 		return true;
5433 
5434 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5435 		if (t == BPF_WRITE)
5436 			env->seen_direct_write = true;
5437 
5438 		return true;
5439 
5440 	default:
5441 		return false;
5442 	}
5443 }
5444 
5445 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5446 			       int size, bool zero_size_allowed)
5447 {
5448 	struct bpf_reg_state *regs = cur_regs(env);
5449 	struct bpf_reg_state *reg = &regs[regno];
5450 	int err;
5451 
5452 	/* We may have added a variable offset to the packet pointer; but any
5453 	 * reg->range we have comes after that.  We are only checking the fixed
5454 	 * offset.
5455 	 */
5456 
5457 	/* We don't allow negative numbers, because we aren't tracking enough
5458 	 * detail to prove they're safe.
5459 	 */
5460 	if (reg->smin_value < 0) {
5461 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5462 			regno);
5463 		return -EACCES;
5464 	}
5465 
5466 	err = reg->range < 0 ? -EINVAL :
5467 	      __check_mem_access(env, regno, off, size, reg->range,
5468 				 zero_size_allowed);
5469 	if (err) {
5470 		verbose(env, "R%d offset is outside of the packet\n", regno);
5471 		return err;
5472 	}
5473 
5474 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5475 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5476 	 * otherwise find_good_pkt_pointers would have refused to set range info
5477 	 * that __check_mem_access would have rejected this pkt access.
5478 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5479 	 */
5480 	env->prog->aux->max_pkt_offset =
5481 		max_t(u32, env->prog->aux->max_pkt_offset,
5482 		      off + reg->umax_value + size - 1);
5483 
5484 	return err;
5485 }
5486 
5487 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5488 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5489 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5490 			    struct btf **btf, u32 *btf_id)
5491 {
5492 	struct bpf_insn_access_aux info = {
5493 		.reg_type = *reg_type,
5494 		.log = &env->log,
5495 	};
5496 
5497 	if (env->ops->is_valid_access &&
5498 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5499 		/* A non zero info.ctx_field_size indicates that this field is a
5500 		 * candidate for later verifier transformation to load the whole
5501 		 * field and then apply a mask when accessed with a narrower
5502 		 * access than actual ctx access size. A zero info.ctx_field_size
5503 		 * will only allow for whole field access and rejects any other
5504 		 * type of narrower access.
5505 		 */
5506 		*reg_type = info.reg_type;
5507 
5508 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5509 			*btf = info.btf;
5510 			*btf_id = info.btf_id;
5511 		} else {
5512 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5513 		}
5514 		/* remember the offset of last byte accessed in ctx */
5515 		if (env->prog->aux->max_ctx_offset < off + size)
5516 			env->prog->aux->max_ctx_offset = off + size;
5517 		return 0;
5518 	}
5519 
5520 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5521 	return -EACCES;
5522 }
5523 
5524 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5525 				  int size)
5526 {
5527 	if (size < 0 || off < 0 ||
5528 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5529 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5530 			off, size);
5531 		return -EACCES;
5532 	}
5533 	return 0;
5534 }
5535 
5536 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5537 			     u32 regno, int off, int size,
5538 			     enum bpf_access_type t)
5539 {
5540 	struct bpf_reg_state *regs = cur_regs(env);
5541 	struct bpf_reg_state *reg = &regs[regno];
5542 	struct bpf_insn_access_aux info = {};
5543 	bool valid;
5544 
5545 	if (reg->smin_value < 0) {
5546 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5547 			regno);
5548 		return -EACCES;
5549 	}
5550 
5551 	switch (reg->type) {
5552 	case PTR_TO_SOCK_COMMON:
5553 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5554 		break;
5555 	case PTR_TO_SOCKET:
5556 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5557 		break;
5558 	case PTR_TO_TCP_SOCK:
5559 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5560 		break;
5561 	case PTR_TO_XDP_SOCK:
5562 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5563 		break;
5564 	default:
5565 		valid = false;
5566 	}
5567 
5568 
5569 	if (valid) {
5570 		env->insn_aux_data[insn_idx].ctx_field_size =
5571 			info.ctx_field_size;
5572 		return 0;
5573 	}
5574 
5575 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5576 		regno, reg_type_str(env, reg->type), off, size);
5577 
5578 	return -EACCES;
5579 }
5580 
5581 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5582 {
5583 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5584 }
5585 
5586 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5587 {
5588 	const struct bpf_reg_state *reg = reg_state(env, regno);
5589 
5590 	return reg->type == PTR_TO_CTX;
5591 }
5592 
5593 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5594 {
5595 	const struct bpf_reg_state *reg = reg_state(env, regno);
5596 
5597 	return type_is_sk_pointer(reg->type);
5598 }
5599 
5600 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5601 {
5602 	const struct bpf_reg_state *reg = reg_state(env, regno);
5603 
5604 	return type_is_pkt_pointer(reg->type);
5605 }
5606 
5607 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5608 {
5609 	const struct bpf_reg_state *reg = reg_state(env, regno);
5610 
5611 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5612 	return reg->type == PTR_TO_FLOW_KEYS;
5613 }
5614 
5615 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5616 #ifdef CONFIG_NET
5617 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5618 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5619 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5620 #endif
5621 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5622 };
5623 
5624 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5625 {
5626 	/* A referenced register is always trusted. */
5627 	if (reg->ref_obj_id)
5628 		return true;
5629 
5630 	/* Types listed in the reg2btf_ids are always trusted */
5631 	if (reg2btf_ids[base_type(reg->type)])
5632 		return true;
5633 
5634 	/* If a register is not referenced, it is trusted if it has the
5635 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5636 	 * other type modifiers may be safe, but we elect to take an opt-in
5637 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5638 	 * not.
5639 	 *
5640 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5641 	 * for whether a register is trusted.
5642 	 */
5643 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5644 	       !bpf_type_has_unsafe_modifiers(reg->type);
5645 }
5646 
5647 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5648 {
5649 	return reg->type & MEM_RCU;
5650 }
5651 
5652 static void clear_trusted_flags(enum bpf_type_flag *flag)
5653 {
5654 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5655 }
5656 
5657 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5658 				   const struct bpf_reg_state *reg,
5659 				   int off, int size, bool strict)
5660 {
5661 	struct tnum reg_off;
5662 	int ip_align;
5663 
5664 	/* Byte size accesses are always allowed. */
5665 	if (!strict || size == 1)
5666 		return 0;
5667 
5668 	/* For platforms that do not have a Kconfig enabling
5669 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5670 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5671 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5672 	 * to this code only in strict mode where we want to emulate
5673 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5674 	 * unconditional IP align value of '2'.
5675 	 */
5676 	ip_align = 2;
5677 
5678 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5679 	if (!tnum_is_aligned(reg_off, size)) {
5680 		char tn_buf[48];
5681 
5682 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5683 		verbose(env,
5684 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5685 			ip_align, tn_buf, reg->off, off, size);
5686 		return -EACCES;
5687 	}
5688 
5689 	return 0;
5690 }
5691 
5692 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5693 				       const struct bpf_reg_state *reg,
5694 				       const char *pointer_desc,
5695 				       int off, int size, bool strict)
5696 {
5697 	struct tnum reg_off;
5698 
5699 	/* Byte size accesses are always allowed. */
5700 	if (!strict || size == 1)
5701 		return 0;
5702 
5703 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5704 	if (!tnum_is_aligned(reg_off, size)) {
5705 		char tn_buf[48];
5706 
5707 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5708 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5709 			pointer_desc, tn_buf, reg->off, off, size);
5710 		return -EACCES;
5711 	}
5712 
5713 	return 0;
5714 }
5715 
5716 static int check_ptr_alignment(struct bpf_verifier_env *env,
5717 			       const struct bpf_reg_state *reg, int off,
5718 			       int size, bool strict_alignment_once)
5719 {
5720 	bool strict = env->strict_alignment || strict_alignment_once;
5721 	const char *pointer_desc = "";
5722 
5723 	switch (reg->type) {
5724 	case PTR_TO_PACKET:
5725 	case PTR_TO_PACKET_META:
5726 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5727 		 * right in front, treat it the very same way.
5728 		 */
5729 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5730 	case PTR_TO_FLOW_KEYS:
5731 		pointer_desc = "flow keys ";
5732 		break;
5733 	case PTR_TO_MAP_KEY:
5734 		pointer_desc = "key ";
5735 		break;
5736 	case PTR_TO_MAP_VALUE:
5737 		pointer_desc = "value ";
5738 		break;
5739 	case PTR_TO_CTX:
5740 		pointer_desc = "context ";
5741 		break;
5742 	case PTR_TO_STACK:
5743 		pointer_desc = "stack ";
5744 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5745 		 * and check_stack_read_fixed_off() relies on stack accesses being
5746 		 * aligned.
5747 		 */
5748 		strict = true;
5749 		break;
5750 	case PTR_TO_SOCKET:
5751 		pointer_desc = "sock ";
5752 		break;
5753 	case PTR_TO_SOCK_COMMON:
5754 		pointer_desc = "sock_common ";
5755 		break;
5756 	case PTR_TO_TCP_SOCK:
5757 		pointer_desc = "tcp_sock ";
5758 		break;
5759 	case PTR_TO_XDP_SOCK:
5760 		pointer_desc = "xdp_sock ";
5761 		break;
5762 	default:
5763 		break;
5764 	}
5765 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5766 					   strict);
5767 }
5768 
5769 /* starting from main bpf function walk all instructions of the function
5770  * and recursively walk all callees that given function can call.
5771  * Ignore jump and exit insns.
5772  * Since recursion is prevented by check_cfg() this algorithm
5773  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5774  */
5775 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5776 {
5777 	struct bpf_subprog_info *subprog = env->subprog_info;
5778 	struct bpf_insn *insn = env->prog->insnsi;
5779 	int depth = 0, frame = 0, i, subprog_end;
5780 	bool tail_call_reachable = false;
5781 	int ret_insn[MAX_CALL_FRAMES];
5782 	int ret_prog[MAX_CALL_FRAMES];
5783 	int j;
5784 
5785 	i = subprog[idx].start;
5786 process_func:
5787 	/* protect against potential stack overflow that might happen when
5788 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5789 	 * depth for such case down to 256 so that the worst case scenario
5790 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5791 	 * 8k).
5792 	 *
5793 	 * To get the idea what might happen, see an example:
5794 	 * func1 -> sub rsp, 128
5795 	 *  subfunc1 -> sub rsp, 256
5796 	 *  tailcall1 -> add rsp, 256
5797 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5798 	 *   subfunc2 -> sub rsp, 64
5799 	 *   subfunc22 -> sub rsp, 128
5800 	 *   tailcall2 -> add rsp, 128
5801 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5802 	 *
5803 	 * tailcall will unwind the current stack frame but it will not get rid
5804 	 * of caller's stack as shown on the example above.
5805 	 */
5806 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5807 		verbose(env,
5808 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5809 			depth);
5810 		return -EACCES;
5811 	}
5812 	/* round up to 32-bytes, since this is granularity
5813 	 * of interpreter stack size
5814 	 */
5815 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5816 	if (depth > MAX_BPF_STACK) {
5817 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5818 			frame + 1, depth);
5819 		return -EACCES;
5820 	}
5821 continue_func:
5822 	subprog_end = subprog[idx + 1].start;
5823 	for (; i < subprog_end; i++) {
5824 		int next_insn, sidx;
5825 
5826 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
5827 			bool err = false;
5828 
5829 			if (!is_bpf_throw_kfunc(insn + i))
5830 				continue;
5831 			if (subprog[idx].is_cb)
5832 				err = true;
5833 			for (int c = 0; c < frame && !err; c++) {
5834 				if (subprog[ret_prog[c]].is_cb) {
5835 					err = true;
5836 					break;
5837 				}
5838 			}
5839 			if (!err)
5840 				continue;
5841 			verbose(env,
5842 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5843 				i, idx);
5844 			return -EINVAL;
5845 		}
5846 
5847 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5848 			continue;
5849 		/* remember insn and function to return to */
5850 		ret_insn[frame] = i + 1;
5851 		ret_prog[frame] = idx;
5852 
5853 		/* find the callee */
5854 		next_insn = i + insn[i].imm + 1;
5855 		sidx = find_subprog(env, next_insn);
5856 		if (sidx < 0) {
5857 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5858 				  next_insn);
5859 			return -EFAULT;
5860 		}
5861 		if (subprog[sidx].is_async_cb) {
5862 			if (subprog[sidx].has_tail_call) {
5863 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5864 				return -EFAULT;
5865 			}
5866 			/* async callbacks don't increase bpf prog stack size unless called directly */
5867 			if (!bpf_pseudo_call(insn + i))
5868 				continue;
5869 			if (subprog[sidx].is_exception_cb) {
5870 				verbose(env, "insn %d cannot call exception cb directly\n", i);
5871 				return -EINVAL;
5872 			}
5873 		}
5874 		i = next_insn;
5875 		idx = sidx;
5876 
5877 		if (subprog[idx].has_tail_call)
5878 			tail_call_reachable = true;
5879 
5880 		frame++;
5881 		if (frame >= MAX_CALL_FRAMES) {
5882 			verbose(env, "the call stack of %d frames is too deep !\n",
5883 				frame);
5884 			return -E2BIG;
5885 		}
5886 		goto process_func;
5887 	}
5888 	/* if tail call got detected across bpf2bpf calls then mark each of the
5889 	 * currently present subprog frames as tail call reachable subprogs;
5890 	 * this info will be utilized by JIT so that we will be preserving the
5891 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5892 	 */
5893 	if (tail_call_reachable)
5894 		for (j = 0; j < frame; j++) {
5895 			if (subprog[ret_prog[j]].is_exception_cb) {
5896 				verbose(env, "cannot tail call within exception cb\n");
5897 				return -EINVAL;
5898 			}
5899 			subprog[ret_prog[j]].tail_call_reachable = true;
5900 		}
5901 	if (subprog[0].tail_call_reachable)
5902 		env->prog->aux->tail_call_reachable = true;
5903 
5904 	/* end of for() loop means the last insn of the 'subprog'
5905 	 * was reached. Doesn't matter whether it was JA or EXIT
5906 	 */
5907 	if (frame == 0)
5908 		return 0;
5909 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5910 	frame--;
5911 	i = ret_insn[frame];
5912 	idx = ret_prog[frame];
5913 	goto continue_func;
5914 }
5915 
5916 static int check_max_stack_depth(struct bpf_verifier_env *env)
5917 {
5918 	struct bpf_subprog_info *si = env->subprog_info;
5919 	int ret;
5920 
5921 	for (int i = 0; i < env->subprog_cnt; i++) {
5922 		if (!i || si[i].is_async_cb) {
5923 			ret = check_max_stack_depth_subprog(env, i);
5924 			if (ret < 0)
5925 				return ret;
5926 		}
5927 		continue;
5928 	}
5929 	return 0;
5930 }
5931 
5932 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5933 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5934 				  const struct bpf_insn *insn, int idx)
5935 {
5936 	int start = idx + insn->imm + 1, subprog;
5937 
5938 	subprog = find_subprog(env, start);
5939 	if (subprog < 0) {
5940 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5941 			  start);
5942 		return -EFAULT;
5943 	}
5944 	return env->subprog_info[subprog].stack_depth;
5945 }
5946 #endif
5947 
5948 static int __check_buffer_access(struct bpf_verifier_env *env,
5949 				 const char *buf_info,
5950 				 const struct bpf_reg_state *reg,
5951 				 int regno, int off, int size)
5952 {
5953 	if (off < 0) {
5954 		verbose(env,
5955 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5956 			regno, buf_info, off, size);
5957 		return -EACCES;
5958 	}
5959 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5960 		char tn_buf[48];
5961 
5962 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5963 		verbose(env,
5964 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5965 			regno, off, tn_buf);
5966 		return -EACCES;
5967 	}
5968 
5969 	return 0;
5970 }
5971 
5972 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5973 				  const struct bpf_reg_state *reg,
5974 				  int regno, int off, int size)
5975 {
5976 	int err;
5977 
5978 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5979 	if (err)
5980 		return err;
5981 
5982 	if (off + size > env->prog->aux->max_tp_access)
5983 		env->prog->aux->max_tp_access = off + size;
5984 
5985 	return 0;
5986 }
5987 
5988 static int check_buffer_access(struct bpf_verifier_env *env,
5989 			       const struct bpf_reg_state *reg,
5990 			       int regno, int off, int size,
5991 			       bool zero_size_allowed,
5992 			       u32 *max_access)
5993 {
5994 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5995 	int err;
5996 
5997 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5998 	if (err)
5999 		return err;
6000 
6001 	if (off + size > *max_access)
6002 		*max_access = off + size;
6003 
6004 	return 0;
6005 }
6006 
6007 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6008 static void zext_32_to_64(struct bpf_reg_state *reg)
6009 {
6010 	reg->var_off = tnum_subreg(reg->var_off);
6011 	__reg_assign_32_into_64(reg);
6012 }
6013 
6014 /* truncate register to smaller size (in bytes)
6015  * must be called with size < BPF_REG_SIZE
6016  */
6017 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6018 {
6019 	u64 mask;
6020 
6021 	/* clear high bits in bit representation */
6022 	reg->var_off = tnum_cast(reg->var_off, size);
6023 
6024 	/* fix arithmetic bounds */
6025 	mask = ((u64)1 << (size * 8)) - 1;
6026 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6027 		reg->umin_value &= mask;
6028 		reg->umax_value &= mask;
6029 	} else {
6030 		reg->umin_value = 0;
6031 		reg->umax_value = mask;
6032 	}
6033 	reg->smin_value = reg->umin_value;
6034 	reg->smax_value = reg->umax_value;
6035 
6036 	/* If size is smaller than 32bit register the 32bit register
6037 	 * values are also truncated so we push 64-bit bounds into
6038 	 * 32-bit bounds. Above were truncated < 32-bits already.
6039 	 */
6040 	if (size < 4) {
6041 		__mark_reg32_unbounded(reg);
6042 		reg_bounds_sync(reg);
6043 	}
6044 }
6045 
6046 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6047 {
6048 	if (size == 1) {
6049 		reg->smin_value = reg->s32_min_value = S8_MIN;
6050 		reg->smax_value = reg->s32_max_value = S8_MAX;
6051 	} else if (size == 2) {
6052 		reg->smin_value = reg->s32_min_value = S16_MIN;
6053 		reg->smax_value = reg->s32_max_value = S16_MAX;
6054 	} else {
6055 		/* size == 4 */
6056 		reg->smin_value = reg->s32_min_value = S32_MIN;
6057 		reg->smax_value = reg->s32_max_value = S32_MAX;
6058 	}
6059 	reg->umin_value = reg->u32_min_value = 0;
6060 	reg->umax_value = U64_MAX;
6061 	reg->u32_max_value = U32_MAX;
6062 	reg->var_off = tnum_unknown;
6063 }
6064 
6065 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6066 {
6067 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6068 	u64 top_smax_value, top_smin_value;
6069 	u64 num_bits = size * 8;
6070 
6071 	if (tnum_is_const(reg->var_off)) {
6072 		u64_cval = reg->var_off.value;
6073 		if (size == 1)
6074 			reg->var_off = tnum_const((s8)u64_cval);
6075 		else if (size == 2)
6076 			reg->var_off = tnum_const((s16)u64_cval);
6077 		else
6078 			/* size == 4 */
6079 			reg->var_off = tnum_const((s32)u64_cval);
6080 
6081 		u64_cval = reg->var_off.value;
6082 		reg->smax_value = reg->smin_value = u64_cval;
6083 		reg->umax_value = reg->umin_value = u64_cval;
6084 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6085 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6086 		return;
6087 	}
6088 
6089 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6090 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6091 
6092 	if (top_smax_value != top_smin_value)
6093 		goto out;
6094 
6095 	/* find the s64_min and s64_min after sign extension */
6096 	if (size == 1) {
6097 		init_s64_max = (s8)reg->smax_value;
6098 		init_s64_min = (s8)reg->smin_value;
6099 	} else if (size == 2) {
6100 		init_s64_max = (s16)reg->smax_value;
6101 		init_s64_min = (s16)reg->smin_value;
6102 	} else {
6103 		init_s64_max = (s32)reg->smax_value;
6104 		init_s64_min = (s32)reg->smin_value;
6105 	}
6106 
6107 	s64_max = max(init_s64_max, init_s64_min);
6108 	s64_min = min(init_s64_max, init_s64_min);
6109 
6110 	/* both of s64_max/s64_min positive or negative */
6111 	if ((s64_max >= 0) == (s64_min >= 0)) {
6112 		reg->smin_value = reg->s32_min_value = s64_min;
6113 		reg->smax_value = reg->s32_max_value = s64_max;
6114 		reg->umin_value = reg->u32_min_value = s64_min;
6115 		reg->umax_value = reg->u32_max_value = s64_max;
6116 		reg->var_off = tnum_range(s64_min, s64_max);
6117 		return;
6118 	}
6119 
6120 out:
6121 	set_sext64_default_val(reg, size);
6122 }
6123 
6124 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6125 {
6126 	if (size == 1) {
6127 		reg->s32_min_value = S8_MIN;
6128 		reg->s32_max_value = S8_MAX;
6129 	} else {
6130 		/* size == 2 */
6131 		reg->s32_min_value = S16_MIN;
6132 		reg->s32_max_value = S16_MAX;
6133 	}
6134 	reg->u32_min_value = 0;
6135 	reg->u32_max_value = U32_MAX;
6136 }
6137 
6138 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6139 {
6140 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6141 	u32 top_smax_value, top_smin_value;
6142 	u32 num_bits = size * 8;
6143 
6144 	if (tnum_is_const(reg->var_off)) {
6145 		u32_val = reg->var_off.value;
6146 		if (size == 1)
6147 			reg->var_off = tnum_const((s8)u32_val);
6148 		else
6149 			reg->var_off = tnum_const((s16)u32_val);
6150 
6151 		u32_val = reg->var_off.value;
6152 		reg->s32_min_value = reg->s32_max_value = u32_val;
6153 		reg->u32_min_value = reg->u32_max_value = u32_val;
6154 		return;
6155 	}
6156 
6157 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6158 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6159 
6160 	if (top_smax_value != top_smin_value)
6161 		goto out;
6162 
6163 	/* find the s32_min and s32_min after sign extension */
6164 	if (size == 1) {
6165 		init_s32_max = (s8)reg->s32_max_value;
6166 		init_s32_min = (s8)reg->s32_min_value;
6167 	} else {
6168 		/* size == 2 */
6169 		init_s32_max = (s16)reg->s32_max_value;
6170 		init_s32_min = (s16)reg->s32_min_value;
6171 	}
6172 	s32_max = max(init_s32_max, init_s32_min);
6173 	s32_min = min(init_s32_max, init_s32_min);
6174 
6175 	if ((s32_min >= 0) == (s32_max >= 0)) {
6176 		reg->s32_min_value = s32_min;
6177 		reg->s32_max_value = s32_max;
6178 		reg->u32_min_value = (u32)s32_min;
6179 		reg->u32_max_value = (u32)s32_max;
6180 		return;
6181 	}
6182 
6183 out:
6184 	set_sext32_default_val(reg, size);
6185 }
6186 
6187 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6188 {
6189 	/* A map is considered read-only if the following condition are true:
6190 	 *
6191 	 * 1) BPF program side cannot change any of the map content. The
6192 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6193 	 *    and was set at map creation time.
6194 	 * 2) The map value(s) have been initialized from user space by a
6195 	 *    loader and then "frozen", such that no new map update/delete
6196 	 *    operations from syscall side are possible for the rest of
6197 	 *    the map's lifetime from that point onwards.
6198 	 * 3) Any parallel/pending map update/delete operations from syscall
6199 	 *    side have been completed. Only after that point, it's safe to
6200 	 *    assume that map value(s) are immutable.
6201 	 */
6202 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6203 	       READ_ONCE(map->frozen) &&
6204 	       !bpf_map_write_active(map);
6205 }
6206 
6207 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6208 			       bool is_ldsx)
6209 {
6210 	void *ptr;
6211 	u64 addr;
6212 	int err;
6213 
6214 	err = map->ops->map_direct_value_addr(map, &addr, off);
6215 	if (err)
6216 		return err;
6217 	ptr = (void *)(long)addr + off;
6218 
6219 	switch (size) {
6220 	case sizeof(u8):
6221 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6222 		break;
6223 	case sizeof(u16):
6224 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6225 		break;
6226 	case sizeof(u32):
6227 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6228 		break;
6229 	case sizeof(u64):
6230 		*val = *(u64 *)ptr;
6231 		break;
6232 	default:
6233 		return -EINVAL;
6234 	}
6235 	return 0;
6236 }
6237 
6238 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6239 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6240 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6241 
6242 /*
6243  * Allow list few fields as RCU trusted or full trusted.
6244  * This logic doesn't allow mix tagging and will be removed once GCC supports
6245  * btf_type_tag.
6246  */
6247 
6248 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6249 BTF_TYPE_SAFE_RCU(struct task_struct) {
6250 	const cpumask_t *cpus_ptr;
6251 	struct css_set __rcu *cgroups;
6252 	struct task_struct __rcu *real_parent;
6253 	struct task_struct *group_leader;
6254 };
6255 
6256 BTF_TYPE_SAFE_RCU(struct cgroup) {
6257 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6258 	struct kernfs_node *kn;
6259 };
6260 
6261 BTF_TYPE_SAFE_RCU(struct css_set) {
6262 	struct cgroup *dfl_cgrp;
6263 };
6264 
6265 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6266 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6267 	struct file __rcu *exe_file;
6268 };
6269 
6270 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6271  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6272  */
6273 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6274 	struct sock *sk;
6275 };
6276 
6277 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6278 	struct sock *sk;
6279 };
6280 
6281 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6282 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6283 	struct seq_file *seq;
6284 };
6285 
6286 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6287 	struct bpf_iter_meta *meta;
6288 	struct task_struct *task;
6289 };
6290 
6291 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6292 	struct file *file;
6293 };
6294 
6295 BTF_TYPE_SAFE_TRUSTED(struct file) {
6296 	struct inode *f_inode;
6297 };
6298 
6299 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6300 	/* no negative dentry-s in places where bpf can see it */
6301 	struct inode *d_inode;
6302 };
6303 
6304 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6305 	struct sock *sk;
6306 };
6307 
6308 static bool type_is_rcu(struct bpf_verifier_env *env,
6309 			struct bpf_reg_state *reg,
6310 			const char *field_name, u32 btf_id)
6311 {
6312 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6313 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6314 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6315 
6316 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6317 }
6318 
6319 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6320 				struct bpf_reg_state *reg,
6321 				const char *field_name, u32 btf_id)
6322 {
6323 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6324 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6325 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6326 
6327 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6328 }
6329 
6330 static bool type_is_trusted(struct bpf_verifier_env *env,
6331 			    struct bpf_reg_state *reg,
6332 			    const char *field_name, u32 btf_id)
6333 {
6334 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6335 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6336 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6337 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6338 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6339 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6340 
6341 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6342 }
6343 
6344 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6345 				   struct bpf_reg_state *regs,
6346 				   int regno, int off, int size,
6347 				   enum bpf_access_type atype,
6348 				   int value_regno)
6349 {
6350 	struct bpf_reg_state *reg = regs + regno;
6351 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6352 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6353 	const char *field_name = NULL;
6354 	enum bpf_type_flag flag = 0;
6355 	u32 btf_id = 0;
6356 	int ret;
6357 
6358 	if (!env->allow_ptr_leaks) {
6359 		verbose(env,
6360 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6361 			tname);
6362 		return -EPERM;
6363 	}
6364 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6365 		verbose(env,
6366 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6367 			tname);
6368 		return -EINVAL;
6369 	}
6370 	if (off < 0) {
6371 		verbose(env,
6372 			"R%d is ptr_%s invalid negative access: off=%d\n",
6373 			regno, tname, off);
6374 		return -EACCES;
6375 	}
6376 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6377 		char tn_buf[48];
6378 
6379 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6380 		verbose(env,
6381 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6382 			regno, tname, off, tn_buf);
6383 		return -EACCES;
6384 	}
6385 
6386 	if (reg->type & MEM_USER) {
6387 		verbose(env,
6388 			"R%d is ptr_%s access user memory: off=%d\n",
6389 			regno, tname, off);
6390 		return -EACCES;
6391 	}
6392 
6393 	if (reg->type & MEM_PERCPU) {
6394 		verbose(env,
6395 			"R%d is ptr_%s access percpu memory: off=%d\n",
6396 			regno, tname, off);
6397 		return -EACCES;
6398 	}
6399 
6400 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6401 		if (!btf_is_kernel(reg->btf)) {
6402 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6403 			return -EFAULT;
6404 		}
6405 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6406 	} else {
6407 		/* Writes are permitted with default btf_struct_access for
6408 		 * program allocated objects (which always have ref_obj_id > 0),
6409 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6410 		 */
6411 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6412 			verbose(env, "only read is supported\n");
6413 			return -EACCES;
6414 		}
6415 
6416 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6417 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
6418 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6419 			return -EFAULT;
6420 		}
6421 
6422 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6423 	}
6424 
6425 	if (ret < 0)
6426 		return ret;
6427 
6428 	if (ret != PTR_TO_BTF_ID) {
6429 		/* just mark; */
6430 
6431 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6432 		/* If this is an untrusted pointer, all pointers formed by walking it
6433 		 * also inherit the untrusted flag.
6434 		 */
6435 		flag = PTR_UNTRUSTED;
6436 
6437 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6438 		/* By default any pointer obtained from walking a trusted pointer is no
6439 		 * longer trusted, unless the field being accessed has explicitly been
6440 		 * marked as inheriting its parent's state of trust (either full or RCU).
6441 		 * For example:
6442 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6443 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6444 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6445 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6446 		 *
6447 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6448 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6449 		 */
6450 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6451 			flag |= PTR_TRUSTED;
6452 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6453 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6454 				/* ignore __rcu tag and mark it MEM_RCU */
6455 				flag |= MEM_RCU;
6456 			} else if (flag & MEM_RCU ||
6457 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6458 				/* __rcu tagged pointers can be NULL */
6459 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6460 
6461 				/* We always trust them */
6462 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6463 				    flag & PTR_UNTRUSTED)
6464 					flag &= ~PTR_UNTRUSTED;
6465 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6466 				/* keep as-is */
6467 			} else {
6468 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6469 				clear_trusted_flags(&flag);
6470 			}
6471 		} else {
6472 			/*
6473 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6474 			 * aggressively mark as untrusted otherwise such
6475 			 * pointers will be plain PTR_TO_BTF_ID without flags
6476 			 * and will be allowed to be passed into helpers for
6477 			 * compat reasons.
6478 			 */
6479 			flag = PTR_UNTRUSTED;
6480 		}
6481 	} else {
6482 		/* Old compat. Deprecated */
6483 		clear_trusted_flags(&flag);
6484 	}
6485 
6486 	if (atype == BPF_READ && value_regno >= 0)
6487 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6488 
6489 	return 0;
6490 }
6491 
6492 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6493 				   struct bpf_reg_state *regs,
6494 				   int regno, int off, int size,
6495 				   enum bpf_access_type atype,
6496 				   int value_regno)
6497 {
6498 	struct bpf_reg_state *reg = regs + regno;
6499 	struct bpf_map *map = reg->map_ptr;
6500 	struct bpf_reg_state map_reg;
6501 	enum bpf_type_flag flag = 0;
6502 	const struct btf_type *t;
6503 	const char *tname;
6504 	u32 btf_id;
6505 	int ret;
6506 
6507 	if (!btf_vmlinux) {
6508 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6509 		return -ENOTSUPP;
6510 	}
6511 
6512 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6513 		verbose(env, "map_ptr access not supported for map type %d\n",
6514 			map->map_type);
6515 		return -ENOTSUPP;
6516 	}
6517 
6518 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6519 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6520 
6521 	if (!env->allow_ptr_leaks) {
6522 		verbose(env,
6523 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6524 			tname);
6525 		return -EPERM;
6526 	}
6527 
6528 	if (off < 0) {
6529 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6530 			regno, tname, off);
6531 		return -EACCES;
6532 	}
6533 
6534 	if (atype != BPF_READ) {
6535 		verbose(env, "only read from %s is supported\n", tname);
6536 		return -EACCES;
6537 	}
6538 
6539 	/* Simulate access to a PTR_TO_BTF_ID */
6540 	memset(&map_reg, 0, sizeof(map_reg));
6541 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6542 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6543 	if (ret < 0)
6544 		return ret;
6545 
6546 	if (value_regno >= 0)
6547 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6548 
6549 	return 0;
6550 }
6551 
6552 /* Check that the stack access at the given offset is within bounds. The
6553  * maximum valid offset is -1.
6554  *
6555  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6556  * -state->allocated_stack for reads.
6557  */
6558 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6559                                           s64 off,
6560                                           struct bpf_func_state *state,
6561                                           enum bpf_access_type t)
6562 {
6563 	int min_valid_off;
6564 
6565 	if (t == BPF_WRITE || env->allow_uninit_stack)
6566 		min_valid_off = -MAX_BPF_STACK;
6567 	else
6568 		min_valid_off = -state->allocated_stack;
6569 
6570 	if (off < min_valid_off || off > -1)
6571 		return -EACCES;
6572 	return 0;
6573 }
6574 
6575 /* Check that the stack access at 'regno + off' falls within the maximum stack
6576  * bounds.
6577  *
6578  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6579  */
6580 static int check_stack_access_within_bounds(
6581 		struct bpf_verifier_env *env,
6582 		int regno, int off, int access_size,
6583 		enum bpf_access_src src, enum bpf_access_type type)
6584 {
6585 	struct bpf_reg_state *regs = cur_regs(env);
6586 	struct bpf_reg_state *reg = regs + regno;
6587 	struct bpf_func_state *state = func(env, reg);
6588 	s64 min_off, max_off;
6589 	int err;
6590 	char *err_extra;
6591 
6592 	if (src == ACCESS_HELPER)
6593 		/* We don't know if helpers are reading or writing (or both). */
6594 		err_extra = " indirect access to";
6595 	else if (type == BPF_READ)
6596 		err_extra = " read from";
6597 	else
6598 		err_extra = " write to";
6599 
6600 	if (tnum_is_const(reg->var_off)) {
6601 		min_off = (s64)reg->var_off.value + off;
6602 		max_off = min_off + access_size;
6603 	} else {
6604 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6605 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6606 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6607 				err_extra, regno);
6608 			return -EACCES;
6609 		}
6610 		min_off = reg->smin_value + off;
6611 		max_off = reg->smax_value + off + access_size;
6612 	}
6613 
6614 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6615 	if (!err && max_off > 0)
6616 		err = -EINVAL; /* out of stack access into non-negative offsets */
6617 
6618 	if (err) {
6619 		if (tnum_is_const(reg->var_off)) {
6620 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6621 				err_extra, regno, off, access_size);
6622 		} else {
6623 			char tn_buf[48];
6624 
6625 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6626 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
6627 				err_extra, regno, tn_buf, off, access_size);
6628 		}
6629 		return err;
6630 	}
6631 
6632 	/* Note that there is no stack access with offset zero, so the needed stack
6633 	 * size is -min_off, not -min_off+1.
6634 	 */
6635 	return grow_stack_state(env, state, -min_off /* size */);
6636 }
6637 
6638 /* check whether memory at (regno + off) is accessible for t = (read | write)
6639  * if t==write, value_regno is a register which value is stored into memory
6640  * if t==read, value_regno is a register which will receive the value from memory
6641  * if t==write && value_regno==-1, some unknown value is stored into memory
6642  * if t==read && value_regno==-1, don't care what we read from memory
6643  */
6644 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6645 			    int off, int bpf_size, enum bpf_access_type t,
6646 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6647 {
6648 	struct bpf_reg_state *regs = cur_regs(env);
6649 	struct bpf_reg_state *reg = regs + regno;
6650 	int size, err = 0;
6651 
6652 	size = bpf_size_to_bytes(bpf_size);
6653 	if (size < 0)
6654 		return size;
6655 
6656 	/* alignment checks will add in reg->off themselves */
6657 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6658 	if (err)
6659 		return err;
6660 
6661 	/* for access checks, reg->off is just part of off */
6662 	off += reg->off;
6663 
6664 	if (reg->type == PTR_TO_MAP_KEY) {
6665 		if (t == BPF_WRITE) {
6666 			verbose(env, "write to change key R%d not allowed\n", regno);
6667 			return -EACCES;
6668 		}
6669 
6670 		err = check_mem_region_access(env, regno, off, size,
6671 					      reg->map_ptr->key_size, false);
6672 		if (err)
6673 			return err;
6674 		if (value_regno >= 0)
6675 			mark_reg_unknown(env, regs, value_regno);
6676 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6677 		struct btf_field *kptr_field = NULL;
6678 
6679 		if (t == BPF_WRITE && value_regno >= 0 &&
6680 		    is_pointer_value(env, value_regno)) {
6681 			verbose(env, "R%d leaks addr into map\n", value_regno);
6682 			return -EACCES;
6683 		}
6684 		err = check_map_access_type(env, regno, off, size, t);
6685 		if (err)
6686 			return err;
6687 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6688 		if (err)
6689 			return err;
6690 		if (tnum_is_const(reg->var_off))
6691 			kptr_field = btf_record_find(reg->map_ptr->record,
6692 						     off + reg->var_off.value, BPF_KPTR);
6693 		if (kptr_field) {
6694 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6695 		} else if (t == BPF_READ && value_regno >= 0) {
6696 			struct bpf_map *map = reg->map_ptr;
6697 
6698 			/* if map is read-only, track its contents as scalars */
6699 			if (tnum_is_const(reg->var_off) &&
6700 			    bpf_map_is_rdonly(map) &&
6701 			    map->ops->map_direct_value_addr) {
6702 				int map_off = off + reg->var_off.value;
6703 				u64 val = 0;
6704 
6705 				err = bpf_map_direct_read(map, map_off, size,
6706 							  &val, is_ldsx);
6707 				if (err)
6708 					return err;
6709 
6710 				regs[value_regno].type = SCALAR_VALUE;
6711 				__mark_reg_known(&regs[value_regno], val);
6712 			} else {
6713 				mark_reg_unknown(env, regs, value_regno);
6714 			}
6715 		}
6716 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6717 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6718 
6719 		if (type_may_be_null(reg->type)) {
6720 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6721 				reg_type_str(env, reg->type));
6722 			return -EACCES;
6723 		}
6724 
6725 		if (t == BPF_WRITE && rdonly_mem) {
6726 			verbose(env, "R%d cannot write into %s\n",
6727 				regno, reg_type_str(env, reg->type));
6728 			return -EACCES;
6729 		}
6730 
6731 		if (t == BPF_WRITE && value_regno >= 0 &&
6732 		    is_pointer_value(env, value_regno)) {
6733 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6734 			return -EACCES;
6735 		}
6736 
6737 		err = check_mem_region_access(env, regno, off, size,
6738 					      reg->mem_size, false);
6739 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6740 			mark_reg_unknown(env, regs, value_regno);
6741 	} else if (reg->type == PTR_TO_CTX) {
6742 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6743 		struct btf *btf = NULL;
6744 		u32 btf_id = 0;
6745 
6746 		if (t == BPF_WRITE && value_regno >= 0 &&
6747 		    is_pointer_value(env, value_regno)) {
6748 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6749 			return -EACCES;
6750 		}
6751 
6752 		err = check_ptr_off_reg(env, reg, regno);
6753 		if (err < 0)
6754 			return err;
6755 
6756 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6757 				       &btf_id);
6758 		if (err)
6759 			verbose_linfo(env, insn_idx, "; ");
6760 		if (!err && t == BPF_READ && value_regno >= 0) {
6761 			/* ctx access returns either a scalar, or a
6762 			 * PTR_TO_PACKET[_META,_END]. In the latter
6763 			 * case, we know the offset is zero.
6764 			 */
6765 			if (reg_type == SCALAR_VALUE) {
6766 				mark_reg_unknown(env, regs, value_regno);
6767 			} else {
6768 				mark_reg_known_zero(env, regs,
6769 						    value_regno);
6770 				if (type_may_be_null(reg_type))
6771 					regs[value_regno].id = ++env->id_gen;
6772 				/* A load of ctx field could have different
6773 				 * actual load size with the one encoded in the
6774 				 * insn. When the dst is PTR, it is for sure not
6775 				 * a sub-register.
6776 				 */
6777 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6778 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6779 					regs[value_regno].btf = btf;
6780 					regs[value_regno].btf_id = btf_id;
6781 				}
6782 			}
6783 			regs[value_regno].type = reg_type;
6784 		}
6785 
6786 	} else if (reg->type == PTR_TO_STACK) {
6787 		/* Basic bounds checks. */
6788 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6789 		if (err)
6790 			return err;
6791 
6792 		if (t == BPF_READ)
6793 			err = check_stack_read(env, regno, off, size,
6794 					       value_regno);
6795 		else
6796 			err = check_stack_write(env, regno, off, size,
6797 						value_regno, insn_idx);
6798 	} else if (reg_is_pkt_pointer(reg)) {
6799 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6800 			verbose(env, "cannot write into packet\n");
6801 			return -EACCES;
6802 		}
6803 		if (t == BPF_WRITE && value_regno >= 0 &&
6804 		    is_pointer_value(env, value_regno)) {
6805 			verbose(env, "R%d leaks addr into packet\n",
6806 				value_regno);
6807 			return -EACCES;
6808 		}
6809 		err = check_packet_access(env, regno, off, size, false);
6810 		if (!err && t == BPF_READ && value_regno >= 0)
6811 			mark_reg_unknown(env, regs, value_regno);
6812 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6813 		if (t == BPF_WRITE && value_regno >= 0 &&
6814 		    is_pointer_value(env, value_regno)) {
6815 			verbose(env, "R%d leaks addr into flow keys\n",
6816 				value_regno);
6817 			return -EACCES;
6818 		}
6819 
6820 		err = check_flow_keys_access(env, off, size);
6821 		if (!err && t == BPF_READ && value_regno >= 0)
6822 			mark_reg_unknown(env, regs, value_regno);
6823 	} else if (type_is_sk_pointer(reg->type)) {
6824 		if (t == BPF_WRITE) {
6825 			verbose(env, "R%d cannot write into %s\n",
6826 				regno, reg_type_str(env, reg->type));
6827 			return -EACCES;
6828 		}
6829 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6830 		if (!err && value_regno >= 0)
6831 			mark_reg_unknown(env, regs, value_regno);
6832 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6833 		err = check_tp_buffer_access(env, reg, regno, off, size);
6834 		if (!err && t == BPF_READ && value_regno >= 0)
6835 			mark_reg_unknown(env, regs, value_regno);
6836 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6837 		   !type_may_be_null(reg->type)) {
6838 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6839 					      value_regno);
6840 	} else if (reg->type == CONST_PTR_TO_MAP) {
6841 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6842 					      value_regno);
6843 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6844 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6845 		u32 *max_access;
6846 
6847 		if (rdonly_mem) {
6848 			if (t == BPF_WRITE) {
6849 				verbose(env, "R%d cannot write into %s\n",
6850 					regno, reg_type_str(env, reg->type));
6851 				return -EACCES;
6852 			}
6853 			max_access = &env->prog->aux->max_rdonly_access;
6854 		} else {
6855 			max_access = &env->prog->aux->max_rdwr_access;
6856 		}
6857 
6858 		err = check_buffer_access(env, reg, regno, off, size, false,
6859 					  max_access);
6860 
6861 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6862 			mark_reg_unknown(env, regs, value_regno);
6863 	} else {
6864 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6865 			reg_type_str(env, reg->type));
6866 		return -EACCES;
6867 	}
6868 
6869 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6870 	    regs[value_regno].type == SCALAR_VALUE) {
6871 		if (!is_ldsx)
6872 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6873 			coerce_reg_to_size(&regs[value_regno], size);
6874 		else
6875 			coerce_reg_to_size_sx(&regs[value_regno], size);
6876 	}
6877 	return err;
6878 }
6879 
6880 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6881 {
6882 	int load_reg;
6883 	int err;
6884 
6885 	switch (insn->imm) {
6886 	case BPF_ADD:
6887 	case BPF_ADD | BPF_FETCH:
6888 	case BPF_AND:
6889 	case BPF_AND | BPF_FETCH:
6890 	case BPF_OR:
6891 	case BPF_OR | BPF_FETCH:
6892 	case BPF_XOR:
6893 	case BPF_XOR | BPF_FETCH:
6894 	case BPF_XCHG:
6895 	case BPF_CMPXCHG:
6896 		break;
6897 	default:
6898 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6899 		return -EINVAL;
6900 	}
6901 
6902 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6903 		verbose(env, "invalid atomic operand size\n");
6904 		return -EINVAL;
6905 	}
6906 
6907 	/* check src1 operand */
6908 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6909 	if (err)
6910 		return err;
6911 
6912 	/* check src2 operand */
6913 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6914 	if (err)
6915 		return err;
6916 
6917 	if (insn->imm == BPF_CMPXCHG) {
6918 		/* Check comparison of R0 with memory location */
6919 		const u32 aux_reg = BPF_REG_0;
6920 
6921 		err = check_reg_arg(env, aux_reg, SRC_OP);
6922 		if (err)
6923 			return err;
6924 
6925 		if (is_pointer_value(env, aux_reg)) {
6926 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6927 			return -EACCES;
6928 		}
6929 	}
6930 
6931 	if (is_pointer_value(env, insn->src_reg)) {
6932 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6933 		return -EACCES;
6934 	}
6935 
6936 	if (is_ctx_reg(env, insn->dst_reg) ||
6937 	    is_pkt_reg(env, insn->dst_reg) ||
6938 	    is_flow_key_reg(env, insn->dst_reg) ||
6939 	    is_sk_reg(env, insn->dst_reg)) {
6940 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6941 			insn->dst_reg,
6942 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6943 		return -EACCES;
6944 	}
6945 
6946 	if (insn->imm & BPF_FETCH) {
6947 		if (insn->imm == BPF_CMPXCHG)
6948 			load_reg = BPF_REG_0;
6949 		else
6950 			load_reg = insn->src_reg;
6951 
6952 		/* check and record load of old value */
6953 		err = check_reg_arg(env, load_reg, DST_OP);
6954 		if (err)
6955 			return err;
6956 	} else {
6957 		/* This instruction accesses a memory location but doesn't
6958 		 * actually load it into a register.
6959 		 */
6960 		load_reg = -1;
6961 	}
6962 
6963 	/* Check whether we can read the memory, with second call for fetch
6964 	 * case to simulate the register fill.
6965 	 */
6966 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6967 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6968 	if (!err && load_reg >= 0)
6969 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6970 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
6971 				       true, false);
6972 	if (err)
6973 		return err;
6974 
6975 	/* Check whether we can write into the same memory. */
6976 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6977 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6978 	if (err)
6979 		return err;
6980 	return 0;
6981 }
6982 
6983 /* When register 'regno' is used to read the stack (either directly or through
6984  * a helper function) make sure that it's within stack boundary and, depending
6985  * on the access type and privileges, that all elements of the stack are
6986  * initialized.
6987  *
6988  * 'off' includes 'regno->off', but not its dynamic part (if any).
6989  *
6990  * All registers that have been spilled on the stack in the slots within the
6991  * read offsets are marked as read.
6992  */
6993 static int check_stack_range_initialized(
6994 		struct bpf_verifier_env *env, int regno, int off,
6995 		int access_size, bool zero_size_allowed,
6996 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6997 {
6998 	struct bpf_reg_state *reg = reg_state(env, regno);
6999 	struct bpf_func_state *state = func(env, reg);
7000 	int err, min_off, max_off, i, j, slot, spi;
7001 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7002 	enum bpf_access_type bounds_check_type;
7003 	/* Some accesses can write anything into the stack, others are
7004 	 * read-only.
7005 	 */
7006 	bool clobber = false;
7007 
7008 	if (access_size == 0 && !zero_size_allowed) {
7009 		verbose(env, "invalid zero-sized read\n");
7010 		return -EACCES;
7011 	}
7012 
7013 	if (type == ACCESS_HELPER) {
7014 		/* The bounds checks for writes are more permissive than for
7015 		 * reads. However, if raw_mode is not set, we'll do extra
7016 		 * checks below.
7017 		 */
7018 		bounds_check_type = BPF_WRITE;
7019 		clobber = true;
7020 	} else {
7021 		bounds_check_type = BPF_READ;
7022 	}
7023 	err = check_stack_access_within_bounds(env, regno, off, access_size,
7024 					       type, bounds_check_type);
7025 	if (err)
7026 		return err;
7027 
7028 
7029 	if (tnum_is_const(reg->var_off)) {
7030 		min_off = max_off = reg->var_off.value + off;
7031 	} else {
7032 		/* Variable offset is prohibited for unprivileged mode for
7033 		 * simplicity since it requires corresponding support in
7034 		 * Spectre masking for stack ALU.
7035 		 * See also retrieve_ptr_limit().
7036 		 */
7037 		if (!env->bypass_spec_v1) {
7038 			char tn_buf[48];
7039 
7040 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7041 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7042 				regno, err_extra, tn_buf);
7043 			return -EACCES;
7044 		}
7045 		/* Only initialized buffer on stack is allowed to be accessed
7046 		 * with variable offset. With uninitialized buffer it's hard to
7047 		 * guarantee that whole memory is marked as initialized on
7048 		 * helper return since specific bounds are unknown what may
7049 		 * cause uninitialized stack leaking.
7050 		 */
7051 		if (meta && meta->raw_mode)
7052 			meta = NULL;
7053 
7054 		min_off = reg->smin_value + off;
7055 		max_off = reg->smax_value + off;
7056 	}
7057 
7058 	if (meta && meta->raw_mode) {
7059 		/* Ensure we won't be overwriting dynptrs when simulating byte
7060 		 * by byte access in check_helper_call using meta.access_size.
7061 		 * This would be a problem if we have a helper in the future
7062 		 * which takes:
7063 		 *
7064 		 *	helper(uninit_mem, len, dynptr)
7065 		 *
7066 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7067 		 * may end up writing to dynptr itself when touching memory from
7068 		 * arg 1. This can be relaxed on a case by case basis for known
7069 		 * safe cases, but reject due to the possibilitiy of aliasing by
7070 		 * default.
7071 		 */
7072 		for (i = min_off; i < max_off + access_size; i++) {
7073 			int stack_off = -i - 1;
7074 
7075 			spi = __get_spi(i);
7076 			/* raw_mode may write past allocated_stack */
7077 			if (state->allocated_stack <= stack_off)
7078 				continue;
7079 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7080 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7081 				return -EACCES;
7082 			}
7083 		}
7084 		meta->access_size = access_size;
7085 		meta->regno = regno;
7086 		return 0;
7087 	}
7088 
7089 	for (i = min_off; i < max_off + access_size; i++) {
7090 		u8 *stype;
7091 
7092 		slot = -i - 1;
7093 		spi = slot / BPF_REG_SIZE;
7094 		if (state->allocated_stack <= slot) {
7095 			verbose(env, "verifier bug: allocated_stack too small");
7096 			return -EFAULT;
7097 		}
7098 
7099 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7100 		if (*stype == STACK_MISC)
7101 			goto mark;
7102 		if ((*stype == STACK_ZERO) ||
7103 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7104 			if (clobber) {
7105 				/* helper can write anything into the stack */
7106 				*stype = STACK_MISC;
7107 			}
7108 			goto mark;
7109 		}
7110 
7111 		if (is_spilled_reg(&state->stack[spi]) &&
7112 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7113 		     env->allow_ptr_leaks)) {
7114 			if (clobber) {
7115 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7116 				for (j = 0; j < BPF_REG_SIZE; j++)
7117 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7118 			}
7119 			goto mark;
7120 		}
7121 
7122 		if (tnum_is_const(reg->var_off)) {
7123 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7124 				err_extra, regno, min_off, i - min_off, access_size);
7125 		} else {
7126 			char tn_buf[48];
7127 
7128 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7129 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7130 				err_extra, regno, tn_buf, i - min_off, access_size);
7131 		}
7132 		return -EACCES;
7133 mark:
7134 		/* reading any byte out of 8-byte 'spill_slot' will cause
7135 		 * the whole slot to be marked as 'read'
7136 		 */
7137 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7138 			      state->stack[spi].spilled_ptr.parent,
7139 			      REG_LIVE_READ64);
7140 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7141 		 * be sure that whether stack slot is written to or not. Hence,
7142 		 * we must still conservatively propagate reads upwards even if
7143 		 * helper may write to the entire memory range.
7144 		 */
7145 	}
7146 	return 0;
7147 }
7148 
7149 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7150 				   int access_size, bool zero_size_allowed,
7151 				   struct bpf_call_arg_meta *meta)
7152 {
7153 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7154 	u32 *max_access;
7155 
7156 	switch (base_type(reg->type)) {
7157 	case PTR_TO_PACKET:
7158 	case PTR_TO_PACKET_META:
7159 		return check_packet_access(env, regno, reg->off, access_size,
7160 					   zero_size_allowed);
7161 	case PTR_TO_MAP_KEY:
7162 		if (meta && meta->raw_mode) {
7163 			verbose(env, "R%d cannot write into %s\n", regno,
7164 				reg_type_str(env, reg->type));
7165 			return -EACCES;
7166 		}
7167 		return check_mem_region_access(env, regno, reg->off, access_size,
7168 					       reg->map_ptr->key_size, false);
7169 	case PTR_TO_MAP_VALUE:
7170 		if (check_map_access_type(env, regno, reg->off, access_size,
7171 					  meta && meta->raw_mode ? BPF_WRITE :
7172 					  BPF_READ))
7173 			return -EACCES;
7174 		return check_map_access(env, regno, reg->off, access_size,
7175 					zero_size_allowed, ACCESS_HELPER);
7176 	case PTR_TO_MEM:
7177 		if (type_is_rdonly_mem(reg->type)) {
7178 			if (meta && meta->raw_mode) {
7179 				verbose(env, "R%d cannot write into %s\n", regno,
7180 					reg_type_str(env, reg->type));
7181 				return -EACCES;
7182 			}
7183 		}
7184 		return check_mem_region_access(env, regno, reg->off,
7185 					       access_size, reg->mem_size,
7186 					       zero_size_allowed);
7187 	case PTR_TO_BUF:
7188 		if (type_is_rdonly_mem(reg->type)) {
7189 			if (meta && meta->raw_mode) {
7190 				verbose(env, "R%d cannot write into %s\n", regno,
7191 					reg_type_str(env, reg->type));
7192 				return -EACCES;
7193 			}
7194 
7195 			max_access = &env->prog->aux->max_rdonly_access;
7196 		} else {
7197 			max_access = &env->prog->aux->max_rdwr_access;
7198 		}
7199 		return check_buffer_access(env, reg, regno, reg->off,
7200 					   access_size, zero_size_allowed,
7201 					   max_access);
7202 	case PTR_TO_STACK:
7203 		return check_stack_range_initialized(
7204 				env,
7205 				regno, reg->off, access_size,
7206 				zero_size_allowed, ACCESS_HELPER, meta);
7207 	case PTR_TO_BTF_ID:
7208 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7209 					       access_size, BPF_READ, -1);
7210 	case PTR_TO_CTX:
7211 		/* in case the function doesn't know how to access the context,
7212 		 * (because we are in a program of type SYSCALL for example), we
7213 		 * can not statically check its size.
7214 		 * Dynamically check it now.
7215 		 */
7216 		if (!env->ops->convert_ctx_access) {
7217 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7218 			int offset = access_size - 1;
7219 
7220 			/* Allow zero-byte read from PTR_TO_CTX */
7221 			if (access_size == 0)
7222 				return zero_size_allowed ? 0 : -EACCES;
7223 
7224 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7225 						atype, -1, false, false);
7226 		}
7227 
7228 		fallthrough;
7229 	default: /* scalar_value or invalid ptr */
7230 		/* Allow zero-byte read from NULL, regardless of pointer type */
7231 		if (zero_size_allowed && access_size == 0 &&
7232 		    register_is_null(reg))
7233 			return 0;
7234 
7235 		verbose(env, "R%d type=%s ", regno,
7236 			reg_type_str(env, reg->type));
7237 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7238 		return -EACCES;
7239 	}
7240 }
7241 
7242 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7243  * size.
7244  *
7245  * @regno is the register containing the access size. regno-1 is the register
7246  * containing the pointer.
7247  */
7248 static int check_mem_size_reg(struct bpf_verifier_env *env,
7249 			      struct bpf_reg_state *reg, u32 regno,
7250 			      bool zero_size_allowed,
7251 			      struct bpf_call_arg_meta *meta)
7252 {
7253 	int err;
7254 
7255 	/* This is used to refine r0 return value bounds for helpers
7256 	 * that enforce this value as an upper bound on return values.
7257 	 * See do_refine_retval_range() for helpers that can refine
7258 	 * the return value. C type of helper is u32 so we pull register
7259 	 * bound from umax_value however, if negative verifier errors
7260 	 * out. Only upper bounds can be learned because retval is an
7261 	 * int type and negative retvals are allowed.
7262 	 */
7263 	meta->msize_max_value = reg->umax_value;
7264 
7265 	/* The register is SCALAR_VALUE; the access check
7266 	 * happens using its boundaries.
7267 	 */
7268 	if (!tnum_is_const(reg->var_off))
7269 		/* For unprivileged variable accesses, disable raw
7270 		 * mode so that the program is required to
7271 		 * initialize all the memory that the helper could
7272 		 * just partially fill up.
7273 		 */
7274 		meta = NULL;
7275 
7276 	if (reg->smin_value < 0) {
7277 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7278 			regno);
7279 		return -EACCES;
7280 	}
7281 
7282 	if (reg->umin_value == 0) {
7283 		err = check_helper_mem_access(env, regno - 1, 0,
7284 					      zero_size_allowed,
7285 					      meta);
7286 		if (err)
7287 			return err;
7288 	}
7289 
7290 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7291 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7292 			regno);
7293 		return -EACCES;
7294 	}
7295 	err = check_helper_mem_access(env, regno - 1,
7296 				      reg->umax_value,
7297 				      zero_size_allowed, meta);
7298 	if (!err)
7299 		err = mark_chain_precision(env, regno);
7300 	return err;
7301 }
7302 
7303 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7304 			 u32 regno, u32 mem_size)
7305 {
7306 	bool may_be_null = type_may_be_null(reg->type);
7307 	struct bpf_reg_state saved_reg;
7308 	struct bpf_call_arg_meta meta;
7309 	int err;
7310 
7311 	if (register_is_null(reg))
7312 		return 0;
7313 
7314 	memset(&meta, 0, sizeof(meta));
7315 	/* Assuming that the register contains a value check if the memory
7316 	 * access is safe. Temporarily save and restore the register's state as
7317 	 * the conversion shouldn't be visible to a caller.
7318 	 */
7319 	if (may_be_null) {
7320 		saved_reg = *reg;
7321 		mark_ptr_not_null_reg(reg);
7322 	}
7323 
7324 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7325 	/* Check access for BPF_WRITE */
7326 	meta.raw_mode = true;
7327 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7328 
7329 	if (may_be_null)
7330 		*reg = saved_reg;
7331 
7332 	return err;
7333 }
7334 
7335 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7336 				    u32 regno)
7337 {
7338 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7339 	bool may_be_null = type_may_be_null(mem_reg->type);
7340 	struct bpf_reg_state saved_reg;
7341 	struct bpf_call_arg_meta meta;
7342 	int err;
7343 
7344 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7345 
7346 	memset(&meta, 0, sizeof(meta));
7347 
7348 	if (may_be_null) {
7349 		saved_reg = *mem_reg;
7350 		mark_ptr_not_null_reg(mem_reg);
7351 	}
7352 
7353 	err = check_mem_size_reg(env, reg, regno, true, &meta);
7354 	/* Check access for BPF_WRITE */
7355 	meta.raw_mode = true;
7356 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7357 
7358 	if (may_be_null)
7359 		*mem_reg = saved_reg;
7360 	return err;
7361 }
7362 
7363 /* Implementation details:
7364  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7365  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7366  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7367  * Two separate bpf_obj_new will also have different reg->id.
7368  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7369  * clears reg->id after value_or_null->value transition, since the verifier only
7370  * cares about the range of access to valid map value pointer and doesn't care
7371  * about actual address of the map element.
7372  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7373  * reg->id > 0 after value_or_null->value transition. By doing so
7374  * two bpf_map_lookups will be considered two different pointers that
7375  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7376  * returned from bpf_obj_new.
7377  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7378  * dead-locks.
7379  * Since only one bpf_spin_lock is allowed the checks are simpler than
7380  * reg_is_refcounted() logic. The verifier needs to remember only
7381  * one spin_lock instead of array of acquired_refs.
7382  * cur_state->active_lock remembers which map value element or allocated
7383  * object got locked and clears it after bpf_spin_unlock.
7384  */
7385 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7386 			     bool is_lock)
7387 {
7388 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7389 	struct bpf_verifier_state *cur = env->cur_state;
7390 	bool is_const = tnum_is_const(reg->var_off);
7391 	u64 val = reg->var_off.value;
7392 	struct bpf_map *map = NULL;
7393 	struct btf *btf = NULL;
7394 	struct btf_record *rec;
7395 
7396 	if (!is_const) {
7397 		verbose(env,
7398 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7399 			regno);
7400 		return -EINVAL;
7401 	}
7402 	if (reg->type == PTR_TO_MAP_VALUE) {
7403 		map = reg->map_ptr;
7404 		if (!map->btf) {
7405 			verbose(env,
7406 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7407 				map->name);
7408 			return -EINVAL;
7409 		}
7410 	} else {
7411 		btf = reg->btf;
7412 	}
7413 
7414 	rec = reg_btf_record(reg);
7415 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7416 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7417 			map ? map->name : "kptr");
7418 		return -EINVAL;
7419 	}
7420 	if (rec->spin_lock_off != val + reg->off) {
7421 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7422 			val + reg->off, rec->spin_lock_off);
7423 		return -EINVAL;
7424 	}
7425 	if (is_lock) {
7426 		if (cur->active_lock.ptr) {
7427 			verbose(env,
7428 				"Locking two bpf_spin_locks are not allowed\n");
7429 			return -EINVAL;
7430 		}
7431 		if (map)
7432 			cur->active_lock.ptr = map;
7433 		else
7434 			cur->active_lock.ptr = btf;
7435 		cur->active_lock.id = reg->id;
7436 	} else {
7437 		void *ptr;
7438 
7439 		if (map)
7440 			ptr = map;
7441 		else
7442 			ptr = btf;
7443 
7444 		if (!cur->active_lock.ptr) {
7445 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7446 			return -EINVAL;
7447 		}
7448 		if (cur->active_lock.ptr != ptr ||
7449 		    cur->active_lock.id != reg->id) {
7450 			verbose(env, "bpf_spin_unlock of different lock\n");
7451 			return -EINVAL;
7452 		}
7453 
7454 		invalidate_non_owning_refs(env);
7455 
7456 		cur->active_lock.ptr = NULL;
7457 		cur->active_lock.id = 0;
7458 	}
7459 	return 0;
7460 }
7461 
7462 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7463 			      struct bpf_call_arg_meta *meta)
7464 {
7465 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7466 	bool is_const = tnum_is_const(reg->var_off);
7467 	struct bpf_map *map = reg->map_ptr;
7468 	u64 val = reg->var_off.value;
7469 
7470 	if (!is_const) {
7471 		verbose(env,
7472 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7473 			regno);
7474 		return -EINVAL;
7475 	}
7476 	if (!map->btf) {
7477 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7478 			map->name);
7479 		return -EINVAL;
7480 	}
7481 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7482 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7483 		return -EINVAL;
7484 	}
7485 	if (map->record->timer_off != val + reg->off) {
7486 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7487 			val + reg->off, map->record->timer_off);
7488 		return -EINVAL;
7489 	}
7490 	if (meta->map_ptr) {
7491 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7492 		return -EFAULT;
7493 	}
7494 	meta->map_uid = reg->map_uid;
7495 	meta->map_ptr = map;
7496 	return 0;
7497 }
7498 
7499 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7500 			     struct bpf_call_arg_meta *meta)
7501 {
7502 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7503 	struct bpf_map *map_ptr = reg->map_ptr;
7504 	struct btf_field *kptr_field;
7505 	u32 kptr_off;
7506 
7507 	if (!tnum_is_const(reg->var_off)) {
7508 		verbose(env,
7509 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7510 			regno);
7511 		return -EINVAL;
7512 	}
7513 	if (!map_ptr->btf) {
7514 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7515 			map_ptr->name);
7516 		return -EINVAL;
7517 	}
7518 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7519 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7520 		return -EINVAL;
7521 	}
7522 
7523 	meta->map_ptr = map_ptr;
7524 	kptr_off = reg->off + reg->var_off.value;
7525 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7526 	if (!kptr_field) {
7527 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7528 		return -EACCES;
7529 	}
7530 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7531 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7532 		return -EACCES;
7533 	}
7534 	meta->kptr_field = kptr_field;
7535 	return 0;
7536 }
7537 
7538 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7539  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7540  *
7541  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7542  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7543  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7544  *
7545  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7546  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7547  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7548  * mutate the view of the dynptr and also possibly destroy it. In the latter
7549  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7550  * memory that dynptr points to.
7551  *
7552  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7553  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7554  * readonly dynptr view yet, hence only the first case is tracked and checked.
7555  *
7556  * This is consistent with how C applies the const modifier to a struct object,
7557  * where the pointer itself inside bpf_dynptr becomes const but not what it
7558  * points to.
7559  *
7560  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7561  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7562  */
7563 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7564 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7565 {
7566 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7567 	int err;
7568 
7569 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7570 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7571 	 */
7572 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7573 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7574 		return -EFAULT;
7575 	}
7576 
7577 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7578 	 *		 constructing a mutable bpf_dynptr object.
7579 	 *
7580 	 *		 Currently, this is only possible with PTR_TO_STACK
7581 	 *		 pointing to a region of at least 16 bytes which doesn't
7582 	 *		 contain an existing bpf_dynptr.
7583 	 *
7584 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7585 	 *		 mutated or destroyed. However, the memory it points to
7586 	 *		 may be mutated.
7587 	 *
7588 	 *  None       - Points to a initialized dynptr that can be mutated and
7589 	 *		 destroyed, including mutation of the memory it points
7590 	 *		 to.
7591 	 */
7592 	if (arg_type & MEM_UNINIT) {
7593 		int i;
7594 
7595 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7596 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7597 			return -EINVAL;
7598 		}
7599 
7600 		/* we write BPF_DW bits (8 bytes) at a time */
7601 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7602 			err = check_mem_access(env, insn_idx, regno,
7603 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7604 			if (err)
7605 				return err;
7606 		}
7607 
7608 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7609 	} else /* MEM_RDONLY and None case from above */ {
7610 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7611 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7612 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7613 			return -EINVAL;
7614 		}
7615 
7616 		if (!is_dynptr_reg_valid_init(env, reg)) {
7617 			verbose(env,
7618 				"Expected an initialized dynptr as arg #%d\n",
7619 				regno);
7620 			return -EINVAL;
7621 		}
7622 
7623 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7624 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7625 			verbose(env,
7626 				"Expected a dynptr of type %s as arg #%d\n",
7627 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7628 			return -EINVAL;
7629 		}
7630 
7631 		err = mark_dynptr_read(env, reg);
7632 	}
7633 	return err;
7634 }
7635 
7636 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7637 {
7638 	struct bpf_func_state *state = func(env, reg);
7639 
7640 	return state->stack[spi].spilled_ptr.ref_obj_id;
7641 }
7642 
7643 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7644 {
7645 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7646 }
7647 
7648 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7649 {
7650 	return meta->kfunc_flags & KF_ITER_NEW;
7651 }
7652 
7653 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7654 {
7655 	return meta->kfunc_flags & KF_ITER_NEXT;
7656 }
7657 
7658 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7659 {
7660 	return meta->kfunc_flags & KF_ITER_DESTROY;
7661 }
7662 
7663 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7664 {
7665 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7666 	 * kfunc is iter state pointer
7667 	 */
7668 	return arg == 0 && is_iter_kfunc(meta);
7669 }
7670 
7671 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7672 			    struct bpf_kfunc_call_arg_meta *meta)
7673 {
7674 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7675 	const struct btf_type *t;
7676 	const struct btf_param *arg;
7677 	int spi, err, i, nr_slots;
7678 	u32 btf_id;
7679 
7680 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7681 	arg = &btf_params(meta->func_proto)[0];
7682 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7683 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7684 	nr_slots = t->size / BPF_REG_SIZE;
7685 
7686 	if (is_iter_new_kfunc(meta)) {
7687 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7688 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7689 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7690 				iter_type_str(meta->btf, btf_id), regno);
7691 			return -EINVAL;
7692 		}
7693 
7694 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7695 			err = check_mem_access(env, insn_idx, regno,
7696 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7697 			if (err)
7698 				return err;
7699 		}
7700 
7701 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
7702 		if (err)
7703 			return err;
7704 	} else {
7705 		/* iter_next() or iter_destroy() expect initialized iter state*/
7706 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
7707 		switch (err) {
7708 		case 0:
7709 			break;
7710 		case -EINVAL:
7711 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7712 				iter_type_str(meta->btf, btf_id), regno);
7713 			return err;
7714 		case -EPROTO:
7715 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
7716 			return err;
7717 		default:
7718 			return err;
7719 		}
7720 
7721 		spi = iter_get_spi(env, reg, nr_slots);
7722 		if (spi < 0)
7723 			return spi;
7724 
7725 		err = mark_iter_read(env, reg, spi, nr_slots);
7726 		if (err)
7727 			return err;
7728 
7729 		/* remember meta->iter info for process_iter_next_call() */
7730 		meta->iter.spi = spi;
7731 		meta->iter.frameno = reg->frameno;
7732 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7733 
7734 		if (is_iter_destroy_kfunc(meta)) {
7735 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7736 			if (err)
7737 				return err;
7738 		}
7739 	}
7740 
7741 	return 0;
7742 }
7743 
7744 /* Look for a previous loop entry at insn_idx: nearest parent state
7745  * stopped at insn_idx with callsites matching those in cur->frame.
7746  */
7747 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7748 						  struct bpf_verifier_state *cur,
7749 						  int insn_idx)
7750 {
7751 	struct bpf_verifier_state_list *sl;
7752 	struct bpf_verifier_state *st;
7753 
7754 	/* Explored states are pushed in stack order, most recent states come first */
7755 	sl = *explored_state(env, insn_idx);
7756 	for (; sl; sl = sl->next) {
7757 		/* If st->branches != 0 state is a part of current DFS verification path,
7758 		 * hence cur & st for a loop.
7759 		 */
7760 		st = &sl->state;
7761 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7762 		    st->dfs_depth < cur->dfs_depth)
7763 			return st;
7764 	}
7765 
7766 	return NULL;
7767 }
7768 
7769 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7770 static bool regs_exact(const struct bpf_reg_state *rold,
7771 		       const struct bpf_reg_state *rcur,
7772 		       struct bpf_idmap *idmap);
7773 
7774 static void maybe_widen_reg(struct bpf_verifier_env *env,
7775 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7776 			    struct bpf_idmap *idmap)
7777 {
7778 	if (rold->type != SCALAR_VALUE)
7779 		return;
7780 	if (rold->type != rcur->type)
7781 		return;
7782 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7783 		return;
7784 	__mark_reg_unknown(env, rcur);
7785 }
7786 
7787 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7788 				   struct bpf_verifier_state *old,
7789 				   struct bpf_verifier_state *cur)
7790 {
7791 	struct bpf_func_state *fold, *fcur;
7792 	int i, fr;
7793 
7794 	reset_idmap_scratch(env);
7795 	for (fr = old->curframe; fr >= 0; fr--) {
7796 		fold = old->frame[fr];
7797 		fcur = cur->frame[fr];
7798 
7799 		for (i = 0; i < MAX_BPF_REG; i++)
7800 			maybe_widen_reg(env,
7801 					&fold->regs[i],
7802 					&fcur->regs[i],
7803 					&env->idmap_scratch);
7804 
7805 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7806 			if (!is_spilled_reg(&fold->stack[i]) ||
7807 			    !is_spilled_reg(&fcur->stack[i]))
7808 				continue;
7809 
7810 			maybe_widen_reg(env,
7811 					&fold->stack[i].spilled_ptr,
7812 					&fcur->stack[i].spilled_ptr,
7813 					&env->idmap_scratch);
7814 		}
7815 	}
7816 	return 0;
7817 }
7818 
7819 /* process_iter_next_call() is called when verifier gets to iterator's next
7820  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7821  * to it as just "iter_next()" in comments below.
7822  *
7823  * BPF verifier relies on a crucial contract for any iter_next()
7824  * implementation: it should *eventually* return NULL, and once that happens
7825  * it should keep returning NULL. That is, once iterator exhausts elements to
7826  * iterate, it should never reset or spuriously return new elements.
7827  *
7828  * With the assumption of such contract, process_iter_next_call() simulates
7829  * a fork in the verifier state to validate loop logic correctness and safety
7830  * without having to simulate infinite amount of iterations.
7831  *
7832  * In current state, we first assume that iter_next() returned NULL and
7833  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7834  * conditions we should not form an infinite loop and should eventually reach
7835  * exit.
7836  *
7837  * Besides that, we also fork current state and enqueue it for later
7838  * verification. In a forked state we keep iterator state as ACTIVE
7839  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7840  * also bump iteration depth to prevent erroneous infinite loop detection
7841  * later on (see iter_active_depths_differ() comment for details). In this
7842  * state we assume that we'll eventually loop back to another iter_next()
7843  * calls (it could be in exactly same location or in some other instruction,
7844  * it doesn't matter, we don't make any unnecessary assumptions about this,
7845  * everything revolves around iterator state in a stack slot, not which
7846  * instruction is calling iter_next()). When that happens, we either will come
7847  * to iter_next() with equivalent state and can conclude that next iteration
7848  * will proceed in exactly the same way as we just verified, so it's safe to
7849  * assume that loop converges. If not, we'll go on another iteration
7850  * simulation with a different input state, until all possible starting states
7851  * are validated or we reach maximum number of instructions limit.
7852  *
7853  * This way, we will either exhaustively discover all possible input states
7854  * that iterator loop can start with and eventually will converge, or we'll
7855  * effectively regress into bounded loop simulation logic and either reach
7856  * maximum number of instructions if loop is not provably convergent, or there
7857  * is some statically known limit on number of iterations (e.g., if there is
7858  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7859  *
7860  * Iteration convergence logic in is_state_visited() relies on exact
7861  * states comparison, which ignores read and precision marks.
7862  * This is necessary because read and precision marks are not finalized
7863  * while in the loop. Exact comparison might preclude convergence for
7864  * simple programs like below:
7865  *
7866  *     i = 0;
7867  *     while(iter_next(&it))
7868  *       i++;
7869  *
7870  * At each iteration step i++ would produce a new distinct state and
7871  * eventually instruction processing limit would be reached.
7872  *
7873  * To avoid such behavior speculatively forget (widen) range for
7874  * imprecise scalar registers, if those registers were not precise at the
7875  * end of the previous iteration and do not match exactly.
7876  *
7877  * This is a conservative heuristic that allows to verify wide range of programs,
7878  * however it precludes verification of programs that conjure an
7879  * imprecise value on the first loop iteration and use it as precise on a second.
7880  * For example, the following safe program would fail to verify:
7881  *
7882  *     struct bpf_num_iter it;
7883  *     int arr[10];
7884  *     int i = 0, a = 0;
7885  *     bpf_iter_num_new(&it, 0, 10);
7886  *     while (bpf_iter_num_next(&it)) {
7887  *       if (a == 0) {
7888  *         a = 1;
7889  *         i = 7; // Because i changed verifier would forget
7890  *                // it's range on second loop entry.
7891  *       } else {
7892  *         arr[i] = 42; // This would fail to verify.
7893  *       }
7894  *     }
7895  *     bpf_iter_num_destroy(&it);
7896  */
7897 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7898 				  struct bpf_kfunc_call_arg_meta *meta)
7899 {
7900 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7901 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7902 	struct bpf_reg_state *cur_iter, *queued_iter;
7903 	int iter_frameno = meta->iter.frameno;
7904 	int iter_spi = meta->iter.spi;
7905 
7906 	BTF_TYPE_EMIT(struct bpf_iter);
7907 
7908 	cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7909 
7910 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7911 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7912 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7913 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7914 		return -EFAULT;
7915 	}
7916 
7917 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7918 		/* Because iter_next() call is a checkpoint is_state_visitied()
7919 		 * should guarantee parent state with same call sites and insn_idx.
7920 		 */
7921 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7922 		    !same_callsites(cur_st->parent, cur_st)) {
7923 			verbose(env, "bug: bad parent state for iter next call");
7924 			return -EFAULT;
7925 		}
7926 		/* Note cur_st->parent in the call below, it is necessary to skip
7927 		 * checkpoint created for cur_st by is_state_visited()
7928 		 * right at this instruction.
7929 		 */
7930 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7931 		/* branch out active iter state */
7932 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7933 		if (!queued_st)
7934 			return -ENOMEM;
7935 
7936 		queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7937 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7938 		queued_iter->iter.depth++;
7939 		if (prev_st)
7940 			widen_imprecise_scalars(env, prev_st, queued_st);
7941 
7942 		queued_fr = queued_st->frame[queued_st->curframe];
7943 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7944 	}
7945 
7946 	/* switch to DRAINED state, but keep the depth unchanged */
7947 	/* mark current iter state as drained and assume returned NULL */
7948 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7949 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
7950 
7951 	return 0;
7952 }
7953 
7954 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7955 {
7956 	return type == ARG_CONST_SIZE ||
7957 	       type == ARG_CONST_SIZE_OR_ZERO;
7958 }
7959 
7960 static bool arg_type_is_release(enum bpf_arg_type type)
7961 {
7962 	return type & OBJ_RELEASE;
7963 }
7964 
7965 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7966 {
7967 	return base_type(type) == ARG_PTR_TO_DYNPTR;
7968 }
7969 
7970 static int int_ptr_type_to_size(enum bpf_arg_type type)
7971 {
7972 	if (type == ARG_PTR_TO_INT)
7973 		return sizeof(u32);
7974 	else if (type == ARG_PTR_TO_LONG)
7975 		return sizeof(u64);
7976 
7977 	return -EINVAL;
7978 }
7979 
7980 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7981 				 const struct bpf_call_arg_meta *meta,
7982 				 enum bpf_arg_type *arg_type)
7983 {
7984 	if (!meta->map_ptr) {
7985 		/* kernel subsystem misconfigured verifier */
7986 		verbose(env, "invalid map_ptr to access map->type\n");
7987 		return -EACCES;
7988 	}
7989 
7990 	switch (meta->map_ptr->map_type) {
7991 	case BPF_MAP_TYPE_SOCKMAP:
7992 	case BPF_MAP_TYPE_SOCKHASH:
7993 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7994 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7995 		} else {
7996 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
7997 			return -EINVAL;
7998 		}
7999 		break;
8000 	case BPF_MAP_TYPE_BLOOM_FILTER:
8001 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8002 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8003 		break;
8004 	default:
8005 		break;
8006 	}
8007 	return 0;
8008 }
8009 
8010 struct bpf_reg_types {
8011 	const enum bpf_reg_type types[10];
8012 	u32 *btf_id;
8013 };
8014 
8015 static const struct bpf_reg_types sock_types = {
8016 	.types = {
8017 		PTR_TO_SOCK_COMMON,
8018 		PTR_TO_SOCKET,
8019 		PTR_TO_TCP_SOCK,
8020 		PTR_TO_XDP_SOCK,
8021 	},
8022 };
8023 
8024 #ifdef CONFIG_NET
8025 static const struct bpf_reg_types btf_id_sock_common_types = {
8026 	.types = {
8027 		PTR_TO_SOCK_COMMON,
8028 		PTR_TO_SOCKET,
8029 		PTR_TO_TCP_SOCK,
8030 		PTR_TO_XDP_SOCK,
8031 		PTR_TO_BTF_ID,
8032 		PTR_TO_BTF_ID | PTR_TRUSTED,
8033 	},
8034 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8035 };
8036 #endif
8037 
8038 static const struct bpf_reg_types mem_types = {
8039 	.types = {
8040 		PTR_TO_STACK,
8041 		PTR_TO_PACKET,
8042 		PTR_TO_PACKET_META,
8043 		PTR_TO_MAP_KEY,
8044 		PTR_TO_MAP_VALUE,
8045 		PTR_TO_MEM,
8046 		PTR_TO_MEM | MEM_RINGBUF,
8047 		PTR_TO_BUF,
8048 		PTR_TO_BTF_ID | PTR_TRUSTED,
8049 	},
8050 };
8051 
8052 static const struct bpf_reg_types int_ptr_types = {
8053 	.types = {
8054 		PTR_TO_STACK,
8055 		PTR_TO_PACKET,
8056 		PTR_TO_PACKET_META,
8057 		PTR_TO_MAP_KEY,
8058 		PTR_TO_MAP_VALUE,
8059 	},
8060 };
8061 
8062 static const struct bpf_reg_types spin_lock_types = {
8063 	.types = {
8064 		PTR_TO_MAP_VALUE,
8065 		PTR_TO_BTF_ID | MEM_ALLOC,
8066 	}
8067 };
8068 
8069 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8070 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8071 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8072 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8073 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8074 static const struct bpf_reg_types btf_ptr_types = {
8075 	.types = {
8076 		PTR_TO_BTF_ID,
8077 		PTR_TO_BTF_ID | PTR_TRUSTED,
8078 		PTR_TO_BTF_ID | MEM_RCU,
8079 	},
8080 };
8081 static const struct bpf_reg_types percpu_btf_ptr_types = {
8082 	.types = {
8083 		PTR_TO_BTF_ID | MEM_PERCPU,
8084 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8085 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8086 	}
8087 };
8088 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8089 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8090 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8091 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8092 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8093 static const struct bpf_reg_types dynptr_types = {
8094 	.types = {
8095 		PTR_TO_STACK,
8096 		CONST_PTR_TO_DYNPTR,
8097 	}
8098 };
8099 
8100 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8101 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8102 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8103 	[ARG_CONST_SIZE]		= &scalar_types,
8104 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8105 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8106 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8107 	[ARG_PTR_TO_CTX]		= &context_types,
8108 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8109 #ifdef CONFIG_NET
8110 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8111 #endif
8112 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8113 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8114 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8115 	[ARG_PTR_TO_MEM]		= &mem_types,
8116 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8117 	[ARG_PTR_TO_INT]		= &int_ptr_types,
8118 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
8119 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8120 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8121 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8122 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8123 	[ARG_PTR_TO_TIMER]		= &timer_types,
8124 	[ARG_PTR_TO_KPTR]		= &kptr_types,
8125 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8126 };
8127 
8128 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8129 			  enum bpf_arg_type arg_type,
8130 			  const u32 *arg_btf_id,
8131 			  struct bpf_call_arg_meta *meta)
8132 {
8133 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8134 	enum bpf_reg_type expected, type = reg->type;
8135 	const struct bpf_reg_types *compatible;
8136 	int i, j;
8137 
8138 	compatible = compatible_reg_types[base_type(arg_type)];
8139 	if (!compatible) {
8140 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8141 		return -EFAULT;
8142 	}
8143 
8144 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8145 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8146 	 *
8147 	 * Same for MAYBE_NULL:
8148 	 *
8149 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8150 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8151 	 *
8152 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8153 	 *
8154 	 * Therefore we fold these flags depending on the arg_type before comparison.
8155 	 */
8156 	if (arg_type & MEM_RDONLY)
8157 		type &= ~MEM_RDONLY;
8158 	if (arg_type & PTR_MAYBE_NULL)
8159 		type &= ~PTR_MAYBE_NULL;
8160 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8161 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8162 
8163 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) {
8164 		type &= ~MEM_ALLOC;
8165 		type &= ~MEM_PERCPU;
8166 	}
8167 
8168 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8169 		expected = compatible->types[i];
8170 		if (expected == NOT_INIT)
8171 			break;
8172 
8173 		if (type == expected)
8174 			goto found;
8175 	}
8176 
8177 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8178 	for (j = 0; j + 1 < i; j++)
8179 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8180 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8181 	return -EACCES;
8182 
8183 found:
8184 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8185 		return 0;
8186 
8187 	if (compatible == &mem_types) {
8188 		if (!(arg_type & MEM_RDONLY)) {
8189 			verbose(env,
8190 				"%s() may write into memory pointed by R%d type=%s\n",
8191 				func_id_name(meta->func_id),
8192 				regno, reg_type_str(env, reg->type));
8193 			return -EACCES;
8194 		}
8195 		return 0;
8196 	}
8197 
8198 	switch ((int)reg->type) {
8199 	case PTR_TO_BTF_ID:
8200 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8201 	case PTR_TO_BTF_ID | MEM_RCU:
8202 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8203 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8204 	{
8205 		/* For bpf_sk_release, it needs to match against first member
8206 		 * 'struct sock_common', hence make an exception for it. This
8207 		 * allows bpf_sk_release to work for multiple socket types.
8208 		 */
8209 		bool strict_type_match = arg_type_is_release(arg_type) &&
8210 					 meta->func_id != BPF_FUNC_sk_release;
8211 
8212 		if (type_may_be_null(reg->type) &&
8213 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8214 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8215 			return -EACCES;
8216 		}
8217 
8218 		if (!arg_btf_id) {
8219 			if (!compatible->btf_id) {
8220 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8221 				return -EFAULT;
8222 			}
8223 			arg_btf_id = compatible->btf_id;
8224 		}
8225 
8226 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8227 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8228 				return -EACCES;
8229 		} else {
8230 			if (arg_btf_id == BPF_PTR_POISON) {
8231 				verbose(env, "verifier internal error:");
8232 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8233 					regno);
8234 				return -EACCES;
8235 			}
8236 
8237 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8238 						  btf_vmlinux, *arg_btf_id,
8239 						  strict_type_match)) {
8240 				verbose(env, "R%d is of type %s but %s is expected\n",
8241 					regno, btf_type_name(reg->btf, reg->btf_id),
8242 					btf_type_name(btf_vmlinux, *arg_btf_id));
8243 				return -EACCES;
8244 			}
8245 		}
8246 		break;
8247 	}
8248 	case PTR_TO_BTF_ID | MEM_ALLOC:
8249 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8250 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8251 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8252 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8253 			return -EFAULT;
8254 		}
8255 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8256 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8257 				return -EACCES;
8258 		}
8259 		break;
8260 	case PTR_TO_BTF_ID | MEM_PERCPU:
8261 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8262 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8263 		/* Handled by helper specific checks */
8264 		break;
8265 	default:
8266 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8267 		return -EFAULT;
8268 	}
8269 	return 0;
8270 }
8271 
8272 static struct btf_field *
8273 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8274 {
8275 	struct btf_field *field;
8276 	struct btf_record *rec;
8277 
8278 	rec = reg_btf_record(reg);
8279 	if (!rec)
8280 		return NULL;
8281 
8282 	field = btf_record_find(rec, off, fields);
8283 	if (!field)
8284 		return NULL;
8285 
8286 	return field;
8287 }
8288 
8289 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8290 				  const struct bpf_reg_state *reg, int regno,
8291 				  enum bpf_arg_type arg_type)
8292 {
8293 	u32 type = reg->type;
8294 
8295 	/* When referenced register is passed to release function, its fixed
8296 	 * offset must be 0.
8297 	 *
8298 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8299 	 * meta->release_regno.
8300 	 */
8301 	if (arg_type_is_release(arg_type)) {
8302 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8303 		 * may not directly point to the object being released, but to
8304 		 * dynptr pointing to such object, which might be at some offset
8305 		 * on the stack. In that case, we simply to fallback to the
8306 		 * default handling.
8307 		 */
8308 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8309 			return 0;
8310 
8311 		/* Doing check_ptr_off_reg check for the offset will catch this
8312 		 * because fixed_off_ok is false, but checking here allows us
8313 		 * to give the user a better error message.
8314 		 */
8315 		if (reg->off) {
8316 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8317 				regno);
8318 			return -EINVAL;
8319 		}
8320 		return __check_ptr_off_reg(env, reg, regno, false);
8321 	}
8322 
8323 	switch (type) {
8324 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8325 	case PTR_TO_STACK:
8326 	case PTR_TO_PACKET:
8327 	case PTR_TO_PACKET_META:
8328 	case PTR_TO_MAP_KEY:
8329 	case PTR_TO_MAP_VALUE:
8330 	case PTR_TO_MEM:
8331 	case PTR_TO_MEM | MEM_RDONLY:
8332 	case PTR_TO_MEM | MEM_RINGBUF:
8333 	case PTR_TO_BUF:
8334 	case PTR_TO_BUF | MEM_RDONLY:
8335 	case SCALAR_VALUE:
8336 		return 0;
8337 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8338 	 * fixed offset.
8339 	 */
8340 	case PTR_TO_BTF_ID:
8341 	case PTR_TO_BTF_ID | MEM_ALLOC:
8342 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8343 	case PTR_TO_BTF_ID | MEM_RCU:
8344 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8345 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8346 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8347 		 * its fixed offset must be 0. In the other cases, fixed offset
8348 		 * can be non-zero. This was already checked above. So pass
8349 		 * fixed_off_ok as true to allow fixed offset for all other
8350 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8351 		 * still need to do checks instead of returning.
8352 		 */
8353 		return __check_ptr_off_reg(env, reg, regno, true);
8354 	default:
8355 		return __check_ptr_off_reg(env, reg, regno, false);
8356 	}
8357 }
8358 
8359 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8360 						const struct bpf_func_proto *fn,
8361 						struct bpf_reg_state *regs)
8362 {
8363 	struct bpf_reg_state *state = NULL;
8364 	int i;
8365 
8366 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8367 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8368 			if (state) {
8369 				verbose(env, "verifier internal error: multiple dynptr args\n");
8370 				return NULL;
8371 			}
8372 			state = &regs[BPF_REG_1 + i];
8373 		}
8374 
8375 	if (!state)
8376 		verbose(env, "verifier internal error: no dynptr arg found\n");
8377 
8378 	return state;
8379 }
8380 
8381 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8382 {
8383 	struct bpf_func_state *state = func(env, reg);
8384 	int spi;
8385 
8386 	if (reg->type == CONST_PTR_TO_DYNPTR)
8387 		return reg->id;
8388 	spi = dynptr_get_spi(env, reg);
8389 	if (spi < 0)
8390 		return spi;
8391 	return state->stack[spi].spilled_ptr.id;
8392 }
8393 
8394 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8395 {
8396 	struct bpf_func_state *state = func(env, reg);
8397 	int spi;
8398 
8399 	if (reg->type == CONST_PTR_TO_DYNPTR)
8400 		return reg->ref_obj_id;
8401 	spi = dynptr_get_spi(env, reg);
8402 	if (spi < 0)
8403 		return spi;
8404 	return state->stack[spi].spilled_ptr.ref_obj_id;
8405 }
8406 
8407 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8408 					    struct bpf_reg_state *reg)
8409 {
8410 	struct bpf_func_state *state = func(env, reg);
8411 	int spi;
8412 
8413 	if (reg->type == CONST_PTR_TO_DYNPTR)
8414 		return reg->dynptr.type;
8415 
8416 	spi = __get_spi(reg->off);
8417 	if (spi < 0) {
8418 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8419 		return BPF_DYNPTR_TYPE_INVALID;
8420 	}
8421 
8422 	return state->stack[spi].spilled_ptr.dynptr.type;
8423 }
8424 
8425 static int check_reg_const_str(struct bpf_verifier_env *env,
8426 			       struct bpf_reg_state *reg, u32 regno)
8427 {
8428 	struct bpf_map *map = reg->map_ptr;
8429 	int err;
8430 	int map_off;
8431 	u64 map_addr;
8432 	char *str_ptr;
8433 
8434 	if (reg->type != PTR_TO_MAP_VALUE)
8435 		return -EINVAL;
8436 
8437 	if (!bpf_map_is_rdonly(map)) {
8438 		verbose(env, "R%d does not point to a readonly map'\n", regno);
8439 		return -EACCES;
8440 	}
8441 
8442 	if (!tnum_is_const(reg->var_off)) {
8443 		verbose(env, "R%d is not a constant address'\n", regno);
8444 		return -EACCES;
8445 	}
8446 
8447 	if (!map->ops->map_direct_value_addr) {
8448 		verbose(env, "no direct value access support for this map type\n");
8449 		return -EACCES;
8450 	}
8451 
8452 	err = check_map_access(env, regno, reg->off,
8453 			       map->value_size - reg->off, false,
8454 			       ACCESS_HELPER);
8455 	if (err)
8456 		return err;
8457 
8458 	map_off = reg->off + reg->var_off.value;
8459 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8460 	if (err) {
8461 		verbose(env, "direct value access on string failed\n");
8462 		return err;
8463 	}
8464 
8465 	str_ptr = (char *)(long)(map_addr);
8466 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8467 		verbose(env, "string is not zero-terminated\n");
8468 		return -EINVAL;
8469 	}
8470 	return 0;
8471 }
8472 
8473 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8474 			  struct bpf_call_arg_meta *meta,
8475 			  const struct bpf_func_proto *fn,
8476 			  int insn_idx)
8477 {
8478 	u32 regno = BPF_REG_1 + arg;
8479 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8480 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8481 	enum bpf_reg_type type = reg->type;
8482 	u32 *arg_btf_id = NULL;
8483 	int err = 0;
8484 
8485 	if (arg_type == ARG_DONTCARE)
8486 		return 0;
8487 
8488 	err = check_reg_arg(env, regno, SRC_OP);
8489 	if (err)
8490 		return err;
8491 
8492 	if (arg_type == ARG_ANYTHING) {
8493 		if (is_pointer_value(env, regno)) {
8494 			verbose(env, "R%d leaks addr into helper function\n",
8495 				regno);
8496 			return -EACCES;
8497 		}
8498 		return 0;
8499 	}
8500 
8501 	if (type_is_pkt_pointer(type) &&
8502 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8503 		verbose(env, "helper access to the packet is not allowed\n");
8504 		return -EACCES;
8505 	}
8506 
8507 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8508 		err = resolve_map_arg_type(env, meta, &arg_type);
8509 		if (err)
8510 			return err;
8511 	}
8512 
8513 	if (register_is_null(reg) && type_may_be_null(arg_type))
8514 		/* A NULL register has a SCALAR_VALUE type, so skip
8515 		 * type checking.
8516 		 */
8517 		goto skip_type_check;
8518 
8519 	/* arg_btf_id and arg_size are in a union. */
8520 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8521 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8522 		arg_btf_id = fn->arg_btf_id[arg];
8523 
8524 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8525 	if (err)
8526 		return err;
8527 
8528 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8529 	if (err)
8530 		return err;
8531 
8532 skip_type_check:
8533 	if (arg_type_is_release(arg_type)) {
8534 		if (arg_type_is_dynptr(arg_type)) {
8535 			struct bpf_func_state *state = func(env, reg);
8536 			int spi;
8537 
8538 			/* Only dynptr created on stack can be released, thus
8539 			 * the get_spi and stack state checks for spilled_ptr
8540 			 * should only be done before process_dynptr_func for
8541 			 * PTR_TO_STACK.
8542 			 */
8543 			if (reg->type == PTR_TO_STACK) {
8544 				spi = dynptr_get_spi(env, reg);
8545 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8546 					verbose(env, "arg %d is an unacquired reference\n", regno);
8547 					return -EINVAL;
8548 				}
8549 			} else {
8550 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8551 				return -EINVAL;
8552 			}
8553 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8554 			verbose(env, "R%d must be referenced when passed to release function\n",
8555 				regno);
8556 			return -EINVAL;
8557 		}
8558 		if (meta->release_regno) {
8559 			verbose(env, "verifier internal error: more than one release argument\n");
8560 			return -EFAULT;
8561 		}
8562 		meta->release_regno = regno;
8563 	}
8564 
8565 	if (reg->ref_obj_id) {
8566 		if (meta->ref_obj_id) {
8567 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8568 				regno, reg->ref_obj_id,
8569 				meta->ref_obj_id);
8570 			return -EFAULT;
8571 		}
8572 		meta->ref_obj_id = reg->ref_obj_id;
8573 	}
8574 
8575 	switch (base_type(arg_type)) {
8576 	case ARG_CONST_MAP_PTR:
8577 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8578 		if (meta->map_ptr) {
8579 			/* Use map_uid (which is unique id of inner map) to reject:
8580 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8581 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8582 			 * if (inner_map1 && inner_map2) {
8583 			 *     timer = bpf_map_lookup_elem(inner_map1);
8584 			 *     if (timer)
8585 			 *         // mismatch would have been allowed
8586 			 *         bpf_timer_init(timer, inner_map2);
8587 			 * }
8588 			 *
8589 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8590 			 */
8591 			if (meta->map_ptr != reg->map_ptr ||
8592 			    meta->map_uid != reg->map_uid) {
8593 				verbose(env,
8594 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8595 					meta->map_uid, reg->map_uid);
8596 				return -EINVAL;
8597 			}
8598 		}
8599 		meta->map_ptr = reg->map_ptr;
8600 		meta->map_uid = reg->map_uid;
8601 		break;
8602 	case ARG_PTR_TO_MAP_KEY:
8603 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8604 		 * check that [key, key + map->key_size) are within
8605 		 * stack limits and initialized
8606 		 */
8607 		if (!meta->map_ptr) {
8608 			/* in function declaration map_ptr must come before
8609 			 * map_key, so that it's verified and known before
8610 			 * we have to check map_key here. Otherwise it means
8611 			 * that kernel subsystem misconfigured verifier
8612 			 */
8613 			verbose(env, "invalid map_ptr to access map->key\n");
8614 			return -EACCES;
8615 		}
8616 		err = check_helper_mem_access(env, regno,
8617 					      meta->map_ptr->key_size, false,
8618 					      NULL);
8619 		break;
8620 	case ARG_PTR_TO_MAP_VALUE:
8621 		if (type_may_be_null(arg_type) && register_is_null(reg))
8622 			return 0;
8623 
8624 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8625 		 * check [value, value + map->value_size) validity
8626 		 */
8627 		if (!meta->map_ptr) {
8628 			/* kernel subsystem misconfigured verifier */
8629 			verbose(env, "invalid map_ptr to access map->value\n");
8630 			return -EACCES;
8631 		}
8632 		meta->raw_mode = arg_type & MEM_UNINIT;
8633 		err = check_helper_mem_access(env, regno,
8634 					      meta->map_ptr->value_size, false,
8635 					      meta);
8636 		break;
8637 	case ARG_PTR_TO_PERCPU_BTF_ID:
8638 		if (!reg->btf_id) {
8639 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8640 			return -EACCES;
8641 		}
8642 		meta->ret_btf = reg->btf;
8643 		meta->ret_btf_id = reg->btf_id;
8644 		break;
8645 	case ARG_PTR_TO_SPIN_LOCK:
8646 		if (in_rbtree_lock_required_cb(env)) {
8647 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8648 			return -EACCES;
8649 		}
8650 		if (meta->func_id == BPF_FUNC_spin_lock) {
8651 			err = process_spin_lock(env, regno, true);
8652 			if (err)
8653 				return err;
8654 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8655 			err = process_spin_lock(env, regno, false);
8656 			if (err)
8657 				return err;
8658 		} else {
8659 			verbose(env, "verifier internal error\n");
8660 			return -EFAULT;
8661 		}
8662 		break;
8663 	case ARG_PTR_TO_TIMER:
8664 		err = process_timer_func(env, regno, meta);
8665 		if (err)
8666 			return err;
8667 		break;
8668 	case ARG_PTR_TO_FUNC:
8669 		meta->subprogno = reg->subprogno;
8670 		break;
8671 	case ARG_PTR_TO_MEM:
8672 		/* The access to this pointer is only checked when we hit the
8673 		 * next is_mem_size argument below.
8674 		 */
8675 		meta->raw_mode = arg_type & MEM_UNINIT;
8676 		if (arg_type & MEM_FIXED_SIZE) {
8677 			err = check_helper_mem_access(env, regno,
8678 						      fn->arg_size[arg], false,
8679 						      meta);
8680 		}
8681 		break;
8682 	case ARG_CONST_SIZE:
8683 		err = check_mem_size_reg(env, reg, regno, false, meta);
8684 		break;
8685 	case ARG_CONST_SIZE_OR_ZERO:
8686 		err = check_mem_size_reg(env, reg, regno, true, meta);
8687 		break;
8688 	case ARG_PTR_TO_DYNPTR:
8689 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8690 		if (err)
8691 			return err;
8692 		break;
8693 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8694 		if (!tnum_is_const(reg->var_off)) {
8695 			verbose(env, "R%d is not a known constant'\n",
8696 				regno);
8697 			return -EACCES;
8698 		}
8699 		meta->mem_size = reg->var_off.value;
8700 		err = mark_chain_precision(env, regno);
8701 		if (err)
8702 			return err;
8703 		break;
8704 	case ARG_PTR_TO_INT:
8705 	case ARG_PTR_TO_LONG:
8706 	{
8707 		int size = int_ptr_type_to_size(arg_type);
8708 
8709 		err = check_helper_mem_access(env, regno, size, false, meta);
8710 		if (err)
8711 			return err;
8712 		err = check_ptr_alignment(env, reg, 0, size, true);
8713 		break;
8714 	}
8715 	case ARG_PTR_TO_CONST_STR:
8716 	{
8717 		err = check_reg_const_str(env, reg, regno);
8718 		if (err)
8719 			return err;
8720 		break;
8721 	}
8722 	case ARG_PTR_TO_KPTR:
8723 		err = process_kptr_func(env, regno, meta);
8724 		if (err)
8725 			return err;
8726 		break;
8727 	}
8728 
8729 	return err;
8730 }
8731 
8732 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8733 {
8734 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8735 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8736 
8737 	if (func_id != BPF_FUNC_map_update_elem)
8738 		return false;
8739 
8740 	/* It's not possible to get access to a locked struct sock in these
8741 	 * contexts, so updating is safe.
8742 	 */
8743 	switch (type) {
8744 	case BPF_PROG_TYPE_TRACING:
8745 		if (eatype == BPF_TRACE_ITER)
8746 			return true;
8747 		break;
8748 	case BPF_PROG_TYPE_SOCKET_FILTER:
8749 	case BPF_PROG_TYPE_SCHED_CLS:
8750 	case BPF_PROG_TYPE_SCHED_ACT:
8751 	case BPF_PROG_TYPE_XDP:
8752 	case BPF_PROG_TYPE_SK_REUSEPORT:
8753 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8754 	case BPF_PROG_TYPE_SK_LOOKUP:
8755 		return true;
8756 	default:
8757 		break;
8758 	}
8759 
8760 	verbose(env, "cannot update sockmap in this context\n");
8761 	return false;
8762 }
8763 
8764 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8765 {
8766 	return env->prog->jit_requested &&
8767 	       bpf_jit_supports_subprog_tailcalls();
8768 }
8769 
8770 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8771 					struct bpf_map *map, int func_id)
8772 {
8773 	if (!map)
8774 		return 0;
8775 
8776 	/* We need a two way check, first is from map perspective ... */
8777 	switch (map->map_type) {
8778 	case BPF_MAP_TYPE_PROG_ARRAY:
8779 		if (func_id != BPF_FUNC_tail_call)
8780 			goto error;
8781 		break;
8782 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8783 		if (func_id != BPF_FUNC_perf_event_read &&
8784 		    func_id != BPF_FUNC_perf_event_output &&
8785 		    func_id != BPF_FUNC_skb_output &&
8786 		    func_id != BPF_FUNC_perf_event_read_value &&
8787 		    func_id != BPF_FUNC_xdp_output)
8788 			goto error;
8789 		break;
8790 	case BPF_MAP_TYPE_RINGBUF:
8791 		if (func_id != BPF_FUNC_ringbuf_output &&
8792 		    func_id != BPF_FUNC_ringbuf_reserve &&
8793 		    func_id != BPF_FUNC_ringbuf_query &&
8794 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8795 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8796 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8797 			goto error;
8798 		break;
8799 	case BPF_MAP_TYPE_USER_RINGBUF:
8800 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8801 			goto error;
8802 		break;
8803 	case BPF_MAP_TYPE_STACK_TRACE:
8804 		if (func_id != BPF_FUNC_get_stackid)
8805 			goto error;
8806 		break;
8807 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8808 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8809 		    func_id != BPF_FUNC_current_task_under_cgroup)
8810 			goto error;
8811 		break;
8812 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8813 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8814 		if (func_id != BPF_FUNC_get_local_storage)
8815 			goto error;
8816 		break;
8817 	case BPF_MAP_TYPE_DEVMAP:
8818 	case BPF_MAP_TYPE_DEVMAP_HASH:
8819 		if (func_id != BPF_FUNC_redirect_map &&
8820 		    func_id != BPF_FUNC_map_lookup_elem)
8821 			goto error;
8822 		break;
8823 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8824 	 * appear.
8825 	 */
8826 	case BPF_MAP_TYPE_CPUMAP:
8827 		if (func_id != BPF_FUNC_redirect_map)
8828 			goto error;
8829 		break;
8830 	case BPF_MAP_TYPE_XSKMAP:
8831 		if (func_id != BPF_FUNC_redirect_map &&
8832 		    func_id != BPF_FUNC_map_lookup_elem)
8833 			goto error;
8834 		break;
8835 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8836 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8837 		if (func_id != BPF_FUNC_map_lookup_elem)
8838 			goto error;
8839 		break;
8840 	case BPF_MAP_TYPE_SOCKMAP:
8841 		if (func_id != BPF_FUNC_sk_redirect_map &&
8842 		    func_id != BPF_FUNC_sock_map_update &&
8843 		    func_id != BPF_FUNC_map_delete_elem &&
8844 		    func_id != BPF_FUNC_msg_redirect_map &&
8845 		    func_id != BPF_FUNC_sk_select_reuseport &&
8846 		    func_id != BPF_FUNC_map_lookup_elem &&
8847 		    !may_update_sockmap(env, func_id))
8848 			goto error;
8849 		break;
8850 	case BPF_MAP_TYPE_SOCKHASH:
8851 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8852 		    func_id != BPF_FUNC_sock_hash_update &&
8853 		    func_id != BPF_FUNC_map_delete_elem &&
8854 		    func_id != BPF_FUNC_msg_redirect_hash &&
8855 		    func_id != BPF_FUNC_sk_select_reuseport &&
8856 		    func_id != BPF_FUNC_map_lookup_elem &&
8857 		    !may_update_sockmap(env, func_id))
8858 			goto error;
8859 		break;
8860 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8861 		if (func_id != BPF_FUNC_sk_select_reuseport)
8862 			goto error;
8863 		break;
8864 	case BPF_MAP_TYPE_QUEUE:
8865 	case BPF_MAP_TYPE_STACK:
8866 		if (func_id != BPF_FUNC_map_peek_elem &&
8867 		    func_id != BPF_FUNC_map_pop_elem &&
8868 		    func_id != BPF_FUNC_map_push_elem)
8869 			goto error;
8870 		break;
8871 	case BPF_MAP_TYPE_SK_STORAGE:
8872 		if (func_id != BPF_FUNC_sk_storage_get &&
8873 		    func_id != BPF_FUNC_sk_storage_delete &&
8874 		    func_id != BPF_FUNC_kptr_xchg)
8875 			goto error;
8876 		break;
8877 	case BPF_MAP_TYPE_INODE_STORAGE:
8878 		if (func_id != BPF_FUNC_inode_storage_get &&
8879 		    func_id != BPF_FUNC_inode_storage_delete &&
8880 		    func_id != BPF_FUNC_kptr_xchg)
8881 			goto error;
8882 		break;
8883 	case BPF_MAP_TYPE_TASK_STORAGE:
8884 		if (func_id != BPF_FUNC_task_storage_get &&
8885 		    func_id != BPF_FUNC_task_storage_delete &&
8886 		    func_id != BPF_FUNC_kptr_xchg)
8887 			goto error;
8888 		break;
8889 	case BPF_MAP_TYPE_CGRP_STORAGE:
8890 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8891 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8892 		    func_id != BPF_FUNC_kptr_xchg)
8893 			goto error;
8894 		break;
8895 	case BPF_MAP_TYPE_BLOOM_FILTER:
8896 		if (func_id != BPF_FUNC_map_peek_elem &&
8897 		    func_id != BPF_FUNC_map_push_elem)
8898 			goto error;
8899 		break;
8900 	default:
8901 		break;
8902 	}
8903 
8904 	/* ... and second from the function itself. */
8905 	switch (func_id) {
8906 	case BPF_FUNC_tail_call:
8907 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8908 			goto error;
8909 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8910 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8911 			return -EINVAL;
8912 		}
8913 		break;
8914 	case BPF_FUNC_perf_event_read:
8915 	case BPF_FUNC_perf_event_output:
8916 	case BPF_FUNC_perf_event_read_value:
8917 	case BPF_FUNC_skb_output:
8918 	case BPF_FUNC_xdp_output:
8919 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8920 			goto error;
8921 		break;
8922 	case BPF_FUNC_ringbuf_output:
8923 	case BPF_FUNC_ringbuf_reserve:
8924 	case BPF_FUNC_ringbuf_query:
8925 	case BPF_FUNC_ringbuf_reserve_dynptr:
8926 	case BPF_FUNC_ringbuf_submit_dynptr:
8927 	case BPF_FUNC_ringbuf_discard_dynptr:
8928 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8929 			goto error;
8930 		break;
8931 	case BPF_FUNC_user_ringbuf_drain:
8932 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8933 			goto error;
8934 		break;
8935 	case BPF_FUNC_get_stackid:
8936 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8937 			goto error;
8938 		break;
8939 	case BPF_FUNC_current_task_under_cgroup:
8940 	case BPF_FUNC_skb_under_cgroup:
8941 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8942 			goto error;
8943 		break;
8944 	case BPF_FUNC_redirect_map:
8945 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8946 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8947 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8948 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8949 			goto error;
8950 		break;
8951 	case BPF_FUNC_sk_redirect_map:
8952 	case BPF_FUNC_msg_redirect_map:
8953 	case BPF_FUNC_sock_map_update:
8954 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8955 			goto error;
8956 		break;
8957 	case BPF_FUNC_sk_redirect_hash:
8958 	case BPF_FUNC_msg_redirect_hash:
8959 	case BPF_FUNC_sock_hash_update:
8960 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8961 			goto error;
8962 		break;
8963 	case BPF_FUNC_get_local_storage:
8964 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8965 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8966 			goto error;
8967 		break;
8968 	case BPF_FUNC_sk_select_reuseport:
8969 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8970 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8971 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8972 			goto error;
8973 		break;
8974 	case BPF_FUNC_map_pop_elem:
8975 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8976 		    map->map_type != BPF_MAP_TYPE_STACK)
8977 			goto error;
8978 		break;
8979 	case BPF_FUNC_map_peek_elem:
8980 	case BPF_FUNC_map_push_elem:
8981 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8982 		    map->map_type != BPF_MAP_TYPE_STACK &&
8983 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8984 			goto error;
8985 		break;
8986 	case BPF_FUNC_map_lookup_percpu_elem:
8987 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8988 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8989 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8990 			goto error;
8991 		break;
8992 	case BPF_FUNC_sk_storage_get:
8993 	case BPF_FUNC_sk_storage_delete:
8994 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8995 			goto error;
8996 		break;
8997 	case BPF_FUNC_inode_storage_get:
8998 	case BPF_FUNC_inode_storage_delete:
8999 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9000 			goto error;
9001 		break;
9002 	case BPF_FUNC_task_storage_get:
9003 	case BPF_FUNC_task_storage_delete:
9004 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9005 			goto error;
9006 		break;
9007 	case BPF_FUNC_cgrp_storage_get:
9008 	case BPF_FUNC_cgrp_storage_delete:
9009 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9010 			goto error;
9011 		break;
9012 	default:
9013 		break;
9014 	}
9015 
9016 	return 0;
9017 error:
9018 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9019 		map->map_type, func_id_name(func_id), func_id);
9020 	return -EINVAL;
9021 }
9022 
9023 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9024 {
9025 	int count = 0;
9026 
9027 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
9028 		count++;
9029 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
9030 		count++;
9031 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
9032 		count++;
9033 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
9034 		count++;
9035 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9036 		count++;
9037 
9038 	/* We only support one arg being in raw mode at the moment,
9039 	 * which is sufficient for the helper functions we have
9040 	 * right now.
9041 	 */
9042 	return count <= 1;
9043 }
9044 
9045 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9046 {
9047 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9048 	bool has_size = fn->arg_size[arg] != 0;
9049 	bool is_next_size = false;
9050 
9051 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9052 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9053 
9054 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9055 		return is_next_size;
9056 
9057 	return has_size == is_next_size || is_next_size == is_fixed;
9058 }
9059 
9060 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9061 {
9062 	/* bpf_xxx(..., buf, len) call will access 'len'
9063 	 * bytes from memory 'buf'. Both arg types need
9064 	 * to be paired, so make sure there's no buggy
9065 	 * helper function specification.
9066 	 */
9067 	if (arg_type_is_mem_size(fn->arg1_type) ||
9068 	    check_args_pair_invalid(fn, 0) ||
9069 	    check_args_pair_invalid(fn, 1) ||
9070 	    check_args_pair_invalid(fn, 2) ||
9071 	    check_args_pair_invalid(fn, 3) ||
9072 	    check_args_pair_invalid(fn, 4))
9073 		return false;
9074 
9075 	return true;
9076 }
9077 
9078 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9079 {
9080 	int i;
9081 
9082 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9083 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9084 			return !!fn->arg_btf_id[i];
9085 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9086 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9087 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9088 		    /* arg_btf_id and arg_size are in a union. */
9089 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9090 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9091 			return false;
9092 	}
9093 
9094 	return true;
9095 }
9096 
9097 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9098 {
9099 	return check_raw_mode_ok(fn) &&
9100 	       check_arg_pair_ok(fn) &&
9101 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9102 }
9103 
9104 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9105  * are now invalid, so turn them into unknown SCALAR_VALUE.
9106  *
9107  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9108  * since these slices point to packet data.
9109  */
9110 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9111 {
9112 	struct bpf_func_state *state;
9113 	struct bpf_reg_state *reg;
9114 
9115 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9116 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9117 			mark_reg_invalid(env, reg);
9118 	}));
9119 }
9120 
9121 enum {
9122 	AT_PKT_END = -1,
9123 	BEYOND_PKT_END = -2,
9124 };
9125 
9126 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9127 {
9128 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9129 	struct bpf_reg_state *reg = &state->regs[regn];
9130 
9131 	if (reg->type != PTR_TO_PACKET)
9132 		/* PTR_TO_PACKET_META is not supported yet */
9133 		return;
9134 
9135 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9136 	 * How far beyond pkt_end it goes is unknown.
9137 	 * if (!range_open) it's the case of pkt >= pkt_end
9138 	 * if (range_open) it's the case of pkt > pkt_end
9139 	 * hence this pointer is at least 1 byte bigger than pkt_end
9140 	 */
9141 	if (range_open)
9142 		reg->range = BEYOND_PKT_END;
9143 	else
9144 		reg->range = AT_PKT_END;
9145 }
9146 
9147 /* The pointer with the specified id has released its reference to kernel
9148  * resources. Identify all copies of the same pointer and clear the reference.
9149  */
9150 static int release_reference(struct bpf_verifier_env *env,
9151 			     int ref_obj_id)
9152 {
9153 	struct bpf_func_state *state;
9154 	struct bpf_reg_state *reg;
9155 	int err;
9156 
9157 	err = release_reference_state(cur_func(env), ref_obj_id);
9158 	if (err)
9159 		return err;
9160 
9161 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9162 		if (reg->ref_obj_id == ref_obj_id)
9163 			mark_reg_invalid(env, reg);
9164 	}));
9165 
9166 	return 0;
9167 }
9168 
9169 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9170 {
9171 	struct bpf_func_state *unused;
9172 	struct bpf_reg_state *reg;
9173 
9174 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9175 		if (type_is_non_owning_ref(reg->type))
9176 			mark_reg_invalid(env, reg);
9177 	}));
9178 }
9179 
9180 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9181 				    struct bpf_reg_state *regs)
9182 {
9183 	int i;
9184 
9185 	/* after the call registers r0 - r5 were scratched */
9186 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9187 		mark_reg_not_init(env, regs, caller_saved[i]);
9188 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9189 	}
9190 }
9191 
9192 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9193 				   struct bpf_func_state *caller,
9194 				   struct bpf_func_state *callee,
9195 				   int insn_idx);
9196 
9197 static int set_callee_state(struct bpf_verifier_env *env,
9198 			    struct bpf_func_state *caller,
9199 			    struct bpf_func_state *callee, int insn_idx);
9200 
9201 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9202 			    set_callee_state_fn set_callee_state_cb,
9203 			    struct bpf_verifier_state *state)
9204 {
9205 	struct bpf_func_state *caller, *callee;
9206 	int err;
9207 
9208 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9209 		verbose(env, "the call stack of %d frames is too deep\n",
9210 			state->curframe + 2);
9211 		return -E2BIG;
9212 	}
9213 
9214 	if (state->frame[state->curframe + 1]) {
9215 		verbose(env, "verifier bug. Frame %d already allocated\n",
9216 			state->curframe + 1);
9217 		return -EFAULT;
9218 	}
9219 
9220 	caller = state->frame[state->curframe];
9221 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9222 	if (!callee)
9223 		return -ENOMEM;
9224 	state->frame[state->curframe + 1] = callee;
9225 
9226 	/* callee cannot access r0, r6 - r9 for reading and has to write
9227 	 * into its own stack before reading from it.
9228 	 * callee can read/write into caller's stack
9229 	 */
9230 	init_func_state(env, callee,
9231 			/* remember the callsite, it will be used by bpf_exit */
9232 			callsite,
9233 			state->curframe + 1 /* frameno within this callchain */,
9234 			subprog /* subprog number within this prog */);
9235 	/* Transfer references to the callee */
9236 	err = copy_reference_state(callee, caller);
9237 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9238 	if (err)
9239 		goto err_out;
9240 
9241 	/* only increment it after check_reg_arg() finished */
9242 	state->curframe++;
9243 
9244 	return 0;
9245 
9246 err_out:
9247 	free_func_state(callee);
9248 	state->frame[state->curframe + 1] = NULL;
9249 	return err;
9250 }
9251 
9252 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
9253 				    const struct btf *btf,
9254 				    struct bpf_reg_state *regs)
9255 {
9256 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
9257 	struct bpf_verifier_log *log = &env->log;
9258 	u32 i;
9259 	int ret;
9260 
9261 	ret = btf_prepare_func_args(env, subprog);
9262 	if (ret)
9263 		return ret;
9264 
9265 	/* check that BTF function arguments match actual types that the
9266 	 * verifier sees.
9267 	 */
9268 	for (i = 0; i < sub->arg_cnt; i++) {
9269 		u32 regno = i + 1;
9270 		struct bpf_reg_state *reg = &regs[regno];
9271 		struct bpf_subprog_arg_info *arg = &sub->args[i];
9272 
9273 		if (arg->arg_type == ARG_ANYTHING) {
9274 			if (reg->type != SCALAR_VALUE) {
9275 				bpf_log(log, "R%d is not a scalar\n", regno);
9276 				return -EINVAL;
9277 			}
9278 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
9279 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9280 			if (ret < 0)
9281 				return ret;
9282 			/* If function expects ctx type in BTF check that caller
9283 			 * is passing PTR_TO_CTX.
9284 			 */
9285 			if (reg->type != PTR_TO_CTX) {
9286 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
9287 				return -EINVAL;
9288 			}
9289 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
9290 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9291 			if (ret < 0)
9292 				return ret;
9293 			if (check_mem_reg(env, reg, regno, arg->mem_size))
9294 				return -EINVAL;
9295 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
9296 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
9297 				return -EINVAL;
9298 			}
9299 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
9300 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
9301 			if (ret)
9302 				return ret;
9303 		} else {
9304 			bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n",
9305 				i, arg->arg_type);
9306 			return -EFAULT;
9307 		}
9308 	}
9309 
9310 	return 0;
9311 }
9312 
9313 /* Compare BTF of a function call with given bpf_reg_state.
9314  * Returns:
9315  * EFAULT - there is a verifier bug. Abort verification.
9316  * EINVAL - there is a type mismatch or BTF is not available.
9317  * 0 - BTF matches with what bpf_reg_state expects.
9318  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
9319  */
9320 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
9321 				  struct bpf_reg_state *regs)
9322 {
9323 	struct bpf_prog *prog = env->prog;
9324 	struct btf *btf = prog->aux->btf;
9325 	u32 btf_id;
9326 	int err;
9327 
9328 	if (!prog->aux->func_info)
9329 		return -EINVAL;
9330 
9331 	btf_id = prog->aux->func_info[subprog].type_id;
9332 	if (!btf_id)
9333 		return -EFAULT;
9334 
9335 	if (prog->aux->func_info_aux[subprog].unreliable)
9336 		return -EINVAL;
9337 
9338 	err = btf_check_func_arg_match(env, subprog, btf, regs);
9339 	/* Compiler optimizations can remove arguments from static functions
9340 	 * or mismatched type can be passed into a global function.
9341 	 * In such cases mark the function as unreliable from BTF point of view.
9342 	 */
9343 	if (err)
9344 		prog->aux->func_info_aux[subprog].unreliable = true;
9345 	return err;
9346 }
9347 
9348 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9349 			      int insn_idx, int subprog,
9350 			      set_callee_state_fn set_callee_state_cb)
9351 {
9352 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9353 	struct bpf_func_state *caller, *callee;
9354 	int err;
9355 
9356 	caller = state->frame[state->curframe];
9357 	err = btf_check_subprog_call(env, subprog, caller->regs);
9358 	if (err == -EFAULT)
9359 		return err;
9360 
9361 	/* set_callee_state is used for direct subprog calls, but we are
9362 	 * interested in validating only BPF helpers that can call subprogs as
9363 	 * callbacks
9364 	 */
9365 	env->subprog_info[subprog].is_cb = true;
9366 	if (bpf_pseudo_kfunc_call(insn) &&
9367 	    !is_sync_callback_calling_kfunc(insn->imm)) {
9368 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9369 			func_id_name(insn->imm), insn->imm);
9370 		return -EFAULT;
9371 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9372 		   !is_callback_calling_function(insn->imm)) { /* helper */
9373 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9374 			func_id_name(insn->imm), insn->imm);
9375 		return -EFAULT;
9376 	}
9377 
9378 	if (insn->code == (BPF_JMP | BPF_CALL) &&
9379 	    insn->src_reg == 0 &&
9380 	    insn->imm == BPF_FUNC_timer_set_callback) {
9381 		struct bpf_verifier_state *async_cb;
9382 
9383 		/* there is no real recursion here. timer callbacks are async */
9384 		env->subprog_info[subprog].is_async_cb = true;
9385 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9386 					 insn_idx, subprog);
9387 		if (!async_cb)
9388 			return -EFAULT;
9389 		callee = async_cb->frame[0];
9390 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9391 
9392 		/* Convert bpf_timer_set_callback() args into timer callback args */
9393 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9394 		if (err)
9395 			return err;
9396 
9397 		return 0;
9398 	}
9399 
9400 	/* for callback functions enqueue entry to callback and
9401 	 * proceed with next instruction within current frame.
9402 	 */
9403 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9404 	if (!callback_state)
9405 		return -ENOMEM;
9406 
9407 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9408 			       callback_state);
9409 	if (err)
9410 		return err;
9411 
9412 	callback_state->callback_unroll_depth++;
9413 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9414 	caller->callback_depth = 0;
9415 	return 0;
9416 }
9417 
9418 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9419 			   int *insn_idx)
9420 {
9421 	struct bpf_verifier_state *state = env->cur_state;
9422 	struct bpf_func_state *caller;
9423 	int err, subprog, target_insn;
9424 
9425 	target_insn = *insn_idx + insn->imm + 1;
9426 	subprog = find_subprog(env, target_insn);
9427 	if (subprog < 0) {
9428 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9429 		return -EFAULT;
9430 	}
9431 
9432 	caller = state->frame[state->curframe];
9433 	err = btf_check_subprog_call(env, subprog, caller->regs);
9434 	if (err == -EFAULT)
9435 		return err;
9436 	if (subprog_is_global(env, subprog)) {
9437 		const char *sub_name = subprog_name(env, subprog);
9438 
9439 		if (err) {
9440 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
9441 				subprog, sub_name);
9442 			return err;
9443 		}
9444 
9445 		verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
9446 			subprog, sub_name);
9447 		/* mark global subprog for verifying after main prog */
9448 		subprog_aux(env, subprog)->called = true;
9449 		clear_caller_saved_regs(env, caller->regs);
9450 
9451 		/* All global functions return a 64-bit SCALAR_VALUE */
9452 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9453 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9454 
9455 		/* continue with next insn after call */
9456 		return 0;
9457 	}
9458 
9459 	/* for regular function entry setup new frame and continue
9460 	 * from that frame.
9461 	 */
9462 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9463 	if (err)
9464 		return err;
9465 
9466 	clear_caller_saved_regs(env, caller->regs);
9467 
9468 	/* and go analyze first insn of the callee */
9469 	*insn_idx = env->subprog_info[subprog].start - 1;
9470 
9471 	if (env->log.level & BPF_LOG_LEVEL) {
9472 		verbose(env, "caller:\n");
9473 		print_verifier_state(env, caller, true);
9474 		verbose(env, "callee:\n");
9475 		print_verifier_state(env, state->frame[state->curframe], true);
9476 	}
9477 
9478 	return 0;
9479 }
9480 
9481 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9482 				   struct bpf_func_state *caller,
9483 				   struct bpf_func_state *callee)
9484 {
9485 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9486 	 *      void *callback_ctx, u64 flags);
9487 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9488 	 *      void *callback_ctx);
9489 	 */
9490 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9491 
9492 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9493 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9494 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9495 
9496 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9497 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9498 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9499 
9500 	/* pointer to stack or null */
9501 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9502 
9503 	/* unused */
9504 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9505 	return 0;
9506 }
9507 
9508 static int set_callee_state(struct bpf_verifier_env *env,
9509 			    struct bpf_func_state *caller,
9510 			    struct bpf_func_state *callee, int insn_idx)
9511 {
9512 	int i;
9513 
9514 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9515 	 * pointers, which connects us up to the liveness chain
9516 	 */
9517 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9518 		callee->regs[i] = caller->regs[i];
9519 	return 0;
9520 }
9521 
9522 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9523 				       struct bpf_func_state *caller,
9524 				       struct bpf_func_state *callee,
9525 				       int insn_idx)
9526 {
9527 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9528 	struct bpf_map *map;
9529 	int err;
9530 
9531 	if (bpf_map_ptr_poisoned(insn_aux)) {
9532 		verbose(env, "tail_call abusing map_ptr\n");
9533 		return -EINVAL;
9534 	}
9535 
9536 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9537 	if (!map->ops->map_set_for_each_callback_args ||
9538 	    !map->ops->map_for_each_callback) {
9539 		verbose(env, "callback function not allowed for map\n");
9540 		return -ENOTSUPP;
9541 	}
9542 
9543 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9544 	if (err)
9545 		return err;
9546 
9547 	callee->in_callback_fn = true;
9548 	callee->callback_ret_range = retval_range(0, 1);
9549 	return 0;
9550 }
9551 
9552 static int set_loop_callback_state(struct bpf_verifier_env *env,
9553 				   struct bpf_func_state *caller,
9554 				   struct bpf_func_state *callee,
9555 				   int insn_idx)
9556 {
9557 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9558 	 *	    u64 flags);
9559 	 * callback_fn(u32 index, void *callback_ctx);
9560 	 */
9561 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9562 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9563 
9564 	/* unused */
9565 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9566 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9567 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9568 
9569 	callee->in_callback_fn = true;
9570 	callee->callback_ret_range = retval_range(0, 1);
9571 	return 0;
9572 }
9573 
9574 static int set_timer_callback_state(struct bpf_verifier_env *env,
9575 				    struct bpf_func_state *caller,
9576 				    struct bpf_func_state *callee,
9577 				    int insn_idx)
9578 {
9579 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9580 
9581 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9582 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9583 	 */
9584 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9585 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9586 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9587 
9588 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9589 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9590 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9591 
9592 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9593 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9594 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9595 
9596 	/* unused */
9597 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9598 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9599 	callee->in_async_callback_fn = true;
9600 	callee->callback_ret_range = retval_range(0, 1);
9601 	return 0;
9602 }
9603 
9604 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9605 				       struct bpf_func_state *caller,
9606 				       struct bpf_func_state *callee,
9607 				       int insn_idx)
9608 {
9609 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9610 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9611 	 * (callback_fn)(struct task_struct *task,
9612 	 *               struct vm_area_struct *vma, void *callback_ctx);
9613 	 */
9614 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9615 
9616 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9617 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9618 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9619 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
9620 
9621 	/* pointer to stack or null */
9622 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9623 
9624 	/* unused */
9625 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9626 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9627 	callee->in_callback_fn = true;
9628 	callee->callback_ret_range = retval_range(0, 1);
9629 	return 0;
9630 }
9631 
9632 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9633 					   struct bpf_func_state *caller,
9634 					   struct bpf_func_state *callee,
9635 					   int insn_idx)
9636 {
9637 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9638 	 *			  callback_ctx, u64 flags);
9639 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9640 	 */
9641 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9642 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9643 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9644 
9645 	/* unused */
9646 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9647 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9648 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9649 
9650 	callee->in_callback_fn = true;
9651 	callee->callback_ret_range = retval_range(0, 1);
9652 	return 0;
9653 }
9654 
9655 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9656 					 struct bpf_func_state *caller,
9657 					 struct bpf_func_state *callee,
9658 					 int insn_idx)
9659 {
9660 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9661 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9662 	 *
9663 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9664 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9665 	 * by this point, so look at 'root'
9666 	 */
9667 	struct btf_field *field;
9668 
9669 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9670 				      BPF_RB_ROOT);
9671 	if (!field || !field->graph_root.value_btf_id)
9672 		return -EFAULT;
9673 
9674 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9675 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9676 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9677 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9678 
9679 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9680 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9681 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9682 	callee->in_callback_fn = true;
9683 	callee->callback_ret_range = retval_range(0, 1);
9684 	return 0;
9685 }
9686 
9687 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9688 
9689 /* Are we currently verifying the callback for a rbtree helper that must
9690  * be called with lock held? If so, no need to complain about unreleased
9691  * lock
9692  */
9693 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9694 {
9695 	struct bpf_verifier_state *state = env->cur_state;
9696 	struct bpf_insn *insn = env->prog->insnsi;
9697 	struct bpf_func_state *callee;
9698 	int kfunc_btf_id;
9699 
9700 	if (!state->curframe)
9701 		return false;
9702 
9703 	callee = state->frame[state->curframe];
9704 
9705 	if (!callee->in_callback_fn)
9706 		return false;
9707 
9708 	kfunc_btf_id = insn[callee->callsite].imm;
9709 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9710 }
9711 
9712 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg)
9713 {
9714 	return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
9715 }
9716 
9717 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9718 {
9719 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9720 	struct bpf_func_state *caller, *callee;
9721 	struct bpf_reg_state *r0;
9722 	bool in_callback_fn;
9723 	int err;
9724 
9725 	callee = state->frame[state->curframe];
9726 	r0 = &callee->regs[BPF_REG_0];
9727 	if (r0->type == PTR_TO_STACK) {
9728 		/* technically it's ok to return caller's stack pointer
9729 		 * (or caller's caller's pointer) back to the caller,
9730 		 * since these pointers are valid. Only current stack
9731 		 * pointer will be invalid as soon as function exits,
9732 		 * but let's be conservative
9733 		 */
9734 		verbose(env, "cannot return stack pointer to the caller\n");
9735 		return -EINVAL;
9736 	}
9737 
9738 	caller = state->frame[state->curframe - 1];
9739 	if (callee->in_callback_fn) {
9740 		if (r0->type != SCALAR_VALUE) {
9741 			verbose(env, "R0 not a scalar value\n");
9742 			return -EACCES;
9743 		}
9744 
9745 		/* we are going to rely on register's precise value */
9746 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9747 		err = err ?: mark_chain_precision(env, BPF_REG_0);
9748 		if (err)
9749 			return err;
9750 
9751 		/* enforce R0 return value range */
9752 		if (!retval_range_within(callee->callback_ret_range, r0)) {
9753 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
9754 					       "At callback return", "R0");
9755 			return -EINVAL;
9756 		}
9757 		if (!calls_callback(env, callee->callsite)) {
9758 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9759 				*insn_idx, callee->callsite);
9760 			return -EFAULT;
9761 		}
9762 	} else {
9763 		/* return to the caller whatever r0 had in the callee */
9764 		caller->regs[BPF_REG_0] = *r0;
9765 	}
9766 
9767 	/* callback_fn frame should have released its own additions to parent's
9768 	 * reference state at this point, or check_reference_leak would
9769 	 * complain, hence it must be the same as the caller. There is no need
9770 	 * to copy it back.
9771 	 */
9772 	if (!callee->in_callback_fn) {
9773 		/* Transfer references to the caller */
9774 		err = copy_reference_state(caller, callee);
9775 		if (err)
9776 			return err;
9777 	}
9778 
9779 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9780 	 * there function call logic would reschedule callback visit. If iteration
9781 	 * converges is_state_visited() would prune that visit eventually.
9782 	 */
9783 	in_callback_fn = callee->in_callback_fn;
9784 	if (in_callback_fn)
9785 		*insn_idx = callee->callsite;
9786 	else
9787 		*insn_idx = callee->callsite + 1;
9788 
9789 	if (env->log.level & BPF_LOG_LEVEL) {
9790 		verbose(env, "returning from callee:\n");
9791 		print_verifier_state(env, callee, true);
9792 		verbose(env, "to caller at %d:\n", *insn_idx);
9793 		print_verifier_state(env, caller, true);
9794 	}
9795 	/* clear everything in the callee. In case of exceptional exits using
9796 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
9797 	free_func_state(callee);
9798 	state->frame[state->curframe--] = NULL;
9799 
9800 	/* for callbacks widen imprecise scalars to make programs like below verify:
9801 	 *
9802 	 *   struct ctx { int i; }
9803 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9804 	 *   ...
9805 	 *   struct ctx = { .i = 0; }
9806 	 *   bpf_loop(100, cb, &ctx, 0);
9807 	 *
9808 	 * This is similar to what is done in process_iter_next_call() for open
9809 	 * coded iterators.
9810 	 */
9811 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9812 	if (prev_st) {
9813 		err = widen_imprecise_scalars(env, prev_st, state);
9814 		if (err)
9815 			return err;
9816 	}
9817 	return 0;
9818 }
9819 
9820 static int do_refine_retval_range(struct bpf_verifier_env *env,
9821 				  struct bpf_reg_state *regs, int ret_type,
9822 				  int func_id,
9823 				  struct bpf_call_arg_meta *meta)
9824 {
9825 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9826 
9827 	if (ret_type != RET_INTEGER)
9828 		return 0;
9829 
9830 	switch (func_id) {
9831 	case BPF_FUNC_get_stack:
9832 	case BPF_FUNC_get_task_stack:
9833 	case BPF_FUNC_probe_read_str:
9834 	case BPF_FUNC_probe_read_kernel_str:
9835 	case BPF_FUNC_probe_read_user_str:
9836 		ret_reg->smax_value = meta->msize_max_value;
9837 		ret_reg->s32_max_value = meta->msize_max_value;
9838 		ret_reg->smin_value = -MAX_ERRNO;
9839 		ret_reg->s32_min_value = -MAX_ERRNO;
9840 		reg_bounds_sync(ret_reg);
9841 		break;
9842 	case BPF_FUNC_get_smp_processor_id:
9843 		ret_reg->umax_value = nr_cpu_ids - 1;
9844 		ret_reg->u32_max_value = nr_cpu_ids - 1;
9845 		ret_reg->smax_value = nr_cpu_ids - 1;
9846 		ret_reg->s32_max_value = nr_cpu_ids - 1;
9847 		ret_reg->umin_value = 0;
9848 		ret_reg->u32_min_value = 0;
9849 		ret_reg->smin_value = 0;
9850 		ret_reg->s32_min_value = 0;
9851 		reg_bounds_sync(ret_reg);
9852 		break;
9853 	}
9854 
9855 	return reg_bounds_sanity_check(env, ret_reg, "retval");
9856 }
9857 
9858 static int
9859 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9860 		int func_id, int insn_idx)
9861 {
9862 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9863 	struct bpf_map *map = meta->map_ptr;
9864 
9865 	if (func_id != BPF_FUNC_tail_call &&
9866 	    func_id != BPF_FUNC_map_lookup_elem &&
9867 	    func_id != BPF_FUNC_map_update_elem &&
9868 	    func_id != BPF_FUNC_map_delete_elem &&
9869 	    func_id != BPF_FUNC_map_push_elem &&
9870 	    func_id != BPF_FUNC_map_pop_elem &&
9871 	    func_id != BPF_FUNC_map_peek_elem &&
9872 	    func_id != BPF_FUNC_for_each_map_elem &&
9873 	    func_id != BPF_FUNC_redirect_map &&
9874 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9875 		return 0;
9876 
9877 	if (map == NULL) {
9878 		verbose(env, "kernel subsystem misconfigured verifier\n");
9879 		return -EINVAL;
9880 	}
9881 
9882 	/* In case of read-only, some additional restrictions
9883 	 * need to be applied in order to prevent altering the
9884 	 * state of the map from program side.
9885 	 */
9886 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9887 	    (func_id == BPF_FUNC_map_delete_elem ||
9888 	     func_id == BPF_FUNC_map_update_elem ||
9889 	     func_id == BPF_FUNC_map_push_elem ||
9890 	     func_id == BPF_FUNC_map_pop_elem)) {
9891 		verbose(env, "write into map forbidden\n");
9892 		return -EACCES;
9893 	}
9894 
9895 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9896 		bpf_map_ptr_store(aux, meta->map_ptr,
9897 				  !meta->map_ptr->bypass_spec_v1);
9898 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9899 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9900 				  !meta->map_ptr->bypass_spec_v1);
9901 	return 0;
9902 }
9903 
9904 static int
9905 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9906 		int func_id, int insn_idx)
9907 {
9908 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9909 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9910 	struct bpf_map *map = meta->map_ptr;
9911 	u64 val, max;
9912 	int err;
9913 
9914 	if (func_id != BPF_FUNC_tail_call)
9915 		return 0;
9916 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9917 		verbose(env, "kernel subsystem misconfigured verifier\n");
9918 		return -EINVAL;
9919 	}
9920 
9921 	reg = &regs[BPF_REG_3];
9922 	val = reg->var_off.value;
9923 	max = map->max_entries;
9924 
9925 	if (!(is_reg_const(reg, false) && val < max)) {
9926 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9927 		return 0;
9928 	}
9929 
9930 	err = mark_chain_precision(env, BPF_REG_3);
9931 	if (err)
9932 		return err;
9933 	if (bpf_map_key_unseen(aux))
9934 		bpf_map_key_store(aux, val);
9935 	else if (!bpf_map_key_poisoned(aux) &&
9936 		  bpf_map_key_immediate(aux) != val)
9937 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9938 	return 0;
9939 }
9940 
9941 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
9942 {
9943 	struct bpf_func_state *state = cur_func(env);
9944 	bool refs_lingering = false;
9945 	int i;
9946 
9947 	if (!exception_exit && state->frameno && !state->in_callback_fn)
9948 		return 0;
9949 
9950 	for (i = 0; i < state->acquired_refs; i++) {
9951 		if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9952 			continue;
9953 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9954 			state->refs[i].id, state->refs[i].insn_idx);
9955 		refs_lingering = true;
9956 	}
9957 	return refs_lingering ? -EINVAL : 0;
9958 }
9959 
9960 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9961 				   struct bpf_reg_state *regs)
9962 {
9963 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9964 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9965 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9966 	struct bpf_bprintf_data data = {};
9967 	int err, fmt_map_off, num_args;
9968 	u64 fmt_addr;
9969 	char *fmt;
9970 
9971 	/* data must be an array of u64 */
9972 	if (data_len_reg->var_off.value % 8)
9973 		return -EINVAL;
9974 	num_args = data_len_reg->var_off.value / 8;
9975 
9976 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9977 	 * and map_direct_value_addr is set.
9978 	 */
9979 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9980 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9981 						  fmt_map_off);
9982 	if (err) {
9983 		verbose(env, "verifier bug\n");
9984 		return -EFAULT;
9985 	}
9986 	fmt = (char *)(long)fmt_addr + fmt_map_off;
9987 
9988 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9989 	 * can focus on validating the format specifiers.
9990 	 */
9991 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9992 	if (err < 0)
9993 		verbose(env, "Invalid format string\n");
9994 
9995 	return err;
9996 }
9997 
9998 static int check_get_func_ip(struct bpf_verifier_env *env)
9999 {
10000 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10001 	int func_id = BPF_FUNC_get_func_ip;
10002 
10003 	if (type == BPF_PROG_TYPE_TRACING) {
10004 		if (!bpf_prog_has_trampoline(env->prog)) {
10005 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
10006 				func_id_name(func_id), func_id);
10007 			return -ENOTSUPP;
10008 		}
10009 		return 0;
10010 	} else if (type == BPF_PROG_TYPE_KPROBE) {
10011 		return 0;
10012 	}
10013 
10014 	verbose(env, "func %s#%d not supported for program type %d\n",
10015 		func_id_name(func_id), func_id, type);
10016 	return -ENOTSUPP;
10017 }
10018 
10019 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
10020 {
10021 	return &env->insn_aux_data[env->insn_idx];
10022 }
10023 
10024 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10025 {
10026 	struct bpf_reg_state *regs = cur_regs(env);
10027 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
10028 	bool reg_is_null = register_is_null(reg);
10029 
10030 	if (reg_is_null)
10031 		mark_chain_precision(env, BPF_REG_4);
10032 
10033 	return reg_is_null;
10034 }
10035 
10036 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10037 {
10038 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10039 
10040 	if (!state->initialized) {
10041 		state->initialized = 1;
10042 		state->fit_for_inline = loop_flag_is_zero(env);
10043 		state->callback_subprogno = subprogno;
10044 		return;
10045 	}
10046 
10047 	if (!state->fit_for_inline)
10048 		return;
10049 
10050 	state->fit_for_inline = (loop_flag_is_zero(env) &&
10051 				 state->callback_subprogno == subprogno);
10052 }
10053 
10054 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10055 			     int *insn_idx_p)
10056 {
10057 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10058 	bool returns_cpu_specific_alloc_ptr = false;
10059 	const struct bpf_func_proto *fn = NULL;
10060 	enum bpf_return_type ret_type;
10061 	enum bpf_type_flag ret_flag;
10062 	struct bpf_reg_state *regs;
10063 	struct bpf_call_arg_meta meta;
10064 	int insn_idx = *insn_idx_p;
10065 	bool changes_data;
10066 	int i, err, func_id;
10067 
10068 	/* find function prototype */
10069 	func_id = insn->imm;
10070 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
10071 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
10072 			func_id);
10073 		return -EINVAL;
10074 	}
10075 
10076 	if (env->ops->get_func_proto)
10077 		fn = env->ops->get_func_proto(func_id, env->prog);
10078 	if (!fn) {
10079 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
10080 			func_id);
10081 		return -EINVAL;
10082 	}
10083 
10084 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
10085 	if (!env->prog->gpl_compatible && fn->gpl_only) {
10086 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10087 		return -EINVAL;
10088 	}
10089 
10090 	if (fn->allowed && !fn->allowed(env->prog)) {
10091 		verbose(env, "helper call is not allowed in probe\n");
10092 		return -EINVAL;
10093 	}
10094 
10095 	if (!env->prog->aux->sleepable && fn->might_sleep) {
10096 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
10097 		return -EINVAL;
10098 	}
10099 
10100 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
10101 	changes_data = bpf_helper_changes_pkt_data(fn->func);
10102 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10103 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10104 			func_id_name(func_id), func_id);
10105 		return -EINVAL;
10106 	}
10107 
10108 	memset(&meta, 0, sizeof(meta));
10109 	meta.pkt_access = fn->pkt_access;
10110 
10111 	err = check_func_proto(fn, func_id);
10112 	if (err) {
10113 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10114 			func_id_name(func_id), func_id);
10115 		return err;
10116 	}
10117 
10118 	if (env->cur_state->active_rcu_lock) {
10119 		if (fn->might_sleep) {
10120 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10121 				func_id_name(func_id), func_id);
10122 			return -EINVAL;
10123 		}
10124 
10125 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10126 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10127 	}
10128 
10129 	meta.func_id = func_id;
10130 	/* check args */
10131 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10132 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10133 		if (err)
10134 			return err;
10135 	}
10136 
10137 	err = record_func_map(env, &meta, func_id, insn_idx);
10138 	if (err)
10139 		return err;
10140 
10141 	err = record_func_key(env, &meta, func_id, insn_idx);
10142 	if (err)
10143 		return err;
10144 
10145 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10146 	 * is inferred from register state.
10147 	 */
10148 	for (i = 0; i < meta.access_size; i++) {
10149 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10150 				       BPF_WRITE, -1, false, false);
10151 		if (err)
10152 			return err;
10153 	}
10154 
10155 	regs = cur_regs(env);
10156 
10157 	if (meta.release_regno) {
10158 		err = -EINVAL;
10159 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10160 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10161 		 * is safe to do directly.
10162 		 */
10163 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10164 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10165 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10166 				return -EFAULT;
10167 			}
10168 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10169 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10170 			u32 ref_obj_id = meta.ref_obj_id;
10171 			bool in_rcu = in_rcu_cs(env);
10172 			struct bpf_func_state *state;
10173 			struct bpf_reg_state *reg;
10174 
10175 			err = release_reference_state(cur_func(env), ref_obj_id);
10176 			if (!err) {
10177 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10178 					if (reg->ref_obj_id == ref_obj_id) {
10179 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10180 							reg->ref_obj_id = 0;
10181 							reg->type &= ~MEM_ALLOC;
10182 							reg->type |= MEM_RCU;
10183 						} else {
10184 							mark_reg_invalid(env, reg);
10185 						}
10186 					}
10187 				}));
10188 			}
10189 		} else if (meta.ref_obj_id) {
10190 			err = release_reference(env, meta.ref_obj_id);
10191 		} else if (register_is_null(&regs[meta.release_regno])) {
10192 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10193 			 * released is NULL, which must be > R0.
10194 			 */
10195 			err = 0;
10196 		}
10197 		if (err) {
10198 			verbose(env, "func %s#%d reference has not been acquired before\n",
10199 				func_id_name(func_id), func_id);
10200 			return err;
10201 		}
10202 	}
10203 
10204 	switch (func_id) {
10205 	case BPF_FUNC_tail_call:
10206 		err = check_reference_leak(env, false);
10207 		if (err) {
10208 			verbose(env, "tail_call would lead to reference leak\n");
10209 			return err;
10210 		}
10211 		break;
10212 	case BPF_FUNC_get_local_storage:
10213 		/* check that flags argument in get_local_storage(map, flags) is 0,
10214 		 * this is required because get_local_storage() can't return an error.
10215 		 */
10216 		if (!register_is_null(&regs[BPF_REG_2])) {
10217 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10218 			return -EINVAL;
10219 		}
10220 		break;
10221 	case BPF_FUNC_for_each_map_elem:
10222 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10223 					 set_map_elem_callback_state);
10224 		break;
10225 	case BPF_FUNC_timer_set_callback:
10226 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10227 					 set_timer_callback_state);
10228 		break;
10229 	case BPF_FUNC_find_vma:
10230 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10231 					 set_find_vma_callback_state);
10232 		break;
10233 	case BPF_FUNC_snprintf:
10234 		err = check_bpf_snprintf_call(env, regs);
10235 		break;
10236 	case BPF_FUNC_loop:
10237 		update_loop_inline_state(env, meta.subprogno);
10238 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10239 		 * is finished, thus mark it precise.
10240 		 */
10241 		err = mark_chain_precision(env, BPF_REG_1);
10242 		if (err)
10243 			return err;
10244 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10245 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10246 						 set_loop_callback_state);
10247 		} else {
10248 			cur_func(env)->callback_depth = 0;
10249 			if (env->log.level & BPF_LOG_LEVEL2)
10250 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10251 					env->cur_state->curframe);
10252 		}
10253 		break;
10254 	case BPF_FUNC_dynptr_from_mem:
10255 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10256 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10257 				reg_type_str(env, regs[BPF_REG_1].type));
10258 			return -EACCES;
10259 		}
10260 		break;
10261 	case BPF_FUNC_set_retval:
10262 		if (prog_type == BPF_PROG_TYPE_LSM &&
10263 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10264 			if (!env->prog->aux->attach_func_proto->type) {
10265 				/* Make sure programs that attach to void
10266 				 * hooks don't try to modify return value.
10267 				 */
10268 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10269 				return -EINVAL;
10270 			}
10271 		}
10272 		break;
10273 	case BPF_FUNC_dynptr_data:
10274 	{
10275 		struct bpf_reg_state *reg;
10276 		int id, ref_obj_id;
10277 
10278 		reg = get_dynptr_arg_reg(env, fn, regs);
10279 		if (!reg)
10280 			return -EFAULT;
10281 
10282 
10283 		if (meta.dynptr_id) {
10284 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10285 			return -EFAULT;
10286 		}
10287 		if (meta.ref_obj_id) {
10288 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10289 			return -EFAULT;
10290 		}
10291 
10292 		id = dynptr_id(env, reg);
10293 		if (id < 0) {
10294 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10295 			return id;
10296 		}
10297 
10298 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10299 		if (ref_obj_id < 0) {
10300 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10301 			return ref_obj_id;
10302 		}
10303 
10304 		meta.dynptr_id = id;
10305 		meta.ref_obj_id = ref_obj_id;
10306 
10307 		break;
10308 	}
10309 	case BPF_FUNC_dynptr_write:
10310 	{
10311 		enum bpf_dynptr_type dynptr_type;
10312 		struct bpf_reg_state *reg;
10313 
10314 		reg = get_dynptr_arg_reg(env, fn, regs);
10315 		if (!reg)
10316 			return -EFAULT;
10317 
10318 		dynptr_type = dynptr_get_type(env, reg);
10319 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10320 			return -EFAULT;
10321 
10322 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10323 			/* this will trigger clear_all_pkt_pointers(), which will
10324 			 * invalidate all dynptr slices associated with the skb
10325 			 */
10326 			changes_data = true;
10327 
10328 		break;
10329 	}
10330 	case BPF_FUNC_per_cpu_ptr:
10331 	case BPF_FUNC_this_cpu_ptr:
10332 	{
10333 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
10334 		const struct btf_type *type;
10335 
10336 		if (reg->type & MEM_RCU) {
10337 			type = btf_type_by_id(reg->btf, reg->btf_id);
10338 			if (!type || !btf_type_is_struct(type)) {
10339 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
10340 				return -EFAULT;
10341 			}
10342 			returns_cpu_specific_alloc_ptr = true;
10343 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10344 		}
10345 		break;
10346 	}
10347 	case BPF_FUNC_user_ringbuf_drain:
10348 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10349 					 set_user_ringbuf_callback_state);
10350 		break;
10351 	}
10352 
10353 	if (err)
10354 		return err;
10355 
10356 	/* reset caller saved regs */
10357 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10358 		mark_reg_not_init(env, regs, caller_saved[i]);
10359 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10360 	}
10361 
10362 	/* helper call returns 64-bit value. */
10363 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10364 
10365 	/* update return register (already marked as written above) */
10366 	ret_type = fn->ret_type;
10367 	ret_flag = type_flag(ret_type);
10368 
10369 	switch (base_type(ret_type)) {
10370 	case RET_INTEGER:
10371 		/* sets type to SCALAR_VALUE */
10372 		mark_reg_unknown(env, regs, BPF_REG_0);
10373 		break;
10374 	case RET_VOID:
10375 		regs[BPF_REG_0].type = NOT_INIT;
10376 		break;
10377 	case RET_PTR_TO_MAP_VALUE:
10378 		/* There is no offset yet applied, variable or fixed */
10379 		mark_reg_known_zero(env, regs, BPF_REG_0);
10380 		/* remember map_ptr, so that check_map_access()
10381 		 * can check 'value_size' boundary of memory access
10382 		 * to map element returned from bpf_map_lookup_elem()
10383 		 */
10384 		if (meta.map_ptr == NULL) {
10385 			verbose(env,
10386 				"kernel subsystem misconfigured verifier\n");
10387 			return -EINVAL;
10388 		}
10389 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10390 		regs[BPF_REG_0].map_uid = meta.map_uid;
10391 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10392 		if (!type_may_be_null(ret_type) &&
10393 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10394 			regs[BPF_REG_0].id = ++env->id_gen;
10395 		}
10396 		break;
10397 	case RET_PTR_TO_SOCKET:
10398 		mark_reg_known_zero(env, regs, BPF_REG_0);
10399 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10400 		break;
10401 	case RET_PTR_TO_SOCK_COMMON:
10402 		mark_reg_known_zero(env, regs, BPF_REG_0);
10403 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10404 		break;
10405 	case RET_PTR_TO_TCP_SOCK:
10406 		mark_reg_known_zero(env, regs, BPF_REG_0);
10407 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10408 		break;
10409 	case RET_PTR_TO_MEM:
10410 		mark_reg_known_zero(env, regs, BPF_REG_0);
10411 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10412 		regs[BPF_REG_0].mem_size = meta.mem_size;
10413 		break;
10414 	case RET_PTR_TO_MEM_OR_BTF_ID:
10415 	{
10416 		const struct btf_type *t;
10417 
10418 		mark_reg_known_zero(env, regs, BPF_REG_0);
10419 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10420 		if (!btf_type_is_struct(t)) {
10421 			u32 tsize;
10422 			const struct btf_type *ret;
10423 			const char *tname;
10424 
10425 			/* resolve the type size of ksym. */
10426 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10427 			if (IS_ERR(ret)) {
10428 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10429 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10430 					tname, PTR_ERR(ret));
10431 				return -EINVAL;
10432 			}
10433 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10434 			regs[BPF_REG_0].mem_size = tsize;
10435 		} else {
10436 			if (returns_cpu_specific_alloc_ptr) {
10437 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10438 			} else {
10439 				/* MEM_RDONLY may be carried from ret_flag, but it
10440 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10441 				 * it will confuse the check of PTR_TO_BTF_ID in
10442 				 * check_mem_access().
10443 				 */
10444 				ret_flag &= ~MEM_RDONLY;
10445 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10446 			}
10447 
10448 			regs[BPF_REG_0].btf = meta.ret_btf;
10449 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10450 		}
10451 		break;
10452 	}
10453 	case RET_PTR_TO_BTF_ID:
10454 	{
10455 		struct btf *ret_btf;
10456 		int ret_btf_id;
10457 
10458 		mark_reg_known_zero(env, regs, BPF_REG_0);
10459 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10460 		if (func_id == BPF_FUNC_kptr_xchg) {
10461 			ret_btf = meta.kptr_field->kptr.btf;
10462 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10463 			if (!btf_is_kernel(ret_btf)) {
10464 				regs[BPF_REG_0].type |= MEM_ALLOC;
10465 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10466 					regs[BPF_REG_0].type |= MEM_PERCPU;
10467 			}
10468 		} else {
10469 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10470 				verbose(env, "verifier internal error:");
10471 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10472 					func_id_name(func_id));
10473 				return -EINVAL;
10474 			}
10475 			ret_btf = btf_vmlinux;
10476 			ret_btf_id = *fn->ret_btf_id;
10477 		}
10478 		if (ret_btf_id == 0) {
10479 			verbose(env, "invalid return type %u of func %s#%d\n",
10480 				base_type(ret_type), func_id_name(func_id),
10481 				func_id);
10482 			return -EINVAL;
10483 		}
10484 		regs[BPF_REG_0].btf = ret_btf;
10485 		regs[BPF_REG_0].btf_id = ret_btf_id;
10486 		break;
10487 	}
10488 	default:
10489 		verbose(env, "unknown return type %u of func %s#%d\n",
10490 			base_type(ret_type), func_id_name(func_id), func_id);
10491 		return -EINVAL;
10492 	}
10493 
10494 	if (type_may_be_null(regs[BPF_REG_0].type))
10495 		regs[BPF_REG_0].id = ++env->id_gen;
10496 
10497 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10498 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10499 			func_id_name(func_id), func_id);
10500 		return -EFAULT;
10501 	}
10502 
10503 	if (is_dynptr_ref_function(func_id))
10504 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10505 
10506 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10507 		/* For release_reference() */
10508 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10509 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10510 		int id = acquire_reference_state(env, insn_idx);
10511 
10512 		if (id < 0)
10513 			return id;
10514 		/* For mark_ptr_or_null_reg() */
10515 		regs[BPF_REG_0].id = id;
10516 		/* For release_reference() */
10517 		regs[BPF_REG_0].ref_obj_id = id;
10518 	}
10519 
10520 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
10521 	if (err)
10522 		return err;
10523 
10524 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10525 	if (err)
10526 		return err;
10527 
10528 	if ((func_id == BPF_FUNC_get_stack ||
10529 	     func_id == BPF_FUNC_get_task_stack) &&
10530 	    !env->prog->has_callchain_buf) {
10531 		const char *err_str;
10532 
10533 #ifdef CONFIG_PERF_EVENTS
10534 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10535 		err_str = "cannot get callchain buffer for func %s#%d\n";
10536 #else
10537 		err = -ENOTSUPP;
10538 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10539 #endif
10540 		if (err) {
10541 			verbose(env, err_str, func_id_name(func_id), func_id);
10542 			return err;
10543 		}
10544 
10545 		env->prog->has_callchain_buf = true;
10546 	}
10547 
10548 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10549 		env->prog->call_get_stack = true;
10550 
10551 	if (func_id == BPF_FUNC_get_func_ip) {
10552 		if (check_get_func_ip(env))
10553 			return -ENOTSUPP;
10554 		env->prog->call_get_func_ip = true;
10555 	}
10556 
10557 	if (changes_data)
10558 		clear_all_pkt_pointers(env);
10559 	return 0;
10560 }
10561 
10562 /* mark_btf_func_reg_size() is used when the reg size is determined by
10563  * the BTF func_proto's return value size and argument.
10564  */
10565 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10566 				   size_t reg_size)
10567 {
10568 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10569 
10570 	if (regno == BPF_REG_0) {
10571 		/* Function return value */
10572 		reg->live |= REG_LIVE_WRITTEN;
10573 		reg->subreg_def = reg_size == sizeof(u64) ?
10574 			DEF_NOT_SUBREG : env->insn_idx + 1;
10575 	} else {
10576 		/* Function argument */
10577 		if (reg_size == sizeof(u64)) {
10578 			mark_insn_zext(env, reg);
10579 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10580 		} else {
10581 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10582 		}
10583 	}
10584 }
10585 
10586 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10587 {
10588 	return meta->kfunc_flags & KF_ACQUIRE;
10589 }
10590 
10591 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10592 {
10593 	return meta->kfunc_flags & KF_RELEASE;
10594 }
10595 
10596 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10597 {
10598 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10599 }
10600 
10601 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10602 {
10603 	return meta->kfunc_flags & KF_SLEEPABLE;
10604 }
10605 
10606 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10607 {
10608 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10609 }
10610 
10611 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10612 {
10613 	return meta->kfunc_flags & KF_RCU;
10614 }
10615 
10616 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
10617 {
10618 	return meta->kfunc_flags & KF_RCU_PROTECTED;
10619 }
10620 
10621 static bool __kfunc_param_match_suffix(const struct btf *btf,
10622 				       const struct btf_param *arg,
10623 				       const char *suffix)
10624 {
10625 	int suffix_len = strlen(suffix), len;
10626 	const char *param_name;
10627 
10628 	/* In the future, this can be ported to use BTF tagging */
10629 	param_name = btf_name_by_offset(btf, arg->name_off);
10630 	if (str_is_empty(param_name))
10631 		return false;
10632 	len = strlen(param_name);
10633 	if (len < suffix_len)
10634 		return false;
10635 	param_name += len - suffix_len;
10636 	return !strncmp(param_name, suffix, suffix_len);
10637 }
10638 
10639 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10640 				  const struct btf_param *arg,
10641 				  const struct bpf_reg_state *reg)
10642 {
10643 	const struct btf_type *t;
10644 
10645 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10646 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10647 		return false;
10648 
10649 	return __kfunc_param_match_suffix(btf, arg, "__sz");
10650 }
10651 
10652 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10653 					const struct btf_param *arg,
10654 					const struct bpf_reg_state *reg)
10655 {
10656 	const struct btf_type *t;
10657 
10658 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10659 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10660 		return false;
10661 
10662 	return __kfunc_param_match_suffix(btf, arg, "__szk");
10663 }
10664 
10665 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10666 {
10667 	return __kfunc_param_match_suffix(btf, arg, "__opt");
10668 }
10669 
10670 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10671 {
10672 	return __kfunc_param_match_suffix(btf, arg, "__k");
10673 }
10674 
10675 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10676 {
10677 	return __kfunc_param_match_suffix(btf, arg, "__ign");
10678 }
10679 
10680 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10681 {
10682 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
10683 }
10684 
10685 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10686 {
10687 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
10688 }
10689 
10690 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10691 {
10692 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10693 }
10694 
10695 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
10696 {
10697 	return __kfunc_param_match_suffix(btf, arg, "__nullable");
10698 }
10699 
10700 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
10701 {
10702 	return __kfunc_param_match_suffix(btf, arg, "__str");
10703 }
10704 
10705 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10706 					  const struct btf_param *arg,
10707 					  const char *name)
10708 {
10709 	int len, target_len = strlen(name);
10710 	const char *param_name;
10711 
10712 	param_name = btf_name_by_offset(btf, arg->name_off);
10713 	if (str_is_empty(param_name))
10714 		return false;
10715 	len = strlen(param_name);
10716 	if (len != target_len)
10717 		return false;
10718 	if (strcmp(param_name, name))
10719 		return false;
10720 
10721 	return true;
10722 }
10723 
10724 enum {
10725 	KF_ARG_DYNPTR_ID,
10726 	KF_ARG_LIST_HEAD_ID,
10727 	KF_ARG_LIST_NODE_ID,
10728 	KF_ARG_RB_ROOT_ID,
10729 	KF_ARG_RB_NODE_ID,
10730 };
10731 
10732 BTF_ID_LIST(kf_arg_btf_ids)
10733 BTF_ID(struct, bpf_dynptr_kern)
10734 BTF_ID(struct, bpf_list_head)
10735 BTF_ID(struct, bpf_list_node)
10736 BTF_ID(struct, bpf_rb_root)
10737 BTF_ID(struct, bpf_rb_node)
10738 
10739 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10740 				    const struct btf_param *arg, int type)
10741 {
10742 	const struct btf_type *t;
10743 	u32 res_id;
10744 
10745 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10746 	if (!t)
10747 		return false;
10748 	if (!btf_type_is_ptr(t))
10749 		return false;
10750 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10751 	if (!t)
10752 		return false;
10753 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10754 }
10755 
10756 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10757 {
10758 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10759 }
10760 
10761 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10762 {
10763 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10764 }
10765 
10766 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10767 {
10768 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10769 }
10770 
10771 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10772 {
10773 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10774 }
10775 
10776 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10777 {
10778 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10779 }
10780 
10781 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10782 				  const struct btf_param *arg)
10783 {
10784 	const struct btf_type *t;
10785 
10786 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10787 	if (!t)
10788 		return false;
10789 
10790 	return true;
10791 }
10792 
10793 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10794 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10795 					const struct btf *btf,
10796 					const struct btf_type *t, int rec)
10797 {
10798 	const struct btf_type *member_type;
10799 	const struct btf_member *member;
10800 	u32 i;
10801 
10802 	if (!btf_type_is_struct(t))
10803 		return false;
10804 
10805 	for_each_member(i, t, member) {
10806 		const struct btf_array *array;
10807 
10808 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10809 		if (btf_type_is_struct(member_type)) {
10810 			if (rec >= 3) {
10811 				verbose(env, "max struct nesting depth exceeded\n");
10812 				return false;
10813 			}
10814 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10815 				return false;
10816 			continue;
10817 		}
10818 		if (btf_type_is_array(member_type)) {
10819 			array = btf_array(member_type);
10820 			if (!array->nelems)
10821 				return false;
10822 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10823 			if (!btf_type_is_scalar(member_type))
10824 				return false;
10825 			continue;
10826 		}
10827 		if (!btf_type_is_scalar(member_type))
10828 			return false;
10829 	}
10830 	return true;
10831 }
10832 
10833 enum kfunc_ptr_arg_type {
10834 	KF_ARG_PTR_TO_CTX,
10835 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10836 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10837 	KF_ARG_PTR_TO_DYNPTR,
10838 	KF_ARG_PTR_TO_ITER,
10839 	KF_ARG_PTR_TO_LIST_HEAD,
10840 	KF_ARG_PTR_TO_LIST_NODE,
10841 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10842 	KF_ARG_PTR_TO_MEM,
10843 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10844 	KF_ARG_PTR_TO_CALLBACK,
10845 	KF_ARG_PTR_TO_RB_ROOT,
10846 	KF_ARG_PTR_TO_RB_NODE,
10847 	KF_ARG_PTR_TO_NULL,
10848 	KF_ARG_PTR_TO_CONST_STR,
10849 };
10850 
10851 enum special_kfunc_type {
10852 	KF_bpf_obj_new_impl,
10853 	KF_bpf_obj_drop_impl,
10854 	KF_bpf_refcount_acquire_impl,
10855 	KF_bpf_list_push_front_impl,
10856 	KF_bpf_list_push_back_impl,
10857 	KF_bpf_list_pop_front,
10858 	KF_bpf_list_pop_back,
10859 	KF_bpf_cast_to_kern_ctx,
10860 	KF_bpf_rdonly_cast,
10861 	KF_bpf_rcu_read_lock,
10862 	KF_bpf_rcu_read_unlock,
10863 	KF_bpf_rbtree_remove,
10864 	KF_bpf_rbtree_add_impl,
10865 	KF_bpf_rbtree_first,
10866 	KF_bpf_dynptr_from_skb,
10867 	KF_bpf_dynptr_from_xdp,
10868 	KF_bpf_dynptr_slice,
10869 	KF_bpf_dynptr_slice_rdwr,
10870 	KF_bpf_dynptr_clone,
10871 	KF_bpf_percpu_obj_new_impl,
10872 	KF_bpf_percpu_obj_drop_impl,
10873 	KF_bpf_throw,
10874 	KF_bpf_iter_css_task_new,
10875 };
10876 
10877 BTF_SET_START(special_kfunc_set)
10878 BTF_ID(func, bpf_obj_new_impl)
10879 BTF_ID(func, bpf_obj_drop_impl)
10880 BTF_ID(func, bpf_refcount_acquire_impl)
10881 BTF_ID(func, bpf_list_push_front_impl)
10882 BTF_ID(func, bpf_list_push_back_impl)
10883 BTF_ID(func, bpf_list_pop_front)
10884 BTF_ID(func, bpf_list_pop_back)
10885 BTF_ID(func, bpf_cast_to_kern_ctx)
10886 BTF_ID(func, bpf_rdonly_cast)
10887 BTF_ID(func, bpf_rbtree_remove)
10888 BTF_ID(func, bpf_rbtree_add_impl)
10889 BTF_ID(func, bpf_rbtree_first)
10890 BTF_ID(func, bpf_dynptr_from_skb)
10891 BTF_ID(func, bpf_dynptr_from_xdp)
10892 BTF_ID(func, bpf_dynptr_slice)
10893 BTF_ID(func, bpf_dynptr_slice_rdwr)
10894 BTF_ID(func, bpf_dynptr_clone)
10895 BTF_ID(func, bpf_percpu_obj_new_impl)
10896 BTF_ID(func, bpf_percpu_obj_drop_impl)
10897 BTF_ID(func, bpf_throw)
10898 #ifdef CONFIG_CGROUPS
10899 BTF_ID(func, bpf_iter_css_task_new)
10900 #endif
10901 BTF_SET_END(special_kfunc_set)
10902 
10903 BTF_ID_LIST(special_kfunc_list)
10904 BTF_ID(func, bpf_obj_new_impl)
10905 BTF_ID(func, bpf_obj_drop_impl)
10906 BTF_ID(func, bpf_refcount_acquire_impl)
10907 BTF_ID(func, bpf_list_push_front_impl)
10908 BTF_ID(func, bpf_list_push_back_impl)
10909 BTF_ID(func, bpf_list_pop_front)
10910 BTF_ID(func, bpf_list_pop_back)
10911 BTF_ID(func, bpf_cast_to_kern_ctx)
10912 BTF_ID(func, bpf_rdonly_cast)
10913 BTF_ID(func, bpf_rcu_read_lock)
10914 BTF_ID(func, bpf_rcu_read_unlock)
10915 BTF_ID(func, bpf_rbtree_remove)
10916 BTF_ID(func, bpf_rbtree_add_impl)
10917 BTF_ID(func, bpf_rbtree_first)
10918 BTF_ID(func, bpf_dynptr_from_skb)
10919 BTF_ID(func, bpf_dynptr_from_xdp)
10920 BTF_ID(func, bpf_dynptr_slice)
10921 BTF_ID(func, bpf_dynptr_slice_rdwr)
10922 BTF_ID(func, bpf_dynptr_clone)
10923 BTF_ID(func, bpf_percpu_obj_new_impl)
10924 BTF_ID(func, bpf_percpu_obj_drop_impl)
10925 BTF_ID(func, bpf_throw)
10926 #ifdef CONFIG_CGROUPS
10927 BTF_ID(func, bpf_iter_css_task_new)
10928 #else
10929 BTF_ID_UNUSED
10930 #endif
10931 
10932 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10933 {
10934 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10935 	    meta->arg_owning_ref) {
10936 		return false;
10937 	}
10938 
10939 	return meta->kfunc_flags & KF_RET_NULL;
10940 }
10941 
10942 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10943 {
10944 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10945 }
10946 
10947 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10948 {
10949 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10950 }
10951 
10952 static enum kfunc_ptr_arg_type
10953 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10954 		       struct bpf_kfunc_call_arg_meta *meta,
10955 		       const struct btf_type *t, const struct btf_type *ref_t,
10956 		       const char *ref_tname, const struct btf_param *args,
10957 		       int argno, int nargs)
10958 {
10959 	u32 regno = argno + 1;
10960 	struct bpf_reg_state *regs = cur_regs(env);
10961 	struct bpf_reg_state *reg = &regs[regno];
10962 	bool arg_mem_size = false;
10963 
10964 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10965 		return KF_ARG_PTR_TO_CTX;
10966 
10967 	/* In this function, we verify the kfunc's BTF as per the argument type,
10968 	 * leaving the rest of the verification with respect to the register
10969 	 * type to our caller. When a set of conditions hold in the BTF type of
10970 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10971 	 */
10972 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10973 		return KF_ARG_PTR_TO_CTX;
10974 
10975 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10976 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10977 
10978 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10979 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10980 
10981 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10982 		return KF_ARG_PTR_TO_DYNPTR;
10983 
10984 	if (is_kfunc_arg_iter(meta, argno))
10985 		return KF_ARG_PTR_TO_ITER;
10986 
10987 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10988 		return KF_ARG_PTR_TO_LIST_HEAD;
10989 
10990 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10991 		return KF_ARG_PTR_TO_LIST_NODE;
10992 
10993 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10994 		return KF_ARG_PTR_TO_RB_ROOT;
10995 
10996 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10997 		return KF_ARG_PTR_TO_RB_NODE;
10998 
10999 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
11000 		return KF_ARG_PTR_TO_CONST_STR;
11001 
11002 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11003 		if (!btf_type_is_struct(ref_t)) {
11004 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
11005 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
11006 			return -EINVAL;
11007 		}
11008 		return KF_ARG_PTR_TO_BTF_ID;
11009 	}
11010 
11011 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
11012 		return KF_ARG_PTR_TO_CALLBACK;
11013 
11014 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
11015 		return KF_ARG_PTR_TO_NULL;
11016 
11017 	if (argno + 1 < nargs &&
11018 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
11019 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
11020 		arg_mem_size = true;
11021 
11022 	/* This is the catch all argument type of register types supported by
11023 	 * check_helper_mem_access. However, we only allow when argument type is
11024 	 * pointer to scalar, or struct composed (recursively) of scalars. When
11025 	 * arg_mem_size is true, the pointer can be void *.
11026 	 */
11027 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11028 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11029 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
11030 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11031 		return -EINVAL;
11032 	}
11033 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11034 }
11035 
11036 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11037 					struct bpf_reg_state *reg,
11038 					const struct btf_type *ref_t,
11039 					const char *ref_tname, u32 ref_id,
11040 					struct bpf_kfunc_call_arg_meta *meta,
11041 					int argno)
11042 {
11043 	const struct btf_type *reg_ref_t;
11044 	bool strict_type_match = false;
11045 	const struct btf *reg_btf;
11046 	const char *reg_ref_tname;
11047 	u32 reg_ref_id;
11048 
11049 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
11050 		reg_btf = reg->btf;
11051 		reg_ref_id = reg->btf_id;
11052 	} else {
11053 		reg_btf = btf_vmlinux;
11054 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11055 	}
11056 
11057 	/* Enforce strict type matching for calls to kfuncs that are acquiring
11058 	 * or releasing a reference, or are no-cast aliases. We do _not_
11059 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
11060 	 * as we want to enable BPF programs to pass types that are bitwise
11061 	 * equivalent without forcing them to explicitly cast with something
11062 	 * like bpf_cast_to_kern_ctx().
11063 	 *
11064 	 * For example, say we had a type like the following:
11065 	 *
11066 	 * struct bpf_cpumask {
11067 	 *	cpumask_t cpumask;
11068 	 *	refcount_t usage;
11069 	 * };
11070 	 *
11071 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11072 	 * to a struct cpumask, so it would be safe to pass a struct
11073 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11074 	 *
11075 	 * The philosophy here is similar to how we allow scalars of different
11076 	 * types to be passed to kfuncs as long as the size is the same. The
11077 	 * only difference here is that we're simply allowing
11078 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
11079 	 * resolve types.
11080 	 */
11081 	if (is_kfunc_acquire(meta) ||
11082 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
11083 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11084 		strict_type_match = true;
11085 
11086 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
11087 
11088 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
11089 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11090 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
11091 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
11092 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
11093 			btf_type_str(reg_ref_t), reg_ref_tname);
11094 		return -EINVAL;
11095 	}
11096 	return 0;
11097 }
11098 
11099 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11100 {
11101 	struct bpf_verifier_state *state = env->cur_state;
11102 	struct btf_record *rec = reg_btf_record(reg);
11103 
11104 	if (!state->active_lock.ptr) {
11105 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
11106 		return -EFAULT;
11107 	}
11108 
11109 	if (type_flag(reg->type) & NON_OWN_REF) {
11110 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
11111 		return -EFAULT;
11112 	}
11113 
11114 	reg->type |= NON_OWN_REF;
11115 	if (rec->refcount_off >= 0)
11116 		reg->type |= MEM_RCU;
11117 
11118 	return 0;
11119 }
11120 
11121 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
11122 {
11123 	struct bpf_func_state *state, *unused;
11124 	struct bpf_reg_state *reg;
11125 	int i;
11126 
11127 	state = cur_func(env);
11128 
11129 	if (!ref_obj_id) {
11130 		verbose(env, "verifier internal error: ref_obj_id is zero for "
11131 			     "owning -> non-owning conversion\n");
11132 		return -EFAULT;
11133 	}
11134 
11135 	for (i = 0; i < state->acquired_refs; i++) {
11136 		if (state->refs[i].id != ref_obj_id)
11137 			continue;
11138 
11139 		/* Clear ref_obj_id here so release_reference doesn't clobber
11140 		 * the whole reg
11141 		 */
11142 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11143 			if (reg->ref_obj_id == ref_obj_id) {
11144 				reg->ref_obj_id = 0;
11145 				ref_set_non_owning(env, reg);
11146 			}
11147 		}));
11148 		return 0;
11149 	}
11150 
11151 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
11152 	return -EFAULT;
11153 }
11154 
11155 /* Implementation details:
11156  *
11157  * Each register points to some region of memory, which we define as an
11158  * allocation. Each allocation may embed a bpf_spin_lock which protects any
11159  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11160  * allocation. The lock and the data it protects are colocated in the same
11161  * memory region.
11162  *
11163  * Hence, everytime a register holds a pointer value pointing to such
11164  * allocation, the verifier preserves a unique reg->id for it.
11165  *
11166  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11167  * bpf_spin_lock is called.
11168  *
11169  * To enable this, lock state in the verifier captures two values:
11170  *	active_lock.ptr = Register's type specific pointer
11171  *	active_lock.id  = A unique ID for each register pointer value
11172  *
11173  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11174  * supported register types.
11175  *
11176  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11177  * allocated objects is the reg->btf pointer.
11178  *
11179  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11180  * can establish the provenance of the map value statically for each distinct
11181  * lookup into such maps. They always contain a single map value hence unique
11182  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11183  *
11184  * So, in case of global variables, they use array maps with max_entries = 1,
11185  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11186  * into the same map value as max_entries is 1, as described above).
11187  *
11188  * In case of inner map lookups, the inner map pointer has same map_ptr as the
11189  * outer map pointer (in verifier context), but each lookup into an inner map
11190  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11191  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11192  * will get different reg->id assigned to each lookup, hence different
11193  * active_lock.id.
11194  *
11195  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11196  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11197  * returned from bpf_obj_new. Each allocation receives a new reg->id.
11198  */
11199 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11200 {
11201 	void *ptr;
11202 	u32 id;
11203 
11204 	switch ((int)reg->type) {
11205 	case PTR_TO_MAP_VALUE:
11206 		ptr = reg->map_ptr;
11207 		break;
11208 	case PTR_TO_BTF_ID | MEM_ALLOC:
11209 		ptr = reg->btf;
11210 		break;
11211 	default:
11212 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11213 		return -EFAULT;
11214 	}
11215 	id = reg->id;
11216 
11217 	if (!env->cur_state->active_lock.ptr)
11218 		return -EINVAL;
11219 	if (env->cur_state->active_lock.ptr != ptr ||
11220 	    env->cur_state->active_lock.id != id) {
11221 		verbose(env, "held lock and object are not in the same allocation\n");
11222 		return -EINVAL;
11223 	}
11224 	return 0;
11225 }
11226 
11227 static bool is_bpf_list_api_kfunc(u32 btf_id)
11228 {
11229 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11230 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11231 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11232 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11233 }
11234 
11235 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11236 {
11237 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11238 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11239 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11240 }
11241 
11242 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11243 {
11244 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11245 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11246 }
11247 
11248 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11249 {
11250 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11251 }
11252 
11253 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
11254 {
11255 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11256 	       insn->imm == special_kfunc_list[KF_bpf_throw];
11257 }
11258 
11259 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11260 {
11261 	return is_bpf_rbtree_api_kfunc(btf_id);
11262 }
11263 
11264 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11265 					  enum btf_field_type head_field_type,
11266 					  u32 kfunc_btf_id)
11267 {
11268 	bool ret;
11269 
11270 	switch (head_field_type) {
11271 	case BPF_LIST_HEAD:
11272 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11273 		break;
11274 	case BPF_RB_ROOT:
11275 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11276 		break;
11277 	default:
11278 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11279 			btf_field_type_name(head_field_type));
11280 		return false;
11281 	}
11282 
11283 	if (!ret)
11284 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11285 			btf_field_type_name(head_field_type));
11286 	return ret;
11287 }
11288 
11289 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11290 					  enum btf_field_type node_field_type,
11291 					  u32 kfunc_btf_id)
11292 {
11293 	bool ret;
11294 
11295 	switch (node_field_type) {
11296 	case BPF_LIST_NODE:
11297 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11298 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11299 		break;
11300 	case BPF_RB_NODE:
11301 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11302 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11303 		break;
11304 	default:
11305 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11306 			btf_field_type_name(node_field_type));
11307 		return false;
11308 	}
11309 
11310 	if (!ret)
11311 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11312 			btf_field_type_name(node_field_type));
11313 	return ret;
11314 }
11315 
11316 static int
11317 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11318 				   struct bpf_reg_state *reg, u32 regno,
11319 				   struct bpf_kfunc_call_arg_meta *meta,
11320 				   enum btf_field_type head_field_type,
11321 				   struct btf_field **head_field)
11322 {
11323 	const char *head_type_name;
11324 	struct btf_field *field;
11325 	struct btf_record *rec;
11326 	u32 head_off;
11327 
11328 	if (meta->btf != btf_vmlinux) {
11329 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11330 		return -EFAULT;
11331 	}
11332 
11333 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11334 		return -EFAULT;
11335 
11336 	head_type_name = btf_field_type_name(head_field_type);
11337 	if (!tnum_is_const(reg->var_off)) {
11338 		verbose(env,
11339 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11340 			regno, head_type_name);
11341 		return -EINVAL;
11342 	}
11343 
11344 	rec = reg_btf_record(reg);
11345 	head_off = reg->off + reg->var_off.value;
11346 	field = btf_record_find(rec, head_off, head_field_type);
11347 	if (!field) {
11348 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11349 		return -EINVAL;
11350 	}
11351 
11352 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11353 	if (check_reg_allocation_locked(env, reg)) {
11354 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11355 			rec->spin_lock_off, head_type_name);
11356 		return -EINVAL;
11357 	}
11358 
11359 	if (*head_field) {
11360 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11361 		return -EFAULT;
11362 	}
11363 	*head_field = field;
11364 	return 0;
11365 }
11366 
11367 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11368 					   struct bpf_reg_state *reg, u32 regno,
11369 					   struct bpf_kfunc_call_arg_meta *meta)
11370 {
11371 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11372 							  &meta->arg_list_head.field);
11373 }
11374 
11375 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11376 					     struct bpf_reg_state *reg, u32 regno,
11377 					     struct bpf_kfunc_call_arg_meta *meta)
11378 {
11379 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11380 							  &meta->arg_rbtree_root.field);
11381 }
11382 
11383 static int
11384 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11385 				   struct bpf_reg_state *reg, u32 regno,
11386 				   struct bpf_kfunc_call_arg_meta *meta,
11387 				   enum btf_field_type head_field_type,
11388 				   enum btf_field_type node_field_type,
11389 				   struct btf_field **node_field)
11390 {
11391 	const char *node_type_name;
11392 	const struct btf_type *et, *t;
11393 	struct btf_field *field;
11394 	u32 node_off;
11395 
11396 	if (meta->btf != btf_vmlinux) {
11397 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11398 		return -EFAULT;
11399 	}
11400 
11401 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11402 		return -EFAULT;
11403 
11404 	node_type_name = btf_field_type_name(node_field_type);
11405 	if (!tnum_is_const(reg->var_off)) {
11406 		verbose(env,
11407 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11408 			regno, node_type_name);
11409 		return -EINVAL;
11410 	}
11411 
11412 	node_off = reg->off + reg->var_off.value;
11413 	field = reg_find_field_offset(reg, node_off, node_field_type);
11414 	if (!field || field->offset != node_off) {
11415 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11416 		return -EINVAL;
11417 	}
11418 
11419 	field = *node_field;
11420 
11421 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11422 	t = btf_type_by_id(reg->btf, reg->btf_id);
11423 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11424 				  field->graph_root.value_btf_id, true)) {
11425 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11426 			"in struct %s, but arg is at offset=%d in struct %s\n",
11427 			btf_field_type_name(head_field_type),
11428 			btf_field_type_name(node_field_type),
11429 			field->graph_root.node_offset,
11430 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11431 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11432 		return -EINVAL;
11433 	}
11434 	meta->arg_btf = reg->btf;
11435 	meta->arg_btf_id = reg->btf_id;
11436 
11437 	if (node_off != field->graph_root.node_offset) {
11438 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11439 			node_off, btf_field_type_name(node_field_type),
11440 			field->graph_root.node_offset,
11441 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11442 		return -EINVAL;
11443 	}
11444 
11445 	return 0;
11446 }
11447 
11448 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11449 					   struct bpf_reg_state *reg, u32 regno,
11450 					   struct bpf_kfunc_call_arg_meta *meta)
11451 {
11452 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11453 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11454 						  &meta->arg_list_head.field);
11455 }
11456 
11457 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11458 					     struct bpf_reg_state *reg, u32 regno,
11459 					     struct bpf_kfunc_call_arg_meta *meta)
11460 {
11461 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11462 						  BPF_RB_ROOT, BPF_RB_NODE,
11463 						  &meta->arg_rbtree_root.field);
11464 }
11465 
11466 /*
11467  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
11468  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
11469  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
11470  * them can only be attached to some specific hook points.
11471  */
11472 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11473 {
11474 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11475 
11476 	switch (prog_type) {
11477 	case BPF_PROG_TYPE_LSM:
11478 		return true;
11479 	case BPF_PROG_TYPE_TRACING:
11480 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
11481 			return true;
11482 		fallthrough;
11483 	default:
11484 		return env->prog->aux->sleepable;
11485 	}
11486 }
11487 
11488 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11489 			    int insn_idx)
11490 {
11491 	const char *func_name = meta->func_name, *ref_tname;
11492 	const struct btf *btf = meta->btf;
11493 	const struct btf_param *args;
11494 	struct btf_record *rec;
11495 	u32 i, nargs;
11496 	int ret;
11497 
11498 	args = (const struct btf_param *)(meta->func_proto + 1);
11499 	nargs = btf_type_vlen(meta->func_proto);
11500 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11501 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11502 			MAX_BPF_FUNC_REG_ARGS);
11503 		return -EINVAL;
11504 	}
11505 
11506 	/* Check that BTF function arguments match actual types that the
11507 	 * verifier sees.
11508 	 */
11509 	for (i = 0; i < nargs; i++) {
11510 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11511 		const struct btf_type *t, *ref_t, *resolve_ret;
11512 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11513 		u32 regno = i + 1, ref_id, type_size;
11514 		bool is_ret_buf_sz = false;
11515 		int kf_arg_type;
11516 
11517 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11518 
11519 		if (is_kfunc_arg_ignore(btf, &args[i]))
11520 			continue;
11521 
11522 		if (btf_type_is_scalar(t)) {
11523 			if (reg->type != SCALAR_VALUE) {
11524 				verbose(env, "R%d is not a scalar\n", regno);
11525 				return -EINVAL;
11526 			}
11527 
11528 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11529 				if (meta->arg_constant.found) {
11530 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11531 					return -EFAULT;
11532 				}
11533 				if (!tnum_is_const(reg->var_off)) {
11534 					verbose(env, "R%d must be a known constant\n", regno);
11535 					return -EINVAL;
11536 				}
11537 				ret = mark_chain_precision(env, regno);
11538 				if (ret < 0)
11539 					return ret;
11540 				meta->arg_constant.found = true;
11541 				meta->arg_constant.value = reg->var_off.value;
11542 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11543 				meta->r0_rdonly = true;
11544 				is_ret_buf_sz = true;
11545 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11546 				is_ret_buf_sz = true;
11547 			}
11548 
11549 			if (is_ret_buf_sz) {
11550 				if (meta->r0_size) {
11551 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11552 					return -EINVAL;
11553 				}
11554 
11555 				if (!tnum_is_const(reg->var_off)) {
11556 					verbose(env, "R%d is not a const\n", regno);
11557 					return -EINVAL;
11558 				}
11559 
11560 				meta->r0_size = reg->var_off.value;
11561 				ret = mark_chain_precision(env, regno);
11562 				if (ret)
11563 					return ret;
11564 			}
11565 			continue;
11566 		}
11567 
11568 		if (!btf_type_is_ptr(t)) {
11569 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11570 			return -EINVAL;
11571 		}
11572 
11573 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11574 		    (register_is_null(reg) || type_may_be_null(reg->type)) &&
11575 			!is_kfunc_arg_nullable(meta->btf, &args[i])) {
11576 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11577 			return -EACCES;
11578 		}
11579 
11580 		if (reg->ref_obj_id) {
11581 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
11582 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11583 					regno, reg->ref_obj_id,
11584 					meta->ref_obj_id);
11585 				return -EFAULT;
11586 			}
11587 			meta->ref_obj_id = reg->ref_obj_id;
11588 			if (is_kfunc_release(meta))
11589 				meta->release_regno = regno;
11590 		}
11591 
11592 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11593 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11594 
11595 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11596 		if (kf_arg_type < 0)
11597 			return kf_arg_type;
11598 
11599 		switch (kf_arg_type) {
11600 		case KF_ARG_PTR_TO_NULL:
11601 			continue;
11602 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11603 		case KF_ARG_PTR_TO_BTF_ID:
11604 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11605 				break;
11606 
11607 			if (!is_trusted_reg(reg)) {
11608 				if (!is_kfunc_rcu(meta)) {
11609 					verbose(env, "R%d must be referenced or trusted\n", regno);
11610 					return -EINVAL;
11611 				}
11612 				if (!is_rcu_reg(reg)) {
11613 					verbose(env, "R%d must be a rcu pointer\n", regno);
11614 					return -EINVAL;
11615 				}
11616 			}
11617 
11618 			fallthrough;
11619 		case KF_ARG_PTR_TO_CTX:
11620 			/* Trusted arguments have the same offset checks as release arguments */
11621 			arg_type |= OBJ_RELEASE;
11622 			break;
11623 		case KF_ARG_PTR_TO_DYNPTR:
11624 		case KF_ARG_PTR_TO_ITER:
11625 		case KF_ARG_PTR_TO_LIST_HEAD:
11626 		case KF_ARG_PTR_TO_LIST_NODE:
11627 		case KF_ARG_PTR_TO_RB_ROOT:
11628 		case KF_ARG_PTR_TO_RB_NODE:
11629 		case KF_ARG_PTR_TO_MEM:
11630 		case KF_ARG_PTR_TO_MEM_SIZE:
11631 		case KF_ARG_PTR_TO_CALLBACK:
11632 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11633 		case KF_ARG_PTR_TO_CONST_STR:
11634 			/* Trusted by default */
11635 			break;
11636 		default:
11637 			WARN_ON_ONCE(1);
11638 			return -EFAULT;
11639 		}
11640 
11641 		if (is_kfunc_release(meta) && reg->ref_obj_id)
11642 			arg_type |= OBJ_RELEASE;
11643 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11644 		if (ret < 0)
11645 			return ret;
11646 
11647 		switch (kf_arg_type) {
11648 		case KF_ARG_PTR_TO_CTX:
11649 			if (reg->type != PTR_TO_CTX) {
11650 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11651 				return -EINVAL;
11652 			}
11653 
11654 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11655 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11656 				if (ret < 0)
11657 					return -EINVAL;
11658 				meta->ret_btf_id  = ret;
11659 			}
11660 			break;
11661 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11662 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
11663 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
11664 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
11665 					return -EINVAL;
11666 				}
11667 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
11668 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
11669 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
11670 					return -EINVAL;
11671 				}
11672 			} else {
11673 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11674 				return -EINVAL;
11675 			}
11676 			if (!reg->ref_obj_id) {
11677 				verbose(env, "allocated object must be referenced\n");
11678 				return -EINVAL;
11679 			}
11680 			if (meta->btf == btf_vmlinux) {
11681 				meta->arg_btf = reg->btf;
11682 				meta->arg_btf_id = reg->btf_id;
11683 			}
11684 			break;
11685 		case KF_ARG_PTR_TO_DYNPTR:
11686 		{
11687 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11688 			int clone_ref_obj_id = 0;
11689 
11690 			if (reg->type != PTR_TO_STACK &&
11691 			    reg->type != CONST_PTR_TO_DYNPTR) {
11692 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11693 				return -EINVAL;
11694 			}
11695 
11696 			if (reg->type == CONST_PTR_TO_DYNPTR)
11697 				dynptr_arg_type |= MEM_RDONLY;
11698 
11699 			if (is_kfunc_arg_uninit(btf, &args[i]))
11700 				dynptr_arg_type |= MEM_UNINIT;
11701 
11702 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11703 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11704 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11705 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
11706 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11707 				   (dynptr_arg_type & MEM_UNINIT)) {
11708 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11709 
11710 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11711 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11712 					return -EFAULT;
11713 				}
11714 
11715 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11716 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11717 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11718 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11719 					return -EFAULT;
11720 				}
11721 			}
11722 
11723 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11724 			if (ret < 0)
11725 				return ret;
11726 
11727 			if (!(dynptr_arg_type & MEM_UNINIT)) {
11728 				int id = dynptr_id(env, reg);
11729 
11730 				if (id < 0) {
11731 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11732 					return id;
11733 				}
11734 				meta->initialized_dynptr.id = id;
11735 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11736 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11737 			}
11738 
11739 			break;
11740 		}
11741 		case KF_ARG_PTR_TO_ITER:
11742 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
11743 				if (!check_css_task_iter_allowlist(env)) {
11744 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
11745 					return -EINVAL;
11746 				}
11747 			}
11748 			ret = process_iter_arg(env, regno, insn_idx, meta);
11749 			if (ret < 0)
11750 				return ret;
11751 			break;
11752 		case KF_ARG_PTR_TO_LIST_HEAD:
11753 			if (reg->type != PTR_TO_MAP_VALUE &&
11754 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11755 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11756 				return -EINVAL;
11757 			}
11758 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11759 				verbose(env, "allocated object must be referenced\n");
11760 				return -EINVAL;
11761 			}
11762 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11763 			if (ret < 0)
11764 				return ret;
11765 			break;
11766 		case KF_ARG_PTR_TO_RB_ROOT:
11767 			if (reg->type != PTR_TO_MAP_VALUE &&
11768 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11769 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11770 				return -EINVAL;
11771 			}
11772 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11773 				verbose(env, "allocated object must be referenced\n");
11774 				return -EINVAL;
11775 			}
11776 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11777 			if (ret < 0)
11778 				return ret;
11779 			break;
11780 		case KF_ARG_PTR_TO_LIST_NODE:
11781 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11782 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11783 				return -EINVAL;
11784 			}
11785 			if (!reg->ref_obj_id) {
11786 				verbose(env, "allocated object must be referenced\n");
11787 				return -EINVAL;
11788 			}
11789 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11790 			if (ret < 0)
11791 				return ret;
11792 			break;
11793 		case KF_ARG_PTR_TO_RB_NODE:
11794 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11795 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11796 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
11797 					return -EINVAL;
11798 				}
11799 				if (in_rbtree_lock_required_cb(env)) {
11800 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11801 					return -EINVAL;
11802 				}
11803 			} else {
11804 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11805 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
11806 					return -EINVAL;
11807 				}
11808 				if (!reg->ref_obj_id) {
11809 					verbose(env, "allocated object must be referenced\n");
11810 					return -EINVAL;
11811 				}
11812 			}
11813 
11814 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11815 			if (ret < 0)
11816 				return ret;
11817 			break;
11818 		case KF_ARG_PTR_TO_BTF_ID:
11819 			/* Only base_type is checked, further checks are done here */
11820 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11821 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11822 			    !reg2btf_ids[base_type(reg->type)]) {
11823 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11824 				verbose(env, "expected %s or socket\n",
11825 					reg_type_str(env, base_type(reg->type) |
11826 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11827 				return -EINVAL;
11828 			}
11829 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11830 			if (ret < 0)
11831 				return ret;
11832 			break;
11833 		case KF_ARG_PTR_TO_MEM:
11834 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11835 			if (IS_ERR(resolve_ret)) {
11836 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11837 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11838 				return -EINVAL;
11839 			}
11840 			ret = check_mem_reg(env, reg, regno, type_size);
11841 			if (ret < 0)
11842 				return ret;
11843 			break;
11844 		case KF_ARG_PTR_TO_MEM_SIZE:
11845 		{
11846 			struct bpf_reg_state *buff_reg = &regs[regno];
11847 			const struct btf_param *buff_arg = &args[i];
11848 			struct bpf_reg_state *size_reg = &regs[regno + 1];
11849 			const struct btf_param *size_arg = &args[i + 1];
11850 
11851 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11852 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11853 				if (ret < 0) {
11854 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11855 					return ret;
11856 				}
11857 			}
11858 
11859 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11860 				if (meta->arg_constant.found) {
11861 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11862 					return -EFAULT;
11863 				}
11864 				if (!tnum_is_const(size_reg->var_off)) {
11865 					verbose(env, "R%d must be a known constant\n", regno + 1);
11866 					return -EINVAL;
11867 				}
11868 				meta->arg_constant.found = true;
11869 				meta->arg_constant.value = size_reg->var_off.value;
11870 			}
11871 
11872 			/* Skip next '__sz' or '__szk' argument */
11873 			i++;
11874 			break;
11875 		}
11876 		case KF_ARG_PTR_TO_CALLBACK:
11877 			if (reg->type != PTR_TO_FUNC) {
11878 				verbose(env, "arg%d expected pointer to func\n", i);
11879 				return -EINVAL;
11880 			}
11881 			meta->subprogno = reg->subprogno;
11882 			break;
11883 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11884 			if (!type_is_ptr_alloc_obj(reg->type)) {
11885 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11886 				return -EINVAL;
11887 			}
11888 			if (!type_is_non_owning_ref(reg->type))
11889 				meta->arg_owning_ref = true;
11890 
11891 			rec = reg_btf_record(reg);
11892 			if (!rec) {
11893 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
11894 				return -EFAULT;
11895 			}
11896 
11897 			if (rec->refcount_off < 0) {
11898 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11899 				return -EINVAL;
11900 			}
11901 
11902 			meta->arg_btf = reg->btf;
11903 			meta->arg_btf_id = reg->btf_id;
11904 			break;
11905 		case KF_ARG_PTR_TO_CONST_STR:
11906 			if (reg->type != PTR_TO_MAP_VALUE) {
11907 				verbose(env, "arg#%d doesn't point to a const string\n", i);
11908 				return -EINVAL;
11909 			}
11910 			ret = check_reg_const_str(env, reg, regno);
11911 			if (ret)
11912 				return ret;
11913 			break;
11914 		}
11915 	}
11916 
11917 	if (is_kfunc_release(meta) && !meta->release_regno) {
11918 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11919 			func_name);
11920 		return -EINVAL;
11921 	}
11922 
11923 	return 0;
11924 }
11925 
11926 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11927 			    struct bpf_insn *insn,
11928 			    struct bpf_kfunc_call_arg_meta *meta,
11929 			    const char **kfunc_name)
11930 {
11931 	const struct btf_type *func, *func_proto;
11932 	u32 func_id, *kfunc_flags;
11933 	const char *func_name;
11934 	struct btf *desc_btf;
11935 
11936 	if (kfunc_name)
11937 		*kfunc_name = NULL;
11938 
11939 	if (!insn->imm)
11940 		return -EINVAL;
11941 
11942 	desc_btf = find_kfunc_desc_btf(env, insn->off);
11943 	if (IS_ERR(desc_btf))
11944 		return PTR_ERR(desc_btf);
11945 
11946 	func_id = insn->imm;
11947 	func = btf_type_by_id(desc_btf, func_id);
11948 	func_name = btf_name_by_offset(desc_btf, func->name_off);
11949 	if (kfunc_name)
11950 		*kfunc_name = func_name;
11951 	func_proto = btf_type_by_id(desc_btf, func->type);
11952 
11953 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11954 	if (!kfunc_flags) {
11955 		return -EACCES;
11956 	}
11957 
11958 	memset(meta, 0, sizeof(*meta));
11959 	meta->btf = desc_btf;
11960 	meta->func_id = func_id;
11961 	meta->kfunc_flags = *kfunc_flags;
11962 	meta->func_proto = func_proto;
11963 	meta->func_name = func_name;
11964 
11965 	return 0;
11966 }
11967 
11968 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
11969 
11970 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11971 			    int *insn_idx_p)
11972 {
11973 	const struct btf_type *t, *ptr_type;
11974 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
11975 	struct bpf_reg_state *regs = cur_regs(env);
11976 	const char *func_name, *ptr_type_name;
11977 	bool sleepable, rcu_lock, rcu_unlock;
11978 	struct bpf_kfunc_call_arg_meta meta;
11979 	struct bpf_insn_aux_data *insn_aux;
11980 	int err, insn_idx = *insn_idx_p;
11981 	const struct btf_param *args;
11982 	const struct btf_type *ret_t;
11983 	struct btf *desc_btf;
11984 
11985 	/* skip for now, but return error when we find this in fixup_kfunc_call */
11986 	if (!insn->imm)
11987 		return 0;
11988 
11989 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11990 	if (err == -EACCES && func_name)
11991 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
11992 	if (err)
11993 		return err;
11994 	desc_btf = meta.btf;
11995 	insn_aux = &env->insn_aux_data[insn_idx];
11996 
11997 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11998 
11999 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
12000 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
12001 		return -EACCES;
12002 	}
12003 
12004 	sleepable = is_kfunc_sleepable(&meta);
12005 	if (sleepable && !env->prog->aux->sleepable) {
12006 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
12007 		return -EACCES;
12008 	}
12009 
12010 	/* Check the arguments */
12011 	err = check_kfunc_args(env, &meta, insn_idx);
12012 	if (err < 0)
12013 		return err;
12014 
12015 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12016 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12017 					 set_rbtree_add_callback_state);
12018 		if (err) {
12019 			verbose(env, "kfunc %s#%d failed callback verification\n",
12020 				func_name, meta.func_id);
12021 			return err;
12022 		}
12023 	}
12024 
12025 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
12026 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
12027 
12028 	if (env->cur_state->active_rcu_lock) {
12029 		struct bpf_func_state *state;
12030 		struct bpf_reg_state *reg;
12031 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
12032 
12033 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
12034 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
12035 			return -EACCES;
12036 		}
12037 
12038 		if (rcu_lock) {
12039 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
12040 			return -EINVAL;
12041 		} else if (rcu_unlock) {
12042 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
12043 				if (reg->type & MEM_RCU) {
12044 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
12045 					reg->type |= PTR_UNTRUSTED;
12046 				}
12047 			}));
12048 			env->cur_state->active_rcu_lock = false;
12049 		} else if (sleepable) {
12050 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
12051 			return -EACCES;
12052 		}
12053 	} else if (rcu_lock) {
12054 		env->cur_state->active_rcu_lock = true;
12055 	} else if (rcu_unlock) {
12056 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
12057 		return -EINVAL;
12058 	}
12059 
12060 	/* In case of release function, we get register number of refcounted
12061 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
12062 	 */
12063 	if (meta.release_regno) {
12064 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
12065 		if (err) {
12066 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12067 				func_name, meta.func_id);
12068 			return err;
12069 		}
12070 	}
12071 
12072 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12073 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12074 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12075 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
12076 		insn_aux->insert_off = regs[BPF_REG_2].off;
12077 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
12078 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
12079 		if (err) {
12080 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
12081 				func_name, meta.func_id);
12082 			return err;
12083 		}
12084 
12085 		err = release_reference(env, release_ref_obj_id);
12086 		if (err) {
12087 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12088 				func_name, meta.func_id);
12089 			return err;
12090 		}
12091 	}
12092 
12093 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
12094 		if (!bpf_jit_supports_exceptions()) {
12095 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
12096 				func_name, meta.func_id);
12097 			return -ENOTSUPP;
12098 		}
12099 		env->seen_exception = true;
12100 
12101 		/* In the case of the default callback, the cookie value passed
12102 		 * to bpf_throw becomes the return value of the program.
12103 		 */
12104 		if (!env->exception_callback_subprog) {
12105 			err = check_return_code(env, BPF_REG_1, "R1");
12106 			if (err < 0)
12107 				return err;
12108 		}
12109 	}
12110 
12111 	for (i = 0; i < CALLER_SAVED_REGS; i++)
12112 		mark_reg_not_init(env, regs, caller_saved[i]);
12113 
12114 	/* Check return type */
12115 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
12116 
12117 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
12118 		/* Only exception is bpf_obj_new_impl */
12119 		if (meta.btf != btf_vmlinux ||
12120 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
12121 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
12122 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
12123 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
12124 			return -EINVAL;
12125 		}
12126 	}
12127 
12128 	if (btf_type_is_scalar(t)) {
12129 		mark_reg_unknown(env, regs, BPF_REG_0);
12130 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
12131 	} else if (btf_type_is_ptr(t)) {
12132 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
12133 
12134 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12135 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
12136 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12137 				struct btf_struct_meta *struct_meta;
12138 				struct btf *ret_btf;
12139 				u32 ret_btf_id;
12140 
12141 				if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
12142 					return -ENOMEM;
12143 
12144 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12145 					if (!bpf_global_percpu_ma_set) {
12146 						mutex_lock(&bpf_percpu_ma_lock);
12147 						if (!bpf_global_percpu_ma_set) {
12148 							err = bpf_mem_alloc_init(&bpf_global_percpu_ma, 0, true);
12149 							if (!err)
12150 								bpf_global_percpu_ma_set = true;
12151 						}
12152 						mutex_unlock(&bpf_percpu_ma_lock);
12153 						if (err)
12154 							return err;
12155 					}
12156 				}
12157 
12158 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
12159 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12160 					return -EINVAL;
12161 				}
12162 
12163 				ret_btf = env->prog->aux->btf;
12164 				ret_btf_id = meta.arg_constant.value;
12165 
12166 				/* This may be NULL due to user not supplying a BTF */
12167 				if (!ret_btf) {
12168 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12169 					return -EINVAL;
12170 				}
12171 
12172 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12173 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
12174 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12175 					return -EINVAL;
12176 				}
12177 
12178 				struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12179 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12180 					if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12181 						verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12182 						return -EINVAL;
12183 					}
12184 
12185 					if (struct_meta) {
12186 						verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12187 						return -EINVAL;
12188 					}
12189 				}
12190 
12191 				mark_reg_known_zero(env, regs, BPF_REG_0);
12192 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12193 				regs[BPF_REG_0].btf = ret_btf;
12194 				regs[BPF_REG_0].btf_id = ret_btf_id;
12195 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12196 					regs[BPF_REG_0].type |= MEM_PERCPU;
12197 
12198 				insn_aux->obj_new_size = ret_t->size;
12199 				insn_aux->kptr_struct_meta = struct_meta;
12200 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12201 				mark_reg_known_zero(env, regs, BPF_REG_0);
12202 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12203 				regs[BPF_REG_0].btf = meta.arg_btf;
12204 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
12205 
12206 				insn_aux->kptr_struct_meta =
12207 					btf_find_struct_meta(meta.arg_btf,
12208 							     meta.arg_btf_id);
12209 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12210 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12211 				struct btf_field *field = meta.arg_list_head.field;
12212 
12213 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12214 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12215 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12216 				struct btf_field *field = meta.arg_rbtree_root.field;
12217 
12218 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12219 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12220 				mark_reg_known_zero(env, regs, BPF_REG_0);
12221 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12222 				regs[BPF_REG_0].btf = desc_btf;
12223 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12224 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12225 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12226 				if (!ret_t || !btf_type_is_struct(ret_t)) {
12227 					verbose(env,
12228 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
12229 					return -EINVAL;
12230 				}
12231 
12232 				mark_reg_known_zero(env, regs, BPF_REG_0);
12233 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12234 				regs[BPF_REG_0].btf = desc_btf;
12235 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
12236 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12237 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12238 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
12239 
12240 				mark_reg_known_zero(env, regs, BPF_REG_0);
12241 
12242 				if (!meta.arg_constant.found) {
12243 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
12244 					return -EFAULT;
12245 				}
12246 
12247 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
12248 
12249 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12250 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12251 
12252 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12253 					regs[BPF_REG_0].type |= MEM_RDONLY;
12254 				} else {
12255 					/* this will set env->seen_direct_write to true */
12256 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12257 						verbose(env, "the prog does not allow writes to packet data\n");
12258 						return -EINVAL;
12259 					}
12260 				}
12261 
12262 				if (!meta.initialized_dynptr.id) {
12263 					verbose(env, "verifier internal error: no dynptr id\n");
12264 					return -EFAULT;
12265 				}
12266 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
12267 
12268 				/* we don't need to set BPF_REG_0's ref obj id
12269 				 * because packet slices are not refcounted (see
12270 				 * dynptr_type_refcounted)
12271 				 */
12272 			} else {
12273 				verbose(env, "kernel function %s unhandled dynamic return type\n",
12274 					meta.func_name);
12275 				return -EFAULT;
12276 			}
12277 		} else if (!__btf_type_is_struct(ptr_type)) {
12278 			if (!meta.r0_size) {
12279 				__u32 sz;
12280 
12281 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
12282 					meta.r0_size = sz;
12283 					meta.r0_rdonly = true;
12284 				}
12285 			}
12286 			if (!meta.r0_size) {
12287 				ptr_type_name = btf_name_by_offset(desc_btf,
12288 								   ptr_type->name_off);
12289 				verbose(env,
12290 					"kernel function %s returns pointer type %s %s is not supported\n",
12291 					func_name,
12292 					btf_type_str(ptr_type),
12293 					ptr_type_name);
12294 				return -EINVAL;
12295 			}
12296 
12297 			mark_reg_known_zero(env, regs, BPF_REG_0);
12298 			regs[BPF_REG_0].type = PTR_TO_MEM;
12299 			regs[BPF_REG_0].mem_size = meta.r0_size;
12300 
12301 			if (meta.r0_rdonly)
12302 				regs[BPF_REG_0].type |= MEM_RDONLY;
12303 
12304 			/* Ensures we don't access the memory after a release_reference() */
12305 			if (meta.ref_obj_id)
12306 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12307 		} else {
12308 			mark_reg_known_zero(env, regs, BPF_REG_0);
12309 			regs[BPF_REG_0].btf = desc_btf;
12310 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12311 			regs[BPF_REG_0].btf_id = ptr_type_id;
12312 		}
12313 
12314 		if (is_kfunc_ret_null(&meta)) {
12315 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12316 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12317 			regs[BPF_REG_0].id = ++env->id_gen;
12318 		}
12319 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12320 		if (is_kfunc_acquire(&meta)) {
12321 			int id = acquire_reference_state(env, insn_idx);
12322 
12323 			if (id < 0)
12324 				return id;
12325 			if (is_kfunc_ret_null(&meta))
12326 				regs[BPF_REG_0].id = id;
12327 			regs[BPF_REG_0].ref_obj_id = id;
12328 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12329 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12330 		}
12331 
12332 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12333 			regs[BPF_REG_0].id = ++env->id_gen;
12334 	} else if (btf_type_is_void(t)) {
12335 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12336 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
12337 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12338 				insn_aux->kptr_struct_meta =
12339 					btf_find_struct_meta(meta.arg_btf,
12340 							     meta.arg_btf_id);
12341 			}
12342 		}
12343 	}
12344 
12345 	nargs = btf_type_vlen(meta.func_proto);
12346 	args = (const struct btf_param *)(meta.func_proto + 1);
12347 	for (i = 0; i < nargs; i++) {
12348 		u32 regno = i + 1;
12349 
12350 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12351 		if (btf_type_is_ptr(t))
12352 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12353 		else
12354 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12355 			mark_btf_func_reg_size(env, regno, t->size);
12356 	}
12357 
12358 	if (is_iter_next_kfunc(&meta)) {
12359 		err = process_iter_next_call(env, insn_idx, &meta);
12360 		if (err)
12361 			return err;
12362 	}
12363 
12364 	return 0;
12365 }
12366 
12367 static bool signed_add_overflows(s64 a, s64 b)
12368 {
12369 	/* Do the add in u64, where overflow is well-defined */
12370 	s64 res = (s64)((u64)a + (u64)b);
12371 
12372 	if (b < 0)
12373 		return res > a;
12374 	return res < a;
12375 }
12376 
12377 static bool signed_add32_overflows(s32 a, s32 b)
12378 {
12379 	/* Do the add in u32, where overflow is well-defined */
12380 	s32 res = (s32)((u32)a + (u32)b);
12381 
12382 	if (b < 0)
12383 		return res > a;
12384 	return res < a;
12385 }
12386 
12387 static bool signed_sub_overflows(s64 a, s64 b)
12388 {
12389 	/* Do the sub in u64, where overflow is well-defined */
12390 	s64 res = (s64)((u64)a - (u64)b);
12391 
12392 	if (b < 0)
12393 		return res < a;
12394 	return res > a;
12395 }
12396 
12397 static bool signed_sub32_overflows(s32 a, s32 b)
12398 {
12399 	/* Do the sub in u32, where overflow is well-defined */
12400 	s32 res = (s32)((u32)a - (u32)b);
12401 
12402 	if (b < 0)
12403 		return res < a;
12404 	return res > a;
12405 }
12406 
12407 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12408 				  const struct bpf_reg_state *reg,
12409 				  enum bpf_reg_type type)
12410 {
12411 	bool known = tnum_is_const(reg->var_off);
12412 	s64 val = reg->var_off.value;
12413 	s64 smin = reg->smin_value;
12414 
12415 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12416 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12417 			reg_type_str(env, type), val);
12418 		return false;
12419 	}
12420 
12421 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12422 		verbose(env, "%s pointer offset %d is not allowed\n",
12423 			reg_type_str(env, type), reg->off);
12424 		return false;
12425 	}
12426 
12427 	if (smin == S64_MIN) {
12428 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12429 			reg_type_str(env, type));
12430 		return false;
12431 	}
12432 
12433 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12434 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12435 			smin, reg_type_str(env, type));
12436 		return false;
12437 	}
12438 
12439 	return true;
12440 }
12441 
12442 enum {
12443 	REASON_BOUNDS	= -1,
12444 	REASON_TYPE	= -2,
12445 	REASON_PATHS	= -3,
12446 	REASON_LIMIT	= -4,
12447 	REASON_STACK	= -5,
12448 };
12449 
12450 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12451 			      u32 *alu_limit, bool mask_to_left)
12452 {
12453 	u32 max = 0, ptr_limit = 0;
12454 
12455 	switch (ptr_reg->type) {
12456 	case PTR_TO_STACK:
12457 		/* Offset 0 is out-of-bounds, but acceptable start for the
12458 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12459 		 * offset where we would need to deal with min/max bounds is
12460 		 * currently prohibited for unprivileged.
12461 		 */
12462 		max = MAX_BPF_STACK + mask_to_left;
12463 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12464 		break;
12465 	case PTR_TO_MAP_VALUE:
12466 		max = ptr_reg->map_ptr->value_size;
12467 		ptr_limit = (mask_to_left ?
12468 			     ptr_reg->smin_value :
12469 			     ptr_reg->umax_value) + ptr_reg->off;
12470 		break;
12471 	default:
12472 		return REASON_TYPE;
12473 	}
12474 
12475 	if (ptr_limit >= max)
12476 		return REASON_LIMIT;
12477 	*alu_limit = ptr_limit;
12478 	return 0;
12479 }
12480 
12481 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12482 				    const struct bpf_insn *insn)
12483 {
12484 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12485 }
12486 
12487 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12488 				       u32 alu_state, u32 alu_limit)
12489 {
12490 	/* If we arrived here from different branches with different
12491 	 * state or limits to sanitize, then this won't work.
12492 	 */
12493 	if (aux->alu_state &&
12494 	    (aux->alu_state != alu_state ||
12495 	     aux->alu_limit != alu_limit))
12496 		return REASON_PATHS;
12497 
12498 	/* Corresponding fixup done in do_misc_fixups(). */
12499 	aux->alu_state = alu_state;
12500 	aux->alu_limit = alu_limit;
12501 	return 0;
12502 }
12503 
12504 static int sanitize_val_alu(struct bpf_verifier_env *env,
12505 			    struct bpf_insn *insn)
12506 {
12507 	struct bpf_insn_aux_data *aux = cur_aux(env);
12508 
12509 	if (can_skip_alu_sanitation(env, insn))
12510 		return 0;
12511 
12512 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12513 }
12514 
12515 static bool sanitize_needed(u8 opcode)
12516 {
12517 	return opcode == BPF_ADD || opcode == BPF_SUB;
12518 }
12519 
12520 struct bpf_sanitize_info {
12521 	struct bpf_insn_aux_data aux;
12522 	bool mask_to_left;
12523 };
12524 
12525 static struct bpf_verifier_state *
12526 sanitize_speculative_path(struct bpf_verifier_env *env,
12527 			  const struct bpf_insn *insn,
12528 			  u32 next_idx, u32 curr_idx)
12529 {
12530 	struct bpf_verifier_state *branch;
12531 	struct bpf_reg_state *regs;
12532 
12533 	branch = push_stack(env, next_idx, curr_idx, true);
12534 	if (branch && insn) {
12535 		regs = branch->frame[branch->curframe]->regs;
12536 		if (BPF_SRC(insn->code) == BPF_K) {
12537 			mark_reg_unknown(env, regs, insn->dst_reg);
12538 		} else if (BPF_SRC(insn->code) == BPF_X) {
12539 			mark_reg_unknown(env, regs, insn->dst_reg);
12540 			mark_reg_unknown(env, regs, insn->src_reg);
12541 		}
12542 	}
12543 	return branch;
12544 }
12545 
12546 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12547 			    struct bpf_insn *insn,
12548 			    const struct bpf_reg_state *ptr_reg,
12549 			    const struct bpf_reg_state *off_reg,
12550 			    struct bpf_reg_state *dst_reg,
12551 			    struct bpf_sanitize_info *info,
12552 			    const bool commit_window)
12553 {
12554 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12555 	struct bpf_verifier_state *vstate = env->cur_state;
12556 	bool off_is_imm = tnum_is_const(off_reg->var_off);
12557 	bool off_is_neg = off_reg->smin_value < 0;
12558 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12559 	u8 opcode = BPF_OP(insn->code);
12560 	u32 alu_state, alu_limit;
12561 	struct bpf_reg_state tmp;
12562 	bool ret;
12563 	int err;
12564 
12565 	if (can_skip_alu_sanitation(env, insn))
12566 		return 0;
12567 
12568 	/* We already marked aux for masking from non-speculative
12569 	 * paths, thus we got here in the first place. We only care
12570 	 * to explore bad access from here.
12571 	 */
12572 	if (vstate->speculative)
12573 		goto do_sim;
12574 
12575 	if (!commit_window) {
12576 		if (!tnum_is_const(off_reg->var_off) &&
12577 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12578 			return REASON_BOUNDS;
12579 
12580 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12581 				     (opcode == BPF_SUB && !off_is_neg);
12582 	}
12583 
12584 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12585 	if (err < 0)
12586 		return err;
12587 
12588 	if (commit_window) {
12589 		/* In commit phase we narrow the masking window based on
12590 		 * the observed pointer move after the simulated operation.
12591 		 */
12592 		alu_state = info->aux.alu_state;
12593 		alu_limit = abs(info->aux.alu_limit - alu_limit);
12594 	} else {
12595 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12596 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12597 		alu_state |= ptr_is_dst_reg ?
12598 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12599 
12600 		/* Limit pruning on unknown scalars to enable deep search for
12601 		 * potential masking differences from other program paths.
12602 		 */
12603 		if (!off_is_imm)
12604 			env->explore_alu_limits = true;
12605 	}
12606 
12607 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12608 	if (err < 0)
12609 		return err;
12610 do_sim:
12611 	/* If we're in commit phase, we're done here given we already
12612 	 * pushed the truncated dst_reg into the speculative verification
12613 	 * stack.
12614 	 *
12615 	 * Also, when register is a known constant, we rewrite register-based
12616 	 * operation to immediate-based, and thus do not need masking (and as
12617 	 * a consequence, do not need to simulate the zero-truncation either).
12618 	 */
12619 	if (commit_window || off_is_imm)
12620 		return 0;
12621 
12622 	/* Simulate and find potential out-of-bounds access under
12623 	 * speculative execution from truncation as a result of
12624 	 * masking when off was not within expected range. If off
12625 	 * sits in dst, then we temporarily need to move ptr there
12626 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12627 	 * for cases where we use K-based arithmetic in one direction
12628 	 * and truncated reg-based in the other in order to explore
12629 	 * bad access.
12630 	 */
12631 	if (!ptr_is_dst_reg) {
12632 		tmp = *dst_reg;
12633 		copy_register_state(dst_reg, ptr_reg);
12634 	}
12635 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12636 					env->insn_idx);
12637 	if (!ptr_is_dst_reg && ret)
12638 		*dst_reg = tmp;
12639 	return !ret ? REASON_STACK : 0;
12640 }
12641 
12642 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12643 {
12644 	struct bpf_verifier_state *vstate = env->cur_state;
12645 
12646 	/* If we simulate paths under speculation, we don't update the
12647 	 * insn as 'seen' such that when we verify unreachable paths in
12648 	 * the non-speculative domain, sanitize_dead_code() can still
12649 	 * rewrite/sanitize them.
12650 	 */
12651 	if (!vstate->speculative)
12652 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12653 }
12654 
12655 static int sanitize_err(struct bpf_verifier_env *env,
12656 			const struct bpf_insn *insn, int reason,
12657 			const struct bpf_reg_state *off_reg,
12658 			const struct bpf_reg_state *dst_reg)
12659 {
12660 	static const char *err = "pointer arithmetic with it prohibited for !root";
12661 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12662 	u32 dst = insn->dst_reg, src = insn->src_reg;
12663 
12664 	switch (reason) {
12665 	case REASON_BOUNDS:
12666 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12667 			off_reg == dst_reg ? dst : src, err);
12668 		break;
12669 	case REASON_TYPE:
12670 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12671 			off_reg == dst_reg ? src : dst, err);
12672 		break;
12673 	case REASON_PATHS:
12674 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12675 			dst, op, err);
12676 		break;
12677 	case REASON_LIMIT:
12678 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12679 			dst, op, err);
12680 		break;
12681 	case REASON_STACK:
12682 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12683 			dst, err);
12684 		break;
12685 	default:
12686 		verbose(env, "verifier internal error: unknown reason (%d)\n",
12687 			reason);
12688 		break;
12689 	}
12690 
12691 	return -EACCES;
12692 }
12693 
12694 /* check that stack access falls within stack limits and that 'reg' doesn't
12695  * have a variable offset.
12696  *
12697  * Variable offset is prohibited for unprivileged mode for simplicity since it
12698  * requires corresponding support in Spectre masking for stack ALU.  See also
12699  * retrieve_ptr_limit().
12700  *
12701  *
12702  * 'off' includes 'reg->off'.
12703  */
12704 static int check_stack_access_for_ptr_arithmetic(
12705 				struct bpf_verifier_env *env,
12706 				int regno,
12707 				const struct bpf_reg_state *reg,
12708 				int off)
12709 {
12710 	if (!tnum_is_const(reg->var_off)) {
12711 		char tn_buf[48];
12712 
12713 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12714 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12715 			regno, tn_buf, off);
12716 		return -EACCES;
12717 	}
12718 
12719 	if (off >= 0 || off < -MAX_BPF_STACK) {
12720 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
12721 			"prohibited for !root; off=%d\n", regno, off);
12722 		return -EACCES;
12723 	}
12724 
12725 	return 0;
12726 }
12727 
12728 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12729 				 const struct bpf_insn *insn,
12730 				 const struct bpf_reg_state *dst_reg)
12731 {
12732 	u32 dst = insn->dst_reg;
12733 
12734 	/* For unprivileged we require that resulting offset must be in bounds
12735 	 * in order to be able to sanitize access later on.
12736 	 */
12737 	if (env->bypass_spec_v1)
12738 		return 0;
12739 
12740 	switch (dst_reg->type) {
12741 	case PTR_TO_STACK:
12742 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12743 					dst_reg->off + dst_reg->var_off.value))
12744 			return -EACCES;
12745 		break;
12746 	case PTR_TO_MAP_VALUE:
12747 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12748 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12749 				"prohibited for !root\n", dst);
12750 			return -EACCES;
12751 		}
12752 		break;
12753 	default:
12754 		break;
12755 	}
12756 
12757 	return 0;
12758 }
12759 
12760 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12761  * Caller should also handle BPF_MOV case separately.
12762  * If we return -EACCES, caller may want to try again treating pointer as a
12763  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12764  */
12765 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12766 				   struct bpf_insn *insn,
12767 				   const struct bpf_reg_state *ptr_reg,
12768 				   const struct bpf_reg_state *off_reg)
12769 {
12770 	struct bpf_verifier_state *vstate = env->cur_state;
12771 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12772 	struct bpf_reg_state *regs = state->regs, *dst_reg;
12773 	bool known = tnum_is_const(off_reg->var_off);
12774 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12775 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12776 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12777 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12778 	struct bpf_sanitize_info info = {};
12779 	u8 opcode = BPF_OP(insn->code);
12780 	u32 dst = insn->dst_reg;
12781 	int ret;
12782 
12783 	dst_reg = &regs[dst];
12784 
12785 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12786 	    smin_val > smax_val || umin_val > umax_val) {
12787 		/* Taint dst register if offset had invalid bounds derived from
12788 		 * e.g. dead branches.
12789 		 */
12790 		__mark_reg_unknown(env, dst_reg);
12791 		return 0;
12792 	}
12793 
12794 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
12795 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
12796 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12797 			__mark_reg_unknown(env, dst_reg);
12798 			return 0;
12799 		}
12800 
12801 		verbose(env,
12802 			"R%d 32-bit pointer arithmetic prohibited\n",
12803 			dst);
12804 		return -EACCES;
12805 	}
12806 
12807 	if (ptr_reg->type & PTR_MAYBE_NULL) {
12808 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12809 			dst, reg_type_str(env, ptr_reg->type));
12810 		return -EACCES;
12811 	}
12812 
12813 	switch (base_type(ptr_reg->type)) {
12814 	case CONST_PTR_TO_MAP:
12815 		/* smin_val represents the known value */
12816 		if (known && smin_val == 0 && opcode == BPF_ADD)
12817 			break;
12818 		fallthrough;
12819 	case PTR_TO_PACKET_END:
12820 	case PTR_TO_SOCKET:
12821 	case PTR_TO_SOCK_COMMON:
12822 	case PTR_TO_TCP_SOCK:
12823 	case PTR_TO_XDP_SOCK:
12824 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12825 			dst, reg_type_str(env, ptr_reg->type));
12826 		return -EACCES;
12827 	default:
12828 		break;
12829 	}
12830 
12831 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12832 	 * The id may be overwritten later if we create a new variable offset.
12833 	 */
12834 	dst_reg->type = ptr_reg->type;
12835 	dst_reg->id = ptr_reg->id;
12836 
12837 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12838 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12839 		return -EINVAL;
12840 
12841 	/* pointer types do not carry 32-bit bounds at the moment. */
12842 	__mark_reg32_unbounded(dst_reg);
12843 
12844 	if (sanitize_needed(opcode)) {
12845 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12846 				       &info, false);
12847 		if (ret < 0)
12848 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12849 	}
12850 
12851 	switch (opcode) {
12852 	case BPF_ADD:
12853 		/* We can take a fixed offset as long as it doesn't overflow
12854 		 * the s32 'off' field
12855 		 */
12856 		if (known && (ptr_reg->off + smin_val ==
12857 			      (s64)(s32)(ptr_reg->off + smin_val))) {
12858 			/* pointer += K.  Accumulate it into fixed offset */
12859 			dst_reg->smin_value = smin_ptr;
12860 			dst_reg->smax_value = smax_ptr;
12861 			dst_reg->umin_value = umin_ptr;
12862 			dst_reg->umax_value = umax_ptr;
12863 			dst_reg->var_off = ptr_reg->var_off;
12864 			dst_reg->off = ptr_reg->off + smin_val;
12865 			dst_reg->raw = ptr_reg->raw;
12866 			break;
12867 		}
12868 		/* A new variable offset is created.  Note that off_reg->off
12869 		 * == 0, since it's a scalar.
12870 		 * dst_reg gets the pointer type and since some positive
12871 		 * integer value was added to the pointer, give it a new 'id'
12872 		 * if it's a PTR_TO_PACKET.
12873 		 * this creates a new 'base' pointer, off_reg (variable) gets
12874 		 * added into the variable offset, and we copy the fixed offset
12875 		 * from ptr_reg.
12876 		 */
12877 		if (signed_add_overflows(smin_ptr, smin_val) ||
12878 		    signed_add_overflows(smax_ptr, smax_val)) {
12879 			dst_reg->smin_value = S64_MIN;
12880 			dst_reg->smax_value = S64_MAX;
12881 		} else {
12882 			dst_reg->smin_value = smin_ptr + smin_val;
12883 			dst_reg->smax_value = smax_ptr + smax_val;
12884 		}
12885 		if (umin_ptr + umin_val < umin_ptr ||
12886 		    umax_ptr + umax_val < umax_ptr) {
12887 			dst_reg->umin_value = 0;
12888 			dst_reg->umax_value = U64_MAX;
12889 		} else {
12890 			dst_reg->umin_value = umin_ptr + umin_val;
12891 			dst_reg->umax_value = umax_ptr + umax_val;
12892 		}
12893 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12894 		dst_reg->off = ptr_reg->off;
12895 		dst_reg->raw = ptr_reg->raw;
12896 		if (reg_is_pkt_pointer(ptr_reg)) {
12897 			dst_reg->id = ++env->id_gen;
12898 			/* something was added to pkt_ptr, set range to zero */
12899 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12900 		}
12901 		break;
12902 	case BPF_SUB:
12903 		if (dst_reg == off_reg) {
12904 			/* scalar -= pointer.  Creates an unknown scalar */
12905 			verbose(env, "R%d tried to subtract pointer from scalar\n",
12906 				dst);
12907 			return -EACCES;
12908 		}
12909 		/* We don't allow subtraction from FP, because (according to
12910 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
12911 		 * be able to deal with it.
12912 		 */
12913 		if (ptr_reg->type == PTR_TO_STACK) {
12914 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
12915 				dst);
12916 			return -EACCES;
12917 		}
12918 		if (known && (ptr_reg->off - smin_val ==
12919 			      (s64)(s32)(ptr_reg->off - smin_val))) {
12920 			/* pointer -= K.  Subtract it from fixed offset */
12921 			dst_reg->smin_value = smin_ptr;
12922 			dst_reg->smax_value = smax_ptr;
12923 			dst_reg->umin_value = umin_ptr;
12924 			dst_reg->umax_value = umax_ptr;
12925 			dst_reg->var_off = ptr_reg->var_off;
12926 			dst_reg->id = ptr_reg->id;
12927 			dst_reg->off = ptr_reg->off - smin_val;
12928 			dst_reg->raw = ptr_reg->raw;
12929 			break;
12930 		}
12931 		/* A new variable offset is created.  If the subtrahend is known
12932 		 * nonnegative, then any reg->range we had before is still good.
12933 		 */
12934 		if (signed_sub_overflows(smin_ptr, smax_val) ||
12935 		    signed_sub_overflows(smax_ptr, smin_val)) {
12936 			/* Overflow possible, we know nothing */
12937 			dst_reg->smin_value = S64_MIN;
12938 			dst_reg->smax_value = S64_MAX;
12939 		} else {
12940 			dst_reg->smin_value = smin_ptr - smax_val;
12941 			dst_reg->smax_value = smax_ptr - smin_val;
12942 		}
12943 		if (umin_ptr < umax_val) {
12944 			/* Overflow possible, we know nothing */
12945 			dst_reg->umin_value = 0;
12946 			dst_reg->umax_value = U64_MAX;
12947 		} else {
12948 			/* Cannot overflow (as long as bounds are consistent) */
12949 			dst_reg->umin_value = umin_ptr - umax_val;
12950 			dst_reg->umax_value = umax_ptr - umin_val;
12951 		}
12952 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12953 		dst_reg->off = ptr_reg->off;
12954 		dst_reg->raw = ptr_reg->raw;
12955 		if (reg_is_pkt_pointer(ptr_reg)) {
12956 			dst_reg->id = ++env->id_gen;
12957 			/* something was added to pkt_ptr, set range to zero */
12958 			if (smin_val < 0)
12959 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12960 		}
12961 		break;
12962 	case BPF_AND:
12963 	case BPF_OR:
12964 	case BPF_XOR:
12965 		/* bitwise ops on pointers are troublesome, prohibit. */
12966 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12967 			dst, bpf_alu_string[opcode >> 4]);
12968 		return -EACCES;
12969 	default:
12970 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
12971 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12972 			dst, bpf_alu_string[opcode >> 4]);
12973 		return -EACCES;
12974 	}
12975 
12976 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12977 		return -EINVAL;
12978 	reg_bounds_sync(dst_reg);
12979 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12980 		return -EACCES;
12981 	if (sanitize_needed(opcode)) {
12982 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12983 				       &info, true);
12984 		if (ret < 0)
12985 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12986 	}
12987 
12988 	return 0;
12989 }
12990 
12991 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12992 				 struct bpf_reg_state *src_reg)
12993 {
12994 	s32 smin_val = src_reg->s32_min_value;
12995 	s32 smax_val = src_reg->s32_max_value;
12996 	u32 umin_val = src_reg->u32_min_value;
12997 	u32 umax_val = src_reg->u32_max_value;
12998 
12999 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
13000 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
13001 		dst_reg->s32_min_value = S32_MIN;
13002 		dst_reg->s32_max_value = S32_MAX;
13003 	} else {
13004 		dst_reg->s32_min_value += smin_val;
13005 		dst_reg->s32_max_value += smax_val;
13006 	}
13007 	if (dst_reg->u32_min_value + umin_val < umin_val ||
13008 	    dst_reg->u32_max_value + umax_val < umax_val) {
13009 		dst_reg->u32_min_value = 0;
13010 		dst_reg->u32_max_value = U32_MAX;
13011 	} else {
13012 		dst_reg->u32_min_value += umin_val;
13013 		dst_reg->u32_max_value += umax_val;
13014 	}
13015 }
13016 
13017 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
13018 			       struct bpf_reg_state *src_reg)
13019 {
13020 	s64 smin_val = src_reg->smin_value;
13021 	s64 smax_val = src_reg->smax_value;
13022 	u64 umin_val = src_reg->umin_value;
13023 	u64 umax_val = src_reg->umax_value;
13024 
13025 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
13026 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
13027 		dst_reg->smin_value = S64_MIN;
13028 		dst_reg->smax_value = S64_MAX;
13029 	} else {
13030 		dst_reg->smin_value += smin_val;
13031 		dst_reg->smax_value += smax_val;
13032 	}
13033 	if (dst_reg->umin_value + umin_val < umin_val ||
13034 	    dst_reg->umax_value + umax_val < umax_val) {
13035 		dst_reg->umin_value = 0;
13036 		dst_reg->umax_value = U64_MAX;
13037 	} else {
13038 		dst_reg->umin_value += umin_val;
13039 		dst_reg->umax_value += umax_val;
13040 	}
13041 }
13042 
13043 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
13044 				 struct bpf_reg_state *src_reg)
13045 {
13046 	s32 smin_val = src_reg->s32_min_value;
13047 	s32 smax_val = src_reg->s32_max_value;
13048 	u32 umin_val = src_reg->u32_min_value;
13049 	u32 umax_val = src_reg->u32_max_value;
13050 
13051 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
13052 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
13053 		/* Overflow possible, we know nothing */
13054 		dst_reg->s32_min_value = S32_MIN;
13055 		dst_reg->s32_max_value = S32_MAX;
13056 	} else {
13057 		dst_reg->s32_min_value -= smax_val;
13058 		dst_reg->s32_max_value -= smin_val;
13059 	}
13060 	if (dst_reg->u32_min_value < umax_val) {
13061 		/* Overflow possible, we know nothing */
13062 		dst_reg->u32_min_value = 0;
13063 		dst_reg->u32_max_value = U32_MAX;
13064 	} else {
13065 		/* Cannot overflow (as long as bounds are consistent) */
13066 		dst_reg->u32_min_value -= umax_val;
13067 		dst_reg->u32_max_value -= umin_val;
13068 	}
13069 }
13070 
13071 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
13072 			       struct bpf_reg_state *src_reg)
13073 {
13074 	s64 smin_val = src_reg->smin_value;
13075 	s64 smax_val = src_reg->smax_value;
13076 	u64 umin_val = src_reg->umin_value;
13077 	u64 umax_val = src_reg->umax_value;
13078 
13079 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
13080 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
13081 		/* Overflow possible, we know nothing */
13082 		dst_reg->smin_value = S64_MIN;
13083 		dst_reg->smax_value = S64_MAX;
13084 	} else {
13085 		dst_reg->smin_value -= smax_val;
13086 		dst_reg->smax_value -= smin_val;
13087 	}
13088 	if (dst_reg->umin_value < umax_val) {
13089 		/* Overflow possible, we know nothing */
13090 		dst_reg->umin_value = 0;
13091 		dst_reg->umax_value = U64_MAX;
13092 	} else {
13093 		/* Cannot overflow (as long as bounds are consistent) */
13094 		dst_reg->umin_value -= umax_val;
13095 		dst_reg->umax_value -= umin_val;
13096 	}
13097 }
13098 
13099 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13100 				 struct bpf_reg_state *src_reg)
13101 {
13102 	s32 smin_val = src_reg->s32_min_value;
13103 	u32 umin_val = src_reg->u32_min_value;
13104 	u32 umax_val = src_reg->u32_max_value;
13105 
13106 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
13107 		/* Ain't nobody got time to multiply that sign */
13108 		__mark_reg32_unbounded(dst_reg);
13109 		return;
13110 	}
13111 	/* Both values are positive, so we can work with unsigned and
13112 	 * copy the result to signed (unless it exceeds S32_MAX).
13113 	 */
13114 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
13115 		/* Potential overflow, we know nothing */
13116 		__mark_reg32_unbounded(dst_reg);
13117 		return;
13118 	}
13119 	dst_reg->u32_min_value *= umin_val;
13120 	dst_reg->u32_max_value *= umax_val;
13121 	if (dst_reg->u32_max_value > S32_MAX) {
13122 		/* Overflow possible, we know nothing */
13123 		dst_reg->s32_min_value = S32_MIN;
13124 		dst_reg->s32_max_value = S32_MAX;
13125 	} else {
13126 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13127 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13128 	}
13129 }
13130 
13131 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13132 			       struct bpf_reg_state *src_reg)
13133 {
13134 	s64 smin_val = src_reg->smin_value;
13135 	u64 umin_val = src_reg->umin_value;
13136 	u64 umax_val = src_reg->umax_value;
13137 
13138 	if (smin_val < 0 || dst_reg->smin_value < 0) {
13139 		/* Ain't nobody got time to multiply that sign */
13140 		__mark_reg64_unbounded(dst_reg);
13141 		return;
13142 	}
13143 	/* Both values are positive, so we can work with unsigned and
13144 	 * copy the result to signed (unless it exceeds S64_MAX).
13145 	 */
13146 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
13147 		/* Potential overflow, we know nothing */
13148 		__mark_reg64_unbounded(dst_reg);
13149 		return;
13150 	}
13151 	dst_reg->umin_value *= umin_val;
13152 	dst_reg->umax_value *= umax_val;
13153 	if (dst_reg->umax_value > S64_MAX) {
13154 		/* Overflow possible, we know nothing */
13155 		dst_reg->smin_value = S64_MIN;
13156 		dst_reg->smax_value = S64_MAX;
13157 	} else {
13158 		dst_reg->smin_value = dst_reg->umin_value;
13159 		dst_reg->smax_value = dst_reg->umax_value;
13160 	}
13161 }
13162 
13163 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13164 				 struct bpf_reg_state *src_reg)
13165 {
13166 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13167 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13168 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13169 	s32 smin_val = src_reg->s32_min_value;
13170 	u32 umax_val = src_reg->u32_max_value;
13171 
13172 	if (src_known && dst_known) {
13173 		__mark_reg32_known(dst_reg, var32_off.value);
13174 		return;
13175 	}
13176 
13177 	/* We get our minimum from the var_off, since that's inherently
13178 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13179 	 */
13180 	dst_reg->u32_min_value = var32_off.value;
13181 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13182 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13183 		/* Lose signed bounds when ANDing negative numbers,
13184 		 * ain't nobody got time for that.
13185 		 */
13186 		dst_reg->s32_min_value = S32_MIN;
13187 		dst_reg->s32_max_value = S32_MAX;
13188 	} else {
13189 		/* ANDing two positives gives a positive, so safe to
13190 		 * cast result into s64.
13191 		 */
13192 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13193 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13194 	}
13195 }
13196 
13197 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
13198 			       struct bpf_reg_state *src_reg)
13199 {
13200 	bool src_known = tnum_is_const(src_reg->var_off);
13201 	bool dst_known = tnum_is_const(dst_reg->var_off);
13202 	s64 smin_val = src_reg->smin_value;
13203 	u64 umax_val = src_reg->umax_value;
13204 
13205 	if (src_known && dst_known) {
13206 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13207 		return;
13208 	}
13209 
13210 	/* We get our minimum from the var_off, since that's inherently
13211 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13212 	 */
13213 	dst_reg->umin_value = dst_reg->var_off.value;
13214 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13215 	if (dst_reg->smin_value < 0 || smin_val < 0) {
13216 		/* Lose signed bounds when ANDing negative numbers,
13217 		 * ain't nobody got time for that.
13218 		 */
13219 		dst_reg->smin_value = S64_MIN;
13220 		dst_reg->smax_value = S64_MAX;
13221 	} else {
13222 		/* ANDing two positives gives a positive, so safe to
13223 		 * cast result into s64.
13224 		 */
13225 		dst_reg->smin_value = dst_reg->umin_value;
13226 		dst_reg->smax_value = dst_reg->umax_value;
13227 	}
13228 	/* We may learn something more from the var_off */
13229 	__update_reg_bounds(dst_reg);
13230 }
13231 
13232 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13233 				struct bpf_reg_state *src_reg)
13234 {
13235 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13236 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13237 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13238 	s32 smin_val = src_reg->s32_min_value;
13239 	u32 umin_val = src_reg->u32_min_value;
13240 
13241 	if (src_known && dst_known) {
13242 		__mark_reg32_known(dst_reg, var32_off.value);
13243 		return;
13244 	}
13245 
13246 	/* We get our maximum from the var_off, and our minimum is the
13247 	 * maximum of the operands' minima
13248 	 */
13249 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13250 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13251 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13252 		/* Lose signed bounds when ORing negative numbers,
13253 		 * ain't nobody got time for that.
13254 		 */
13255 		dst_reg->s32_min_value = S32_MIN;
13256 		dst_reg->s32_max_value = S32_MAX;
13257 	} else {
13258 		/* ORing two positives gives a positive, so safe to
13259 		 * cast result into s64.
13260 		 */
13261 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13262 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13263 	}
13264 }
13265 
13266 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13267 			      struct bpf_reg_state *src_reg)
13268 {
13269 	bool src_known = tnum_is_const(src_reg->var_off);
13270 	bool dst_known = tnum_is_const(dst_reg->var_off);
13271 	s64 smin_val = src_reg->smin_value;
13272 	u64 umin_val = src_reg->umin_value;
13273 
13274 	if (src_known && dst_known) {
13275 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13276 		return;
13277 	}
13278 
13279 	/* We get our maximum from the var_off, and our minimum is the
13280 	 * maximum of the operands' minima
13281 	 */
13282 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13283 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13284 	if (dst_reg->smin_value < 0 || smin_val < 0) {
13285 		/* Lose signed bounds when ORing negative numbers,
13286 		 * ain't nobody got time for that.
13287 		 */
13288 		dst_reg->smin_value = S64_MIN;
13289 		dst_reg->smax_value = S64_MAX;
13290 	} else {
13291 		/* ORing two positives gives a positive, so safe to
13292 		 * cast result into s64.
13293 		 */
13294 		dst_reg->smin_value = dst_reg->umin_value;
13295 		dst_reg->smax_value = dst_reg->umax_value;
13296 	}
13297 	/* We may learn something more from the var_off */
13298 	__update_reg_bounds(dst_reg);
13299 }
13300 
13301 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13302 				 struct bpf_reg_state *src_reg)
13303 {
13304 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13305 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13306 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13307 	s32 smin_val = src_reg->s32_min_value;
13308 
13309 	if (src_known && dst_known) {
13310 		__mark_reg32_known(dst_reg, var32_off.value);
13311 		return;
13312 	}
13313 
13314 	/* We get both minimum and maximum from the var32_off. */
13315 	dst_reg->u32_min_value = var32_off.value;
13316 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13317 
13318 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13319 		/* XORing two positive sign numbers gives a positive,
13320 		 * so safe to cast u32 result into s32.
13321 		 */
13322 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13323 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13324 	} else {
13325 		dst_reg->s32_min_value = S32_MIN;
13326 		dst_reg->s32_max_value = S32_MAX;
13327 	}
13328 }
13329 
13330 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13331 			       struct bpf_reg_state *src_reg)
13332 {
13333 	bool src_known = tnum_is_const(src_reg->var_off);
13334 	bool dst_known = tnum_is_const(dst_reg->var_off);
13335 	s64 smin_val = src_reg->smin_value;
13336 
13337 	if (src_known && dst_known) {
13338 		/* dst_reg->var_off.value has been updated earlier */
13339 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13340 		return;
13341 	}
13342 
13343 	/* We get both minimum and maximum from the var_off. */
13344 	dst_reg->umin_value = dst_reg->var_off.value;
13345 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13346 
13347 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13348 		/* XORing two positive sign numbers gives a positive,
13349 		 * so safe to cast u64 result into s64.
13350 		 */
13351 		dst_reg->smin_value = dst_reg->umin_value;
13352 		dst_reg->smax_value = dst_reg->umax_value;
13353 	} else {
13354 		dst_reg->smin_value = S64_MIN;
13355 		dst_reg->smax_value = S64_MAX;
13356 	}
13357 
13358 	__update_reg_bounds(dst_reg);
13359 }
13360 
13361 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13362 				   u64 umin_val, u64 umax_val)
13363 {
13364 	/* We lose all sign bit information (except what we can pick
13365 	 * up from var_off)
13366 	 */
13367 	dst_reg->s32_min_value = S32_MIN;
13368 	dst_reg->s32_max_value = S32_MAX;
13369 	/* If we might shift our top bit out, then we know nothing */
13370 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13371 		dst_reg->u32_min_value = 0;
13372 		dst_reg->u32_max_value = U32_MAX;
13373 	} else {
13374 		dst_reg->u32_min_value <<= umin_val;
13375 		dst_reg->u32_max_value <<= umax_val;
13376 	}
13377 }
13378 
13379 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13380 				 struct bpf_reg_state *src_reg)
13381 {
13382 	u32 umax_val = src_reg->u32_max_value;
13383 	u32 umin_val = src_reg->u32_min_value;
13384 	/* u32 alu operation will zext upper bits */
13385 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13386 
13387 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13388 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13389 	/* Not required but being careful mark reg64 bounds as unknown so
13390 	 * that we are forced to pick them up from tnum and zext later and
13391 	 * if some path skips this step we are still safe.
13392 	 */
13393 	__mark_reg64_unbounded(dst_reg);
13394 	__update_reg32_bounds(dst_reg);
13395 }
13396 
13397 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13398 				   u64 umin_val, u64 umax_val)
13399 {
13400 	/* Special case <<32 because it is a common compiler pattern to sign
13401 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13402 	 * positive we know this shift will also be positive so we can track
13403 	 * bounds correctly. Otherwise we lose all sign bit information except
13404 	 * what we can pick up from var_off. Perhaps we can generalize this
13405 	 * later to shifts of any length.
13406 	 */
13407 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13408 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13409 	else
13410 		dst_reg->smax_value = S64_MAX;
13411 
13412 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13413 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13414 	else
13415 		dst_reg->smin_value = S64_MIN;
13416 
13417 	/* If we might shift our top bit out, then we know nothing */
13418 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13419 		dst_reg->umin_value = 0;
13420 		dst_reg->umax_value = U64_MAX;
13421 	} else {
13422 		dst_reg->umin_value <<= umin_val;
13423 		dst_reg->umax_value <<= umax_val;
13424 	}
13425 }
13426 
13427 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13428 			       struct bpf_reg_state *src_reg)
13429 {
13430 	u64 umax_val = src_reg->umax_value;
13431 	u64 umin_val = src_reg->umin_value;
13432 
13433 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13434 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13435 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13436 
13437 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13438 	/* We may learn something more from the var_off */
13439 	__update_reg_bounds(dst_reg);
13440 }
13441 
13442 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13443 				 struct bpf_reg_state *src_reg)
13444 {
13445 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13446 	u32 umax_val = src_reg->u32_max_value;
13447 	u32 umin_val = src_reg->u32_min_value;
13448 
13449 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13450 	 * be negative, then either:
13451 	 * 1) src_reg might be zero, so the sign bit of the result is
13452 	 *    unknown, so we lose our signed bounds
13453 	 * 2) it's known negative, thus the unsigned bounds capture the
13454 	 *    signed bounds
13455 	 * 3) the signed bounds cross zero, so they tell us nothing
13456 	 *    about the result
13457 	 * If the value in dst_reg is known nonnegative, then again the
13458 	 * unsigned bounds capture the signed bounds.
13459 	 * Thus, in all cases it suffices to blow away our signed bounds
13460 	 * and rely on inferring new ones from the unsigned bounds and
13461 	 * var_off of the result.
13462 	 */
13463 	dst_reg->s32_min_value = S32_MIN;
13464 	dst_reg->s32_max_value = S32_MAX;
13465 
13466 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13467 	dst_reg->u32_min_value >>= umax_val;
13468 	dst_reg->u32_max_value >>= umin_val;
13469 
13470 	__mark_reg64_unbounded(dst_reg);
13471 	__update_reg32_bounds(dst_reg);
13472 }
13473 
13474 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13475 			       struct bpf_reg_state *src_reg)
13476 {
13477 	u64 umax_val = src_reg->umax_value;
13478 	u64 umin_val = src_reg->umin_value;
13479 
13480 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13481 	 * be negative, then either:
13482 	 * 1) src_reg might be zero, so the sign bit of the result is
13483 	 *    unknown, so we lose our signed bounds
13484 	 * 2) it's known negative, thus the unsigned bounds capture the
13485 	 *    signed bounds
13486 	 * 3) the signed bounds cross zero, so they tell us nothing
13487 	 *    about the result
13488 	 * If the value in dst_reg is known nonnegative, then again the
13489 	 * unsigned bounds capture the signed bounds.
13490 	 * Thus, in all cases it suffices to blow away our signed bounds
13491 	 * and rely on inferring new ones from the unsigned bounds and
13492 	 * var_off of the result.
13493 	 */
13494 	dst_reg->smin_value = S64_MIN;
13495 	dst_reg->smax_value = S64_MAX;
13496 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13497 	dst_reg->umin_value >>= umax_val;
13498 	dst_reg->umax_value >>= umin_val;
13499 
13500 	/* Its not easy to operate on alu32 bounds here because it depends
13501 	 * on bits being shifted in. Take easy way out and mark unbounded
13502 	 * so we can recalculate later from tnum.
13503 	 */
13504 	__mark_reg32_unbounded(dst_reg);
13505 	__update_reg_bounds(dst_reg);
13506 }
13507 
13508 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13509 				  struct bpf_reg_state *src_reg)
13510 {
13511 	u64 umin_val = src_reg->u32_min_value;
13512 
13513 	/* Upon reaching here, src_known is true and
13514 	 * umax_val is equal to umin_val.
13515 	 */
13516 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13517 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13518 
13519 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13520 
13521 	/* blow away the dst_reg umin_value/umax_value and rely on
13522 	 * dst_reg var_off to refine the result.
13523 	 */
13524 	dst_reg->u32_min_value = 0;
13525 	dst_reg->u32_max_value = U32_MAX;
13526 
13527 	__mark_reg64_unbounded(dst_reg);
13528 	__update_reg32_bounds(dst_reg);
13529 }
13530 
13531 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13532 				struct bpf_reg_state *src_reg)
13533 {
13534 	u64 umin_val = src_reg->umin_value;
13535 
13536 	/* Upon reaching here, src_known is true and umax_val is equal
13537 	 * to umin_val.
13538 	 */
13539 	dst_reg->smin_value >>= umin_val;
13540 	dst_reg->smax_value >>= umin_val;
13541 
13542 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13543 
13544 	/* blow away the dst_reg umin_value/umax_value and rely on
13545 	 * dst_reg var_off to refine the result.
13546 	 */
13547 	dst_reg->umin_value = 0;
13548 	dst_reg->umax_value = U64_MAX;
13549 
13550 	/* Its not easy to operate on alu32 bounds here because it depends
13551 	 * on bits being shifted in from upper 32-bits. Take easy way out
13552 	 * and mark unbounded so we can recalculate later from tnum.
13553 	 */
13554 	__mark_reg32_unbounded(dst_reg);
13555 	__update_reg_bounds(dst_reg);
13556 }
13557 
13558 /* WARNING: This function does calculations on 64-bit values, but the actual
13559  * execution may occur on 32-bit values. Therefore, things like bitshifts
13560  * need extra checks in the 32-bit case.
13561  */
13562 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13563 				      struct bpf_insn *insn,
13564 				      struct bpf_reg_state *dst_reg,
13565 				      struct bpf_reg_state src_reg)
13566 {
13567 	struct bpf_reg_state *regs = cur_regs(env);
13568 	u8 opcode = BPF_OP(insn->code);
13569 	bool src_known;
13570 	s64 smin_val, smax_val;
13571 	u64 umin_val, umax_val;
13572 	s32 s32_min_val, s32_max_val;
13573 	u32 u32_min_val, u32_max_val;
13574 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13575 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13576 	int ret;
13577 
13578 	smin_val = src_reg.smin_value;
13579 	smax_val = src_reg.smax_value;
13580 	umin_val = src_reg.umin_value;
13581 	umax_val = src_reg.umax_value;
13582 
13583 	s32_min_val = src_reg.s32_min_value;
13584 	s32_max_val = src_reg.s32_max_value;
13585 	u32_min_val = src_reg.u32_min_value;
13586 	u32_max_val = src_reg.u32_max_value;
13587 
13588 	if (alu32) {
13589 		src_known = tnum_subreg_is_const(src_reg.var_off);
13590 		if ((src_known &&
13591 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13592 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13593 			/* Taint dst register if offset had invalid bounds
13594 			 * derived from e.g. dead branches.
13595 			 */
13596 			__mark_reg_unknown(env, dst_reg);
13597 			return 0;
13598 		}
13599 	} else {
13600 		src_known = tnum_is_const(src_reg.var_off);
13601 		if ((src_known &&
13602 		     (smin_val != smax_val || umin_val != umax_val)) ||
13603 		    smin_val > smax_val || umin_val > umax_val) {
13604 			/* Taint dst register if offset had invalid bounds
13605 			 * derived from e.g. dead branches.
13606 			 */
13607 			__mark_reg_unknown(env, dst_reg);
13608 			return 0;
13609 		}
13610 	}
13611 
13612 	if (!src_known &&
13613 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13614 		__mark_reg_unknown(env, dst_reg);
13615 		return 0;
13616 	}
13617 
13618 	if (sanitize_needed(opcode)) {
13619 		ret = sanitize_val_alu(env, insn);
13620 		if (ret < 0)
13621 			return sanitize_err(env, insn, ret, NULL, NULL);
13622 	}
13623 
13624 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13625 	 * There are two classes of instructions: The first class we track both
13626 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13627 	 * greatest amount of precision when alu operations are mixed with jmp32
13628 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13629 	 * and BPF_OR. This is possible because these ops have fairly easy to
13630 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13631 	 * See alu32 verifier tests for examples. The second class of
13632 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13633 	 * with regards to tracking sign/unsigned bounds because the bits may
13634 	 * cross subreg boundaries in the alu64 case. When this happens we mark
13635 	 * the reg unbounded in the subreg bound space and use the resulting
13636 	 * tnum to calculate an approximation of the sign/unsigned bounds.
13637 	 */
13638 	switch (opcode) {
13639 	case BPF_ADD:
13640 		scalar32_min_max_add(dst_reg, &src_reg);
13641 		scalar_min_max_add(dst_reg, &src_reg);
13642 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13643 		break;
13644 	case BPF_SUB:
13645 		scalar32_min_max_sub(dst_reg, &src_reg);
13646 		scalar_min_max_sub(dst_reg, &src_reg);
13647 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13648 		break;
13649 	case BPF_MUL:
13650 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13651 		scalar32_min_max_mul(dst_reg, &src_reg);
13652 		scalar_min_max_mul(dst_reg, &src_reg);
13653 		break;
13654 	case BPF_AND:
13655 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13656 		scalar32_min_max_and(dst_reg, &src_reg);
13657 		scalar_min_max_and(dst_reg, &src_reg);
13658 		break;
13659 	case BPF_OR:
13660 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13661 		scalar32_min_max_or(dst_reg, &src_reg);
13662 		scalar_min_max_or(dst_reg, &src_reg);
13663 		break;
13664 	case BPF_XOR:
13665 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13666 		scalar32_min_max_xor(dst_reg, &src_reg);
13667 		scalar_min_max_xor(dst_reg, &src_reg);
13668 		break;
13669 	case BPF_LSH:
13670 		if (umax_val >= insn_bitness) {
13671 			/* Shifts greater than 31 or 63 are undefined.
13672 			 * This includes shifts by a negative number.
13673 			 */
13674 			mark_reg_unknown(env, regs, insn->dst_reg);
13675 			break;
13676 		}
13677 		if (alu32)
13678 			scalar32_min_max_lsh(dst_reg, &src_reg);
13679 		else
13680 			scalar_min_max_lsh(dst_reg, &src_reg);
13681 		break;
13682 	case BPF_RSH:
13683 		if (umax_val >= insn_bitness) {
13684 			/* Shifts greater than 31 or 63 are undefined.
13685 			 * This includes shifts by a negative number.
13686 			 */
13687 			mark_reg_unknown(env, regs, insn->dst_reg);
13688 			break;
13689 		}
13690 		if (alu32)
13691 			scalar32_min_max_rsh(dst_reg, &src_reg);
13692 		else
13693 			scalar_min_max_rsh(dst_reg, &src_reg);
13694 		break;
13695 	case BPF_ARSH:
13696 		if (umax_val >= insn_bitness) {
13697 			/* Shifts greater than 31 or 63 are undefined.
13698 			 * This includes shifts by a negative number.
13699 			 */
13700 			mark_reg_unknown(env, regs, insn->dst_reg);
13701 			break;
13702 		}
13703 		if (alu32)
13704 			scalar32_min_max_arsh(dst_reg, &src_reg);
13705 		else
13706 			scalar_min_max_arsh(dst_reg, &src_reg);
13707 		break;
13708 	default:
13709 		mark_reg_unknown(env, regs, insn->dst_reg);
13710 		break;
13711 	}
13712 
13713 	/* ALU32 ops are zero extended into 64bit register */
13714 	if (alu32)
13715 		zext_32_to_64(dst_reg);
13716 	reg_bounds_sync(dst_reg);
13717 	return 0;
13718 }
13719 
13720 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13721  * and var_off.
13722  */
13723 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13724 				   struct bpf_insn *insn)
13725 {
13726 	struct bpf_verifier_state *vstate = env->cur_state;
13727 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13728 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13729 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13730 	u8 opcode = BPF_OP(insn->code);
13731 	int err;
13732 
13733 	dst_reg = &regs[insn->dst_reg];
13734 	src_reg = NULL;
13735 	if (dst_reg->type != SCALAR_VALUE)
13736 		ptr_reg = dst_reg;
13737 	else
13738 		/* Make sure ID is cleared otherwise dst_reg min/max could be
13739 		 * incorrectly propagated into other registers by find_equal_scalars()
13740 		 */
13741 		dst_reg->id = 0;
13742 	if (BPF_SRC(insn->code) == BPF_X) {
13743 		src_reg = &regs[insn->src_reg];
13744 		if (src_reg->type != SCALAR_VALUE) {
13745 			if (dst_reg->type != SCALAR_VALUE) {
13746 				/* Combining two pointers by any ALU op yields
13747 				 * an arbitrary scalar. Disallow all math except
13748 				 * pointer subtraction
13749 				 */
13750 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13751 					mark_reg_unknown(env, regs, insn->dst_reg);
13752 					return 0;
13753 				}
13754 				verbose(env, "R%d pointer %s pointer prohibited\n",
13755 					insn->dst_reg,
13756 					bpf_alu_string[opcode >> 4]);
13757 				return -EACCES;
13758 			} else {
13759 				/* scalar += pointer
13760 				 * This is legal, but we have to reverse our
13761 				 * src/dest handling in computing the range
13762 				 */
13763 				err = mark_chain_precision(env, insn->dst_reg);
13764 				if (err)
13765 					return err;
13766 				return adjust_ptr_min_max_vals(env, insn,
13767 							       src_reg, dst_reg);
13768 			}
13769 		} else if (ptr_reg) {
13770 			/* pointer += scalar */
13771 			err = mark_chain_precision(env, insn->src_reg);
13772 			if (err)
13773 				return err;
13774 			return adjust_ptr_min_max_vals(env, insn,
13775 						       dst_reg, src_reg);
13776 		} else if (dst_reg->precise) {
13777 			/* if dst_reg is precise, src_reg should be precise as well */
13778 			err = mark_chain_precision(env, insn->src_reg);
13779 			if (err)
13780 				return err;
13781 		}
13782 	} else {
13783 		/* Pretend the src is a reg with a known value, since we only
13784 		 * need to be able to read from this state.
13785 		 */
13786 		off_reg.type = SCALAR_VALUE;
13787 		__mark_reg_known(&off_reg, insn->imm);
13788 		src_reg = &off_reg;
13789 		if (ptr_reg) /* pointer += K */
13790 			return adjust_ptr_min_max_vals(env, insn,
13791 						       ptr_reg, src_reg);
13792 	}
13793 
13794 	/* Got here implies adding two SCALAR_VALUEs */
13795 	if (WARN_ON_ONCE(ptr_reg)) {
13796 		print_verifier_state(env, state, true);
13797 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
13798 		return -EINVAL;
13799 	}
13800 	if (WARN_ON(!src_reg)) {
13801 		print_verifier_state(env, state, true);
13802 		verbose(env, "verifier internal error: no src_reg\n");
13803 		return -EINVAL;
13804 	}
13805 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13806 }
13807 
13808 /* check validity of 32-bit and 64-bit arithmetic operations */
13809 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13810 {
13811 	struct bpf_reg_state *regs = cur_regs(env);
13812 	u8 opcode = BPF_OP(insn->code);
13813 	int err;
13814 
13815 	if (opcode == BPF_END || opcode == BPF_NEG) {
13816 		if (opcode == BPF_NEG) {
13817 			if (BPF_SRC(insn->code) != BPF_K ||
13818 			    insn->src_reg != BPF_REG_0 ||
13819 			    insn->off != 0 || insn->imm != 0) {
13820 				verbose(env, "BPF_NEG uses reserved fields\n");
13821 				return -EINVAL;
13822 			}
13823 		} else {
13824 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13825 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13826 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
13827 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
13828 				verbose(env, "BPF_END uses reserved fields\n");
13829 				return -EINVAL;
13830 			}
13831 		}
13832 
13833 		/* check src operand */
13834 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13835 		if (err)
13836 			return err;
13837 
13838 		if (is_pointer_value(env, insn->dst_reg)) {
13839 			verbose(env, "R%d pointer arithmetic prohibited\n",
13840 				insn->dst_reg);
13841 			return -EACCES;
13842 		}
13843 
13844 		/* check dest operand */
13845 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
13846 		if (err)
13847 			return err;
13848 
13849 	} else if (opcode == BPF_MOV) {
13850 
13851 		if (BPF_SRC(insn->code) == BPF_X) {
13852 			if (insn->imm != 0) {
13853 				verbose(env, "BPF_MOV uses reserved fields\n");
13854 				return -EINVAL;
13855 			}
13856 
13857 			if (BPF_CLASS(insn->code) == BPF_ALU) {
13858 				if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13859 					verbose(env, "BPF_MOV uses reserved fields\n");
13860 					return -EINVAL;
13861 				}
13862 			} else {
13863 				if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13864 				    insn->off != 32) {
13865 					verbose(env, "BPF_MOV uses reserved fields\n");
13866 					return -EINVAL;
13867 				}
13868 			}
13869 
13870 			/* check src operand */
13871 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13872 			if (err)
13873 				return err;
13874 		} else {
13875 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13876 				verbose(env, "BPF_MOV uses reserved fields\n");
13877 				return -EINVAL;
13878 			}
13879 		}
13880 
13881 		/* check dest operand, mark as required later */
13882 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13883 		if (err)
13884 			return err;
13885 
13886 		if (BPF_SRC(insn->code) == BPF_X) {
13887 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
13888 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13889 			bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13890 				       !tnum_is_const(src_reg->var_off);
13891 
13892 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13893 				if (insn->off == 0) {
13894 					/* case: R1 = R2
13895 					 * copy register state to dest reg
13896 					 */
13897 					if (need_id)
13898 						/* Assign src and dst registers the same ID
13899 						 * that will be used by find_equal_scalars()
13900 						 * to propagate min/max range.
13901 						 */
13902 						src_reg->id = ++env->id_gen;
13903 					copy_register_state(dst_reg, src_reg);
13904 					dst_reg->live |= REG_LIVE_WRITTEN;
13905 					dst_reg->subreg_def = DEF_NOT_SUBREG;
13906 				} else {
13907 					/* case: R1 = (s8, s16 s32)R2 */
13908 					if (is_pointer_value(env, insn->src_reg)) {
13909 						verbose(env,
13910 							"R%d sign-extension part of pointer\n",
13911 							insn->src_reg);
13912 						return -EACCES;
13913 					} else if (src_reg->type == SCALAR_VALUE) {
13914 						bool no_sext;
13915 
13916 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13917 						if (no_sext && need_id)
13918 							src_reg->id = ++env->id_gen;
13919 						copy_register_state(dst_reg, src_reg);
13920 						if (!no_sext)
13921 							dst_reg->id = 0;
13922 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13923 						dst_reg->live |= REG_LIVE_WRITTEN;
13924 						dst_reg->subreg_def = DEF_NOT_SUBREG;
13925 					} else {
13926 						mark_reg_unknown(env, regs, insn->dst_reg);
13927 					}
13928 				}
13929 			} else {
13930 				/* R1 = (u32) R2 */
13931 				if (is_pointer_value(env, insn->src_reg)) {
13932 					verbose(env,
13933 						"R%d partial copy of pointer\n",
13934 						insn->src_reg);
13935 					return -EACCES;
13936 				} else if (src_reg->type == SCALAR_VALUE) {
13937 					if (insn->off == 0) {
13938 						bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13939 
13940 						if (is_src_reg_u32 && need_id)
13941 							src_reg->id = ++env->id_gen;
13942 						copy_register_state(dst_reg, src_reg);
13943 						/* Make sure ID is cleared if src_reg is not in u32
13944 						 * range otherwise dst_reg min/max could be incorrectly
13945 						 * propagated into src_reg by find_equal_scalars()
13946 						 */
13947 						if (!is_src_reg_u32)
13948 							dst_reg->id = 0;
13949 						dst_reg->live |= REG_LIVE_WRITTEN;
13950 						dst_reg->subreg_def = env->insn_idx + 1;
13951 					} else {
13952 						/* case: W1 = (s8, s16)W2 */
13953 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13954 
13955 						if (no_sext && need_id)
13956 							src_reg->id = ++env->id_gen;
13957 						copy_register_state(dst_reg, src_reg);
13958 						if (!no_sext)
13959 							dst_reg->id = 0;
13960 						dst_reg->live |= REG_LIVE_WRITTEN;
13961 						dst_reg->subreg_def = env->insn_idx + 1;
13962 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13963 					}
13964 				} else {
13965 					mark_reg_unknown(env, regs,
13966 							 insn->dst_reg);
13967 				}
13968 				zext_32_to_64(dst_reg);
13969 				reg_bounds_sync(dst_reg);
13970 			}
13971 		} else {
13972 			/* case: R = imm
13973 			 * remember the value we stored into this reg
13974 			 */
13975 			/* clear any state __mark_reg_known doesn't set */
13976 			mark_reg_unknown(env, regs, insn->dst_reg);
13977 			regs[insn->dst_reg].type = SCALAR_VALUE;
13978 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13979 				__mark_reg_known(regs + insn->dst_reg,
13980 						 insn->imm);
13981 			} else {
13982 				__mark_reg_known(regs + insn->dst_reg,
13983 						 (u32)insn->imm);
13984 			}
13985 		}
13986 
13987 	} else if (opcode > BPF_END) {
13988 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13989 		return -EINVAL;
13990 
13991 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
13992 
13993 		if (BPF_SRC(insn->code) == BPF_X) {
13994 			if (insn->imm != 0 || insn->off > 1 ||
13995 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13996 				verbose(env, "BPF_ALU uses reserved fields\n");
13997 				return -EINVAL;
13998 			}
13999 			/* check src1 operand */
14000 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14001 			if (err)
14002 				return err;
14003 		} else {
14004 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
14005 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14006 				verbose(env, "BPF_ALU uses reserved fields\n");
14007 				return -EINVAL;
14008 			}
14009 		}
14010 
14011 		/* check src2 operand */
14012 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14013 		if (err)
14014 			return err;
14015 
14016 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
14017 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
14018 			verbose(env, "div by zero\n");
14019 			return -EINVAL;
14020 		}
14021 
14022 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
14023 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
14024 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
14025 
14026 			if (insn->imm < 0 || insn->imm >= size) {
14027 				verbose(env, "invalid shift %d\n", insn->imm);
14028 				return -EINVAL;
14029 			}
14030 		}
14031 
14032 		/* check dest operand */
14033 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14034 		err = err ?: adjust_reg_min_max_vals(env, insn);
14035 		if (err)
14036 			return err;
14037 	}
14038 
14039 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
14040 }
14041 
14042 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
14043 				   struct bpf_reg_state *dst_reg,
14044 				   enum bpf_reg_type type,
14045 				   bool range_right_open)
14046 {
14047 	struct bpf_func_state *state;
14048 	struct bpf_reg_state *reg;
14049 	int new_range;
14050 
14051 	if (dst_reg->off < 0 ||
14052 	    (dst_reg->off == 0 && range_right_open))
14053 		/* This doesn't give us any range */
14054 		return;
14055 
14056 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
14057 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
14058 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
14059 		 * than pkt_end, but that's because it's also less than pkt.
14060 		 */
14061 		return;
14062 
14063 	new_range = dst_reg->off;
14064 	if (range_right_open)
14065 		new_range++;
14066 
14067 	/* Examples for register markings:
14068 	 *
14069 	 * pkt_data in dst register:
14070 	 *
14071 	 *   r2 = r3;
14072 	 *   r2 += 8;
14073 	 *   if (r2 > pkt_end) goto <handle exception>
14074 	 *   <access okay>
14075 	 *
14076 	 *   r2 = r3;
14077 	 *   r2 += 8;
14078 	 *   if (r2 < pkt_end) goto <access okay>
14079 	 *   <handle exception>
14080 	 *
14081 	 *   Where:
14082 	 *     r2 == dst_reg, pkt_end == src_reg
14083 	 *     r2=pkt(id=n,off=8,r=0)
14084 	 *     r3=pkt(id=n,off=0,r=0)
14085 	 *
14086 	 * pkt_data in src register:
14087 	 *
14088 	 *   r2 = r3;
14089 	 *   r2 += 8;
14090 	 *   if (pkt_end >= r2) goto <access okay>
14091 	 *   <handle exception>
14092 	 *
14093 	 *   r2 = r3;
14094 	 *   r2 += 8;
14095 	 *   if (pkt_end <= r2) goto <handle exception>
14096 	 *   <access okay>
14097 	 *
14098 	 *   Where:
14099 	 *     pkt_end == dst_reg, r2 == src_reg
14100 	 *     r2=pkt(id=n,off=8,r=0)
14101 	 *     r3=pkt(id=n,off=0,r=0)
14102 	 *
14103 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
14104 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
14105 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
14106 	 * the check.
14107 	 */
14108 
14109 	/* If our ids match, then we must have the same max_value.  And we
14110 	 * don't care about the other reg's fixed offset, since if it's too big
14111 	 * the range won't allow anything.
14112 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
14113 	 */
14114 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14115 		if (reg->type == type && reg->id == dst_reg->id)
14116 			/* keep the maximum range already checked */
14117 			reg->range = max(reg->range, new_range);
14118 	}));
14119 }
14120 
14121 /*
14122  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
14123  */
14124 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14125 				  u8 opcode, bool is_jmp32)
14126 {
14127 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
14128 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
14129 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
14130 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
14131 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
14132 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
14133 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
14134 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
14135 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
14136 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
14137 
14138 	switch (opcode) {
14139 	case BPF_JEQ:
14140 		/* constants, umin/umax and smin/smax checks would be
14141 		 * redundant in this case because they all should match
14142 		 */
14143 		if (tnum_is_const(t1) && tnum_is_const(t2))
14144 			return t1.value == t2.value;
14145 		/* non-overlapping ranges */
14146 		if (umin1 > umax2 || umax1 < umin2)
14147 			return 0;
14148 		if (smin1 > smax2 || smax1 < smin2)
14149 			return 0;
14150 		if (!is_jmp32) {
14151 			/* if 64-bit ranges are inconclusive, see if we can
14152 			 * utilize 32-bit subrange knowledge to eliminate
14153 			 * branches that can't be taken a priori
14154 			 */
14155 			if (reg1->u32_min_value > reg2->u32_max_value ||
14156 			    reg1->u32_max_value < reg2->u32_min_value)
14157 				return 0;
14158 			if (reg1->s32_min_value > reg2->s32_max_value ||
14159 			    reg1->s32_max_value < reg2->s32_min_value)
14160 				return 0;
14161 		}
14162 		break;
14163 	case BPF_JNE:
14164 		/* constants, umin/umax and smin/smax checks would be
14165 		 * redundant in this case because they all should match
14166 		 */
14167 		if (tnum_is_const(t1) && tnum_is_const(t2))
14168 			return t1.value != t2.value;
14169 		/* non-overlapping ranges */
14170 		if (umin1 > umax2 || umax1 < umin2)
14171 			return 1;
14172 		if (smin1 > smax2 || smax1 < smin2)
14173 			return 1;
14174 		if (!is_jmp32) {
14175 			/* if 64-bit ranges are inconclusive, see if we can
14176 			 * utilize 32-bit subrange knowledge to eliminate
14177 			 * branches that can't be taken a priori
14178 			 */
14179 			if (reg1->u32_min_value > reg2->u32_max_value ||
14180 			    reg1->u32_max_value < reg2->u32_min_value)
14181 				return 1;
14182 			if (reg1->s32_min_value > reg2->s32_max_value ||
14183 			    reg1->s32_max_value < reg2->s32_min_value)
14184 				return 1;
14185 		}
14186 		break;
14187 	case BPF_JSET:
14188 		if (!is_reg_const(reg2, is_jmp32)) {
14189 			swap(reg1, reg2);
14190 			swap(t1, t2);
14191 		}
14192 		if (!is_reg_const(reg2, is_jmp32))
14193 			return -1;
14194 		if ((~t1.mask & t1.value) & t2.value)
14195 			return 1;
14196 		if (!((t1.mask | t1.value) & t2.value))
14197 			return 0;
14198 		break;
14199 	case BPF_JGT:
14200 		if (umin1 > umax2)
14201 			return 1;
14202 		else if (umax1 <= umin2)
14203 			return 0;
14204 		break;
14205 	case BPF_JSGT:
14206 		if (smin1 > smax2)
14207 			return 1;
14208 		else if (smax1 <= smin2)
14209 			return 0;
14210 		break;
14211 	case BPF_JLT:
14212 		if (umax1 < umin2)
14213 			return 1;
14214 		else if (umin1 >= umax2)
14215 			return 0;
14216 		break;
14217 	case BPF_JSLT:
14218 		if (smax1 < smin2)
14219 			return 1;
14220 		else if (smin1 >= smax2)
14221 			return 0;
14222 		break;
14223 	case BPF_JGE:
14224 		if (umin1 >= umax2)
14225 			return 1;
14226 		else if (umax1 < umin2)
14227 			return 0;
14228 		break;
14229 	case BPF_JSGE:
14230 		if (smin1 >= smax2)
14231 			return 1;
14232 		else if (smax1 < smin2)
14233 			return 0;
14234 		break;
14235 	case BPF_JLE:
14236 		if (umax1 <= umin2)
14237 			return 1;
14238 		else if (umin1 > umax2)
14239 			return 0;
14240 		break;
14241 	case BPF_JSLE:
14242 		if (smax1 <= smin2)
14243 			return 1;
14244 		else if (smin1 > smax2)
14245 			return 0;
14246 		break;
14247 	}
14248 
14249 	return -1;
14250 }
14251 
14252 static int flip_opcode(u32 opcode)
14253 {
14254 	/* How can we transform "a <op> b" into "b <op> a"? */
14255 	static const u8 opcode_flip[16] = {
14256 		/* these stay the same */
14257 		[BPF_JEQ  >> 4] = BPF_JEQ,
14258 		[BPF_JNE  >> 4] = BPF_JNE,
14259 		[BPF_JSET >> 4] = BPF_JSET,
14260 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14261 		[BPF_JGE  >> 4] = BPF_JLE,
14262 		[BPF_JGT  >> 4] = BPF_JLT,
14263 		[BPF_JLE  >> 4] = BPF_JGE,
14264 		[BPF_JLT  >> 4] = BPF_JGT,
14265 		[BPF_JSGE >> 4] = BPF_JSLE,
14266 		[BPF_JSGT >> 4] = BPF_JSLT,
14267 		[BPF_JSLE >> 4] = BPF_JSGE,
14268 		[BPF_JSLT >> 4] = BPF_JSGT
14269 	};
14270 	return opcode_flip[opcode >> 4];
14271 }
14272 
14273 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14274 				   struct bpf_reg_state *src_reg,
14275 				   u8 opcode)
14276 {
14277 	struct bpf_reg_state *pkt;
14278 
14279 	if (src_reg->type == PTR_TO_PACKET_END) {
14280 		pkt = dst_reg;
14281 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14282 		pkt = src_reg;
14283 		opcode = flip_opcode(opcode);
14284 	} else {
14285 		return -1;
14286 	}
14287 
14288 	if (pkt->range >= 0)
14289 		return -1;
14290 
14291 	switch (opcode) {
14292 	case BPF_JLE:
14293 		/* pkt <= pkt_end */
14294 		fallthrough;
14295 	case BPF_JGT:
14296 		/* pkt > pkt_end */
14297 		if (pkt->range == BEYOND_PKT_END)
14298 			/* pkt has at last one extra byte beyond pkt_end */
14299 			return opcode == BPF_JGT;
14300 		break;
14301 	case BPF_JLT:
14302 		/* pkt < pkt_end */
14303 		fallthrough;
14304 	case BPF_JGE:
14305 		/* pkt >= pkt_end */
14306 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14307 			return opcode == BPF_JGE;
14308 		break;
14309 	}
14310 	return -1;
14311 }
14312 
14313 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
14314  * and return:
14315  *  1 - branch will be taken and "goto target" will be executed
14316  *  0 - branch will not be taken and fall-through to next insn
14317  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
14318  *      range [0,10]
14319  */
14320 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14321 			   u8 opcode, bool is_jmp32)
14322 {
14323 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
14324 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
14325 
14326 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
14327 		u64 val;
14328 
14329 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
14330 		if (!is_reg_const(reg2, is_jmp32)) {
14331 			opcode = flip_opcode(opcode);
14332 			swap(reg1, reg2);
14333 		}
14334 		/* and ensure that reg2 is a constant */
14335 		if (!is_reg_const(reg2, is_jmp32))
14336 			return -1;
14337 
14338 		if (!reg_not_null(reg1))
14339 			return -1;
14340 
14341 		/* If pointer is valid tests against zero will fail so we can
14342 		 * use this to direct branch taken.
14343 		 */
14344 		val = reg_const_value(reg2, is_jmp32);
14345 		if (val != 0)
14346 			return -1;
14347 
14348 		switch (opcode) {
14349 		case BPF_JEQ:
14350 			return 0;
14351 		case BPF_JNE:
14352 			return 1;
14353 		default:
14354 			return -1;
14355 		}
14356 	}
14357 
14358 	/* now deal with two scalars, but not necessarily constants */
14359 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
14360 }
14361 
14362 /* Opcode that corresponds to a *false* branch condition.
14363  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
14364  */
14365 static u8 rev_opcode(u8 opcode)
14366 {
14367 	switch (opcode) {
14368 	case BPF_JEQ:		return BPF_JNE;
14369 	case BPF_JNE:		return BPF_JEQ;
14370 	/* JSET doesn't have it's reverse opcode in BPF, so add
14371 	 * BPF_X flag to denote the reverse of that operation
14372 	 */
14373 	case BPF_JSET:		return BPF_JSET | BPF_X;
14374 	case BPF_JSET | BPF_X:	return BPF_JSET;
14375 	case BPF_JGE:		return BPF_JLT;
14376 	case BPF_JGT:		return BPF_JLE;
14377 	case BPF_JLE:		return BPF_JGT;
14378 	case BPF_JLT:		return BPF_JGE;
14379 	case BPF_JSGE:		return BPF_JSLT;
14380 	case BPF_JSGT:		return BPF_JSLE;
14381 	case BPF_JSLE:		return BPF_JSGT;
14382 	case BPF_JSLT:		return BPF_JSGE;
14383 	default:		return 0;
14384 	}
14385 }
14386 
14387 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
14388 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14389 				u8 opcode, bool is_jmp32)
14390 {
14391 	struct tnum t;
14392 	u64 val;
14393 
14394 again:
14395 	switch (opcode) {
14396 	case BPF_JEQ:
14397 		if (is_jmp32) {
14398 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14399 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14400 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14401 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14402 			reg2->u32_min_value = reg1->u32_min_value;
14403 			reg2->u32_max_value = reg1->u32_max_value;
14404 			reg2->s32_min_value = reg1->s32_min_value;
14405 			reg2->s32_max_value = reg1->s32_max_value;
14406 
14407 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
14408 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14409 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
14410 		} else {
14411 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
14412 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14413 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
14414 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14415 			reg2->umin_value = reg1->umin_value;
14416 			reg2->umax_value = reg1->umax_value;
14417 			reg2->smin_value = reg1->smin_value;
14418 			reg2->smax_value = reg1->smax_value;
14419 
14420 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
14421 			reg2->var_off = reg1->var_off;
14422 		}
14423 		break;
14424 	case BPF_JNE:
14425 		if (!is_reg_const(reg2, is_jmp32))
14426 			swap(reg1, reg2);
14427 		if (!is_reg_const(reg2, is_jmp32))
14428 			break;
14429 
14430 		/* try to recompute the bound of reg1 if reg2 is a const and
14431 		 * is exactly the edge of reg1.
14432 		 */
14433 		val = reg_const_value(reg2, is_jmp32);
14434 		if (is_jmp32) {
14435 			/* u32_min_value is not equal to 0xffffffff at this point,
14436 			 * because otherwise u32_max_value is 0xffffffff as well,
14437 			 * in such a case both reg1 and reg2 would be constants,
14438 			 * jump would be predicted and reg_set_min_max() won't
14439 			 * be called.
14440 			 *
14441 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
14442 			 * below.
14443 			 */
14444 			if (reg1->u32_min_value == (u32)val)
14445 				reg1->u32_min_value++;
14446 			if (reg1->u32_max_value == (u32)val)
14447 				reg1->u32_max_value--;
14448 			if (reg1->s32_min_value == (s32)val)
14449 				reg1->s32_min_value++;
14450 			if (reg1->s32_max_value == (s32)val)
14451 				reg1->s32_max_value--;
14452 		} else {
14453 			if (reg1->umin_value == (u64)val)
14454 				reg1->umin_value++;
14455 			if (reg1->umax_value == (u64)val)
14456 				reg1->umax_value--;
14457 			if (reg1->smin_value == (s64)val)
14458 				reg1->smin_value++;
14459 			if (reg1->smax_value == (s64)val)
14460 				reg1->smax_value--;
14461 		}
14462 		break;
14463 	case BPF_JSET:
14464 		if (!is_reg_const(reg2, is_jmp32))
14465 			swap(reg1, reg2);
14466 		if (!is_reg_const(reg2, is_jmp32))
14467 			break;
14468 		val = reg_const_value(reg2, is_jmp32);
14469 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
14470 		 * requires single bit to learn something useful. E.g., if we
14471 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
14472 		 * are actually set? We can learn something definite only if
14473 		 * it's a single-bit value to begin with.
14474 		 *
14475 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
14476 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
14477 		 * bit 1 is set, which we can readily use in adjustments.
14478 		 */
14479 		if (!is_power_of_2(val))
14480 			break;
14481 		if (is_jmp32) {
14482 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
14483 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14484 		} else {
14485 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
14486 		}
14487 		break;
14488 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
14489 		if (!is_reg_const(reg2, is_jmp32))
14490 			swap(reg1, reg2);
14491 		if (!is_reg_const(reg2, is_jmp32))
14492 			break;
14493 		val = reg_const_value(reg2, is_jmp32);
14494 		if (is_jmp32) {
14495 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
14496 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14497 		} else {
14498 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
14499 		}
14500 		break;
14501 	case BPF_JLE:
14502 		if (is_jmp32) {
14503 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14504 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14505 		} else {
14506 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14507 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
14508 		}
14509 		break;
14510 	case BPF_JLT:
14511 		if (is_jmp32) {
14512 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
14513 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
14514 		} else {
14515 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
14516 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
14517 		}
14518 		break;
14519 	case BPF_JSLE:
14520 		if (is_jmp32) {
14521 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14522 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14523 		} else {
14524 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14525 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
14526 		}
14527 		break;
14528 	case BPF_JSLT:
14529 		if (is_jmp32) {
14530 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
14531 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
14532 		} else {
14533 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
14534 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
14535 		}
14536 		break;
14537 	case BPF_JGE:
14538 	case BPF_JGT:
14539 	case BPF_JSGE:
14540 	case BPF_JSGT:
14541 		/* just reuse LE/LT logic above */
14542 		opcode = flip_opcode(opcode);
14543 		swap(reg1, reg2);
14544 		goto again;
14545 	default:
14546 		return;
14547 	}
14548 }
14549 
14550 /* Adjusts the register min/max values in the case that the dst_reg and
14551  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
14552  * check, in which case we havea fake SCALAR_VALUE representing insn->imm).
14553  * Technically we can do similar adjustments for pointers to the same object,
14554  * but we don't support that right now.
14555  */
14556 static int reg_set_min_max(struct bpf_verifier_env *env,
14557 			   struct bpf_reg_state *true_reg1,
14558 			   struct bpf_reg_state *true_reg2,
14559 			   struct bpf_reg_state *false_reg1,
14560 			   struct bpf_reg_state *false_reg2,
14561 			   u8 opcode, bool is_jmp32)
14562 {
14563 	int err;
14564 
14565 	/* If either register is a pointer, we can't learn anything about its
14566 	 * variable offset from the compare (unless they were a pointer into
14567 	 * the same object, but we don't bother with that).
14568 	 */
14569 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
14570 		return 0;
14571 
14572 	/* fallthrough (FALSE) branch */
14573 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
14574 	reg_bounds_sync(false_reg1);
14575 	reg_bounds_sync(false_reg2);
14576 
14577 	/* jump (TRUE) branch */
14578 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
14579 	reg_bounds_sync(true_reg1);
14580 	reg_bounds_sync(true_reg2);
14581 
14582 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
14583 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
14584 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
14585 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
14586 	return err;
14587 }
14588 
14589 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14590 				 struct bpf_reg_state *reg, u32 id,
14591 				 bool is_null)
14592 {
14593 	if (type_may_be_null(reg->type) && reg->id == id &&
14594 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14595 		/* Old offset (both fixed and variable parts) should have been
14596 		 * known-zero, because we don't allow pointer arithmetic on
14597 		 * pointers that might be NULL. If we see this happening, don't
14598 		 * convert the register.
14599 		 *
14600 		 * But in some cases, some helpers that return local kptrs
14601 		 * advance offset for the returned pointer. In those cases, it
14602 		 * is fine to expect to see reg->off.
14603 		 */
14604 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14605 			return;
14606 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14607 		    WARN_ON_ONCE(reg->off))
14608 			return;
14609 
14610 		if (is_null) {
14611 			reg->type = SCALAR_VALUE;
14612 			/* We don't need id and ref_obj_id from this point
14613 			 * onwards anymore, thus we should better reset it,
14614 			 * so that state pruning has chances to take effect.
14615 			 */
14616 			reg->id = 0;
14617 			reg->ref_obj_id = 0;
14618 
14619 			return;
14620 		}
14621 
14622 		mark_ptr_not_null_reg(reg);
14623 
14624 		if (!reg_may_point_to_spin_lock(reg)) {
14625 			/* For not-NULL ptr, reg->ref_obj_id will be reset
14626 			 * in release_reference().
14627 			 *
14628 			 * reg->id is still used by spin_lock ptr. Other
14629 			 * than spin_lock ptr type, reg->id can be reset.
14630 			 */
14631 			reg->id = 0;
14632 		}
14633 	}
14634 }
14635 
14636 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14637  * be folded together at some point.
14638  */
14639 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14640 				  bool is_null)
14641 {
14642 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14643 	struct bpf_reg_state *regs = state->regs, *reg;
14644 	u32 ref_obj_id = regs[regno].ref_obj_id;
14645 	u32 id = regs[regno].id;
14646 
14647 	if (ref_obj_id && ref_obj_id == id && is_null)
14648 		/* regs[regno] is in the " == NULL" branch.
14649 		 * No one could have freed the reference state before
14650 		 * doing the NULL check.
14651 		 */
14652 		WARN_ON_ONCE(release_reference_state(state, id));
14653 
14654 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14655 		mark_ptr_or_null_reg(state, reg, id, is_null);
14656 	}));
14657 }
14658 
14659 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14660 				   struct bpf_reg_state *dst_reg,
14661 				   struct bpf_reg_state *src_reg,
14662 				   struct bpf_verifier_state *this_branch,
14663 				   struct bpf_verifier_state *other_branch)
14664 {
14665 	if (BPF_SRC(insn->code) != BPF_X)
14666 		return false;
14667 
14668 	/* Pointers are always 64-bit. */
14669 	if (BPF_CLASS(insn->code) == BPF_JMP32)
14670 		return false;
14671 
14672 	switch (BPF_OP(insn->code)) {
14673 	case BPF_JGT:
14674 		if ((dst_reg->type == PTR_TO_PACKET &&
14675 		     src_reg->type == PTR_TO_PACKET_END) ||
14676 		    (dst_reg->type == PTR_TO_PACKET_META &&
14677 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14678 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14679 			find_good_pkt_pointers(this_branch, dst_reg,
14680 					       dst_reg->type, false);
14681 			mark_pkt_end(other_branch, insn->dst_reg, true);
14682 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14683 			    src_reg->type == PTR_TO_PACKET) ||
14684 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14685 			    src_reg->type == PTR_TO_PACKET_META)) {
14686 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
14687 			find_good_pkt_pointers(other_branch, src_reg,
14688 					       src_reg->type, true);
14689 			mark_pkt_end(this_branch, insn->src_reg, false);
14690 		} else {
14691 			return false;
14692 		}
14693 		break;
14694 	case BPF_JLT:
14695 		if ((dst_reg->type == PTR_TO_PACKET &&
14696 		     src_reg->type == PTR_TO_PACKET_END) ||
14697 		    (dst_reg->type == PTR_TO_PACKET_META &&
14698 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14699 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14700 			find_good_pkt_pointers(other_branch, dst_reg,
14701 					       dst_reg->type, true);
14702 			mark_pkt_end(this_branch, insn->dst_reg, false);
14703 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14704 			    src_reg->type == PTR_TO_PACKET) ||
14705 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14706 			    src_reg->type == PTR_TO_PACKET_META)) {
14707 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
14708 			find_good_pkt_pointers(this_branch, src_reg,
14709 					       src_reg->type, false);
14710 			mark_pkt_end(other_branch, insn->src_reg, true);
14711 		} else {
14712 			return false;
14713 		}
14714 		break;
14715 	case BPF_JGE:
14716 		if ((dst_reg->type == PTR_TO_PACKET &&
14717 		     src_reg->type == PTR_TO_PACKET_END) ||
14718 		    (dst_reg->type == PTR_TO_PACKET_META &&
14719 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14720 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14721 			find_good_pkt_pointers(this_branch, dst_reg,
14722 					       dst_reg->type, true);
14723 			mark_pkt_end(other_branch, insn->dst_reg, false);
14724 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14725 			    src_reg->type == PTR_TO_PACKET) ||
14726 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14727 			    src_reg->type == PTR_TO_PACKET_META)) {
14728 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14729 			find_good_pkt_pointers(other_branch, src_reg,
14730 					       src_reg->type, false);
14731 			mark_pkt_end(this_branch, insn->src_reg, true);
14732 		} else {
14733 			return false;
14734 		}
14735 		break;
14736 	case BPF_JLE:
14737 		if ((dst_reg->type == PTR_TO_PACKET &&
14738 		     src_reg->type == PTR_TO_PACKET_END) ||
14739 		    (dst_reg->type == PTR_TO_PACKET_META &&
14740 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14741 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14742 			find_good_pkt_pointers(other_branch, dst_reg,
14743 					       dst_reg->type, false);
14744 			mark_pkt_end(this_branch, insn->dst_reg, true);
14745 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14746 			    src_reg->type == PTR_TO_PACKET) ||
14747 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14748 			    src_reg->type == PTR_TO_PACKET_META)) {
14749 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14750 			find_good_pkt_pointers(this_branch, src_reg,
14751 					       src_reg->type, true);
14752 			mark_pkt_end(other_branch, insn->src_reg, false);
14753 		} else {
14754 			return false;
14755 		}
14756 		break;
14757 	default:
14758 		return false;
14759 	}
14760 
14761 	return true;
14762 }
14763 
14764 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14765 			       struct bpf_reg_state *known_reg)
14766 {
14767 	struct bpf_func_state *state;
14768 	struct bpf_reg_state *reg;
14769 
14770 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14771 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14772 			copy_register_state(reg, known_reg);
14773 	}));
14774 }
14775 
14776 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14777 			     struct bpf_insn *insn, int *insn_idx)
14778 {
14779 	struct bpf_verifier_state *this_branch = env->cur_state;
14780 	struct bpf_verifier_state *other_branch;
14781 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14782 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14783 	struct bpf_reg_state *eq_branch_regs;
14784 	struct bpf_reg_state fake_reg = {};
14785 	u8 opcode = BPF_OP(insn->code);
14786 	bool is_jmp32;
14787 	int pred = -1;
14788 	int err;
14789 
14790 	/* Only conditional jumps are expected to reach here. */
14791 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
14792 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14793 		return -EINVAL;
14794 	}
14795 
14796 	/* check src2 operand */
14797 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14798 	if (err)
14799 		return err;
14800 
14801 	dst_reg = &regs[insn->dst_reg];
14802 	if (BPF_SRC(insn->code) == BPF_X) {
14803 		if (insn->imm != 0) {
14804 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14805 			return -EINVAL;
14806 		}
14807 
14808 		/* check src1 operand */
14809 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14810 		if (err)
14811 			return err;
14812 
14813 		src_reg = &regs[insn->src_reg];
14814 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14815 		    is_pointer_value(env, insn->src_reg)) {
14816 			verbose(env, "R%d pointer comparison prohibited\n",
14817 				insn->src_reg);
14818 			return -EACCES;
14819 		}
14820 	} else {
14821 		if (insn->src_reg != BPF_REG_0) {
14822 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14823 			return -EINVAL;
14824 		}
14825 		src_reg = &fake_reg;
14826 		src_reg->type = SCALAR_VALUE;
14827 		__mark_reg_known(src_reg, insn->imm);
14828 	}
14829 
14830 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14831 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
14832 	if (pred >= 0) {
14833 		/* If we get here with a dst_reg pointer type it is because
14834 		 * above is_branch_taken() special cased the 0 comparison.
14835 		 */
14836 		if (!__is_pointer_value(false, dst_reg))
14837 			err = mark_chain_precision(env, insn->dst_reg);
14838 		if (BPF_SRC(insn->code) == BPF_X && !err &&
14839 		    !__is_pointer_value(false, src_reg))
14840 			err = mark_chain_precision(env, insn->src_reg);
14841 		if (err)
14842 			return err;
14843 	}
14844 
14845 	if (pred == 1) {
14846 		/* Only follow the goto, ignore fall-through. If needed, push
14847 		 * the fall-through branch for simulation under speculative
14848 		 * execution.
14849 		 */
14850 		if (!env->bypass_spec_v1 &&
14851 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
14852 					       *insn_idx))
14853 			return -EFAULT;
14854 		if (env->log.level & BPF_LOG_LEVEL)
14855 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14856 		*insn_idx += insn->off;
14857 		return 0;
14858 	} else if (pred == 0) {
14859 		/* Only follow the fall-through branch, since that's where the
14860 		 * program will go. If needed, push the goto branch for
14861 		 * simulation under speculative execution.
14862 		 */
14863 		if (!env->bypass_spec_v1 &&
14864 		    !sanitize_speculative_path(env, insn,
14865 					       *insn_idx + insn->off + 1,
14866 					       *insn_idx))
14867 			return -EFAULT;
14868 		if (env->log.level & BPF_LOG_LEVEL)
14869 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14870 		return 0;
14871 	}
14872 
14873 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14874 				  false);
14875 	if (!other_branch)
14876 		return -EFAULT;
14877 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14878 
14879 	if (BPF_SRC(insn->code) == BPF_X) {
14880 		err = reg_set_min_max(env,
14881 				      &other_branch_regs[insn->dst_reg],
14882 				      &other_branch_regs[insn->src_reg],
14883 				      dst_reg, src_reg, opcode, is_jmp32);
14884 	} else /* BPF_SRC(insn->code) == BPF_K */ {
14885 		err = reg_set_min_max(env,
14886 				      &other_branch_regs[insn->dst_reg],
14887 				      src_reg /* fake one */,
14888 				      dst_reg, src_reg /* same fake one */,
14889 				      opcode, is_jmp32);
14890 	}
14891 	if (err)
14892 		return err;
14893 
14894 	if (BPF_SRC(insn->code) == BPF_X &&
14895 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
14896 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14897 		find_equal_scalars(this_branch, src_reg);
14898 		find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14899 	}
14900 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14901 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14902 		find_equal_scalars(this_branch, dst_reg);
14903 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14904 	}
14905 
14906 	/* if one pointer register is compared to another pointer
14907 	 * register check if PTR_MAYBE_NULL could be lifted.
14908 	 * E.g. register A - maybe null
14909 	 *      register B - not null
14910 	 * for JNE A, B, ... - A is not null in the false branch;
14911 	 * for JEQ A, B, ... - A is not null in the true branch.
14912 	 *
14913 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
14914 	 * not need to be null checked by the BPF program, i.e.,
14915 	 * could be null even without PTR_MAYBE_NULL marking, so
14916 	 * only propagate nullness when neither reg is that type.
14917 	 */
14918 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14919 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14920 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14921 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
14922 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14923 		eq_branch_regs = NULL;
14924 		switch (opcode) {
14925 		case BPF_JEQ:
14926 			eq_branch_regs = other_branch_regs;
14927 			break;
14928 		case BPF_JNE:
14929 			eq_branch_regs = regs;
14930 			break;
14931 		default:
14932 			/* do nothing */
14933 			break;
14934 		}
14935 		if (eq_branch_regs) {
14936 			if (type_may_be_null(src_reg->type))
14937 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14938 			else
14939 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14940 		}
14941 	}
14942 
14943 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14944 	 * NOTE: these optimizations below are related with pointer comparison
14945 	 *       which will never be JMP32.
14946 	 */
14947 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14948 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14949 	    type_may_be_null(dst_reg->type)) {
14950 		/* Mark all identical registers in each branch as either
14951 		 * safe or unknown depending R == 0 or R != 0 conditional.
14952 		 */
14953 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14954 				      opcode == BPF_JNE);
14955 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14956 				      opcode == BPF_JEQ);
14957 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14958 					   this_branch, other_branch) &&
14959 		   is_pointer_value(env, insn->dst_reg)) {
14960 		verbose(env, "R%d pointer comparison prohibited\n",
14961 			insn->dst_reg);
14962 		return -EACCES;
14963 	}
14964 	if (env->log.level & BPF_LOG_LEVEL)
14965 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
14966 	return 0;
14967 }
14968 
14969 /* verify BPF_LD_IMM64 instruction */
14970 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14971 {
14972 	struct bpf_insn_aux_data *aux = cur_aux(env);
14973 	struct bpf_reg_state *regs = cur_regs(env);
14974 	struct bpf_reg_state *dst_reg;
14975 	struct bpf_map *map;
14976 	int err;
14977 
14978 	if (BPF_SIZE(insn->code) != BPF_DW) {
14979 		verbose(env, "invalid BPF_LD_IMM insn\n");
14980 		return -EINVAL;
14981 	}
14982 	if (insn->off != 0) {
14983 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14984 		return -EINVAL;
14985 	}
14986 
14987 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
14988 	if (err)
14989 		return err;
14990 
14991 	dst_reg = &regs[insn->dst_reg];
14992 	if (insn->src_reg == 0) {
14993 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14994 
14995 		dst_reg->type = SCALAR_VALUE;
14996 		__mark_reg_known(&regs[insn->dst_reg], imm);
14997 		return 0;
14998 	}
14999 
15000 	/* All special src_reg cases are listed below. From this point onwards
15001 	 * we either succeed and assign a corresponding dst_reg->type after
15002 	 * zeroing the offset, or fail and reject the program.
15003 	 */
15004 	mark_reg_known_zero(env, regs, insn->dst_reg);
15005 
15006 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
15007 		dst_reg->type = aux->btf_var.reg_type;
15008 		switch (base_type(dst_reg->type)) {
15009 		case PTR_TO_MEM:
15010 			dst_reg->mem_size = aux->btf_var.mem_size;
15011 			break;
15012 		case PTR_TO_BTF_ID:
15013 			dst_reg->btf = aux->btf_var.btf;
15014 			dst_reg->btf_id = aux->btf_var.btf_id;
15015 			break;
15016 		default:
15017 			verbose(env, "bpf verifier is misconfigured\n");
15018 			return -EFAULT;
15019 		}
15020 		return 0;
15021 	}
15022 
15023 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
15024 		struct bpf_prog_aux *aux = env->prog->aux;
15025 		u32 subprogno = find_subprog(env,
15026 					     env->insn_idx + insn->imm + 1);
15027 
15028 		if (!aux->func_info) {
15029 			verbose(env, "missing btf func_info\n");
15030 			return -EINVAL;
15031 		}
15032 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
15033 			verbose(env, "callback function not static\n");
15034 			return -EINVAL;
15035 		}
15036 
15037 		dst_reg->type = PTR_TO_FUNC;
15038 		dst_reg->subprogno = subprogno;
15039 		return 0;
15040 	}
15041 
15042 	map = env->used_maps[aux->map_index];
15043 	dst_reg->map_ptr = map;
15044 
15045 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
15046 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
15047 		dst_reg->type = PTR_TO_MAP_VALUE;
15048 		dst_reg->off = aux->map_off;
15049 		WARN_ON_ONCE(map->max_entries != 1);
15050 		/* We want reg->id to be same (0) as map_value is not distinct */
15051 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
15052 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
15053 		dst_reg->type = CONST_PTR_TO_MAP;
15054 	} else {
15055 		verbose(env, "bpf verifier is misconfigured\n");
15056 		return -EINVAL;
15057 	}
15058 
15059 	return 0;
15060 }
15061 
15062 static bool may_access_skb(enum bpf_prog_type type)
15063 {
15064 	switch (type) {
15065 	case BPF_PROG_TYPE_SOCKET_FILTER:
15066 	case BPF_PROG_TYPE_SCHED_CLS:
15067 	case BPF_PROG_TYPE_SCHED_ACT:
15068 		return true;
15069 	default:
15070 		return false;
15071 	}
15072 }
15073 
15074 /* verify safety of LD_ABS|LD_IND instructions:
15075  * - they can only appear in the programs where ctx == skb
15076  * - since they are wrappers of function calls, they scratch R1-R5 registers,
15077  *   preserve R6-R9, and store return value into R0
15078  *
15079  * Implicit input:
15080  *   ctx == skb == R6 == CTX
15081  *
15082  * Explicit input:
15083  *   SRC == any register
15084  *   IMM == 32-bit immediate
15085  *
15086  * Output:
15087  *   R0 - 8/16/32-bit skb data converted to cpu endianness
15088  */
15089 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
15090 {
15091 	struct bpf_reg_state *regs = cur_regs(env);
15092 	static const int ctx_reg = BPF_REG_6;
15093 	u8 mode = BPF_MODE(insn->code);
15094 	int i, err;
15095 
15096 	if (!may_access_skb(resolve_prog_type(env->prog))) {
15097 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
15098 		return -EINVAL;
15099 	}
15100 
15101 	if (!env->ops->gen_ld_abs) {
15102 		verbose(env, "bpf verifier is misconfigured\n");
15103 		return -EINVAL;
15104 	}
15105 
15106 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
15107 	    BPF_SIZE(insn->code) == BPF_DW ||
15108 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
15109 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
15110 		return -EINVAL;
15111 	}
15112 
15113 	/* check whether implicit source operand (register R6) is readable */
15114 	err = check_reg_arg(env, ctx_reg, SRC_OP);
15115 	if (err)
15116 		return err;
15117 
15118 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
15119 	 * gen_ld_abs() may terminate the program at runtime, leading to
15120 	 * reference leak.
15121 	 */
15122 	err = check_reference_leak(env, false);
15123 	if (err) {
15124 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
15125 		return err;
15126 	}
15127 
15128 	if (env->cur_state->active_lock.ptr) {
15129 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
15130 		return -EINVAL;
15131 	}
15132 
15133 	if (env->cur_state->active_rcu_lock) {
15134 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
15135 		return -EINVAL;
15136 	}
15137 
15138 	if (regs[ctx_reg].type != PTR_TO_CTX) {
15139 		verbose(env,
15140 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
15141 		return -EINVAL;
15142 	}
15143 
15144 	if (mode == BPF_IND) {
15145 		/* check explicit source operand */
15146 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
15147 		if (err)
15148 			return err;
15149 	}
15150 
15151 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
15152 	if (err < 0)
15153 		return err;
15154 
15155 	/* reset caller saved regs to unreadable */
15156 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
15157 		mark_reg_not_init(env, regs, caller_saved[i]);
15158 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
15159 	}
15160 
15161 	/* mark destination R0 register as readable, since it contains
15162 	 * the value fetched from the packet.
15163 	 * Already marked as written above.
15164 	 */
15165 	mark_reg_unknown(env, regs, BPF_REG_0);
15166 	/* ld_abs load up to 32-bit skb data. */
15167 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
15168 	return 0;
15169 }
15170 
15171 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
15172 {
15173 	const char *exit_ctx = "At program exit";
15174 	struct tnum enforce_attach_type_range = tnum_unknown;
15175 	const struct bpf_prog *prog = env->prog;
15176 	struct bpf_reg_state *reg;
15177 	struct bpf_retval_range range = retval_range(0, 1);
15178 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15179 	int err;
15180 	struct bpf_func_state *frame = env->cur_state->frame[0];
15181 	const bool is_subprog = frame->subprogno;
15182 
15183 	/* LSM and struct_ops func-ptr's return type could be "void" */
15184 	if (!is_subprog || frame->in_exception_callback_fn) {
15185 		switch (prog_type) {
15186 		case BPF_PROG_TYPE_LSM:
15187 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
15188 				/* See below, can be 0 or 0-1 depending on hook. */
15189 				break;
15190 			fallthrough;
15191 		case BPF_PROG_TYPE_STRUCT_OPS:
15192 			if (!prog->aux->attach_func_proto->type)
15193 				return 0;
15194 			break;
15195 		default:
15196 			break;
15197 		}
15198 	}
15199 
15200 	/* eBPF calling convention is such that R0 is used
15201 	 * to return the value from eBPF program.
15202 	 * Make sure that it's readable at this time
15203 	 * of bpf_exit, which means that program wrote
15204 	 * something into it earlier
15205 	 */
15206 	err = check_reg_arg(env, regno, SRC_OP);
15207 	if (err)
15208 		return err;
15209 
15210 	if (is_pointer_value(env, regno)) {
15211 		verbose(env, "R%d leaks addr as return value\n", regno);
15212 		return -EACCES;
15213 	}
15214 
15215 	reg = cur_regs(env) + regno;
15216 
15217 	if (frame->in_async_callback_fn) {
15218 		/* enforce return zero from async callbacks like timer */
15219 		exit_ctx = "At async callback return";
15220 		range = retval_range(0, 0);
15221 		goto enforce_retval;
15222 	}
15223 
15224 	if (is_subprog && !frame->in_exception_callback_fn) {
15225 		if (reg->type != SCALAR_VALUE) {
15226 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
15227 				regno, reg_type_str(env, reg->type));
15228 			return -EINVAL;
15229 		}
15230 		return 0;
15231 	}
15232 
15233 	switch (prog_type) {
15234 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15235 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15236 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15237 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
15238 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15239 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15240 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
15241 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15242 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
15243 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
15244 			range = retval_range(1, 1);
15245 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15246 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15247 			range = retval_range(0, 3);
15248 		break;
15249 	case BPF_PROG_TYPE_CGROUP_SKB:
15250 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15251 			range = retval_range(0, 3);
15252 			enforce_attach_type_range = tnum_range(2, 3);
15253 		}
15254 		break;
15255 	case BPF_PROG_TYPE_CGROUP_SOCK:
15256 	case BPF_PROG_TYPE_SOCK_OPS:
15257 	case BPF_PROG_TYPE_CGROUP_DEVICE:
15258 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15259 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15260 		break;
15261 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15262 		if (!env->prog->aux->attach_btf_id)
15263 			return 0;
15264 		range = retval_range(0, 0);
15265 		break;
15266 	case BPF_PROG_TYPE_TRACING:
15267 		switch (env->prog->expected_attach_type) {
15268 		case BPF_TRACE_FENTRY:
15269 		case BPF_TRACE_FEXIT:
15270 			range = retval_range(0, 0);
15271 			break;
15272 		case BPF_TRACE_RAW_TP:
15273 		case BPF_MODIFY_RETURN:
15274 			return 0;
15275 		case BPF_TRACE_ITER:
15276 			break;
15277 		default:
15278 			return -ENOTSUPP;
15279 		}
15280 		break;
15281 	case BPF_PROG_TYPE_SK_LOOKUP:
15282 		range = retval_range(SK_DROP, SK_PASS);
15283 		break;
15284 
15285 	case BPF_PROG_TYPE_LSM:
15286 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15287 			/* Regular BPF_PROG_TYPE_LSM programs can return
15288 			 * any value.
15289 			 */
15290 			return 0;
15291 		}
15292 		if (!env->prog->aux->attach_func_proto->type) {
15293 			/* Make sure programs that attach to void
15294 			 * hooks don't try to modify return value.
15295 			 */
15296 			range = retval_range(1, 1);
15297 		}
15298 		break;
15299 
15300 	case BPF_PROG_TYPE_NETFILTER:
15301 		range = retval_range(NF_DROP, NF_ACCEPT);
15302 		break;
15303 	case BPF_PROG_TYPE_EXT:
15304 		/* freplace program can return anything as its return value
15305 		 * depends on the to-be-replaced kernel func or bpf program.
15306 		 */
15307 	default:
15308 		return 0;
15309 	}
15310 
15311 enforce_retval:
15312 	if (reg->type != SCALAR_VALUE) {
15313 		verbose(env, "%s the register R%d is not a known value (%s)\n",
15314 			exit_ctx, regno, reg_type_str(env, reg->type));
15315 		return -EINVAL;
15316 	}
15317 
15318 	err = mark_chain_precision(env, regno);
15319 	if (err)
15320 		return err;
15321 
15322 	if (!retval_range_within(range, reg)) {
15323 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
15324 		if (!is_subprog &&
15325 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
15326 		    prog_type == BPF_PROG_TYPE_LSM &&
15327 		    !prog->aux->attach_func_proto->type)
15328 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15329 		return -EINVAL;
15330 	}
15331 
15332 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15333 	    tnum_in(enforce_attach_type_range, reg->var_off))
15334 		env->prog->enforce_expected_attach_type = 1;
15335 	return 0;
15336 }
15337 
15338 /* non-recursive DFS pseudo code
15339  * 1  procedure DFS-iterative(G,v):
15340  * 2      label v as discovered
15341  * 3      let S be a stack
15342  * 4      S.push(v)
15343  * 5      while S is not empty
15344  * 6            t <- S.peek()
15345  * 7            if t is what we're looking for:
15346  * 8                return t
15347  * 9            for all edges e in G.adjacentEdges(t) do
15348  * 10               if edge e is already labelled
15349  * 11                   continue with the next edge
15350  * 12               w <- G.adjacentVertex(t,e)
15351  * 13               if vertex w is not discovered and not explored
15352  * 14                   label e as tree-edge
15353  * 15                   label w as discovered
15354  * 16                   S.push(w)
15355  * 17                   continue at 5
15356  * 18               else if vertex w is discovered
15357  * 19                   label e as back-edge
15358  * 20               else
15359  * 21                   // vertex w is explored
15360  * 22                   label e as forward- or cross-edge
15361  * 23           label t as explored
15362  * 24           S.pop()
15363  *
15364  * convention:
15365  * 0x10 - discovered
15366  * 0x11 - discovered and fall-through edge labelled
15367  * 0x12 - discovered and fall-through and branch edges labelled
15368  * 0x20 - explored
15369  */
15370 
15371 enum {
15372 	DISCOVERED = 0x10,
15373 	EXPLORED = 0x20,
15374 	FALLTHROUGH = 1,
15375 	BRANCH = 2,
15376 };
15377 
15378 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15379 {
15380 	env->insn_aux_data[idx].prune_point = true;
15381 }
15382 
15383 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15384 {
15385 	return env->insn_aux_data[insn_idx].prune_point;
15386 }
15387 
15388 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15389 {
15390 	env->insn_aux_data[idx].force_checkpoint = true;
15391 }
15392 
15393 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15394 {
15395 	return env->insn_aux_data[insn_idx].force_checkpoint;
15396 }
15397 
15398 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15399 {
15400 	env->insn_aux_data[idx].calls_callback = true;
15401 }
15402 
15403 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15404 {
15405 	return env->insn_aux_data[insn_idx].calls_callback;
15406 }
15407 
15408 enum {
15409 	DONE_EXPLORING = 0,
15410 	KEEP_EXPLORING = 1,
15411 };
15412 
15413 /* t, w, e - match pseudo-code above:
15414  * t - index of current instruction
15415  * w - next instruction
15416  * e - edge
15417  */
15418 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15419 {
15420 	int *insn_stack = env->cfg.insn_stack;
15421 	int *insn_state = env->cfg.insn_state;
15422 
15423 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15424 		return DONE_EXPLORING;
15425 
15426 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15427 		return DONE_EXPLORING;
15428 
15429 	if (w < 0 || w >= env->prog->len) {
15430 		verbose_linfo(env, t, "%d: ", t);
15431 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15432 		return -EINVAL;
15433 	}
15434 
15435 	if (e == BRANCH) {
15436 		/* mark branch target for state pruning */
15437 		mark_prune_point(env, w);
15438 		mark_jmp_point(env, w);
15439 	}
15440 
15441 	if (insn_state[w] == 0) {
15442 		/* tree-edge */
15443 		insn_state[t] = DISCOVERED | e;
15444 		insn_state[w] = DISCOVERED;
15445 		if (env->cfg.cur_stack >= env->prog->len)
15446 			return -E2BIG;
15447 		insn_stack[env->cfg.cur_stack++] = w;
15448 		return KEEP_EXPLORING;
15449 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15450 		if (env->bpf_capable)
15451 			return DONE_EXPLORING;
15452 		verbose_linfo(env, t, "%d: ", t);
15453 		verbose_linfo(env, w, "%d: ", w);
15454 		verbose(env, "back-edge from insn %d to %d\n", t, w);
15455 		return -EINVAL;
15456 	} else if (insn_state[w] == EXPLORED) {
15457 		/* forward- or cross-edge */
15458 		insn_state[t] = DISCOVERED | e;
15459 	} else {
15460 		verbose(env, "insn state internal bug\n");
15461 		return -EFAULT;
15462 	}
15463 	return DONE_EXPLORING;
15464 }
15465 
15466 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15467 				struct bpf_verifier_env *env,
15468 				bool visit_callee)
15469 {
15470 	int ret, insn_sz;
15471 
15472 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15473 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15474 	if (ret)
15475 		return ret;
15476 
15477 	mark_prune_point(env, t + insn_sz);
15478 	/* when we exit from subprog, we need to record non-linear history */
15479 	mark_jmp_point(env, t + insn_sz);
15480 
15481 	if (visit_callee) {
15482 		mark_prune_point(env, t);
15483 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15484 	}
15485 	return ret;
15486 }
15487 
15488 /* Visits the instruction at index t and returns one of the following:
15489  *  < 0 - an error occurred
15490  *  DONE_EXPLORING - the instruction was fully explored
15491  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15492  */
15493 static int visit_insn(int t, struct bpf_verifier_env *env)
15494 {
15495 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15496 	int ret, off, insn_sz;
15497 
15498 	if (bpf_pseudo_func(insn))
15499 		return visit_func_call_insn(t, insns, env, true);
15500 
15501 	/* All non-branch instructions have a single fall-through edge. */
15502 	if (BPF_CLASS(insn->code) != BPF_JMP &&
15503 	    BPF_CLASS(insn->code) != BPF_JMP32) {
15504 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15505 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15506 	}
15507 
15508 	switch (BPF_OP(insn->code)) {
15509 	case BPF_EXIT:
15510 		return DONE_EXPLORING;
15511 
15512 	case BPF_CALL:
15513 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15514 			/* Mark this call insn as a prune point to trigger
15515 			 * is_state_visited() check before call itself is
15516 			 * processed by __check_func_call(). Otherwise new
15517 			 * async state will be pushed for further exploration.
15518 			 */
15519 			mark_prune_point(env, t);
15520 		/* For functions that invoke callbacks it is not known how many times
15521 		 * callback would be called. Verifier models callback calling functions
15522 		 * by repeatedly visiting callback bodies and returning to origin call
15523 		 * instruction.
15524 		 * In order to stop such iteration verifier needs to identify when a
15525 		 * state identical some state from a previous iteration is reached.
15526 		 * Check below forces creation of checkpoint before callback calling
15527 		 * instruction to allow search for such identical states.
15528 		 */
15529 		if (is_sync_callback_calling_insn(insn)) {
15530 			mark_calls_callback(env, t);
15531 			mark_force_checkpoint(env, t);
15532 			mark_prune_point(env, t);
15533 			mark_jmp_point(env, t);
15534 		}
15535 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15536 			struct bpf_kfunc_call_arg_meta meta;
15537 
15538 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15539 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15540 				mark_prune_point(env, t);
15541 				/* Checking and saving state checkpoints at iter_next() call
15542 				 * is crucial for fast convergence of open-coded iterator loop
15543 				 * logic, so we need to force it. If we don't do that,
15544 				 * is_state_visited() might skip saving a checkpoint, causing
15545 				 * unnecessarily long sequence of not checkpointed
15546 				 * instructions and jumps, leading to exhaustion of jump
15547 				 * history buffer, and potentially other undesired outcomes.
15548 				 * It is expected that with correct open-coded iterators
15549 				 * convergence will happen quickly, so we don't run a risk of
15550 				 * exhausting memory.
15551 				 */
15552 				mark_force_checkpoint(env, t);
15553 			}
15554 		}
15555 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15556 
15557 	case BPF_JA:
15558 		if (BPF_SRC(insn->code) != BPF_K)
15559 			return -EINVAL;
15560 
15561 		if (BPF_CLASS(insn->code) == BPF_JMP)
15562 			off = insn->off;
15563 		else
15564 			off = insn->imm;
15565 
15566 		/* unconditional jump with single edge */
15567 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15568 		if (ret)
15569 			return ret;
15570 
15571 		mark_prune_point(env, t + off + 1);
15572 		mark_jmp_point(env, t + off + 1);
15573 
15574 		return ret;
15575 
15576 	default:
15577 		/* conditional jump with two edges */
15578 		mark_prune_point(env, t);
15579 
15580 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15581 		if (ret)
15582 			return ret;
15583 
15584 		return push_insn(t, t + insn->off + 1, BRANCH, env);
15585 	}
15586 }
15587 
15588 /* non-recursive depth-first-search to detect loops in BPF program
15589  * loop == back-edge in directed graph
15590  */
15591 static int check_cfg(struct bpf_verifier_env *env)
15592 {
15593 	int insn_cnt = env->prog->len;
15594 	int *insn_stack, *insn_state;
15595 	int ex_insn_beg, i, ret = 0;
15596 	bool ex_done = false;
15597 
15598 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15599 	if (!insn_state)
15600 		return -ENOMEM;
15601 
15602 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15603 	if (!insn_stack) {
15604 		kvfree(insn_state);
15605 		return -ENOMEM;
15606 	}
15607 
15608 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15609 	insn_stack[0] = 0; /* 0 is the first instruction */
15610 	env->cfg.cur_stack = 1;
15611 
15612 walk_cfg:
15613 	while (env->cfg.cur_stack > 0) {
15614 		int t = insn_stack[env->cfg.cur_stack - 1];
15615 
15616 		ret = visit_insn(t, env);
15617 		switch (ret) {
15618 		case DONE_EXPLORING:
15619 			insn_state[t] = EXPLORED;
15620 			env->cfg.cur_stack--;
15621 			break;
15622 		case KEEP_EXPLORING:
15623 			break;
15624 		default:
15625 			if (ret > 0) {
15626 				verbose(env, "visit_insn internal bug\n");
15627 				ret = -EFAULT;
15628 			}
15629 			goto err_free;
15630 		}
15631 	}
15632 
15633 	if (env->cfg.cur_stack < 0) {
15634 		verbose(env, "pop stack internal bug\n");
15635 		ret = -EFAULT;
15636 		goto err_free;
15637 	}
15638 
15639 	if (env->exception_callback_subprog && !ex_done) {
15640 		ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
15641 
15642 		insn_state[ex_insn_beg] = DISCOVERED;
15643 		insn_stack[0] = ex_insn_beg;
15644 		env->cfg.cur_stack = 1;
15645 		ex_done = true;
15646 		goto walk_cfg;
15647 	}
15648 
15649 	for (i = 0; i < insn_cnt; i++) {
15650 		struct bpf_insn *insn = &env->prog->insnsi[i];
15651 
15652 		if (insn_state[i] != EXPLORED) {
15653 			verbose(env, "unreachable insn %d\n", i);
15654 			ret = -EINVAL;
15655 			goto err_free;
15656 		}
15657 		if (bpf_is_ldimm64(insn)) {
15658 			if (insn_state[i + 1] != 0) {
15659 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15660 				ret = -EINVAL;
15661 				goto err_free;
15662 			}
15663 			i++; /* skip second half of ldimm64 */
15664 		}
15665 	}
15666 	ret = 0; /* cfg looks good */
15667 
15668 err_free:
15669 	kvfree(insn_state);
15670 	kvfree(insn_stack);
15671 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
15672 	return ret;
15673 }
15674 
15675 static int check_abnormal_return(struct bpf_verifier_env *env)
15676 {
15677 	int i;
15678 
15679 	for (i = 1; i < env->subprog_cnt; i++) {
15680 		if (env->subprog_info[i].has_ld_abs) {
15681 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15682 			return -EINVAL;
15683 		}
15684 		if (env->subprog_info[i].has_tail_call) {
15685 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15686 			return -EINVAL;
15687 		}
15688 	}
15689 	return 0;
15690 }
15691 
15692 /* The minimum supported BTF func info size */
15693 #define MIN_BPF_FUNCINFO_SIZE	8
15694 #define MAX_FUNCINFO_REC_SIZE	252
15695 
15696 static int check_btf_func_early(struct bpf_verifier_env *env,
15697 				const union bpf_attr *attr,
15698 				bpfptr_t uattr)
15699 {
15700 	u32 krec_size = sizeof(struct bpf_func_info);
15701 	const struct btf_type *type, *func_proto;
15702 	u32 i, nfuncs, urec_size, min_size;
15703 	struct bpf_func_info *krecord;
15704 	struct bpf_prog *prog;
15705 	const struct btf *btf;
15706 	u32 prev_offset = 0;
15707 	bpfptr_t urecord;
15708 	int ret = -ENOMEM;
15709 
15710 	nfuncs = attr->func_info_cnt;
15711 	if (!nfuncs) {
15712 		if (check_abnormal_return(env))
15713 			return -EINVAL;
15714 		return 0;
15715 	}
15716 
15717 	urec_size = attr->func_info_rec_size;
15718 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15719 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
15720 	    urec_size % sizeof(u32)) {
15721 		verbose(env, "invalid func info rec size %u\n", urec_size);
15722 		return -EINVAL;
15723 	}
15724 
15725 	prog = env->prog;
15726 	btf = prog->aux->btf;
15727 
15728 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15729 	min_size = min_t(u32, krec_size, urec_size);
15730 
15731 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15732 	if (!krecord)
15733 		return -ENOMEM;
15734 
15735 	for (i = 0; i < nfuncs; i++) {
15736 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15737 		if (ret) {
15738 			if (ret == -E2BIG) {
15739 				verbose(env, "nonzero tailing record in func info");
15740 				/* set the size kernel expects so loader can zero
15741 				 * out the rest of the record.
15742 				 */
15743 				if (copy_to_bpfptr_offset(uattr,
15744 							  offsetof(union bpf_attr, func_info_rec_size),
15745 							  &min_size, sizeof(min_size)))
15746 					ret = -EFAULT;
15747 			}
15748 			goto err_free;
15749 		}
15750 
15751 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15752 			ret = -EFAULT;
15753 			goto err_free;
15754 		}
15755 
15756 		/* check insn_off */
15757 		ret = -EINVAL;
15758 		if (i == 0) {
15759 			if (krecord[i].insn_off) {
15760 				verbose(env,
15761 					"nonzero insn_off %u for the first func info record",
15762 					krecord[i].insn_off);
15763 				goto err_free;
15764 			}
15765 		} else if (krecord[i].insn_off <= prev_offset) {
15766 			verbose(env,
15767 				"same or smaller insn offset (%u) than previous func info record (%u)",
15768 				krecord[i].insn_off, prev_offset);
15769 			goto err_free;
15770 		}
15771 
15772 		/* check type_id */
15773 		type = btf_type_by_id(btf, krecord[i].type_id);
15774 		if (!type || !btf_type_is_func(type)) {
15775 			verbose(env, "invalid type id %d in func info",
15776 				krecord[i].type_id);
15777 			goto err_free;
15778 		}
15779 
15780 		func_proto = btf_type_by_id(btf, type->type);
15781 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15782 			/* btf_func_check() already verified it during BTF load */
15783 			goto err_free;
15784 
15785 		prev_offset = krecord[i].insn_off;
15786 		bpfptr_add(&urecord, urec_size);
15787 	}
15788 
15789 	prog->aux->func_info = krecord;
15790 	prog->aux->func_info_cnt = nfuncs;
15791 	return 0;
15792 
15793 err_free:
15794 	kvfree(krecord);
15795 	return ret;
15796 }
15797 
15798 static int check_btf_func(struct bpf_verifier_env *env,
15799 			  const union bpf_attr *attr,
15800 			  bpfptr_t uattr)
15801 {
15802 	const struct btf_type *type, *func_proto, *ret_type;
15803 	u32 i, nfuncs, urec_size;
15804 	struct bpf_func_info *krecord;
15805 	struct bpf_func_info_aux *info_aux = NULL;
15806 	struct bpf_prog *prog;
15807 	const struct btf *btf;
15808 	bpfptr_t urecord;
15809 	bool scalar_return;
15810 	int ret = -ENOMEM;
15811 
15812 	nfuncs = attr->func_info_cnt;
15813 	if (!nfuncs) {
15814 		if (check_abnormal_return(env))
15815 			return -EINVAL;
15816 		return 0;
15817 	}
15818 	if (nfuncs != env->subprog_cnt) {
15819 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15820 		return -EINVAL;
15821 	}
15822 
15823 	urec_size = attr->func_info_rec_size;
15824 
15825 	prog = env->prog;
15826 	btf = prog->aux->btf;
15827 
15828 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15829 
15830 	krecord = prog->aux->func_info;
15831 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15832 	if (!info_aux)
15833 		return -ENOMEM;
15834 
15835 	for (i = 0; i < nfuncs; i++) {
15836 		/* check insn_off */
15837 		ret = -EINVAL;
15838 
15839 		if (env->subprog_info[i].start != krecord[i].insn_off) {
15840 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15841 			goto err_free;
15842 		}
15843 
15844 		/* Already checked type_id */
15845 		type = btf_type_by_id(btf, krecord[i].type_id);
15846 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15847 		/* Already checked func_proto */
15848 		func_proto = btf_type_by_id(btf, type->type);
15849 
15850 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15851 		scalar_return =
15852 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15853 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15854 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15855 			goto err_free;
15856 		}
15857 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15858 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15859 			goto err_free;
15860 		}
15861 
15862 		bpfptr_add(&urecord, urec_size);
15863 	}
15864 
15865 	prog->aux->func_info_aux = info_aux;
15866 	return 0;
15867 
15868 err_free:
15869 	kfree(info_aux);
15870 	return ret;
15871 }
15872 
15873 static void adjust_btf_func(struct bpf_verifier_env *env)
15874 {
15875 	struct bpf_prog_aux *aux = env->prog->aux;
15876 	int i;
15877 
15878 	if (!aux->func_info)
15879 		return;
15880 
15881 	/* func_info is not available for hidden subprogs */
15882 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
15883 		aux->func_info[i].insn_off = env->subprog_info[i].start;
15884 }
15885 
15886 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
15887 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
15888 
15889 static int check_btf_line(struct bpf_verifier_env *env,
15890 			  const union bpf_attr *attr,
15891 			  bpfptr_t uattr)
15892 {
15893 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15894 	struct bpf_subprog_info *sub;
15895 	struct bpf_line_info *linfo;
15896 	struct bpf_prog *prog;
15897 	const struct btf *btf;
15898 	bpfptr_t ulinfo;
15899 	int err;
15900 
15901 	nr_linfo = attr->line_info_cnt;
15902 	if (!nr_linfo)
15903 		return 0;
15904 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15905 		return -EINVAL;
15906 
15907 	rec_size = attr->line_info_rec_size;
15908 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15909 	    rec_size > MAX_LINEINFO_REC_SIZE ||
15910 	    rec_size & (sizeof(u32) - 1))
15911 		return -EINVAL;
15912 
15913 	/* Need to zero it in case the userspace may
15914 	 * pass in a smaller bpf_line_info object.
15915 	 */
15916 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15917 			 GFP_KERNEL | __GFP_NOWARN);
15918 	if (!linfo)
15919 		return -ENOMEM;
15920 
15921 	prog = env->prog;
15922 	btf = prog->aux->btf;
15923 
15924 	s = 0;
15925 	sub = env->subprog_info;
15926 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15927 	expected_size = sizeof(struct bpf_line_info);
15928 	ncopy = min_t(u32, expected_size, rec_size);
15929 	for (i = 0; i < nr_linfo; i++) {
15930 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15931 		if (err) {
15932 			if (err == -E2BIG) {
15933 				verbose(env, "nonzero tailing record in line_info");
15934 				if (copy_to_bpfptr_offset(uattr,
15935 							  offsetof(union bpf_attr, line_info_rec_size),
15936 							  &expected_size, sizeof(expected_size)))
15937 					err = -EFAULT;
15938 			}
15939 			goto err_free;
15940 		}
15941 
15942 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15943 			err = -EFAULT;
15944 			goto err_free;
15945 		}
15946 
15947 		/*
15948 		 * Check insn_off to ensure
15949 		 * 1) strictly increasing AND
15950 		 * 2) bounded by prog->len
15951 		 *
15952 		 * The linfo[0].insn_off == 0 check logically falls into
15953 		 * the later "missing bpf_line_info for func..." case
15954 		 * because the first linfo[0].insn_off must be the
15955 		 * first sub also and the first sub must have
15956 		 * subprog_info[0].start == 0.
15957 		 */
15958 		if ((i && linfo[i].insn_off <= prev_offset) ||
15959 		    linfo[i].insn_off >= prog->len) {
15960 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15961 				i, linfo[i].insn_off, prev_offset,
15962 				prog->len);
15963 			err = -EINVAL;
15964 			goto err_free;
15965 		}
15966 
15967 		if (!prog->insnsi[linfo[i].insn_off].code) {
15968 			verbose(env,
15969 				"Invalid insn code at line_info[%u].insn_off\n",
15970 				i);
15971 			err = -EINVAL;
15972 			goto err_free;
15973 		}
15974 
15975 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15976 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15977 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15978 			err = -EINVAL;
15979 			goto err_free;
15980 		}
15981 
15982 		if (s != env->subprog_cnt) {
15983 			if (linfo[i].insn_off == sub[s].start) {
15984 				sub[s].linfo_idx = i;
15985 				s++;
15986 			} else if (sub[s].start < linfo[i].insn_off) {
15987 				verbose(env, "missing bpf_line_info for func#%u\n", s);
15988 				err = -EINVAL;
15989 				goto err_free;
15990 			}
15991 		}
15992 
15993 		prev_offset = linfo[i].insn_off;
15994 		bpfptr_add(&ulinfo, rec_size);
15995 	}
15996 
15997 	if (s != env->subprog_cnt) {
15998 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15999 			env->subprog_cnt - s, s);
16000 		err = -EINVAL;
16001 		goto err_free;
16002 	}
16003 
16004 	prog->aux->linfo = linfo;
16005 	prog->aux->nr_linfo = nr_linfo;
16006 
16007 	return 0;
16008 
16009 err_free:
16010 	kvfree(linfo);
16011 	return err;
16012 }
16013 
16014 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
16015 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
16016 
16017 static int check_core_relo(struct bpf_verifier_env *env,
16018 			   const union bpf_attr *attr,
16019 			   bpfptr_t uattr)
16020 {
16021 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
16022 	struct bpf_core_relo core_relo = {};
16023 	struct bpf_prog *prog = env->prog;
16024 	const struct btf *btf = prog->aux->btf;
16025 	struct bpf_core_ctx ctx = {
16026 		.log = &env->log,
16027 		.btf = btf,
16028 	};
16029 	bpfptr_t u_core_relo;
16030 	int err;
16031 
16032 	nr_core_relo = attr->core_relo_cnt;
16033 	if (!nr_core_relo)
16034 		return 0;
16035 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
16036 		return -EINVAL;
16037 
16038 	rec_size = attr->core_relo_rec_size;
16039 	if (rec_size < MIN_CORE_RELO_SIZE ||
16040 	    rec_size > MAX_CORE_RELO_SIZE ||
16041 	    rec_size % sizeof(u32))
16042 		return -EINVAL;
16043 
16044 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
16045 	expected_size = sizeof(struct bpf_core_relo);
16046 	ncopy = min_t(u32, expected_size, rec_size);
16047 
16048 	/* Unlike func_info and line_info, copy and apply each CO-RE
16049 	 * relocation record one at a time.
16050 	 */
16051 	for (i = 0; i < nr_core_relo; i++) {
16052 		/* future proofing when sizeof(bpf_core_relo) changes */
16053 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
16054 		if (err) {
16055 			if (err == -E2BIG) {
16056 				verbose(env, "nonzero tailing record in core_relo");
16057 				if (copy_to_bpfptr_offset(uattr,
16058 							  offsetof(union bpf_attr, core_relo_rec_size),
16059 							  &expected_size, sizeof(expected_size)))
16060 					err = -EFAULT;
16061 			}
16062 			break;
16063 		}
16064 
16065 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
16066 			err = -EFAULT;
16067 			break;
16068 		}
16069 
16070 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
16071 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
16072 				i, core_relo.insn_off, prog->len);
16073 			err = -EINVAL;
16074 			break;
16075 		}
16076 
16077 		err = bpf_core_apply(&ctx, &core_relo, i,
16078 				     &prog->insnsi[core_relo.insn_off / 8]);
16079 		if (err)
16080 			break;
16081 		bpfptr_add(&u_core_relo, rec_size);
16082 	}
16083 	return err;
16084 }
16085 
16086 static int check_btf_info_early(struct bpf_verifier_env *env,
16087 				const union bpf_attr *attr,
16088 				bpfptr_t uattr)
16089 {
16090 	struct btf *btf;
16091 	int err;
16092 
16093 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
16094 		if (check_abnormal_return(env))
16095 			return -EINVAL;
16096 		return 0;
16097 	}
16098 
16099 	btf = btf_get_by_fd(attr->prog_btf_fd);
16100 	if (IS_ERR(btf))
16101 		return PTR_ERR(btf);
16102 	if (btf_is_kernel(btf)) {
16103 		btf_put(btf);
16104 		return -EACCES;
16105 	}
16106 	env->prog->aux->btf = btf;
16107 
16108 	err = check_btf_func_early(env, attr, uattr);
16109 	if (err)
16110 		return err;
16111 	return 0;
16112 }
16113 
16114 static int check_btf_info(struct bpf_verifier_env *env,
16115 			  const union bpf_attr *attr,
16116 			  bpfptr_t uattr)
16117 {
16118 	int err;
16119 
16120 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
16121 		if (check_abnormal_return(env))
16122 			return -EINVAL;
16123 		return 0;
16124 	}
16125 
16126 	err = check_btf_func(env, attr, uattr);
16127 	if (err)
16128 		return err;
16129 
16130 	err = check_btf_line(env, attr, uattr);
16131 	if (err)
16132 		return err;
16133 
16134 	err = check_core_relo(env, attr, uattr);
16135 	if (err)
16136 		return err;
16137 
16138 	return 0;
16139 }
16140 
16141 /* check %cur's range satisfies %old's */
16142 static bool range_within(struct bpf_reg_state *old,
16143 			 struct bpf_reg_state *cur)
16144 {
16145 	return old->umin_value <= cur->umin_value &&
16146 	       old->umax_value >= cur->umax_value &&
16147 	       old->smin_value <= cur->smin_value &&
16148 	       old->smax_value >= cur->smax_value &&
16149 	       old->u32_min_value <= cur->u32_min_value &&
16150 	       old->u32_max_value >= cur->u32_max_value &&
16151 	       old->s32_min_value <= cur->s32_min_value &&
16152 	       old->s32_max_value >= cur->s32_max_value;
16153 }
16154 
16155 /* If in the old state two registers had the same id, then they need to have
16156  * the same id in the new state as well.  But that id could be different from
16157  * the old state, so we need to track the mapping from old to new ids.
16158  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
16159  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
16160  * regs with a different old id could still have new id 9, we don't care about
16161  * that.
16162  * So we look through our idmap to see if this old id has been seen before.  If
16163  * so, we require the new id to match; otherwise, we add the id pair to the map.
16164  */
16165 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16166 {
16167 	struct bpf_id_pair *map = idmap->map;
16168 	unsigned int i;
16169 
16170 	/* either both IDs should be set or both should be zero */
16171 	if (!!old_id != !!cur_id)
16172 		return false;
16173 
16174 	if (old_id == 0) /* cur_id == 0 as well */
16175 		return true;
16176 
16177 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
16178 		if (!map[i].old) {
16179 			/* Reached an empty slot; haven't seen this id before */
16180 			map[i].old = old_id;
16181 			map[i].cur = cur_id;
16182 			return true;
16183 		}
16184 		if (map[i].old == old_id)
16185 			return map[i].cur == cur_id;
16186 		if (map[i].cur == cur_id)
16187 			return false;
16188 	}
16189 	/* We ran out of idmap slots, which should be impossible */
16190 	WARN_ON_ONCE(1);
16191 	return false;
16192 }
16193 
16194 /* Similar to check_ids(), but allocate a unique temporary ID
16195  * for 'old_id' or 'cur_id' of zero.
16196  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
16197  */
16198 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16199 {
16200 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
16201 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
16202 
16203 	return check_ids(old_id, cur_id, idmap);
16204 }
16205 
16206 static void clean_func_state(struct bpf_verifier_env *env,
16207 			     struct bpf_func_state *st)
16208 {
16209 	enum bpf_reg_liveness live;
16210 	int i, j;
16211 
16212 	for (i = 0; i < BPF_REG_FP; i++) {
16213 		live = st->regs[i].live;
16214 		/* liveness must not touch this register anymore */
16215 		st->regs[i].live |= REG_LIVE_DONE;
16216 		if (!(live & REG_LIVE_READ))
16217 			/* since the register is unused, clear its state
16218 			 * to make further comparison simpler
16219 			 */
16220 			__mark_reg_not_init(env, &st->regs[i]);
16221 	}
16222 
16223 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
16224 		live = st->stack[i].spilled_ptr.live;
16225 		/* liveness must not touch this stack slot anymore */
16226 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
16227 		if (!(live & REG_LIVE_READ)) {
16228 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
16229 			for (j = 0; j < BPF_REG_SIZE; j++)
16230 				st->stack[i].slot_type[j] = STACK_INVALID;
16231 		}
16232 	}
16233 }
16234 
16235 static void clean_verifier_state(struct bpf_verifier_env *env,
16236 				 struct bpf_verifier_state *st)
16237 {
16238 	int i;
16239 
16240 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
16241 		/* all regs in this state in all frames were already marked */
16242 		return;
16243 
16244 	for (i = 0; i <= st->curframe; i++)
16245 		clean_func_state(env, st->frame[i]);
16246 }
16247 
16248 /* the parentage chains form a tree.
16249  * the verifier states are added to state lists at given insn and
16250  * pushed into state stack for future exploration.
16251  * when the verifier reaches bpf_exit insn some of the verifer states
16252  * stored in the state lists have their final liveness state already,
16253  * but a lot of states will get revised from liveness point of view when
16254  * the verifier explores other branches.
16255  * Example:
16256  * 1: r0 = 1
16257  * 2: if r1 == 100 goto pc+1
16258  * 3: r0 = 2
16259  * 4: exit
16260  * when the verifier reaches exit insn the register r0 in the state list of
16261  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
16262  * of insn 2 and goes exploring further. At the insn 4 it will walk the
16263  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
16264  *
16265  * Since the verifier pushes the branch states as it sees them while exploring
16266  * the program the condition of walking the branch instruction for the second
16267  * time means that all states below this branch were already explored and
16268  * their final liveness marks are already propagated.
16269  * Hence when the verifier completes the search of state list in is_state_visited()
16270  * we can call this clean_live_states() function to mark all liveness states
16271  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
16272  * will not be used.
16273  * This function also clears the registers and stack for states that !READ
16274  * to simplify state merging.
16275  *
16276  * Important note here that walking the same branch instruction in the callee
16277  * doesn't meant that the states are DONE. The verifier has to compare
16278  * the callsites
16279  */
16280 static void clean_live_states(struct bpf_verifier_env *env, int insn,
16281 			      struct bpf_verifier_state *cur)
16282 {
16283 	struct bpf_verifier_state_list *sl;
16284 
16285 	sl = *explored_state(env, insn);
16286 	while (sl) {
16287 		if (sl->state.branches)
16288 			goto next;
16289 		if (sl->state.insn_idx != insn ||
16290 		    !same_callsites(&sl->state, cur))
16291 			goto next;
16292 		clean_verifier_state(env, &sl->state);
16293 next:
16294 		sl = sl->next;
16295 	}
16296 }
16297 
16298 static bool regs_exact(const struct bpf_reg_state *rold,
16299 		       const struct bpf_reg_state *rcur,
16300 		       struct bpf_idmap *idmap)
16301 {
16302 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16303 	       check_ids(rold->id, rcur->id, idmap) &&
16304 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16305 }
16306 
16307 /* Returns true if (rold safe implies rcur safe) */
16308 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
16309 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
16310 {
16311 	if (exact)
16312 		return regs_exact(rold, rcur, idmap);
16313 
16314 	if (!(rold->live & REG_LIVE_READ))
16315 		/* explored state didn't use this */
16316 		return true;
16317 	if (rold->type == NOT_INIT)
16318 		/* explored state can't have used this */
16319 		return true;
16320 	if (rcur->type == NOT_INIT)
16321 		return false;
16322 
16323 	/* Enforce that register types have to match exactly, including their
16324 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16325 	 * rule.
16326 	 *
16327 	 * One can make a point that using a pointer register as unbounded
16328 	 * SCALAR would be technically acceptable, but this could lead to
16329 	 * pointer leaks because scalars are allowed to leak while pointers
16330 	 * are not. We could make this safe in special cases if root is
16331 	 * calling us, but it's probably not worth the hassle.
16332 	 *
16333 	 * Also, register types that are *not* MAYBE_NULL could technically be
16334 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16335 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16336 	 * to the same map).
16337 	 * However, if the old MAYBE_NULL register then got NULL checked,
16338 	 * doing so could have affected others with the same id, and we can't
16339 	 * check for that because we lost the id when we converted to
16340 	 * a non-MAYBE_NULL variant.
16341 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
16342 	 * non-MAYBE_NULL registers as well.
16343 	 */
16344 	if (rold->type != rcur->type)
16345 		return false;
16346 
16347 	switch (base_type(rold->type)) {
16348 	case SCALAR_VALUE:
16349 		if (env->explore_alu_limits) {
16350 			/* explore_alu_limits disables tnum_in() and range_within()
16351 			 * logic and requires everything to be strict
16352 			 */
16353 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16354 			       check_scalar_ids(rold->id, rcur->id, idmap);
16355 		}
16356 		if (!rold->precise)
16357 			return true;
16358 		/* Why check_ids() for scalar registers?
16359 		 *
16360 		 * Consider the following BPF code:
16361 		 *   1: r6 = ... unbound scalar, ID=a ...
16362 		 *   2: r7 = ... unbound scalar, ID=b ...
16363 		 *   3: if (r6 > r7) goto +1
16364 		 *   4: r6 = r7
16365 		 *   5: if (r6 > X) goto ...
16366 		 *   6: ... memory operation using r7 ...
16367 		 *
16368 		 * First verification path is [1-6]:
16369 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16370 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16371 		 *   r7 <= X, because r6 and r7 share same id.
16372 		 * Next verification path is [1-4, 6].
16373 		 *
16374 		 * Instruction (6) would be reached in two states:
16375 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16376 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16377 		 *
16378 		 * Use check_ids() to distinguish these states.
16379 		 * ---
16380 		 * Also verify that new value satisfies old value range knowledge.
16381 		 */
16382 		return range_within(rold, rcur) &&
16383 		       tnum_in(rold->var_off, rcur->var_off) &&
16384 		       check_scalar_ids(rold->id, rcur->id, idmap);
16385 	case PTR_TO_MAP_KEY:
16386 	case PTR_TO_MAP_VALUE:
16387 	case PTR_TO_MEM:
16388 	case PTR_TO_BUF:
16389 	case PTR_TO_TP_BUFFER:
16390 		/* If the new min/max/var_off satisfy the old ones and
16391 		 * everything else matches, we are OK.
16392 		 */
16393 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16394 		       range_within(rold, rcur) &&
16395 		       tnum_in(rold->var_off, rcur->var_off) &&
16396 		       check_ids(rold->id, rcur->id, idmap) &&
16397 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16398 	case PTR_TO_PACKET_META:
16399 	case PTR_TO_PACKET:
16400 		/* We must have at least as much range as the old ptr
16401 		 * did, so that any accesses which were safe before are
16402 		 * still safe.  This is true even if old range < old off,
16403 		 * since someone could have accessed through (ptr - k), or
16404 		 * even done ptr -= k in a register, to get a safe access.
16405 		 */
16406 		if (rold->range > rcur->range)
16407 			return false;
16408 		/* If the offsets don't match, we can't trust our alignment;
16409 		 * nor can we be sure that we won't fall out of range.
16410 		 */
16411 		if (rold->off != rcur->off)
16412 			return false;
16413 		/* id relations must be preserved */
16414 		if (!check_ids(rold->id, rcur->id, idmap))
16415 			return false;
16416 		/* new val must satisfy old val knowledge */
16417 		return range_within(rold, rcur) &&
16418 		       tnum_in(rold->var_off, rcur->var_off);
16419 	case PTR_TO_STACK:
16420 		/* two stack pointers are equal only if they're pointing to
16421 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16422 		 */
16423 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16424 	default:
16425 		return regs_exact(rold, rcur, idmap);
16426 	}
16427 }
16428 
16429 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16430 		      struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16431 {
16432 	int i, spi;
16433 
16434 	/* walk slots of the explored stack and ignore any additional
16435 	 * slots in the current stack, since explored(safe) state
16436 	 * didn't use them
16437 	 */
16438 	for (i = 0; i < old->allocated_stack; i++) {
16439 		struct bpf_reg_state *old_reg, *cur_reg;
16440 
16441 		spi = i / BPF_REG_SIZE;
16442 
16443 		if (exact &&
16444 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16445 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16446 			return false;
16447 
16448 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16449 			i += BPF_REG_SIZE - 1;
16450 			/* explored state didn't use this */
16451 			continue;
16452 		}
16453 
16454 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16455 			continue;
16456 
16457 		if (env->allow_uninit_stack &&
16458 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16459 			continue;
16460 
16461 		/* explored stack has more populated slots than current stack
16462 		 * and these slots were used
16463 		 */
16464 		if (i >= cur->allocated_stack)
16465 			return false;
16466 
16467 		/* if old state was safe with misc data in the stack
16468 		 * it will be safe with zero-initialized stack.
16469 		 * The opposite is not true
16470 		 */
16471 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16472 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16473 			continue;
16474 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16475 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16476 			/* Ex: old explored (safe) state has STACK_SPILL in
16477 			 * this stack slot, but current has STACK_MISC ->
16478 			 * this verifier states are not equivalent,
16479 			 * return false to continue verification of this path
16480 			 */
16481 			return false;
16482 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16483 			continue;
16484 		/* Both old and cur are having same slot_type */
16485 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16486 		case STACK_SPILL:
16487 			/* when explored and current stack slot are both storing
16488 			 * spilled registers, check that stored pointers types
16489 			 * are the same as well.
16490 			 * Ex: explored safe path could have stored
16491 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16492 			 * but current path has stored:
16493 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16494 			 * such verifier states are not equivalent.
16495 			 * return false to continue verification of this path
16496 			 */
16497 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16498 				     &cur->stack[spi].spilled_ptr, idmap, exact))
16499 				return false;
16500 			break;
16501 		case STACK_DYNPTR:
16502 			old_reg = &old->stack[spi].spilled_ptr;
16503 			cur_reg = &cur->stack[spi].spilled_ptr;
16504 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16505 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16506 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16507 				return false;
16508 			break;
16509 		case STACK_ITER:
16510 			old_reg = &old->stack[spi].spilled_ptr;
16511 			cur_reg = &cur->stack[spi].spilled_ptr;
16512 			/* iter.depth is not compared between states as it
16513 			 * doesn't matter for correctness and would otherwise
16514 			 * prevent convergence; we maintain it only to prevent
16515 			 * infinite loop check triggering, see
16516 			 * iter_active_depths_differ()
16517 			 */
16518 			if (old_reg->iter.btf != cur_reg->iter.btf ||
16519 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16520 			    old_reg->iter.state != cur_reg->iter.state ||
16521 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16522 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16523 				return false;
16524 			break;
16525 		case STACK_MISC:
16526 		case STACK_ZERO:
16527 		case STACK_INVALID:
16528 			continue;
16529 		/* Ensure that new unhandled slot types return false by default */
16530 		default:
16531 			return false;
16532 		}
16533 	}
16534 	return true;
16535 }
16536 
16537 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16538 		    struct bpf_idmap *idmap)
16539 {
16540 	int i;
16541 
16542 	if (old->acquired_refs != cur->acquired_refs)
16543 		return false;
16544 
16545 	for (i = 0; i < old->acquired_refs; i++) {
16546 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16547 			return false;
16548 	}
16549 
16550 	return true;
16551 }
16552 
16553 /* compare two verifier states
16554  *
16555  * all states stored in state_list are known to be valid, since
16556  * verifier reached 'bpf_exit' instruction through them
16557  *
16558  * this function is called when verifier exploring different branches of
16559  * execution popped from the state stack. If it sees an old state that has
16560  * more strict register state and more strict stack state then this execution
16561  * branch doesn't need to be explored further, since verifier already
16562  * concluded that more strict state leads to valid finish.
16563  *
16564  * Therefore two states are equivalent if register state is more conservative
16565  * and explored stack state is more conservative than the current one.
16566  * Example:
16567  *       explored                   current
16568  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16569  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16570  *
16571  * In other words if current stack state (one being explored) has more
16572  * valid slots than old one that already passed validation, it means
16573  * the verifier can stop exploring and conclude that current state is valid too
16574  *
16575  * Similarly with registers. If explored state has register type as invalid
16576  * whereas register type in current state is meaningful, it means that
16577  * the current state will reach 'bpf_exit' instruction safely
16578  */
16579 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16580 			      struct bpf_func_state *cur, bool exact)
16581 {
16582 	int i;
16583 
16584 	for (i = 0; i < MAX_BPF_REG; i++)
16585 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
16586 			     &env->idmap_scratch, exact))
16587 			return false;
16588 
16589 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16590 		return false;
16591 
16592 	if (!refsafe(old, cur, &env->idmap_scratch))
16593 		return false;
16594 
16595 	return true;
16596 }
16597 
16598 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16599 {
16600 	env->idmap_scratch.tmp_id_gen = env->id_gen;
16601 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16602 }
16603 
16604 static bool states_equal(struct bpf_verifier_env *env,
16605 			 struct bpf_verifier_state *old,
16606 			 struct bpf_verifier_state *cur,
16607 			 bool exact)
16608 {
16609 	int i;
16610 
16611 	if (old->curframe != cur->curframe)
16612 		return false;
16613 
16614 	reset_idmap_scratch(env);
16615 
16616 	/* Verification state from speculative execution simulation
16617 	 * must never prune a non-speculative execution one.
16618 	 */
16619 	if (old->speculative && !cur->speculative)
16620 		return false;
16621 
16622 	if (old->active_lock.ptr != cur->active_lock.ptr)
16623 		return false;
16624 
16625 	/* Old and cur active_lock's have to be either both present
16626 	 * or both absent.
16627 	 */
16628 	if (!!old->active_lock.id != !!cur->active_lock.id)
16629 		return false;
16630 
16631 	if (old->active_lock.id &&
16632 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16633 		return false;
16634 
16635 	if (old->active_rcu_lock != cur->active_rcu_lock)
16636 		return false;
16637 
16638 	/* for states to be equal callsites have to be the same
16639 	 * and all frame states need to be equivalent
16640 	 */
16641 	for (i = 0; i <= old->curframe; i++) {
16642 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
16643 			return false;
16644 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16645 			return false;
16646 	}
16647 	return true;
16648 }
16649 
16650 /* Return 0 if no propagation happened. Return negative error code if error
16651  * happened. Otherwise, return the propagated bit.
16652  */
16653 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16654 				  struct bpf_reg_state *reg,
16655 				  struct bpf_reg_state *parent_reg)
16656 {
16657 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16658 	u8 flag = reg->live & REG_LIVE_READ;
16659 	int err;
16660 
16661 	/* When comes here, read flags of PARENT_REG or REG could be any of
16662 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16663 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16664 	 */
16665 	if (parent_flag == REG_LIVE_READ64 ||
16666 	    /* Or if there is no read flag from REG. */
16667 	    !flag ||
16668 	    /* Or if the read flag from REG is the same as PARENT_REG. */
16669 	    parent_flag == flag)
16670 		return 0;
16671 
16672 	err = mark_reg_read(env, reg, parent_reg, flag);
16673 	if (err)
16674 		return err;
16675 
16676 	return flag;
16677 }
16678 
16679 /* A write screens off any subsequent reads; but write marks come from the
16680  * straight-line code between a state and its parent.  When we arrive at an
16681  * equivalent state (jump target or such) we didn't arrive by the straight-line
16682  * code, so read marks in the state must propagate to the parent regardless
16683  * of the state's write marks. That's what 'parent == state->parent' comparison
16684  * in mark_reg_read() is for.
16685  */
16686 static int propagate_liveness(struct bpf_verifier_env *env,
16687 			      const struct bpf_verifier_state *vstate,
16688 			      struct bpf_verifier_state *vparent)
16689 {
16690 	struct bpf_reg_state *state_reg, *parent_reg;
16691 	struct bpf_func_state *state, *parent;
16692 	int i, frame, err = 0;
16693 
16694 	if (vparent->curframe != vstate->curframe) {
16695 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
16696 		     vparent->curframe, vstate->curframe);
16697 		return -EFAULT;
16698 	}
16699 	/* Propagate read liveness of registers... */
16700 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16701 	for (frame = 0; frame <= vstate->curframe; frame++) {
16702 		parent = vparent->frame[frame];
16703 		state = vstate->frame[frame];
16704 		parent_reg = parent->regs;
16705 		state_reg = state->regs;
16706 		/* We don't need to worry about FP liveness, it's read-only */
16707 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16708 			err = propagate_liveness_reg(env, &state_reg[i],
16709 						     &parent_reg[i]);
16710 			if (err < 0)
16711 				return err;
16712 			if (err == REG_LIVE_READ64)
16713 				mark_insn_zext(env, &parent_reg[i]);
16714 		}
16715 
16716 		/* Propagate stack slots. */
16717 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16718 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16719 			parent_reg = &parent->stack[i].spilled_ptr;
16720 			state_reg = &state->stack[i].spilled_ptr;
16721 			err = propagate_liveness_reg(env, state_reg,
16722 						     parent_reg);
16723 			if (err < 0)
16724 				return err;
16725 		}
16726 	}
16727 	return 0;
16728 }
16729 
16730 /* find precise scalars in the previous equivalent state and
16731  * propagate them into the current state
16732  */
16733 static int propagate_precision(struct bpf_verifier_env *env,
16734 			       const struct bpf_verifier_state *old)
16735 {
16736 	struct bpf_reg_state *state_reg;
16737 	struct bpf_func_state *state;
16738 	int i, err = 0, fr;
16739 	bool first;
16740 
16741 	for (fr = old->curframe; fr >= 0; fr--) {
16742 		state = old->frame[fr];
16743 		state_reg = state->regs;
16744 		first = true;
16745 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16746 			if (state_reg->type != SCALAR_VALUE ||
16747 			    !state_reg->precise ||
16748 			    !(state_reg->live & REG_LIVE_READ))
16749 				continue;
16750 			if (env->log.level & BPF_LOG_LEVEL2) {
16751 				if (first)
16752 					verbose(env, "frame %d: propagating r%d", fr, i);
16753 				else
16754 					verbose(env, ",r%d", i);
16755 			}
16756 			bt_set_frame_reg(&env->bt, fr, i);
16757 			first = false;
16758 		}
16759 
16760 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16761 			if (!is_spilled_reg(&state->stack[i]))
16762 				continue;
16763 			state_reg = &state->stack[i].spilled_ptr;
16764 			if (state_reg->type != SCALAR_VALUE ||
16765 			    !state_reg->precise ||
16766 			    !(state_reg->live & REG_LIVE_READ))
16767 				continue;
16768 			if (env->log.level & BPF_LOG_LEVEL2) {
16769 				if (first)
16770 					verbose(env, "frame %d: propagating fp%d",
16771 						fr, (-i - 1) * BPF_REG_SIZE);
16772 				else
16773 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16774 			}
16775 			bt_set_frame_slot(&env->bt, fr, i);
16776 			first = false;
16777 		}
16778 		if (!first)
16779 			verbose(env, "\n");
16780 	}
16781 
16782 	err = mark_chain_precision_batch(env);
16783 	if (err < 0)
16784 		return err;
16785 
16786 	return 0;
16787 }
16788 
16789 static bool states_maybe_looping(struct bpf_verifier_state *old,
16790 				 struct bpf_verifier_state *cur)
16791 {
16792 	struct bpf_func_state *fold, *fcur;
16793 	int i, fr = cur->curframe;
16794 
16795 	if (old->curframe != fr)
16796 		return false;
16797 
16798 	fold = old->frame[fr];
16799 	fcur = cur->frame[fr];
16800 	for (i = 0; i < MAX_BPF_REG; i++)
16801 		if (memcmp(&fold->regs[i], &fcur->regs[i],
16802 			   offsetof(struct bpf_reg_state, parent)))
16803 			return false;
16804 	return true;
16805 }
16806 
16807 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16808 {
16809 	return env->insn_aux_data[insn_idx].is_iter_next;
16810 }
16811 
16812 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16813  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16814  * states to match, which otherwise would look like an infinite loop. So while
16815  * iter_next() calls are taken care of, we still need to be careful and
16816  * prevent erroneous and too eager declaration of "ininite loop", when
16817  * iterators are involved.
16818  *
16819  * Here's a situation in pseudo-BPF assembly form:
16820  *
16821  *   0: again:                          ; set up iter_next() call args
16822  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16823  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16824  *   3:   if r0 == 0 goto done
16825  *   4:   ... something useful here ...
16826  *   5:   goto again                    ; another iteration
16827  *   6: done:
16828  *   7:   r1 = &it
16829  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16830  *   9:   exit
16831  *
16832  * This is a typical loop. Let's assume that we have a prune point at 1:,
16833  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16834  * again`, assuming other heuristics don't get in a way).
16835  *
16836  * When we first time come to 1:, let's say we have some state X. We proceed
16837  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16838  * Now we come back to validate that forked ACTIVE state. We proceed through
16839  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16840  * are converging. But the problem is that we don't know that yet, as this
16841  * convergence has to happen at iter_next() call site only. So if nothing is
16842  * done, at 1: verifier will use bounded loop logic and declare infinite
16843  * looping (and would be *technically* correct, if not for iterator's
16844  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16845  * don't want that. So what we do in process_iter_next_call() when we go on
16846  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16847  * a different iteration. So when we suspect an infinite loop, we additionally
16848  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16849  * pretend we are not looping and wait for next iter_next() call.
16850  *
16851  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16852  * loop, because that would actually mean infinite loop, as DRAINED state is
16853  * "sticky", and so we'll keep returning into the same instruction with the
16854  * same state (at least in one of possible code paths).
16855  *
16856  * This approach allows to keep infinite loop heuristic even in the face of
16857  * active iterator. E.g., C snippet below is and will be detected as
16858  * inifintely looping:
16859  *
16860  *   struct bpf_iter_num it;
16861  *   int *p, x;
16862  *
16863  *   bpf_iter_num_new(&it, 0, 10);
16864  *   while ((p = bpf_iter_num_next(&t))) {
16865  *       x = p;
16866  *       while (x--) {} // <<-- infinite loop here
16867  *   }
16868  *
16869  */
16870 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16871 {
16872 	struct bpf_reg_state *slot, *cur_slot;
16873 	struct bpf_func_state *state;
16874 	int i, fr;
16875 
16876 	for (fr = old->curframe; fr >= 0; fr--) {
16877 		state = old->frame[fr];
16878 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16879 			if (state->stack[i].slot_type[0] != STACK_ITER)
16880 				continue;
16881 
16882 			slot = &state->stack[i].spilled_ptr;
16883 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16884 				continue;
16885 
16886 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16887 			if (cur_slot->iter.depth != slot->iter.depth)
16888 				return true;
16889 		}
16890 	}
16891 	return false;
16892 }
16893 
16894 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16895 {
16896 	struct bpf_verifier_state_list *new_sl;
16897 	struct bpf_verifier_state_list *sl, **pprev;
16898 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16899 	int i, j, n, err, states_cnt = 0;
16900 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16901 	bool add_new_state = force_new_state;
16902 	bool force_exact;
16903 
16904 	/* bpf progs typically have pruning point every 4 instructions
16905 	 * http://vger.kernel.org/bpfconf2019.html#session-1
16906 	 * Do not add new state for future pruning if the verifier hasn't seen
16907 	 * at least 2 jumps and at least 8 instructions.
16908 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16909 	 * In tests that amounts to up to 50% reduction into total verifier
16910 	 * memory consumption and 20% verifier time speedup.
16911 	 */
16912 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16913 	    env->insn_processed - env->prev_insn_processed >= 8)
16914 		add_new_state = true;
16915 
16916 	pprev = explored_state(env, insn_idx);
16917 	sl = *pprev;
16918 
16919 	clean_live_states(env, insn_idx, cur);
16920 
16921 	while (sl) {
16922 		states_cnt++;
16923 		if (sl->state.insn_idx != insn_idx)
16924 			goto next;
16925 
16926 		if (sl->state.branches) {
16927 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16928 
16929 			if (frame->in_async_callback_fn &&
16930 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16931 				/* Different async_entry_cnt means that the verifier is
16932 				 * processing another entry into async callback.
16933 				 * Seeing the same state is not an indication of infinite
16934 				 * loop or infinite recursion.
16935 				 * But finding the same state doesn't mean that it's safe
16936 				 * to stop processing the current state. The previous state
16937 				 * hasn't yet reached bpf_exit, since state.branches > 0.
16938 				 * Checking in_async_callback_fn alone is not enough either.
16939 				 * Since the verifier still needs to catch infinite loops
16940 				 * inside async callbacks.
16941 				 */
16942 				goto skip_inf_loop_check;
16943 			}
16944 			/* BPF open-coded iterators loop detection is special.
16945 			 * states_maybe_looping() logic is too simplistic in detecting
16946 			 * states that *might* be equivalent, because it doesn't know
16947 			 * about ID remapping, so don't even perform it.
16948 			 * See process_iter_next_call() and iter_active_depths_differ()
16949 			 * for overview of the logic. When current and one of parent
16950 			 * states are detected as equivalent, it's a good thing: we prove
16951 			 * convergence and can stop simulating further iterations.
16952 			 * It's safe to assume that iterator loop will finish, taking into
16953 			 * account iter_next() contract of eventually returning
16954 			 * sticky NULL result.
16955 			 *
16956 			 * Note, that states have to be compared exactly in this case because
16957 			 * read and precision marks might not be finalized inside the loop.
16958 			 * E.g. as in the program below:
16959 			 *
16960 			 *     1. r7 = -16
16961 			 *     2. r6 = bpf_get_prandom_u32()
16962 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
16963 			 *     4.   if (r6 != 42) {
16964 			 *     5.     r7 = -32
16965 			 *     6.     r6 = bpf_get_prandom_u32()
16966 			 *     7.     continue
16967 			 *     8.   }
16968 			 *     9.   r0 = r10
16969 			 *    10.   r0 += r7
16970 			 *    11.   r8 = *(u64 *)(r0 + 0)
16971 			 *    12.   r6 = bpf_get_prandom_u32()
16972 			 *    13. }
16973 			 *
16974 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
16975 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16976 			 * not have read or precision mark for r7 yet, thus inexact states
16977 			 * comparison would discard current state with r7=-32
16978 			 * => unsafe memory access at 11 would not be caught.
16979 			 */
16980 			if (is_iter_next_insn(env, insn_idx)) {
16981 				if (states_equal(env, &sl->state, cur, true)) {
16982 					struct bpf_func_state *cur_frame;
16983 					struct bpf_reg_state *iter_state, *iter_reg;
16984 					int spi;
16985 
16986 					cur_frame = cur->frame[cur->curframe];
16987 					/* btf_check_iter_kfuncs() enforces that
16988 					 * iter state pointer is always the first arg
16989 					 */
16990 					iter_reg = &cur_frame->regs[BPF_REG_1];
16991 					/* current state is valid due to states_equal(),
16992 					 * so we can assume valid iter and reg state,
16993 					 * no need for extra (re-)validations
16994 					 */
16995 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16996 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16997 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
16998 						update_loop_entry(cur, &sl->state);
16999 						goto hit;
17000 					}
17001 				}
17002 				goto skip_inf_loop_check;
17003 			}
17004 			if (calls_callback(env, insn_idx)) {
17005 				if (states_equal(env, &sl->state, cur, true))
17006 					goto hit;
17007 				goto skip_inf_loop_check;
17008 			}
17009 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
17010 			if (states_maybe_looping(&sl->state, cur) &&
17011 			    states_equal(env, &sl->state, cur, false) &&
17012 			    !iter_active_depths_differ(&sl->state, cur) &&
17013 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
17014 				verbose_linfo(env, insn_idx, "; ");
17015 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
17016 				verbose(env, "cur state:");
17017 				print_verifier_state(env, cur->frame[cur->curframe], true);
17018 				verbose(env, "old state:");
17019 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
17020 				return -EINVAL;
17021 			}
17022 			/* if the verifier is processing a loop, avoid adding new state
17023 			 * too often, since different loop iterations have distinct
17024 			 * states and may not help future pruning.
17025 			 * This threshold shouldn't be too low to make sure that
17026 			 * a loop with large bound will be rejected quickly.
17027 			 * The most abusive loop will be:
17028 			 * r1 += 1
17029 			 * if r1 < 1000000 goto pc-2
17030 			 * 1M insn_procssed limit / 100 == 10k peak states.
17031 			 * This threshold shouldn't be too high either, since states
17032 			 * at the end of the loop are likely to be useful in pruning.
17033 			 */
17034 skip_inf_loop_check:
17035 			if (!force_new_state &&
17036 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
17037 			    env->insn_processed - env->prev_insn_processed < 100)
17038 				add_new_state = false;
17039 			goto miss;
17040 		}
17041 		/* If sl->state is a part of a loop and this loop's entry is a part of
17042 		 * current verification path then states have to be compared exactly.
17043 		 * 'force_exact' is needed to catch the following case:
17044 		 *
17045 		 *                initial     Here state 'succ' was processed first,
17046 		 *                  |         it was eventually tracked to produce a
17047 		 *                  V         state identical to 'hdr'.
17048 		 *     .---------> hdr        All branches from 'succ' had been explored
17049 		 *     |            |         and thus 'succ' has its .branches == 0.
17050 		 *     |            V
17051 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
17052 		 *     |    |       |         to the same instruction + callsites.
17053 		 *     |    V       V         In such case it is necessary to check
17054 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
17055 		 *     |    |       |         If 'succ' and 'cur' are a part of the
17056 		 *     |    V       V         same loop exact flag has to be set.
17057 		 *     |   succ <- cur        To check if that is the case, verify
17058 		 *     |    |                 if loop entry of 'succ' is in current
17059 		 *     |    V                 DFS path.
17060 		 *     |   ...
17061 		 *     |    |
17062 		 *     '----'
17063 		 *
17064 		 * Additional details are in the comment before get_loop_entry().
17065 		 */
17066 		loop_entry = get_loop_entry(&sl->state);
17067 		force_exact = loop_entry && loop_entry->branches > 0;
17068 		if (states_equal(env, &sl->state, cur, force_exact)) {
17069 			if (force_exact)
17070 				update_loop_entry(cur, loop_entry);
17071 hit:
17072 			sl->hit_cnt++;
17073 			/* reached equivalent register/stack state,
17074 			 * prune the search.
17075 			 * Registers read by the continuation are read by us.
17076 			 * If we have any write marks in env->cur_state, they
17077 			 * will prevent corresponding reads in the continuation
17078 			 * from reaching our parent (an explored_state).  Our
17079 			 * own state will get the read marks recorded, but
17080 			 * they'll be immediately forgotten as we're pruning
17081 			 * this state and will pop a new one.
17082 			 */
17083 			err = propagate_liveness(env, &sl->state, cur);
17084 
17085 			/* if previous state reached the exit with precision and
17086 			 * current state is equivalent to it (except precsion marks)
17087 			 * the precision needs to be propagated back in
17088 			 * the current state.
17089 			 */
17090 			if (is_jmp_point(env, env->insn_idx))
17091 				err = err ? : push_jmp_history(env, cur, 0);
17092 			err = err ? : propagate_precision(env, &sl->state);
17093 			if (err)
17094 				return err;
17095 			return 1;
17096 		}
17097 miss:
17098 		/* when new state is not going to be added do not increase miss count.
17099 		 * Otherwise several loop iterations will remove the state
17100 		 * recorded earlier. The goal of these heuristics is to have
17101 		 * states from some iterations of the loop (some in the beginning
17102 		 * and some at the end) to help pruning.
17103 		 */
17104 		if (add_new_state)
17105 			sl->miss_cnt++;
17106 		/* heuristic to determine whether this state is beneficial
17107 		 * to keep checking from state equivalence point of view.
17108 		 * Higher numbers increase max_states_per_insn and verification time,
17109 		 * but do not meaningfully decrease insn_processed.
17110 		 * 'n' controls how many times state could miss before eviction.
17111 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
17112 		 * too early would hinder iterator convergence.
17113 		 */
17114 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
17115 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
17116 			/* the state is unlikely to be useful. Remove it to
17117 			 * speed up verification
17118 			 */
17119 			*pprev = sl->next;
17120 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
17121 			    !sl->state.used_as_loop_entry) {
17122 				u32 br = sl->state.branches;
17123 
17124 				WARN_ONCE(br,
17125 					  "BUG live_done but branches_to_explore %d\n",
17126 					  br);
17127 				free_verifier_state(&sl->state, false);
17128 				kfree(sl);
17129 				env->peak_states--;
17130 			} else {
17131 				/* cannot free this state, since parentage chain may
17132 				 * walk it later. Add it for free_list instead to
17133 				 * be freed at the end of verification
17134 				 */
17135 				sl->next = env->free_list;
17136 				env->free_list = sl;
17137 			}
17138 			sl = *pprev;
17139 			continue;
17140 		}
17141 next:
17142 		pprev = &sl->next;
17143 		sl = *pprev;
17144 	}
17145 
17146 	if (env->max_states_per_insn < states_cnt)
17147 		env->max_states_per_insn = states_cnt;
17148 
17149 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
17150 		return 0;
17151 
17152 	if (!add_new_state)
17153 		return 0;
17154 
17155 	/* There were no equivalent states, remember the current one.
17156 	 * Technically the current state is not proven to be safe yet,
17157 	 * but it will either reach outer most bpf_exit (which means it's safe)
17158 	 * or it will be rejected. When there are no loops the verifier won't be
17159 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
17160 	 * again on the way to bpf_exit.
17161 	 * When looping the sl->state.branches will be > 0 and this state
17162 	 * will not be considered for equivalence until branches == 0.
17163 	 */
17164 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
17165 	if (!new_sl)
17166 		return -ENOMEM;
17167 	env->total_states++;
17168 	env->peak_states++;
17169 	env->prev_jmps_processed = env->jmps_processed;
17170 	env->prev_insn_processed = env->insn_processed;
17171 
17172 	/* forget precise markings we inherited, see __mark_chain_precision */
17173 	if (env->bpf_capable)
17174 		mark_all_scalars_imprecise(env, cur);
17175 
17176 	/* add new state to the head of linked list */
17177 	new = &new_sl->state;
17178 	err = copy_verifier_state(new, cur);
17179 	if (err) {
17180 		free_verifier_state(new, false);
17181 		kfree(new_sl);
17182 		return err;
17183 	}
17184 	new->insn_idx = insn_idx;
17185 	WARN_ONCE(new->branches != 1,
17186 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
17187 
17188 	cur->parent = new;
17189 	cur->first_insn_idx = insn_idx;
17190 	cur->dfs_depth = new->dfs_depth + 1;
17191 	clear_jmp_history(cur);
17192 	new_sl->next = *explored_state(env, insn_idx);
17193 	*explored_state(env, insn_idx) = new_sl;
17194 	/* connect new state to parentage chain. Current frame needs all
17195 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
17196 	 * to the stack implicitly by JITs) so in callers' frames connect just
17197 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
17198 	 * the state of the call instruction (with WRITTEN set), and r0 comes
17199 	 * from callee with its full parentage chain, anyway.
17200 	 */
17201 	/* clear write marks in current state: the writes we did are not writes
17202 	 * our child did, so they don't screen off its reads from us.
17203 	 * (There are no read marks in current state, because reads always mark
17204 	 * their parent and current state never has children yet.  Only
17205 	 * explored_states can get read marks.)
17206 	 */
17207 	for (j = 0; j <= cur->curframe; j++) {
17208 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
17209 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
17210 		for (i = 0; i < BPF_REG_FP; i++)
17211 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
17212 	}
17213 
17214 	/* all stack frames are accessible from callee, clear them all */
17215 	for (j = 0; j <= cur->curframe; j++) {
17216 		struct bpf_func_state *frame = cur->frame[j];
17217 		struct bpf_func_state *newframe = new->frame[j];
17218 
17219 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
17220 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
17221 			frame->stack[i].spilled_ptr.parent =
17222 						&newframe->stack[i].spilled_ptr;
17223 		}
17224 	}
17225 	return 0;
17226 }
17227 
17228 /* Return true if it's OK to have the same insn return a different type. */
17229 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
17230 {
17231 	switch (base_type(type)) {
17232 	case PTR_TO_CTX:
17233 	case PTR_TO_SOCKET:
17234 	case PTR_TO_SOCK_COMMON:
17235 	case PTR_TO_TCP_SOCK:
17236 	case PTR_TO_XDP_SOCK:
17237 	case PTR_TO_BTF_ID:
17238 		return false;
17239 	default:
17240 		return true;
17241 	}
17242 }
17243 
17244 /* If an instruction was previously used with particular pointer types, then we
17245  * need to be careful to avoid cases such as the below, where it may be ok
17246  * for one branch accessing the pointer, but not ok for the other branch:
17247  *
17248  * R1 = sock_ptr
17249  * goto X;
17250  * ...
17251  * R1 = some_other_valid_ptr;
17252  * goto X;
17253  * ...
17254  * R2 = *(u32 *)(R1 + 0);
17255  */
17256 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17257 {
17258 	return src != prev && (!reg_type_mismatch_ok(src) ||
17259 			       !reg_type_mismatch_ok(prev));
17260 }
17261 
17262 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17263 			     bool allow_trust_missmatch)
17264 {
17265 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17266 
17267 	if (*prev_type == NOT_INIT) {
17268 		/* Saw a valid insn
17269 		 * dst_reg = *(u32 *)(src_reg + off)
17270 		 * save type to validate intersecting paths
17271 		 */
17272 		*prev_type = type;
17273 	} else if (reg_type_mismatch(type, *prev_type)) {
17274 		/* Abuser program is trying to use the same insn
17275 		 * dst_reg = *(u32*) (src_reg + off)
17276 		 * with different pointer types:
17277 		 * src_reg == ctx in one branch and
17278 		 * src_reg == stack|map in some other branch.
17279 		 * Reject it.
17280 		 */
17281 		if (allow_trust_missmatch &&
17282 		    base_type(type) == PTR_TO_BTF_ID &&
17283 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
17284 			/*
17285 			 * Have to support a use case when one path through
17286 			 * the program yields TRUSTED pointer while another
17287 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
17288 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
17289 			 */
17290 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
17291 		} else {
17292 			verbose(env, "same insn cannot be used with different pointers\n");
17293 			return -EINVAL;
17294 		}
17295 	}
17296 
17297 	return 0;
17298 }
17299 
17300 static int do_check(struct bpf_verifier_env *env)
17301 {
17302 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17303 	struct bpf_verifier_state *state = env->cur_state;
17304 	struct bpf_insn *insns = env->prog->insnsi;
17305 	struct bpf_reg_state *regs;
17306 	int insn_cnt = env->prog->len;
17307 	bool do_print_state = false;
17308 	int prev_insn_idx = -1;
17309 
17310 	for (;;) {
17311 		bool exception_exit = false;
17312 		struct bpf_insn *insn;
17313 		u8 class;
17314 		int err;
17315 
17316 		/* reset current history entry on each new instruction */
17317 		env->cur_hist_ent = NULL;
17318 
17319 		env->prev_insn_idx = prev_insn_idx;
17320 		if (env->insn_idx >= insn_cnt) {
17321 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
17322 				env->insn_idx, insn_cnt);
17323 			return -EFAULT;
17324 		}
17325 
17326 		insn = &insns[env->insn_idx];
17327 		class = BPF_CLASS(insn->code);
17328 
17329 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17330 			verbose(env,
17331 				"BPF program is too large. Processed %d insn\n",
17332 				env->insn_processed);
17333 			return -E2BIG;
17334 		}
17335 
17336 		state->last_insn_idx = env->prev_insn_idx;
17337 
17338 		if (is_prune_point(env, env->insn_idx)) {
17339 			err = is_state_visited(env, env->insn_idx);
17340 			if (err < 0)
17341 				return err;
17342 			if (err == 1) {
17343 				/* found equivalent state, can prune the search */
17344 				if (env->log.level & BPF_LOG_LEVEL) {
17345 					if (do_print_state)
17346 						verbose(env, "\nfrom %d to %d%s: safe\n",
17347 							env->prev_insn_idx, env->insn_idx,
17348 							env->cur_state->speculative ?
17349 							" (speculative execution)" : "");
17350 					else
17351 						verbose(env, "%d: safe\n", env->insn_idx);
17352 				}
17353 				goto process_bpf_exit;
17354 			}
17355 		}
17356 
17357 		if (is_jmp_point(env, env->insn_idx)) {
17358 			err = push_jmp_history(env, state, 0);
17359 			if (err)
17360 				return err;
17361 		}
17362 
17363 		if (signal_pending(current))
17364 			return -EAGAIN;
17365 
17366 		if (need_resched())
17367 			cond_resched();
17368 
17369 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17370 			verbose(env, "\nfrom %d to %d%s:",
17371 				env->prev_insn_idx, env->insn_idx,
17372 				env->cur_state->speculative ?
17373 				" (speculative execution)" : "");
17374 			print_verifier_state(env, state->frame[state->curframe], true);
17375 			do_print_state = false;
17376 		}
17377 
17378 		if (env->log.level & BPF_LOG_LEVEL) {
17379 			const struct bpf_insn_cbs cbs = {
17380 				.cb_call	= disasm_kfunc_name,
17381 				.cb_print	= verbose,
17382 				.private_data	= env,
17383 			};
17384 
17385 			if (verifier_state_scratched(env))
17386 				print_insn_state(env, state->frame[state->curframe]);
17387 
17388 			verbose_linfo(env, env->insn_idx, "; ");
17389 			env->prev_log_pos = env->log.end_pos;
17390 			verbose(env, "%d: ", env->insn_idx);
17391 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17392 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17393 			env->prev_log_pos = env->log.end_pos;
17394 		}
17395 
17396 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17397 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17398 							   env->prev_insn_idx);
17399 			if (err)
17400 				return err;
17401 		}
17402 
17403 		regs = cur_regs(env);
17404 		sanitize_mark_insn_seen(env);
17405 		prev_insn_idx = env->insn_idx;
17406 
17407 		if (class == BPF_ALU || class == BPF_ALU64) {
17408 			err = check_alu_op(env, insn);
17409 			if (err)
17410 				return err;
17411 
17412 		} else if (class == BPF_LDX) {
17413 			enum bpf_reg_type src_reg_type;
17414 
17415 			/* check for reserved fields is already done */
17416 
17417 			/* check src operand */
17418 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17419 			if (err)
17420 				return err;
17421 
17422 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17423 			if (err)
17424 				return err;
17425 
17426 			src_reg_type = regs[insn->src_reg].type;
17427 
17428 			/* check that memory (src_reg + off) is readable,
17429 			 * the state of dst_reg will be updated by this func
17430 			 */
17431 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17432 					       insn->off, BPF_SIZE(insn->code),
17433 					       BPF_READ, insn->dst_reg, false,
17434 					       BPF_MODE(insn->code) == BPF_MEMSX);
17435 			err = err ?: save_aux_ptr_type(env, src_reg_type, true);
17436 			err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], "ldx");
17437 			if (err)
17438 				return err;
17439 		} else if (class == BPF_STX) {
17440 			enum bpf_reg_type dst_reg_type;
17441 
17442 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17443 				err = check_atomic(env, env->insn_idx, insn);
17444 				if (err)
17445 					return err;
17446 				env->insn_idx++;
17447 				continue;
17448 			}
17449 
17450 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17451 				verbose(env, "BPF_STX uses reserved fields\n");
17452 				return -EINVAL;
17453 			}
17454 
17455 			/* check src1 operand */
17456 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17457 			if (err)
17458 				return err;
17459 			/* check src2 operand */
17460 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17461 			if (err)
17462 				return err;
17463 
17464 			dst_reg_type = regs[insn->dst_reg].type;
17465 
17466 			/* check that memory (dst_reg + off) is writeable */
17467 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17468 					       insn->off, BPF_SIZE(insn->code),
17469 					       BPF_WRITE, insn->src_reg, false, false);
17470 			if (err)
17471 				return err;
17472 
17473 			err = save_aux_ptr_type(env, dst_reg_type, false);
17474 			if (err)
17475 				return err;
17476 		} else if (class == BPF_ST) {
17477 			enum bpf_reg_type dst_reg_type;
17478 
17479 			if (BPF_MODE(insn->code) != BPF_MEM ||
17480 			    insn->src_reg != BPF_REG_0) {
17481 				verbose(env, "BPF_ST uses reserved fields\n");
17482 				return -EINVAL;
17483 			}
17484 			/* check src operand */
17485 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17486 			if (err)
17487 				return err;
17488 
17489 			dst_reg_type = regs[insn->dst_reg].type;
17490 
17491 			/* check that memory (dst_reg + off) is writeable */
17492 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17493 					       insn->off, BPF_SIZE(insn->code),
17494 					       BPF_WRITE, -1, false, false);
17495 			if (err)
17496 				return err;
17497 
17498 			err = save_aux_ptr_type(env, dst_reg_type, false);
17499 			if (err)
17500 				return err;
17501 		} else if (class == BPF_JMP || class == BPF_JMP32) {
17502 			u8 opcode = BPF_OP(insn->code);
17503 
17504 			env->jmps_processed++;
17505 			if (opcode == BPF_CALL) {
17506 				if (BPF_SRC(insn->code) != BPF_K ||
17507 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17508 				     && insn->off != 0) ||
17509 				    (insn->src_reg != BPF_REG_0 &&
17510 				     insn->src_reg != BPF_PSEUDO_CALL &&
17511 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17512 				    insn->dst_reg != BPF_REG_0 ||
17513 				    class == BPF_JMP32) {
17514 					verbose(env, "BPF_CALL uses reserved fields\n");
17515 					return -EINVAL;
17516 				}
17517 
17518 				if (env->cur_state->active_lock.ptr) {
17519 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17520 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
17521 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17522 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17523 						verbose(env, "function calls are not allowed while holding a lock\n");
17524 						return -EINVAL;
17525 					}
17526 				}
17527 				if (insn->src_reg == BPF_PSEUDO_CALL) {
17528 					err = check_func_call(env, insn, &env->insn_idx);
17529 				} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17530 					err = check_kfunc_call(env, insn, &env->insn_idx);
17531 					if (!err && is_bpf_throw_kfunc(insn)) {
17532 						exception_exit = true;
17533 						goto process_bpf_exit_full;
17534 					}
17535 				} else {
17536 					err = check_helper_call(env, insn, &env->insn_idx);
17537 				}
17538 				if (err)
17539 					return err;
17540 
17541 				mark_reg_scratched(env, BPF_REG_0);
17542 			} else if (opcode == BPF_JA) {
17543 				if (BPF_SRC(insn->code) != BPF_K ||
17544 				    insn->src_reg != BPF_REG_0 ||
17545 				    insn->dst_reg != BPF_REG_0 ||
17546 				    (class == BPF_JMP && insn->imm != 0) ||
17547 				    (class == BPF_JMP32 && insn->off != 0)) {
17548 					verbose(env, "BPF_JA uses reserved fields\n");
17549 					return -EINVAL;
17550 				}
17551 
17552 				if (class == BPF_JMP)
17553 					env->insn_idx += insn->off + 1;
17554 				else
17555 					env->insn_idx += insn->imm + 1;
17556 				continue;
17557 
17558 			} else if (opcode == BPF_EXIT) {
17559 				if (BPF_SRC(insn->code) != BPF_K ||
17560 				    insn->imm != 0 ||
17561 				    insn->src_reg != BPF_REG_0 ||
17562 				    insn->dst_reg != BPF_REG_0 ||
17563 				    class == BPF_JMP32) {
17564 					verbose(env, "BPF_EXIT uses reserved fields\n");
17565 					return -EINVAL;
17566 				}
17567 process_bpf_exit_full:
17568 				if (env->cur_state->active_lock.ptr &&
17569 				    !in_rbtree_lock_required_cb(env)) {
17570 					verbose(env, "bpf_spin_unlock is missing\n");
17571 					return -EINVAL;
17572 				}
17573 
17574 				if (env->cur_state->active_rcu_lock &&
17575 				    !in_rbtree_lock_required_cb(env)) {
17576 					verbose(env, "bpf_rcu_read_unlock is missing\n");
17577 					return -EINVAL;
17578 				}
17579 
17580 				/* We must do check_reference_leak here before
17581 				 * prepare_func_exit to handle the case when
17582 				 * state->curframe > 0, it may be a callback
17583 				 * function, for which reference_state must
17584 				 * match caller reference state when it exits.
17585 				 */
17586 				err = check_reference_leak(env, exception_exit);
17587 				if (err)
17588 					return err;
17589 
17590 				/* The side effect of the prepare_func_exit
17591 				 * which is being skipped is that it frees
17592 				 * bpf_func_state. Typically, process_bpf_exit
17593 				 * will only be hit with outermost exit.
17594 				 * copy_verifier_state in pop_stack will handle
17595 				 * freeing of any extra bpf_func_state left over
17596 				 * from not processing all nested function
17597 				 * exits. We also skip return code checks as
17598 				 * they are not needed for exceptional exits.
17599 				 */
17600 				if (exception_exit)
17601 					goto process_bpf_exit;
17602 
17603 				if (state->curframe) {
17604 					/* exit from nested function */
17605 					err = prepare_func_exit(env, &env->insn_idx);
17606 					if (err)
17607 						return err;
17608 					do_print_state = true;
17609 					continue;
17610 				}
17611 
17612 				err = check_return_code(env, BPF_REG_0, "R0");
17613 				if (err)
17614 					return err;
17615 process_bpf_exit:
17616 				mark_verifier_state_scratched(env);
17617 				update_branch_counts(env, env->cur_state);
17618 				err = pop_stack(env, &prev_insn_idx,
17619 						&env->insn_idx, pop_log);
17620 				if (err < 0) {
17621 					if (err != -ENOENT)
17622 						return err;
17623 					break;
17624 				} else {
17625 					do_print_state = true;
17626 					continue;
17627 				}
17628 			} else {
17629 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
17630 				if (err)
17631 					return err;
17632 			}
17633 		} else if (class == BPF_LD) {
17634 			u8 mode = BPF_MODE(insn->code);
17635 
17636 			if (mode == BPF_ABS || mode == BPF_IND) {
17637 				err = check_ld_abs(env, insn);
17638 				if (err)
17639 					return err;
17640 
17641 			} else if (mode == BPF_IMM) {
17642 				err = check_ld_imm(env, insn);
17643 				if (err)
17644 					return err;
17645 
17646 				env->insn_idx++;
17647 				sanitize_mark_insn_seen(env);
17648 			} else {
17649 				verbose(env, "invalid BPF_LD mode\n");
17650 				return -EINVAL;
17651 			}
17652 		} else {
17653 			verbose(env, "unknown insn class %d\n", class);
17654 			return -EINVAL;
17655 		}
17656 
17657 		env->insn_idx++;
17658 	}
17659 
17660 	return 0;
17661 }
17662 
17663 static int find_btf_percpu_datasec(struct btf *btf)
17664 {
17665 	const struct btf_type *t;
17666 	const char *tname;
17667 	int i, n;
17668 
17669 	/*
17670 	 * Both vmlinux and module each have their own ".data..percpu"
17671 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17672 	 * types to look at only module's own BTF types.
17673 	 */
17674 	n = btf_nr_types(btf);
17675 	if (btf_is_module(btf))
17676 		i = btf_nr_types(btf_vmlinux);
17677 	else
17678 		i = 1;
17679 
17680 	for(; i < n; i++) {
17681 		t = btf_type_by_id(btf, i);
17682 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17683 			continue;
17684 
17685 		tname = btf_name_by_offset(btf, t->name_off);
17686 		if (!strcmp(tname, ".data..percpu"))
17687 			return i;
17688 	}
17689 
17690 	return -ENOENT;
17691 }
17692 
17693 /* replace pseudo btf_id with kernel symbol address */
17694 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17695 			       struct bpf_insn *insn,
17696 			       struct bpf_insn_aux_data *aux)
17697 {
17698 	const struct btf_var_secinfo *vsi;
17699 	const struct btf_type *datasec;
17700 	struct btf_mod_pair *btf_mod;
17701 	const struct btf_type *t;
17702 	const char *sym_name;
17703 	bool percpu = false;
17704 	u32 type, id = insn->imm;
17705 	struct btf *btf;
17706 	s32 datasec_id;
17707 	u64 addr;
17708 	int i, btf_fd, err;
17709 
17710 	btf_fd = insn[1].imm;
17711 	if (btf_fd) {
17712 		btf = btf_get_by_fd(btf_fd);
17713 		if (IS_ERR(btf)) {
17714 			verbose(env, "invalid module BTF object FD specified.\n");
17715 			return -EINVAL;
17716 		}
17717 	} else {
17718 		if (!btf_vmlinux) {
17719 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17720 			return -EINVAL;
17721 		}
17722 		btf = btf_vmlinux;
17723 		btf_get(btf);
17724 	}
17725 
17726 	t = btf_type_by_id(btf, id);
17727 	if (!t) {
17728 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17729 		err = -ENOENT;
17730 		goto err_put;
17731 	}
17732 
17733 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17734 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17735 		err = -EINVAL;
17736 		goto err_put;
17737 	}
17738 
17739 	sym_name = btf_name_by_offset(btf, t->name_off);
17740 	addr = kallsyms_lookup_name(sym_name);
17741 	if (!addr) {
17742 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17743 			sym_name);
17744 		err = -ENOENT;
17745 		goto err_put;
17746 	}
17747 	insn[0].imm = (u32)addr;
17748 	insn[1].imm = addr >> 32;
17749 
17750 	if (btf_type_is_func(t)) {
17751 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17752 		aux->btf_var.mem_size = 0;
17753 		goto check_btf;
17754 	}
17755 
17756 	datasec_id = find_btf_percpu_datasec(btf);
17757 	if (datasec_id > 0) {
17758 		datasec = btf_type_by_id(btf, datasec_id);
17759 		for_each_vsi(i, datasec, vsi) {
17760 			if (vsi->type == id) {
17761 				percpu = true;
17762 				break;
17763 			}
17764 		}
17765 	}
17766 
17767 	type = t->type;
17768 	t = btf_type_skip_modifiers(btf, type, NULL);
17769 	if (percpu) {
17770 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17771 		aux->btf_var.btf = btf;
17772 		aux->btf_var.btf_id = type;
17773 	} else if (!btf_type_is_struct(t)) {
17774 		const struct btf_type *ret;
17775 		const char *tname;
17776 		u32 tsize;
17777 
17778 		/* resolve the type size of ksym. */
17779 		ret = btf_resolve_size(btf, t, &tsize);
17780 		if (IS_ERR(ret)) {
17781 			tname = btf_name_by_offset(btf, t->name_off);
17782 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17783 				tname, PTR_ERR(ret));
17784 			err = -EINVAL;
17785 			goto err_put;
17786 		}
17787 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17788 		aux->btf_var.mem_size = tsize;
17789 	} else {
17790 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
17791 		aux->btf_var.btf = btf;
17792 		aux->btf_var.btf_id = type;
17793 	}
17794 check_btf:
17795 	/* check whether we recorded this BTF (and maybe module) already */
17796 	for (i = 0; i < env->used_btf_cnt; i++) {
17797 		if (env->used_btfs[i].btf == btf) {
17798 			btf_put(btf);
17799 			return 0;
17800 		}
17801 	}
17802 
17803 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
17804 		err = -E2BIG;
17805 		goto err_put;
17806 	}
17807 
17808 	btf_mod = &env->used_btfs[env->used_btf_cnt];
17809 	btf_mod->btf = btf;
17810 	btf_mod->module = NULL;
17811 
17812 	/* if we reference variables from kernel module, bump its refcount */
17813 	if (btf_is_module(btf)) {
17814 		btf_mod->module = btf_try_get_module(btf);
17815 		if (!btf_mod->module) {
17816 			err = -ENXIO;
17817 			goto err_put;
17818 		}
17819 	}
17820 
17821 	env->used_btf_cnt++;
17822 
17823 	return 0;
17824 err_put:
17825 	btf_put(btf);
17826 	return err;
17827 }
17828 
17829 static bool is_tracing_prog_type(enum bpf_prog_type type)
17830 {
17831 	switch (type) {
17832 	case BPF_PROG_TYPE_KPROBE:
17833 	case BPF_PROG_TYPE_TRACEPOINT:
17834 	case BPF_PROG_TYPE_PERF_EVENT:
17835 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17836 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17837 		return true;
17838 	default:
17839 		return false;
17840 	}
17841 }
17842 
17843 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17844 					struct bpf_map *map,
17845 					struct bpf_prog *prog)
17846 
17847 {
17848 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17849 
17850 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17851 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
17852 		if (is_tracing_prog_type(prog_type)) {
17853 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17854 			return -EINVAL;
17855 		}
17856 	}
17857 
17858 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17859 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17860 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17861 			return -EINVAL;
17862 		}
17863 
17864 		if (is_tracing_prog_type(prog_type)) {
17865 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17866 			return -EINVAL;
17867 		}
17868 	}
17869 
17870 	if (btf_record_has_field(map->record, BPF_TIMER)) {
17871 		if (is_tracing_prog_type(prog_type)) {
17872 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
17873 			return -EINVAL;
17874 		}
17875 	}
17876 
17877 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17878 	    !bpf_offload_prog_map_match(prog, map)) {
17879 		verbose(env, "offload device mismatch between prog and map\n");
17880 		return -EINVAL;
17881 	}
17882 
17883 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17884 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17885 		return -EINVAL;
17886 	}
17887 
17888 	if (prog->aux->sleepable)
17889 		switch (map->map_type) {
17890 		case BPF_MAP_TYPE_HASH:
17891 		case BPF_MAP_TYPE_LRU_HASH:
17892 		case BPF_MAP_TYPE_ARRAY:
17893 		case BPF_MAP_TYPE_PERCPU_HASH:
17894 		case BPF_MAP_TYPE_PERCPU_ARRAY:
17895 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17896 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17897 		case BPF_MAP_TYPE_HASH_OF_MAPS:
17898 		case BPF_MAP_TYPE_RINGBUF:
17899 		case BPF_MAP_TYPE_USER_RINGBUF:
17900 		case BPF_MAP_TYPE_INODE_STORAGE:
17901 		case BPF_MAP_TYPE_SK_STORAGE:
17902 		case BPF_MAP_TYPE_TASK_STORAGE:
17903 		case BPF_MAP_TYPE_CGRP_STORAGE:
17904 			break;
17905 		default:
17906 			verbose(env,
17907 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17908 			return -EINVAL;
17909 		}
17910 
17911 	return 0;
17912 }
17913 
17914 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17915 {
17916 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17917 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17918 }
17919 
17920 /* find and rewrite pseudo imm in ld_imm64 instructions:
17921  *
17922  * 1. if it accesses map FD, replace it with actual map pointer.
17923  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17924  *
17925  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17926  */
17927 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17928 {
17929 	struct bpf_insn *insn = env->prog->insnsi;
17930 	int insn_cnt = env->prog->len;
17931 	int i, j, err;
17932 
17933 	err = bpf_prog_calc_tag(env->prog);
17934 	if (err)
17935 		return err;
17936 
17937 	for (i = 0; i < insn_cnt; i++, insn++) {
17938 		if (BPF_CLASS(insn->code) == BPF_LDX &&
17939 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17940 		    insn->imm != 0)) {
17941 			verbose(env, "BPF_LDX uses reserved fields\n");
17942 			return -EINVAL;
17943 		}
17944 
17945 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17946 			struct bpf_insn_aux_data *aux;
17947 			struct bpf_map *map;
17948 			struct fd f;
17949 			u64 addr;
17950 			u32 fd;
17951 
17952 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
17953 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17954 			    insn[1].off != 0) {
17955 				verbose(env, "invalid bpf_ld_imm64 insn\n");
17956 				return -EINVAL;
17957 			}
17958 
17959 			if (insn[0].src_reg == 0)
17960 				/* valid generic load 64-bit imm */
17961 				goto next_insn;
17962 
17963 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17964 				aux = &env->insn_aux_data[i];
17965 				err = check_pseudo_btf_id(env, insn, aux);
17966 				if (err)
17967 					return err;
17968 				goto next_insn;
17969 			}
17970 
17971 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17972 				aux = &env->insn_aux_data[i];
17973 				aux->ptr_type = PTR_TO_FUNC;
17974 				goto next_insn;
17975 			}
17976 
17977 			/* In final convert_pseudo_ld_imm64() step, this is
17978 			 * converted into regular 64-bit imm load insn.
17979 			 */
17980 			switch (insn[0].src_reg) {
17981 			case BPF_PSEUDO_MAP_VALUE:
17982 			case BPF_PSEUDO_MAP_IDX_VALUE:
17983 				break;
17984 			case BPF_PSEUDO_MAP_FD:
17985 			case BPF_PSEUDO_MAP_IDX:
17986 				if (insn[1].imm == 0)
17987 					break;
17988 				fallthrough;
17989 			default:
17990 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17991 				return -EINVAL;
17992 			}
17993 
17994 			switch (insn[0].src_reg) {
17995 			case BPF_PSEUDO_MAP_IDX_VALUE:
17996 			case BPF_PSEUDO_MAP_IDX:
17997 				if (bpfptr_is_null(env->fd_array)) {
17998 					verbose(env, "fd_idx without fd_array is invalid\n");
17999 					return -EPROTO;
18000 				}
18001 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
18002 							    insn[0].imm * sizeof(fd),
18003 							    sizeof(fd)))
18004 					return -EFAULT;
18005 				break;
18006 			default:
18007 				fd = insn[0].imm;
18008 				break;
18009 			}
18010 
18011 			f = fdget(fd);
18012 			map = __bpf_map_get(f);
18013 			if (IS_ERR(map)) {
18014 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
18015 					insn[0].imm);
18016 				return PTR_ERR(map);
18017 			}
18018 
18019 			err = check_map_prog_compatibility(env, map, env->prog);
18020 			if (err) {
18021 				fdput(f);
18022 				return err;
18023 			}
18024 
18025 			aux = &env->insn_aux_data[i];
18026 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
18027 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
18028 				addr = (unsigned long)map;
18029 			} else {
18030 				u32 off = insn[1].imm;
18031 
18032 				if (off >= BPF_MAX_VAR_OFF) {
18033 					verbose(env, "direct value offset of %u is not allowed\n", off);
18034 					fdput(f);
18035 					return -EINVAL;
18036 				}
18037 
18038 				if (!map->ops->map_direct_value_addr) {
18039 					verbose(env, "no direct value access support for this map type\n");
18040 					fdput(f);
18041 					return -EINVAL;
18042 				}
18043 
18044 				err = map->ops->map_direct_value_addr(map, &addr, off);
18045 				if (err) {
18046 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
18047 						map->value_size, off);
18048 					fdput(f);
18049 					return err;
18050 				}
18051 
18052 				aux->map_off = off;
18053 				addr += off;
18054 			}
18055 
18056 			insn[0].imm = (u32)addr;
18057 			insn[1].imm = addr >> 32;
18058 
18059 			/* check whether we recorded this map already */
18060 			for (j = 0; j < env->used_map_cnt; j++) {
18061 				if (env->used_maps[j] == map) {
18062 					aux->map_index = j;
18063 					fdput(f);
18064 					goto next_insn;
18065 				}
18066 			}
18067 
18068 			if (env->used_map_cnt >= MAX_USED_MAPS) {
18069 				fdput(f);
18070 				return -E2BIG;
18071 			}
18072 
18073 			if (env->prog->aux->sleepable)
18074 				atomic64_inc(&map->sleepable_refcnt);
18075 			/* hold the map. If the program is rejected by verifier,
18076 			 * the map will be released by release_maps() or it
18077 			 * will be used by the valid program until it's unloaded
18078 			 * and all maps are released in bpf_free_used_maps()
18079 			 */
18080 			bpf_map_inc(map);
18081 
18082 			aux->map_index = env->used_map_cnt;
18083 			env->used_maps[env->used_map_cnt++] = map;
18084 
18085 			if (bpf_map_is_cgroup_storage(map) &&
18086 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
18087 				verbose(env, "only one cgroup storage of each type is allowed\n");
18088 				fdput(f);
18089 				return -EBUSY;
18090 			}
18091 
18092 			fdput(f);
18093 next_insn:
18094 			insn++;
18095 			i++;
18096 			continue;
18097 		}
18098 
18099 		/* Basic sanity check before we invest more work here. */
18100 		if (!bpf_opcode_in_insntable(insn->code)) {
18101 			verbose(env, "unknown opcode %02x\n", insn->code);
18102 			return -EINVAL;
18103 		}
18104 	}
18105 
18106 	/* now all pseudo BPF_LD_IMM64 instructions load valid
18107 	 * 'struct bpf_map *' into a register instead of user map_fd.
18108 	 * These pointers will be used later by verifier to validate map access.
18109 	 */
18110 	return 0;
18111 }
18112 
18113 /* drop refcnt of maps used by the rejected program */
18114 static void release_maps(struct bpf_verifier_env *env)
18115 {
18116 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
18117 			     env->used_map_cnt);
18118 }
18119 
18120 /* drop refcnt of maps used by the rejected program */
18121 static void release_btfs(struct bpf_verifier_env *env)
18122 {
18123 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
18124 			     env->used_btf_cnt);
18125 }
18126 
18127 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
18128 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
18129 {
18130 	struct bpf_insn *insn = env->prog->insnsi;
18131 	int insn_cnt = env->prog->len;
18132 	int i;
18133 
18134 	for (i = 0; i < insn_cnt; i++, insn++) {
18135 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
18136 			continue;
18137 		if (insn->src_reg == BPF_PSEUDO_FUNC)
18138 			continue;
18139 		insn->src_reg = 0;
18140 	}
18141 }
18142 
18143 /* single env->prog->insni[off] instruction was replaced with the range
18144  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
18145  * [0, off) and [off, end) to new locations, so the patched range stays zero
18146  */
18147 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
18148 				 struct bpf_insn_aux_data *new_data,
18149 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
18150 {
18151 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
18152 	struct bpf_insn *insn = new_prog->insnsi;
18153 	u32 old_seen = old_data[off].seen;
18154 	u32 prog_len;
18155 	int i;
18156 
18157 	/* aux info at OFF always needs adjustment, no matter fast path
18158 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
18159 	 * original insn at old prog.
18160 	 */
18161 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
18162 
18163 	if (cnt == 1)
18164 		return;
18165 	prog_len = new_prog->len;
18166 
18167 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
18168 	memcpy(new_data + off + cnt - 1, old_data + off,
18169 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
18170 	for (i = off; i < off + cnt - 1; i++) {
18171 		/* Expand insni[off]'s seen count to the patched range. */
18172 		new_data[i].seen = old_seen;
18173 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
18174 	}
18175 	env->insn_aux_data = new_data;
18176 	vfree(old_data);
18177 }
18178 
18179 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
18180 {
18181 	int i;
18182 
18183 	if (len == 1)
18184 		return;
18185 	/* NOTE: fake 'exit' subprog should be updated as well. */
18186 	for (i = 0; i <= env->subprog_cnt; i++) {
18187 		if (env->subprog_info[i].start <= off)
18188 			continue;
18189 		env->subprog_info[i].start += len - 1;
18190 	}
18191 }
18192 
18193 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
18194 {
18195 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
18196 	int i, sz = prog->aux->size_poke_tab;
18197 	struct bpf_jit_poke_descriptor *desc;
18198 
18199 	for (i = 0; i < sz; i++) {
18200 		desc = &tab[i];
18201 		if (desc->insn_idx <= off)
18202 			continue;
18203 		desc->insn_idx += len - 1;
18204 	}
18205 }
18206 
18207 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
18208 					    const struct bpf_insn *patch, u32 len)
18209 {
18210 	struct bpf_prog *new_prog;
18211 	struct bpf_insn_aux_data *new_data = NULL;
18212 
18213 	if (len > 1) {
18214 		new_data = vzalloc(array_size(env->prog->len + len - 1,
18215 					      sizeof(struct bpf_insn_aux_data)));
18216 		if (!new_data)
18217 			return NULL;
18218 	}
18219 
18220 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
18221 	if (IS_ERR(new_prog)) {
18222 		if (PTR_ERR(new_prog) == -ERANGE)
18223 			verbose(env,
18224 				"insn %d cannot be patched due to 16-bit range\n",
18225 				env->insn_aux_data[off].orig_idx);
18226 		vfree(new_data);
18227 		return NULL;
18228 	}
18229 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
18230 	adjust_subprog_starts(env, off, len);
18231 	adjust_poke_descs(new_prog, off, len);
18232 	return new_prog;
18233 }
18234 
18235 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
18236 					      u32 off, u32 cnt)
18237 {
18238 	int i, j;
18239 
18240 	/* find first prog starting at or after off (first to remove) */
18241 	for (i = 0; i < env->subprog_cnt; i++)
18242 		if (env->subprog_info[i].start >= off)
18243 			break;
18244 	/* find first prog starting at or after off + cnt (first to stay) */
18245 	for (j = i; j < env->subprog_cnt; j++)
18246 		if (env->subprog_info[j].start >= off + cnt)
18247 			break;
18248 	/* if j doesn't start exactly at off + cnt, we are just removing
18249 	 * the front of previous prog
18250 	 */
18251 	if (env->subprog_info[j].start != off + cnt)
18252 		j--;
18253 
18254 	if (j > i) {
18255 		struct bpf_prog_aux *aux = env->prog->aux;
18256 		int move;
18257 
18258 		/* move fake 'exit' subprog as well */
18259 		move = env->subprog_cnt + 1 - j;
18260 
18261 		memmove(env->subprog_info + i,
18262 			env->subprog_info + j,
18263 			sizeof(*env->subprog_info) * move);
18264 		env->subprog_cnt -= j - i;
18265 
18266 		/* remove func_info */
18267 		if (aux->func_info) {
18268 			move = aux->func_info_cnt - j;
18269 
18270 			memmove(aux->func_info + i,
18271 				aux->func_info + j,
18272 				sizeof(*aux->func_info) * move);
18273 			aux->func_info_cnt -= j - i;
18274 			/* func_info->insn_off is set after all code rewrites,
18275 			 * in adjust_btf_func() - no need to adjust
18276 			 */
18277 		}
18278 	} else {
18279 		/* convert i from "first prog to remove" to "first to adjust" */
18280 		if (env->subprog_info[i].start == off)
18281 			i++;
18282 	}
18283 
18284 	/* update fake 'exit' subprog as well */
18285 	for (; i <= env->subprog_cnt; i++)
18286 		env->subprog_info[i].start -= cnt;
18287 
18288 	return 0;
18289 }
18290 
18291 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
18292 				      u32 cnt)
18293 {
18294 	struct bpf_prog *prog = env->prog;
18295 	u32 i, l_off, l_cnt, nr_linfo;
18296 	struct bpf_line_info *linfo;
18297 
18298 	nr_linfo = prog->aux->nr_linfo;
18299 	if (!nr_linfo)
18300 		return 0;
18301 
18302 	linfo = prog->aux->linfo;
18303 
18304 	/* find first line info to remove, count lines to be removed */
18305 	for (i = 0; i < nr_linfo; i++)
18306 		if (linfo[i].insn_off >= off)
18307 			break;
18308 
18309 	l_off = i;
18310 	l_cnt = 0;
18311 	for (; i < nr_linfo; i++)
18312 		if (linfo[i].insn_off < off + cnt)
18313 			l_cnt++;
18314 		else
18315 			break;
18316 
18317 	/* First live insn doesn't match first live linfo, it needs to "inherit"
18318 	 * last removed linfo.  prog is already modified, so prog->len == off
18319 	 * means no live instructions after (tail of the program was removed).
18320 	 */
18321 	if (prog->len != off && l_cnt &&
18322 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
18323 		l_cnt--;
18324 		linfo[--i].insn_off = off + cnt;
18325 	}
18326 
18327 	/* remove the line info which refer to the removed instructions */
18328 	if (l_cnt) {
18329 		memmove(linfo + l_off, linfo + i,
18330 			sizeof(*linfo) * (nr_linfo - i));
18331 
18332 		prog->aux->nr_linfo -= l_cnt;
18333 		nr_linfo = prog->aux->nr_linfo;
18334 	}
18335 
18336 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
18337 	for (i = l_off; i < nr_linfo; i++)
18338 		linfo[i].insn_off -= cnt;
18339 
18340 	/* fix up all subprogs (incl. 'exit') which start >= off */
18341 	for (i = 0; i <= env->subprog_cnt; i++)
18342 		if (env->subprog_info[i].linfo_idx > l_off) {
18343 			/* program may have started in the removed region but
18344 			 * may not be fully removed
18345 			 */
18346 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18347 				env->subprog_info[i].linfo_idx -= l_cnt;
18348 			else
18349 				env->subprog_info[i].linfo_idx = l_off;
18350 		}
18351 
18352 	return 0;
18353 }
18354 
18355 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18356 {
18357 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18358 	unsigned int orig_prog_len = env->prog->len;
18359 	int err;
18360 
18361 	if (bpf_prog_is_offloaded(env->prog->aux))
18362 		bpf_prog_offload_remove_insns(env, off, cnt);
18363 
18364 	err = bpf_remove_insns(env->prog, off, cnt);
18365 	if (err)
18366 		return err;
18367 
18368 	err = adjust_subprog_starts_after_remove(env, off, cnt);
18369 	if (err)
18370 		return err;
18371 
18372 	err = bpf_adj_linfo_after_remove(env, off, cnt);
18373 	if (err)
18374 		return err;
18375 
18376 	memmove(aux_data + off,	aux_data + off + cnt,
18377 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18378 
18379 	return 0;
18380 }
18381 
18382 /* The verifier does more data flow analysis than llvm and will not
18383  * explore branches that are dead at run time. Malicious programs can
18384  * have dead code too. Therefore replace all dead at-run-time code
18385  * with 'ja -1'.
18386  *
18387  * Just nops are not optimal, e.g. if they would sit at the end of the
18388  * program and through another bug we would manage to jump there, then
18389  * we'd execute beyond program memory otherwise. Returning exception
18390  * code also wouldn't work since we can have subprogs where the dead
18391  * code could be located.
18392  */
18393 static void sanitize_dead_code(struct bpf_verifier_env *env)
18394 {
18395 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18396 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18397 	struct bpf_insn *insn = env->prog->insnsi;
18398 	const int insn_cnt = env->prog->len;
18399 	int i;
18400 
18401 	for (i = 0; i < insn_cnt; i++) {
18402 		if (aux_data[i].seen)
18403 			continue;
18404 		memcpy(insn + i, &trap, sizeof(trap));
18405 		aux_data[i].zext_dst = false;
18406 	}
18407 }
18408 
18409 static bool insn_is_cond_jump(u8 code)
18410 {
18411 	u8 op;
18412 
18413 	op = BPF_OP(code);
18414 	if (BPF_CLASS(code) == BPF_JMP32)
18415 		return op != BPF_JA;
18416 
18417 	if (BPF_CLASS(code) != BPF_JMP)
18418 		return false;
18419 
18420 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18421 }
18422 
18423 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18424 {
18425 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18426 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18427 	struct bpf_insn *insn = env->prog->insnsi;
18428 	const int insn_cnt = env->prog->len;
18429 	int i;
18430 
18431 	for (i = 0; i < insn_cnt; i++, insn++) {
18432 		if (!insn_is_cond_jump(insn->code))
18433 			continue;
18434 
18435 		if (!aux_data[i + 1].seen)
18436 			ja.off = insn->off;
18437 		else if (!aux_data[i + 1 + insn->off].seen)
18438 			ja.off = 0;
18439 		else
18440 			continue;
18441 
18442 		if (bpf_prog_is_offloaded(env->prog->aux))
18443 			bpf_prog_offload_replace_insn(env, i, &ja);
18444 
18445 		memcpy(insn, &ja, sizeof(ja));
18446 	}
18447 }
18448 
18449 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18450 {
18451 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18452 	int insn_cnt = env->prog->len;
18453 	int i, err;
18454 
18455 	for (i = 0; i < insn_cnt; i++) {
18456 		int j;
18457 
18458 		j = 0;
18459 		while (i + j < insn_cnt && !aux_data[i + j].seen)
18460 			j++;
18461 		if (!j)
18462 			continue;
18463 
18464 		err = verifier_remove_insns(env, i, j);
18465 		if (err)
18466 			return err;
18467 		insn_cnt = env->prog->len;
18468 	}
18469 
18470 	return 0;
18471 }
18472 
18473 static int opt_remove_nops(struct bpf_verifier_env *env)
18474 {
18475 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18476 	struct bpf_insn *insn = env->prog->insnsi;
18477 	int insn_cnt = env->prog->len;
18478 	int i, err;
18479 
18480 	for (i = 0; i < insn_cnt; i++) {
18481 		if (memcmp(&insn[i], &ja, sizeof(ja)))
18482 			continue;
18483 
18484 		err = verifier_remove_insns(env, i, 1);
18485 		if (err)
18486 			return err;
18487 		insn_cnt--;
18488 		i--;
18489 	}
18490 
18491 	return 0;
18492 }
18493 
18494 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18495 					 const union bpf_attr *attr)
18496 {
18497 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18498 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18499 	int i, patch_len, delta = 0, len = env->prog->len;
18500 	struct bpf_insn *insns = env->prog->insnsi;
18501 	struct bpf_prog *new_prog;
18502 	bool rnd_hi32;
18503 
18504 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18505 	zext_patch[1] = BPF_ZEXT_REG(0);
18506 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18507 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18508 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18509 	for (i = 0; i < len; i++) {
18510 		int adj_idx = i + delta;
18511 		struct bpf_insn insn;
18512 		int load_reg;
18513 
18514 		insn = insns[adj_idx];
18515 		load_reg = insn_def_regno(&insn);
18516 		if (!aux[adj_idx].zext_dst) {
18517 			u8 code, class;
18518 			u32 imm_rnd;
18519 
18520 			if (!rnd_hi32)
18521 				continue;
18522 
18523 			code = insn.code;
18524 			class = BPF_CLASS(code);
18525 			if (load_reg == -1)
18526 				continue;
18527 
18528 			/* NOTE: arg "reg" (the fourth one) is only used for
18529 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
18530 			 *       here.
18531 			 */
18532 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18533 				if (class == BPF_LD &&
18534 				    BPF_MODE(code) == BPF_IMM)
18535 					i++;
18536 				continue;
18537 			}
18538 
18539 			/* ctx load could be transformed into wider load. */
18540 			if (class == BPF_LDX &&
18541 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
18542 				continue;
18543 
18544 			imm_rnd = get_random_u32();
18545 			rnd_hi32_patch[0] = insn;
18546 			rnd_hi32_patch[1].imm = imm_rnd;
18547 			rnd_hi32_patch[3].dst_reg = load_reg;
18548 			patch = rnd_hi32_patch;
18549 			patch_len = 4;
18550 			goto apply_patch_buffer;
18551 		}
18552 
18553 		/* Add in an zero-extend instruction if a) the JIT has requested
18554 		 * it or b) it's a CMPXCHG.
18555 		 *
18556 		 * The latter is because: BPF_CMPXCHG always loads a value into
18557 		 * R0, therefore always zero-extends. However some archs'
18558 		 * equivalent instruction only does this load when the
18559 		 * comparison is successful. This detail of CMPXCHG is
18560 		 * orthogonal to the general zero-extension behaviour of the
18561 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
18562 		 */
18563 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18564 			continue;
18565 
18566 		/* Zero-extension is done by the caller. */
18567 		if (bpf_pseudo_kfunc_call(&insn))
18568 			continue;
18569 
18570 		if (WARN_ON(load_reg == -1)) {
18571 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18572 			return -EFAULT;
18573 		}
18574 
18575 		zext_patch[0] = insn;
18576 		zext_patch[1].dst_reg = load_reg;
18577 		zext_patch[1].src_reg = load_reg;
18578 		patch = zext_patch;
18579 		patch_len = 2;
18580 apply_patch_buffer:
18581 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18582 		if (!new_prog)
18583 			return -ENOMEM;
18584 		env->prog = new_prog;
18585 		insns = new_prog->insnsi;
18586 		aux = env->insn_aux_data;
18587 		delta += patch_len - 1;
18588 	}
18589 
18590 	return 0;
18591 }
18592 
18593 /* convert load instructions that access fields of a context type into a
18594  * sequence of instructions that access fields of the underlying structure:
18595  *     struct __sk_buff    -> struct sk_buff
18596  *     struct bpf_sock_ops -> struct sock
18597  */
18598 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18599 {
18600 	const struct bpf_verifier_ops *ops = env->ops;
18601 	int i, cnt, size, ctx_field_size, delta = 0;
18602 	const int insn_cnt = env->prog->len;
18603 	struct bpf_insn insn_buf[16], *insn;
18604 	u32 target_size, size_default, off;
18605 	struct bpf_prog *new_prog;
18606 	enum bpf_access_type type;
18607 	bool is_narrower_load;
18608 
18609 	if (ops->gen_prologue || env->seen_direct_write) {
18610 		if (!ops->gen_prologue) {
18611 			verbose(env, "bpf verifier is misconfigured\n");
18612 			return -EINVAL;
18613 		}
18614 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18615 					env->prog);
18616 		if (cnt >= ARRAY_SIZE(insn_buf)) {
18617 			verbose(env, "bpf verifier is misconfigured\n");
18618 			return -EINVAL;
18619 		} else if (cnt) {
18620 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18621 			if (!new_prog)
18622 				return -ENOMEM;
18623 
18624 			env->prog = new_prog;
18625 			delta += cnt - 1;
18626 		}
18627 	}
18628 
18629 	if (bpf_prog_is_offloaded(env->prog->aux))
18630 		return 0;
18631 
18632 	insn = env->prog->insnsi + delta;
18633 
18634 	for (i = 0; i < insn_cnt; i++, insn++) {
18635 		bpf_convert_ctx_access_t convert_ctx_access;
18636 		u8 mode;
18637 
18638 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18639 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18640 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18641 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18642 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18643 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18644 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18645 			type = BPF_READ;
18646 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18647 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18648 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18649 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18650 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18651 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18652 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18653 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18654 			type = BPF_WRITE;
18655 		} else {
18656 			continue;
18657 		}
18658 
18659 		if (type == BPF_WRITE &&
18660 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
18661 			struct bpf_insn patch[] = {
18662 				*insn,
18663 				BPF_ST_NOSPEC(),
18664 			};
18665 
18666 			cnt = ARRAY_SIZE(patch);
18667 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18668 			if (!new_prog)
18669 				return -ENOMEM;
18670 
18671 			delta    += cnt - 1;
18672 			env->prog = new_prog;
18673 			insn      = new_prog->insnsi + i + delta;
18674 			continue;
18675 		}
18676 
18677 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18678 		case PTR_TO_CTX:
18679 			if (!ops->convert_ctx_access)
18680 				continue;
18681 			convert_ctx_access = ops->convert_ctx_access;
18682 			break;
18683 		case PTR_TO_SOCKET:
18684 		case PTR_TO_SOCK_COMMON:
18685 			convert_ctx_access = bpf_sock_convert_ctx_access;
18686 			break;
18687 		case PTR_TO_TCP_SOCK:
18688 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18689 			break;
18690 		case PTR_TO_XDP_SOCK:
18691 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18692 			break;
18693 		case PTR_TO_BTF_ID:
18694 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18695 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18696 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18697 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18698 		 * any faults for loads into such types. BPF_WRITE is disallowed
18699 		 * for this case.
18700 		 */
18701 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18702 			if (type == BPF_READ) {
18703 				if (BPF_MODE(insn->code) == BPF_MEM)
18704 					insn->code = BPF_LDX | BPF_PROBE_MEM |
18705 						     BPF_SIZE((insn)->code);
18706 				else
18707 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18708 						     BPF_SIZE((insn)->code);
18709 				env->prog->aux->num_exentries++;
18710 			}
18711 			continue;
18712 		default:
18713 			continue;
18714 		}
18715 
18716 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18717 		size = BPF_LDST_BYTES(insn);
18718 		mode = BPF_MODE(insn->code);
18719 
18720 		/* If the read access is a narrower load of the field,
18721 		 * convert to a 4/8-byte load, to minimum program type specific
18722 		 * convert_ctx_access changes. If conversion is successful,
18723 		 * we will apply proper mask to the result.
18724 		 */
18725 		is_narrower_load = size < ctx_field_size;
18726 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18727 		off = insn->off;
18728 		if (is_narrower_load) {
18729 			u8 size_code;
18730 
18731 			if (type == BPF_WRITE) {
18732 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18733 				return -EINVAL;
18734 			}
18735 
18736 			size_code = BPF_H;
18737 			if (ctx_field_size == 4)
18738 				size_code = BPF_W;
18739 			else if (ctx_field_size == 8)
18740 				size_code = BPF_DW;
18741 
18742 			insn->off = off & ~(size_default - 1);
18743 			insn->code = BPF_LDX | BPF_MEM | size_code;
18744 		}
18745 
18746 		target_size = 0;
18747 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18748 					 &target_size);
18749 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18750 		    (ctx_field_size && !target_size)) {
18751 			verbose(env, "bpf verifier is misconfigured\n");
18752 			return -EINVAL;
18753 		}
18754 
18755 		if (is_narrower_load && size < target_size) {
18756 			u8 shift = bpf_ctx_narrow_access_offset(
18757 				off, size, size_default) * 8;
18758 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18759 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18760 				return -EINVAL;
18761 			}
18762 			if (ctx_field_size <= 4) {
18763 				if (shift)
18764 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18765 									insn->dst_reg,
18766 									shift);
18767 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18768 								(1 << size * 8) - 1);
18769 			} else {
18770 				if (shift)
18771 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18772 									insn->dst_reg,
18773 									shift);
18774 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18775 								(1ULL << size * 8) - 1);
18776 			}
18777 		}
18778 		if (mode == BPF_MEMSX)
18779 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18780 						       insn->dst_reg, insn->dst_reg,
18781 						       size * 8, 0);
18782 
18783 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18784 		if (!new_prog)
18785 			return -ENOMEM;
18786 
18787 		delta += cnt - 1;
18788 
18789 		/* keep walking new program and skip insns we just inserted */
18790 		env->prog = new_prog;
18791 		insn      = new_prog->insnsi + i + delta;
18792 	}
18793 
18794 	return 0;
18795 }
18796 
18797 static int jit_subprogs(struct bpf_verifier_env *env)
18798 {
18799 	struct bpf_prog *prog = env->prog, **func, *tmp;
18800 	int i, j, subprog_start, subprog_end = 0, len, subprog;
18801 	struct bpf_map *map_ptr;
18802 	struct bpf_insn *insn;
18803 	void *old_bpf_func;
18804 	int err, num_exentries;
18805 
18806 	if (env->subprog_cnt <= 1)
18807 		return 0;
18808 
18809 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18810 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18811 			continue;
18812 
18813 		/* Upon error here we cannot fall back to interpreter but
18814 		 * need a hard reject of the program. Thus -EFAULT is
18815 		 * propagated in any case.
18816 		 */
18817 		subprog = find_subprog(env, i + insn->imm + 1);
18818 		if (subprog < 0) {
18819 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18820 				  i + insn->imm + 1);
18821 			return -EFAULT;
18822 		}
18823 		/* temporarily remember subprog id inside insn instead of
18824 		 * aux_data, since next loop will split up all insns into funcs
18825 		 */
18826 		insn->off = subprog;
18827 		/* remember original imm in case JIT fails and fallback
18828 		 * to interpreter will be needed
18829 		 */
18830 		env->insn_aux_data[i].call_imm = insn->imm;
18831 		/* point imm to __bpf_call_base+1 from JITs point of view */
18832 		insn->imm = 1;
18833 		if (bpf_pseudo_func(insn))
18834 			/* jit (e.g. x86_64) may emit fewer instructions
18835 			 * if it learns a u32 imm is the same as a u64 imm.
18836 			 * Force a non zero here.
18837 			 */
18838 			insn[1].imm = 1;
18839 	}
18840 
18841 	err = bpf_prog_alloc_jited_linfo(prog);
18842 	if (err)
18843 		goto out_undo_insn;
18844 
18845 	err = -ENOMEM;
18846 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18847 	if (!func)
18848 		goto out_undo_insn;
18849 
18850 	for (i = 0; i < env->subprog_cnt; i++) {
18851 		subprog_start = subprog_end;
18852 		subprog_end = env->subprog_info[i + 1].start;
18853 
18854 		len = subprog_end - subprog_start;
18855 		/* bpf_prog_run() doesn't call subprogs directly,
18856 		 * hence main prog stats include the runtime of subprogs.
18857 		 * subprogs don't have IDs and not reachable via prog_get_next_id
18858 		 * func[i]->stats will never be accessed and stays NULL
18859 		 */
18860 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18861 		if (!func[i])
18862 			goto out_free;
18863 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18864 		       len * sizeof(struct bpf_insn));
18865 		func[i]->type = prog->type;
18866 		func[i]->len = len;
18867 		if (bpf_prog_calc_tag(func[i]))
18868 			goto out_free;
18869 		func[i]->is_func = 1;
18870 		func[i]->aux->func_idx = i;
18871 		/* Below members will be freed only at prog->aux */
18872 		func[i]->aux->btf = prog->aux->btf;
18873 		func[i]->aux->func_info = prog->aux->func_info;
18874 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18875 		func[i]->aux->poke_tab = prog->aux->poke_tab;
18876 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18877 
18878 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
18879 			struct bpf_jit_poke_descriptor *poke;
18880 
18881 			poke = &prog->aux->poke_tab[j];
18882 			if (poke->insn_idx < subprog_end &&
18883 			    poke->insn_idx >= subprog_start)
18884 				poke->aux = func[i]->aux;
18885 		}
18886 
18887 		func[i]->aux->name[0] = 'F';
18888 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18889 		func[i]->jit_requested = 1;
18890 		func[i]->blinding_requested = prog->blinding_requested;
18891 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18892 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18893 		func[i]->aux->linfo = prog->aux->linfo;
18894 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18895 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18896 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18897 		num_exentries = 0;
18898 		insn = func[i]->insnsi;
18899 		for (j = 0; j < func[i]->len; j++, insn++) {
18900 			if (BPF_CLASS(insn->code) == BPF_LDX &&
18901 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18902 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18903 				num_exentries++;
18904 		}
18905 		func[i]->aux->num_exentries = num_exentries;
18906 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18907 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
18908 		if (!i)
18909 			func[i]->aux->exception_boundary = env->seen_exception;
18910 		func[i] = bpf_int_jit_compile(func[i]);
18911 		if (!func[i]->jited) {
18912 			err = -ENOTSUPP;
18913 			goto out_free;
18914 		}
18915 		cond_resched();
18916 	}
18917 
18918 	/* at this point all bpf functions were successfully JITed
18919 	 * now populate all bpf_calls with correct addresses and
18920 	 * run last pass of JIT
18921 	 */
18922 	for (i = 0; i < env->subprog_cnt; i++) {
18923 		insn = func[i]->insnsi;
18924 		for (j = 0; j < func[i]->len; j++, insn++) {
18925 			if (bpf_pseudo_func(insn)) {
18926 				subprog = insn->off;
18927 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18928 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18929 				continue;
18930 			}
18931 			if (!bpf_pseudo_call(insn))
18932 				continue;
18933 			subprog = insn->off;
18934 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18935 		}
18936 
18937 		/* we use the aux data to keep a list of the start addresses
18938 		 * of the JITed images for each function in the program
18939 		 *
18940 		 * for some architectures, such as powerpc64, the imm field
18941 		 * might not be large enough to hold the offset of the start
18942 		 * address of the callee's JITed image from __bpf_call_base
18943 		 *
18944 		 * in such cases, we can lookup the start address of a callee
18945 		 * by using its subprog id, available from the off field of
18946 		 * the call instruction, as an index for this list
18947 		 */
18948 		func[i]->aux->func = func;
18949 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
18950 		func[i]->aux->real_func_cnt = env->subprog_cnt;
18951 	}
18952 	for (i = 0; i < env->subprog_cnt; i++) {
18953 		old_bpf_func = func[i]->bpf_func;
18954 		tmp = bpf_int_jit_compile(func[i]);
18955 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18956 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18957 			err = -ENOTSUPP;
18958 			goto out_free;
18959 		}
18960 		cond_resched();
18961 	}
18962 
18963 	/* finally lock prog and jit images for all functions and
18964 	 * populate kallsysm. Begin at the first subprogram, since
18965 	 * bpf_prog_load will add the kallsyms for the main program.
18966 	 */
18967 	for (i = 1; i < env->subprog_cnt; i++) {
18968 		bpf_prog_lock_ro(func[i]);
18969 		bpf_prog_kallsyms_add(func[i]);
18970 	}
18971 
18972 	/* Last step: make now unused interpreter insns from main
18973 	 * prog consistent for later dump requests, so they can
18974 	 * later look the same as if they were interpreted only.
18975 	 */
18976 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18977 		if (bpf_pseudo_func(insn)) {
18978 			insn[0].imm = env->insn_aux_data[i].call_imm;
18979 			insn[1].imm = insn->off;
18980 			insn->off = 0;
18981 			continue;
18982 		}
18983 		if (!bpf_pseudo_call(insn))
18984 			continue;
18985 		insn->off = env->insn_aux_data[i].call_imm;
18986 		subprog = find_subprog(env, i + insn->off + 1);
18987 		insn->imm = subprog;
18988 	}
18989 
18990 	prog->jited = 1;
18991 	prog->bpf_func = func[0]->bpf_func;
18992 	prog->jited_len = func[0]->jited_len;
18993 	prog->aux->extable = func[0]->aux->extable;
18994 	prog->aux->num_exentries = func[0]->aux->num_exentries;
18995 	prog->aux->func = func;
18996 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
18997 	prog->aux->real_func_cnt = env->subprog_cnt;
18998 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
18999 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
19000 	bpf_prog_jit_attempt_done(prog);
19001 	return 0;
19002 out_free:
19003 	/* We failed JIT'ing, so at this point we need to unregister poke
19004 	 * descriptors from subprogs, so that kernel is not attempting to
19005 	 * patch it anymore as we're freeing the subprog JIT memory.
19006 	 */
19007 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19008 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19009 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
19010 	}
19011 	/* At this point we're guaranteed that poke descriptors are not
19012 	 * live anymore. We can just unlink its descriptor table as it's
19013 	 * released with the main prog.
19014 	 */
19015 	for (i = 0; i < env->subprog_cnt; i++) {
19016 		if (!func[i])
19017 			continue;
19018 		func[i]->aux->poke_tab = NULL;
19019 		bpf_jit_free(func[i]);
19020 	}
19021 	kfree(func);
19022 out_undo_insn:
19023 	/* cleanup main prog to be interpreted */
19024 	prog->jit_requested = 0;
19025 	prog->blinding_requested = 0;
19026 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19027 		if (!bpf_pseudo_call(insn))
19028 			continue;
19029 		insn->off = 0;
19030 		insn->imm = env->insn_aux_data[i].call_imm;
19031 	}
19032 	bpf_prog_jit_attempt_done(prog);
19033 	return err;
19034 }
19035 
19036 static int fixup_call_args(struct bpf_verifier_env *env)
19037 {
19038 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19039 	struct bpf_prog *prog = env->prog;
19040 	struct bpf_insn *insn = prog->insnsi;
19041 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
19042 	int i, depth;
19043 #endif
19044 	int err = 0;
19045 
19046 	if (env->prog->jit_requested &&
19047 	    !bpf_prog_is_offloaded(env->prog->aux)) {
19048 		err = jit_subprogs(env);
19049 		if (err == 0)
19050 			return 0;
19051 		if (err == -EFAULT)
19052 			return err;
19053 	}
19054 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19055 	if (has_kfunc_call) {
19056 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
19057 		return -EINVAL;
19058 	}
19059 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
19060 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
19061 		 * have to be rejected, since interpreter doesn't support them yet.
19062 		 */
19063 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
19064 		return -EINVAL;
19065 	}
19066 	for (i = 0; i < prog->len; i++, insn++) {
19067 		if (bpf_pseudo_func(insn)) {
19068 			/* When JIT fails the progs with callback calls
19069 			 * have to be rejected, since interpreter doesn't support them yet.
19070 			 */
19071 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
19072 			return -EINVAL;
19073 		}
19074 
19075 		if (!bpf_pseudo_call(insn))
19076 			continue;
19077 		depth = get_callee_stack_depth(env, insn, i);
19078 		if (depth < 0)
19079 			return depth;
19080 		bpf_patch_call_args(insn, depth);
19081 	}
19082 	err = 0;
19083 #endif
19084 	return err;
19085 }
19086 
19087 /* replace a generic kfunc with a specialized version if necessary */
19088 static void specialize_kfunc(struct bpf_verifier_env *env,
19089 			     u32 func_id, u16 offset, unsigned long *addr)
19090 {
19091 	struct bpf_prog *prog = env->prog;
19092 	bool seen_direct_write;
19093 	void *xdp_kfunc;
19094 	bool is_rdonly;
19095 
19096 	if (bpf_dev_bound_kfunc_id(func_id)) {
19097 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
19098 		if (xdp_kfunc) {
19099 			*addr = (unsigned long)xdp_kfunc;
19100 			return;
19101 		}
19102 		/* fallback to default kfunc when not supported by netdev */
19103 	}
19104 
19105 	if (offset)
19106 		return;
19107 
19108 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
19109 		seen_direct_write = env->seen_direct_write;
19110 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
19111 
19112 		if (is_rdonly)
19113 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
19114 
19115 		/* restore env->seen_direct_write to its original value, since
19116 		 * may_access_direct_pkt_data mutates it
19117 		 */
19118 		env->seen_direct_write = seen_direct_write;
19119 	}
19120 }
19121 
19122 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
19123 					    u16 struct_meta_reg,
19124 					    u16 node_offset_reg,
19125 					    struct bpf_insn *insn,
19126 					    struct bpf_insn *insn_buf,
19127 					    int *cnt)
19128 {
19129 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
19130 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
19131 
19132 	insn_buf[0] = addr[0];
19133 	insn_buf[1] = addr[1];
19134 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
19135 	insn_buf[3] = *insn;
19136 	*cnt = 4;
19137 }
19138 
19139 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
19140 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
19141 {
19142 	const struct bpf_kfunc_desc *desc;
19143 
19144 	if (!insn->imm) {
19145 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
19146 		return -EINVAL;
19147 	}
19148 
19149 	*cnt = 0;
19150 
19151 	/* insn->imm has the btf func_id. Replace it with an offset relative to
19152 	 * __bpf_call_base, unless the JIT needs to call functions that are
19153 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
19154 	 */
19155 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
19156 	if (!desc) {
19157 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
19158 			insn->imm);
19159 		return -EFAULT;
19160 	}
19161 
19162 	if (!bpf_jit_supports_far_kfunc_call())
19163 		insn->imm = BPF_CALL_IMM(desc->addr);
19164 	if (insn->off)
19165 		return 0;
19166 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
19167 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
19168 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19169 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19170 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
19171 
19172 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
19173 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19174 				insn_idx);
19175 			return -EFAULT;
19176 		}
19177 
19178 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
19179 		insn_buf[1] = addr[0];
19180 		insn_buf[2] = addr[1];
19181 		insn_buf[3] = *insn;
19182 		*cnt = 4;
19183 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
19184 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
19185 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
19186 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19187 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19188 
19189 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
19190 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19191 				insn_idx);
19192 			return -EFAULT;
19193 		}
19194 
19195 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
19196 		    !kptr_struct_meta) {
19197 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19198 				insn_idx);
19199 			return -EFAULT;
19200 		}
19201 
19202 		insn_buf[0] = addr[0];
19203 		insn_buf[1] = addr[1];
19204 		insn_buf[2] = *insn;
19205 		*cnt = 3;
19206 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
19207 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
19208 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19209 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19210 		int struct_meta_reg = BPF_REG_3;
19211 		int node_offset_reg = BPF_REG_4;
19212 
19213 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
19214 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19215 			struct_meta_reg = BPF_REG_4;
19216 			node_offset_reg = BPF_REG_5;
19217 		}
19218 
19219 		if (!kptr_struct_meta) {
19220 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19221 				insn_idx);
19222 			return -EFAULT;
19223 		}
19224 
19225 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
19226 						node_offset_reg, insn, insn_buf, cnt);
19227 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
19228 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
19229 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
19230 		*cnt = 1;
19231 	}
19232 	return 0;
19233 }
19234 
19235 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
19236 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
19237 {
19238 	struct bpf_subprog_info *info = env->subprog_info;
19239 	int cnt = env->subprog_cnt;
19240 	struct bpf_prog *prog;
19241 
19242 	/* We only reserve one slot for hidden subprogs in subprog_info. */
19243 	if (env->hidden_subprog_cnt) {
19244 		verbose(env, "verifier internal error: only one hidden subprog supported\n");
19245 		return -EFAULT;
19246 	}
19247 	/* We're not patching any existing instruction, just appending the new
19248 	 * ones for the hidden subprog. Hence all of the adjustment operations
19249 	 * in bpf_patch_insn_data are no-ops.
19250 	 */
19251 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
19252 	if (!prog)
19253 		return -ENOMEM;
19254 	env->prog = prog;
19255 	info[cnt + 1].start = info[cnt].start;
19256 	info[cnt].start = prog->len - len + 1;
19257 	env->subprog_cnt++;
19258 	env->hidden_subprog_cnt++;
19259 	return 0;
19260 }
19261 
19262 /* Do various post-verification rewrites in a single program pass.
19263  * These rewrites simplify JIT and interpreter implementations.
19264  */
19265 static int do_misc_fixups(struct bpf_verifier_env *env)
19266 {
19267 	struct bpf_prog *prog = env->prog;
19268 	enum bpf_attach_type eatype = prog->expected_attach_type;
19269 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
19270 	struct bpf_insn *insn = prog->insnsi;
19271 	const struct bpf_func_proto *fn;
19272 	const int insn_cnt = prog->len;
19273 	const struct bpf_map_ops *ops;
19274 	struct bpf_insn_aux_data *aux;
19275 	struct bpf_insn insn_buf[16];
19276 	struct bpf_prog *new_prog;
19277 	struct bpf_map *map_ptr;
19278 	int i, ret, cnt, delta = 0;
19279 
19280 	if (env->seen_exception && !env->exception_callback_subprog) {
19281 		struct bpf_insn patch[] = {
19282 			env->prog->insnsi[insn_cnt - 1],
19283 			BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
19284 			BPF_EXIT_INSN(),
19285 		};
19286 
19287 		ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
19288 		if (ret < 0)
19289 			return ret;
19290 		prog = env->prog;
19291 		insn = prog->insnsi;
19292 
19293 		env->exception_callback_subprog = env->subprog_cnt - 1;
19294 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
19295 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
19296 	}
19297 
19298 	for (i = 0; i < insn_cnt; i++, insn++) {
19299 		/* Make divide-by-zero exceptions impossible. */
19300 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
19301 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
19302 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
19303 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
19304 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
19305 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
19306 			struct bpf_insn *patchlet;
19307 			struct bpf_insn chk_and_div[] = {
19308 				/* [R,W]x div 0 -> 0 */
19309 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19310 					     BPF_JNE | BPF_K, insn->src_reg,
19311 					     0, 2, 0),
19312 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
19313 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19314 				*insn,
19315 			};
19316 			struct bpf_insn chk_and_mod[] = {
19317 				/* [R,W]x mod 0 -> [R,W]x */
19318 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19319 					     BPF_JEQ | BPF_K, insn->src_reg,
19320 					     0, 1 + (is64 ? 0 : 1), 0),
19321 				*insn,
19322 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19323 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
19324 			};
19325 
19326 			patchlet = isdiv ? chk_and_div : chk_and_mod;
19327 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
19328 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
19329 
19330 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
19331 			if (!new_prog)
19332 				return -ENOMEM;
19333 
19334 			delta    += cnt - 1;
19335 			env->prog = prog = new_prog;
19336 			insn      = new_prog->insnsi + i + delta;
19337 			continue;
19338 		}
19339 
19340 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
19341 		if (BPF_CLASS(insn->code) == BPF_LD &&
19342 		    (BPF_MODE(insn->code) == BPF_ABS ||
19343 		     BPF_MODE(insn->code) == BPF_IND)) {
19344 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
19345 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19346 				verbose(env, "bpf verifier is misconfigured\n");
19347 				return -EINVAL;
19348 			}
19349 
19350 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19351 			if (!new_prog)
19352 				return -ENOMEM;
19353 
19354 			delta    += cnt - 1;
19355 			env->prog = prog = new_prog;
19356 			insn      = new_prog->insnsi + i + delta;
19357 			continue;
19358 		}
19359 
19360 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
19361 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
19362 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
19363 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
19364 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
19365 			struct bpf_insn *patch = &insn_buf[0];
19366 			bool issrc, isneg, isimm;
19367 			u32 off_reg;
19368 
19369 			aux = &env->insn_aux_data[i + delta];
19370 			if (!aux->alu_state ||
19371 			    aux->alu_state == BPF_ALU_NON_POINTER)
19372 				continue;
19373 
19374 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
19375 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
19376 				BPF_ALU_SANITIZE_SRC;
19377 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
19378 
19379 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
19380 			if (isimm) {
19381 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19382 			} else {
19383 				if (isneg)
19384 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19385 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19386 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
19387 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
19388 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
19389 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
19390 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
19391 			}
19392 			if (!issrc)
19393 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
19394 			insn->src_reg = BPF_REG_AX;
19395 			if (isneg)
19396 				insn->code = insn->code == code_add ?
19397 					     code_sub : code_add;
19398 			*patch++ = *insn;
19399 			if (issrc && isneg && !isimm)
19400 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19401 			cnt = patch - insn_buf;
19402 
19403 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19404 			if (!new_prog)
19405 				return -ENOMEM;
19406 
19407 			delta    += cnt - 1;
19408 			env->prog = prog = new_prog;
19409 			insn      = new_prog->insnsi + i + delta;
19410 			continue;
19411 		}
19412 
19413 		if (insn->code != (BPF_JMP | BPF_CALL))
19414 			continue;
19415 		if (insn->src_reg == BPF_PSEUDO_CALL)
19416 			continue;
19417 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19418 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19419 			if (ret)
19420 				return ret;
19421 			if (cnt == 0)
19422 				continue;
19423 
19424 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19425 			if (!new_prog)
19426 				return -ENOMEM;
19427 
19428 			delta	 += cnt - 1;
19429 			env->prog = prog = new_prog;
19430 			insn	  = new_prog->insnsi + i + delta;
19431 			continue;
19432 		}
19433 
19434 		if (insn->imm == BPF_FUNC_get_route_realm)
19435 			prog->dst_needed = 1;
19436 		if (insn->imm == BPF_FUNC_get_prandom_u32)
19437 			bpf_user_rnd_init_once();
19438 		if (insn->imm == BPF_FUNC_override_return)
19439 			prog->kprobe_override = 1;
19440 		if (insn->imm == BPF_FUNC_tail_call) {
19441 			/* If we tail call into other programs, we
19442 			 * cannot make any assumptions since they can
19443 			 * be replaced dynamically during runtime in
19444 			 * the program array.
19445 			 */
19446 			prog->cb_access = 1;
19447 			if (!allow_tail_call_in_subprogs(env))
19448 				prog->aux->stack_depth = MAX_BPF_STACK;
19449 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19450 
19451 			/* mark bpf_tail_call as different opcode to avoid
19452 			 * conditional branch in the interpreter for every normal
19453 			 * call and to prevent accidental JITing by JIT compiler
19454 			 * that doesn't support bpf_tail_call yet
19455 			 */
19456 			insn->imm = 0;
19457 			insn->code = BPF_JMP | BPF_TAIL_CALL;
19458 
19459 			aux = &env->insn_aux_data[i + delta];
19460 			if (env->bpf_capable && !prog->blinding_requested &&
19461 			    prog->jit_requested &&
19462 			    !bpf_map_key_poisoned(aux) &&
19463 			    !bpf_map_ptr_poisoned(aux) &&
19464 			    !bpf_map_ptr_unpriv(aux)) {
19465 				struct bpf_jit_poke_descriptor desc = {
19466 					.reason = BPF_POKE_REASON_TAIL_CALL,
19467 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19468 					.tail_call.key = bpf_map_key_immediate(aux),
19469 					.insn_idx = i + delta,
19470 				};
19471 
19472 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
19473 				if (ret < 0) {
19474 					verbose(env, "adding tail call poke descriptor failed\n");
19475 					return ret;
19476 				}
19477 
19478 				insn->imm = ret + 1;
19479 				continue;
19480 			}
19481 
19482 			if (!bpf_map_ptr_unpriv(aux))
19483 				continue;
19484 
19485 			/* instead of changing every JIT dealing with tail_call
19486 			 * emit two extra insns:
19487 			 * if (index >= max_entries) goto out;
19488 			 * index &= array->index_mask;
19489 			 * to avoid out-of-bounds cpu speculation
19490 			 */
19491 			if (bpf_map_ptr_poisoned(aux)) {
19492 				verbose(env, "tail_call abusing map_ptr\n");
19493 				return -EINVAL;
19494 			}
19495 
19496 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19497 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19498 						  map_ptr->max_entries, 2);
19499 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19500 						    container_of(map_ptr,
19501 								 struct bpf_array,
19502 								 map)->index_mask);
19503 			insn_buf[2] = *insn;
19504 			cnt = 3;
19505 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19506 			if (!new_prog)
19507 				return -ENOMEM;
19508 
19509 			delta    += cnt - 1;
19510 			env->prog = prog = new_prog;
19511 			insn      = new_prog->insnsi + i + delta;
19512 			continue;
19513 		}
19514 
19515 		if (insn->imm == BPF_FUNC_timer_set_callback) {
19516 			/* The verifier will process callback_fn as many times as necessary
19517 			 * with different maps and the register states prepared by
19518 			 * set_timer_callback_state will be accurate.
19519 			 *
19520 			 * The following use case is valid:
19521 			 *   map1 is shared by prog1, prog2, prog3.
19522 			 *   prog1 calls bpf_timer_init for some map1 elements
19523 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
19524 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
19525 			 *   prog3 calls bpf_timer_start for some map1 elements.
19526 			 *     Those that were not both bpf_timer_init-ed and
19527 			 *     bpf_timer_set_callback-ed will return -EINVAL.
19528 			 */
19529 			struct bpf_insn ld_addrs[2] = {
19530 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19531 			};
19532 
19533 			insn_buf[0] = ld_addrs[0];
19534 			insn_buf[1] = ld_addrs[1];
19535 			insn_buf[2] = *insn;
19536 			cnt = 3;
19537 
19538 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19539 			if (!new_prog)
19540 				return -ENOMEM;
19541 
19542 			delta    += cnt - 1;
19543 			env->prog = prog = new_prog;
19544 			insn      = new_prog->insnsi + i + delta;
19545 			goto patch_call_imm;
19546 		}
19547 
19548 		if (is_storage_get_function(insn->imm)) {
19549 			if (!env->prog->aux->sleepable ||
19550 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
19551 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19552 			else
19553 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19554 			insn_buf[1] = *insn;
19555 			cnt = 2;
19556 
19557 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19558 			if (!new_prog)
19559 				return -ENOMEM;
19560 
19561 			delta += cnt - 1;
19562 			env->prog = prog = new_prog;
19563 			insn = new_prog->insnsi + i + delta;
19564 			goto patch_call_imm;
19565 		}
19566 
19567 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
19568 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
19569 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
19570 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
19571 			 */
19572 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
19573 			insn_buf[1] = *insn;
19574 			cnt = 2;
19575 
19576 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19577 			if (!new_prog)
19578 				return -ENOMEM;
19579 
19580 			delta += cnt - 1;
19581 			env->prog = prog = new_prog;
19582 			insn = new_prog->insnsi + i + delta;
19583 			goto patch_call_imm;
19584 		}
19585 
19586 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19587 		 * and other inlining handlers are currently limited to 64 bit
19588 		 * only.
19589 		 */
19590 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19591 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
19592 		     insn->imm == BPF_FUNC_map_update_elem ||
19593 		     insn->imm == BPF_FUNC_map_delete_elem ||
19594 		     insn->imm == BPF_FUNC_map_push_elem   ||
19595 		     insn->imm == BPF_FUNC_map_pop_elem    ||
19596 		     insn->imm == BPF_FUNC_map_peek_elem   ||
19597 		     insn->imm == BPF_FUNC_redirect_map    ||
19598 		     insn->imm == BPF_FUNC_for_each_map_elem ||
19599 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19600 			aux = &env->insn_aux_data[i + delta];
19601 			if (bpf_map_ptr_poisoned(aux))
19602 				goto patch_call_imm;
19603 
19604 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19605 			ops = map_ptr->ops;
19606 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
19607 			    ops->map_gen_lookup) {
19608 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19609 				if (cnt == -EOPNOTSUPP)
19610 					goto patch_map_ops_generic;
19611 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19612 					verbose(env, "bpf verifier is misconfigured\n");
19613 					return -EINVAL;
19614 				}
19615 
19616 				new_prog = bpf_patch_insn_data(env, i + delta,
19617 							       insn_buf, cnt);
19618 				if (!new_prog)
19619 					return -ENOMEM;
19620 
19621 				delta    += cnt - 1;
19622 				env->prog = prog = new_prog;
19623 				insn      = new_prog->insnsi + i + delta;
19624 				continue;
19625 			}
19626 
19627 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19628 				     (void *(*)(struct bpf_map *map, void *key))NULL));
19629 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19630 				     (long (*)(struct bpf_map *map, void *key))NULL));
19631 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19632 				     (long (*)(struct bpf_map *map, void *key, void *value,
19633 					      u64 flags))NULL));
19634 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19635 				     (long (*)(struct bpf_map *map, void *value,
19636 					      u64 flags))NULL));
19637 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19638 				     (long (*)(struct bpf_map *map, void *value))NULL));
19639 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19640 				     (long (*)(struct bpf_map *map, void *value))NULL));
19641 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
19642 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19643 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19644 				     (long (*)(struct bpf_map *map,
19645 					      bpf_callback_t callback_fn,
19646 					      void *callback_ctx,
19647 					      u64 flags))NULL));
19648 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19649 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19650 
19651 patch_map_ops_generic:
19652 			switch (insn->imm) {
19653 			case BPF_FUNC_map_lookup_elem:
19654 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19655 				continue;
19656 			case BPF_FUNC_map_update_elem:
19657 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19658 				continue;
19659 			case BPF_FUNC_map_delete_elem:
19660 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19661 				continue;
19662 			case BPF_FUNC_map_push_elem:
19663 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19664 				continue;
19665 			case BPF_FUNC_map_pop_elem:
19666 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19667 				continue;
19668 			case BPF_FUNC_map_peek_elem:
19669 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19670 				continue;
19671 			case BPF_FUNC_redirect_map:
19672 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
19673 				continue;
19674 			case BPF_FUNC_for_each_map_elem:
19675 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19676 				continue;
19677 			case BPF_FUNC_map_lookup_percpu_elem:
19678 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19679 				continue;
19680 			}
19681 
19682 			goto patch_call_imm;
19683 		}
19684 
19685 		/* Implement bpf_jiffies64 inline. */
19686 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19687 		    insn->imm == BPF_FUNC_jiffies64) {
19688 			struct bpf_insn ld_jiffies_addr[2] = {
19689 				BPF_LD_IMM64(BPF_REG_0,
19690 					     (unsigned long)&jiffies),
19691 			};
19692 
19693 			insn_buf[0] = ld_jiffies_addr[0];
19694 			insn_buf[1] = ld_jiffies_addr[1];
19695 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19696 						  BPF_REG_0, 0);
19697 			cnt = 3;
19698 
19699 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19700 						       cnt);
19701 			if (!new_prog)
19702 				return -ENOMEM;
19703 
19704 			delta    += cnt - 1;
19705 			env->prog = prog = new_prog;
19706 			insn      = new_prog->insnsi + i + delta;
19707 			continue;
19708 		}
19709 
19710 		/* Implement bpf_get_func_arg inline. */
19711 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19712 		    insn->imm == BPF_FUNC_get_func_arg) {
19713 			/* Load nr_args from ctx - 8 */
19714 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19715 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19716 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19717 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19718 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19719 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19720 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19721 			insn_buf[7] = BPF_JMP_A(1);
19722 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19723 			cnt = 9;
19724 
19725 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19726 			if (!new_prog)
19727 				return -ENOMEM;
19728 
19729 			delta    += cnt - 1;
19730 			env->prog = prog = new_prog;
19731 			insn      = new_prog->insnsi + i + delta;
19732 			continue;
19733 		}
19734 
19735 		/* Implement bpf_get_func_ret inline. */
19736 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19737 		    insn->imm == BPF_FUNC_get_func_ret) {
19738 			if (eatype == BPF_TRACE_FEXIT ||
19739 			    eatype == BPF_MODIFY_RETURN) {
19740 				/* Load nr_args from ctx - 8 */
19741 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19742 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19743 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19744 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19745 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19746 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19747 				cnt = 6;
19748 			} else {
19749 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19750 				cnt = 1;
19751 			}
19752 
19753 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19754 			if (!new_prog)
19755 				return -ENOMEM;
19756 
19757 			delta    += cnt - 1;
19758 			env->prog = prog = new_prog;
19759 			insn      = new_prog->insnsi + i + delta;
19760 			continue;
19761 		}
19762 
19763 		/* Implement get_func_arg_cnt inline. */
19764 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19765 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
19766 			/* Load nr_args from ctx - 8 */
19767 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19768 
19769 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19770 			if (!new_prog)
19771 				return -ENOMEM;
19772 
19773 			env->prog = prog = new_prog;
19774 			insn      = new_prog->insnsi + i + delta;
19775 			continue;
19776 		}
19777 
19778 		/* Implement bpf_get_func_ip inline. */
19779 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19780 		    insn->imm == BPF_FUNC_get_func_ip) {
19781 			/* Load IP address from ctx - 16 */
19782 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19783 
19784 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19785 			if (!new_prog)
19786 				return -ENOMEM;
19787 
19788 			env->prog = prog = new_prog;
19789 			insn      = new_prog->insnsi + i + delta;
19790 			continue;
19791 		}
19792 
19793 patch_call_imm:
19794 		fn = env->ops->get_func_proto(insn->imm, env->prog);
19795 		/* all functions that have prototype and verifier allowed
19796 		 * programs to call them, must be real in-kernel functions
19797 		 */
19798 		if (!fn->func) {
19799 			verbose(env,
19800 				"kernel subsystem misconfigured func %s#%d\n",
19801 				func_id_name(insn->imm), insn->imm);
19802 			return -EFAULT;
19803 		}
19804 		insn->imm = fn->func - __bpf_call_base;
19805 	}
19806 
19807 	/* Since poke tab is now finalized, publish aux to tracker. */
19808 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19809 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19810 		if (!map_ptr->ops->map_poke_track ||
19811 		    !map_ptr->ops->map_poke_untrack ||
19812 		    !map_ptr->ops->map_poke_run) {
19813 			verbose(env, "bpf verifier is misconfigured\n");
19814 			return -EINVAL;
19815 		}
19816 
19817 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19818 		if (ret < 0) {
19819 			verbose(env, "tracking tail call prog failed\n");
19820 			return ret;
19821 		}
19822 	}
19823 
19824 	sort_kfunc_descs_by_imm_off(env->prog);
19825 
19826 	return 0;
19827 }
19828 
19829 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19830 					int position,
19831 					s32 stack_base,
19832 					u32 callback_subprogno,
19833 					u32 *cnt)
19834 {
19835 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19836 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19837 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19838 	int reg_loop_max = BPF_REG_6;
19839 	int reg_loop_cnt = BPF_REG_7;
19840 	int reg_loop_ctx = BPF_REG_8;
19841 
19842 	struct bpf_prog *new_prog;
19843 	u32 callback_start;
19844 	u32 call_insn_offset;
19845 	s32 callback_offset;
19846 
19847 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
19848 	 * be careful to modify this code in sync.
19849 	 */
19850 	struct bpf_insn insn_buf[] = {
19851 		/* Return error and jump to the end of the patch if
19852 		 * expected number of iterations is too big.
19853 		 */
19854 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19855 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19856 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19857 		/* spill R6, R7, R8 to use these as loop vars */
19858 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19859 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19860 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19861 		/* initialize loop vars */
19862 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19863 		BPF_MOV32_IMM(reg_loop_cnt, 0),
19864 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19865 		/* loop header,
19866 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
19867 		 */
19868 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19869 		/* callback call,
19870 		 * correct callback offset would be set after patching
19871 		 */
19872 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19873 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19874 		BPF_CALL_REL(0),
19875 		/* increment loop counter */
19876 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19877 		/* jump to loop header if callback returned 0 */
19878 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19879 		/* return value of bpf_loop,
19880 		 * set R0 to the number of iterations
19881 		 */
19882 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19883 		/* restore original values of R6, R7, R8 */
19884 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19885 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19886 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19887 	};
19888 
19889 	*cnt = ARRAY_SIZE(insn_buf);
19890 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19891 	if (!new_prog)
19892 		return new_prog;
19893 
19894 	/* callback start is known only after patching */
19895 	callback_start = env->subprog_info[callback_subprogno].start;
19896 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19897 	call_insn_offset = position + 12;
19898 	callback_offset = callback_start - call_insn_offset - 1;
19899 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
19900 
19901 	return new_prog;
19902 }
19903 
19904 static bool is_bpf_loop_call(struct bpf_insn *insn)
19905 {
19906 	return insn->code == (BPF_JMP | BPF_CALL) &&
19907 		insn->src_reg == 0 &&
19908 		insn->imm == BPF_FUNC_loop;
19909 }
19910 
19911 /* For all sub-programs in the program (including main) check
19912  * insn_aux_data to see if there are bpf_loop calls that require
19913  * inlining. If such calls are found the calls are replaced with a
19914  * sequence of instructions produced by `inline_bpf_loop` function and
19915  * subprog stack_depth is increased by the size of 3 registers.
19916  * This stack space is used to spill values of the R6, R7, R8.  These
19917  * registers are used to store the loop bound, counter and context
19918  * variables.
19919  */
19920 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19921 {
19922 	struct bpf_subprog_info *subprogs = env->subprog_info;
19923 	int i, cur_subprog = 0, cnt, delta = 0;
19924 	struct bpf_insn *insn = env->prog->insnsi;
19925 	int insn_cnt = env->prog->len;
19926 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
19927 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19928 	u16 stack_depth_extra = 0;
19929 
19930 	for (i = 0; i < insn_cnt; i++, insn++) {
19931 		struct bpf_loop_inline_state *inline_state =
19932 			&env->insn_aux_data[i + delta].loop_inline_state;
19933 
19934 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19935 			struct bpf_prog *new_prog;
19936 
19937 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19938 			new_prog = inline_bpf_loop(env,
19939 						   i + delta,
19940 						   -(stack_depth + stack_depth_extra),
19941 						   inline_state->callback_subprogno,
19942 						   &cnt);
19943 			if (!new_prog)
19944 				return -ENOMEM;
19945 
19946 			delta     += cnt - 1;
19947 			env->prog  = new_prog;
19948 			insn       = new_prog->insnsi + i + delta;
19949 		}
19950 
19951 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19952 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
19953 			cur_subprog++;
19954 			stack_depth = subprogs[cur_subprog].stack_depth;
19955 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19956 			stack_depth_extra = 0;
19957 		}
19958 	}
19959 
19960 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19961 
19962 	return 0;
19963 }
19964 
19965 static void free_states(struct bpf_verifier_env *env)
19966 {
19967 	struct bpf_verifier_state_list *sl, *sln;
19968 	int i;
19969 
19970 	sl = env->free_list;
19971 	while (sl) {
19972 		sln = sl->next;
19973 		free_verifier_state(&sl->state, false);
19974 		kfree(sl);
19975 		sl = sln;
19976 	}
19977 	env->free_list = NULL;
19978 
19979 	if (!env->explored_states)
19980 		return;
19981 
19982 	for (i = 0; i < state_htab_size(env); i++) {
19983 		sl = env->explored_states[i];
19984 
19985 		while (sl) {
19986 			sln = sl->next;
19987 			free_verifier_state(&sl->state, false);
19988 			kfree(sl);
19989 			sl = sln;
19990 		}
19991 		env->explored_states[i] = NULL;
19992 	}
19993 }
19994 
19995 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19996 {
19997 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19998 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
19999 	struct bpf_verifier_state *state;
20000 	struct bpf_reg_state *regs;
20001 	int ret, i;
20002 
20003 	env->prev_linfo = NULL;
20004 	env->pass_cnt++;
20005 
20006 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
20007 	if (!state)
20008 		return -ENOMEM;
20009 	state->curframe = 0;
20010 	state->speculative = false;
20011 	state->branches = 1;
20012 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
20013 	if (!state->frame[0]) {
20014 		kfree(state);
20015 		return -ENOMEM;
20016 	}
20017 	env->cur_state = state;
20018 	init_func_state(env, state->frame[0],
20019 			BPF_MAIN_FUNC /* callsite */,
20020 			0 /* frameno */,
20021 			subprog);
20022 	state->first_insn_idx = env->subprog_info[subprog].start;
20023 	state->last_insn_idx = -1;
20024 
20025 
20026 	regs = state->frame[state->curframe]->regs;
20027 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
20028 		const char *sub_name = subprog_name(env, subprog);
20029 		struct bpf_subprog_arg_info *arg;
20030 		struct bpf_reg_state *reg;
20031 
20032 		verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
20033 		ret = btf_prepare_func_args(env, subprog);
20034 		if (ret)
20035 			goto out;
20036 
20037 		if (subprog_is_exc_cb(env, subprog)) {
20038 			state->frame[0]->in_exception_callback_fn = true;
20039 			/* We have already ensured that the callback returns an integer, just
20040 			 * like all global subprogs. We need to determine it only has a single
20041 			 * scalar argument.
20042 			 */
20043 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
20044 				verbose(env, "exception cb only supports single integer argument\n");
20045 				ret = -EINVAL;
20046 				goto out;
20047 			}
20048 		}
20049 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
20050 			arg = &sub->args[i - BPF_REG_1];
20051 			reg = &regs[i];
20052 
20053 			if (arg->arg_type == ARG_PTR_TO_CTX) {
20054 				reg->type = PTR_TO_CTX;
20055 				mark_reg_known_zero(env, regs, i);
20056 			} else if (arg->arg_type == ARG_ANYTHING) {
20057 				reg->type = SCALAR_VALUE;
20058 				mark_reg_unknown(env, regs, i);
20059 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
20060 				/* assume unspecial LOCAL dynptr type */
20061 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
20062 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
20063 				reg->type = PTR_TO_MEM;
20064 				if (arg->arg_type & PTR_MAYBE_NULL)
20065 					reg->type |= PTR_MAYBE_NULL;
20066 				mark_reg_known_zero(env, regs, i);
20067 				reg->mem_size = arg->mem_size;
20068 				reg->id = ++env->id_gen;
20069 			} else {
20070 				WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
20071 					  i - BPF_REG_1, arg->arg_type);
20072 				ret = -EFAULT;
20073 				goto out;
20074 			}
20075 		}
20076 	} else {
20077 		/* if main BPF program has associated BTF info, validate that
20078 		 * it's matching expected signature, and otherwise mark BTF
20079 		 * info for main program as unreliable
20080 		 */
20081 		if (env->prog->aux->func_info_aux) {
20082 			ret = btf_prepare_func_args(env, 0);
20083 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
20084 				env->prog->aux->func_info_aux[0].unreliable = true;
20085 		}
20086 
20087 		/* 1st arg to a function */
20088 		regs[BPF_REG_1].type = PTR_TO_CTX;
20089 		mark_reg_known_zero(env, regs, BPF_REG_1);
20090 	}
20091 
20092 	ret = do_check(env);
20093 out:
20094 	/* check for NULL is necessary, since cur_state can be freed inside
20095 	 * do_check() under memory pressure.
20096 	 */
20097 	if (env->cur_state) {
20098 		free_verifier_state(env->cur_state, true);
20099 		env->cur_state = NULL;
20100 	}
20101 	while (!pop_stack(env, NULL, NULL, false));
20102 	if (!ret && pop_log)
20103 		bpf_vlog_reset(&env->log, 0);
20104 	free_states(env);
20105 	return ret;
20106 }
20107 
20108 /* Lazily verify all global functions based on their BTF, if they are called
20109  * from main BPF program or any of subprograms transitively.
20110  * BPF global subprogs called from dead code are not validated.
20111  * All callable global functions must pass verification.
20112  * Otherwise the whole program is rejected.
20113  * Consider:
20114  * int bar(int);
20115  * int foo(int f)
20116  * {
20117  *    return bar(f);
20118  * }
20119  * int bar(int b)
20120  * {
20121  *    ...
20122  * }
20123  * foo() will be verified first for R1=any_scalar_value. During verification it
20124  * will be assumed that bar() already verified successfully and call to bar()
20125  * from foo() will be checked for type match only. Later bar() will be verified
20126  * independently to check that it's safe for R1=any_scalar_value.
20127  */
20128 static int do_check_subprogs(struct bpf_verifier_env *env)
20129 {
20130 	struct bpf_prog_aux *aux = env->prog->aux;
20131 	struct bpf_func_info_aux *sub_aux;
20132 	int i, ret, new_cnt;
20133 
20134 	if (!aux->func_info)
20135 		return 0;
20136 
20137 	/* exception callback is presumed to be always called */
20138 	if (env->exception_callback_subprog)
20139 		subprog_aux(env, env->exception_callback_subprog)->called = true;
20140 
20141 again:
20142 	new_cnt = 0;
20143 	for (i = 1; i < env->subprog_cnt; i++) {
20144 		if (!subprog_is_global(env, i))
20145 			continue;
20146 
20147 		sub_aux = subprog_aux(env, i);
20148 		if (!sub_aux->called || sub_aux->verified)
20149 			continue;
20150 
20151 		env->insn_idx = env->subprog_info[i].start;
20152 		WARN_ON_ONCE(env->insn_idx == 0);
20153 		ret = do_check_common(env, i);
20154 		if (ret) {
20155 			return ret;
20156 		} else if (env->log.level & BPF_LOG_LEVEL) {
20157 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
20158 				i, subprog_name(env, i));
20159 		}
20160 
20161 		/* We verified new global subprog, it might have called some
20162 		 * more global subprogs that we haven't verified yet, so we
20163 		 * need to do another pass over subprogs to verify those.
20164 		 */
20165 		sub_aux->verified = true;
20166 		new_cnt++;
20167 	}
20168 
20169 	/* We can't loop forever as we verify at least one global subprog on
20170 	 * each pass.
20171 	 */
20172 	if (new_cnt)
20173 		goto again;
20174 
20175 	return 0;
20176 }
20177 
20178 static int do_check_main(struct bpf_verifier_env *env)
20179 {
20180 	int ret;
20181 
20182 	env->insn_idx = 0;
20183 	ret = do_check_common(env, 0);
20184 	if (!ret)
20185 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20186 	return ret;
20187 }
20188 
20189 
20190 static void print_verification_stats(struct bpf_verifier_env *env)
20191 {
20192 	int i;
20193 
20194 	if (env->log.level & BPF_LOG_STATS) {
20195 		verbose(env, "verification time %lld usec\n",
20196 			div_u64(env->verification_time, 1000));
20197 		verbose(env, "stack depth ");
20198 		for (i = 0; i < env->subprog_cnt; i++) {
20199 			u32 depth = env->subprog_info[i].stack_depth;
20200 
20201 			verbose(env, "%d", depth);
20202 			if (i + 1 < env->subprog_cnt)
20203 				verbose(env, "+");
20204 		}
20205 		verbose(env, "\n");
20206 	}
20207 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
20208 		"total_states %d peak_states %d mark_read %d\n",
20209 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
20210 		env->max_states_per_insn, env->total_states,
20211 		env->peak_states, env->longest_mark_read_walk);
20212 }
20213 
20214 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
20215 {
20216 	const struct btf_type *t, *func_proto;
20217 	const struct bpf_struct_ops *st_ops;
20218 	const struct btf_member *member;
20219 	struct bpf_prog *prog = env->prog;
20220 	u32 btf_id, member_idx;
20221 	const char *mname;
20222 
20223 	if (!prog->gpl_compatible) {
20224 		verbose(env, "struct ops programs must have a GPL compatible license\n");
20225 		return -EINVAL;
20226 	}
20227 
20228 	btf_id = prog->aux->attach_btf_id;
20229 	st_ops = bpf_struct_ops_find(btf_id);
20230 	if (!st_ops) {
20231 		verbose(env, "attach_btf_id %u is not a supported struct\n",
20232 			btf_id);
20233 		return -ENOTSUPP;
20234 	}
20235 
20236 	t = st_ops->type;
20237 	member_idx = prog->expected_attach_type;
20238 	if (member_idx >= btf_type_vlen(t)) {
20239 		verbose(env, "attach to invalid member idx %u of struct %s\n",
20240 			member_idx, st_ops->name);
20241 		return -EINVAL;
20242 	}
20243 
20244 	member = &btf_type_member(t)[member_idx];
20245 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
20246 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
20247 					       NULL);
20248 	if (!func_proto) {
20249 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
20250 			mname, member_idx, st_ops->name);
20251 		return -EINVAL;
20252 	}
20253 
20254 	if (st_ops->check_member) {
20255 		int err = st_ops->check_member(t, member, prog);
20256 
20257 		if (err) {
20258 			verbose(env, "attach to unsupported member %s of struct %s\n",
20259 				mname, st_ops->name);
20260 			return err;
20261 		}
20262 	}
20263 
20264 	prog->aux->attach_func_proto = func_proto;
20265 	prog->aux->attach_func_name = mname;
20266 	env->ops = st_ops->verifier_ops;
20267 
20268 	return 0;
20269 }
20270 #define SECURITY_PREFIX "security_"
20271 
20272 static int check_attach_modify_return(unsigned long addr, const char *func_name)
20273 {
20274 	if (within_error_injection_list(addr) ||
20275 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
20276 		return 0;
20277 
20278 	return -EINVAL;
20279 }
20280 
20281 /* list of non-sleepable functions that are otherwise on
20282  * ALLOW_ERROR_INJECTION list
20283  */
20284 BTF_SET_START(btf_non_sleepable_error_inject)
20285 /* Three functions below can be called from sleepable and non-sleepable context.
20286  * Assume non-sleepable from bpf safety point of view.
20287  */
20288 BTF_ID(func, __filemap_add_folio)
20289 BTF_ID(func, should_fail_alloc_page)
20290 BTF_ID(func, should_failslab)
20291 BTF_SET_END(btf_non_sleepable_error_inject)
20292 
20293 static int check_non_sleepable_error_inject(u32 btf_id)
20294 {
20295 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
20296 }
20297 
20298 int bpf_check_attach_target(struct bpf_verifier_log *log,
20299 			    const struct bpf_prog *prog,
20300 			    const struct bpf_prog *tgt_prog,
20301 			    u32 btf_id,
20302 			    struct bpf_attach_target_info *tgt_info)
20303 {
20304 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
20305 	const char prefix[] = "btf_trace_";
20306 	int ret = 0, subprog = -1, i;
20307 	const struct btf_type *t;
20308 	bool conservative = true;
20309 	const char *tname;
20310 	struct btf *btf;
20311 	long addr = 0;
20312 	struct module *mod = NULL;
20313 
20314 	if (!btf_id) {
20315 		bpf_log(log, "Tracing programs must provide btf_id\n");
20316 		return -EINVAL;
20317 	}
20318 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
20319 	if (!btf) {
20320 		bpf_log(log,
20321 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
20322 		return -EINVAL;
20323 	}
20324 	t = btf_type_by_id(btf, btf_id);
20325 	if (!t) {
20326 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
20327 		return -EINVAL;
20328 	}
20329 	tname = btf_name_by_offset(btf, t->name_off);
20330 	if (!tname) {
20331 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
20332 		return -EINVAL;
20333 	}
20334 	if (tgt_prog) {
20335 		struct bpf_prog_aux *aux = tgt_prog->aux;
20336 
20337 		if (bpf_prog_is_dev_bound(prog->aux) &&
20338 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
20339 			bpf_log(log, "Target program bound device mismatch");
20340 			return -EINVAL;
20341 		}
20342 
20343 		for (i = 0; i < aux->func_info_cnt; i++)
20344 			if (aux->func_info[i].type_id == btf_id) {
20345 				subprog = i;
20346 				break;
20347 			}
20348 		if (subprog == -1) {
20349 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
20350 			return -EINVAL;
20351 		}
20352 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
20353 			bpf_log(log,
20354 				"%s programs cannot attach to exception callback\n",
20355 				prog_extension ? "Extension" : "FENTRY/FEXIT");
20356 			return -EINVAL;
20357 		}
20358 		conservative = aux->func_info_aux[subprog].unreliable;
20359 		if (prog_extension) {
20360 			if (conservative) {
20361 				bpf_log(log,
20362 					"Cannot replace static functions\n");
20363 				return -EINVAL;
20364 			}
20365 			if (!prog->jit_requested) {
20366 				bpf_log(log,
20367 					"Extension programs should be JITed\n");
20368 				return -EINVAL;
20369 			}
20370 		}
20371 		if (!tgt_prog->jited) {
20372 			bpf_log(log, "Can attach to only JITed progs\n");
20373 			return -EINVAL;
20374 		}
20375 		if (tgt_prog->type == prog->type) {
20376 			/* Cannot fentry/fexit another fentry/fexit program.
20377 			 * Cannot attach program extension to another extension.
20378 			 * It's ok to attach fentry/fexit to extension program.
20379 			 */
20380 			bpf_log(log, "Cannot recursively attach\n");
20381 			return -EINVAL;
20382 		}
20383 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
20384 		    prog_extension &&
20385 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
20386 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
20387 			/* Program extensions can extend all program types
20388 			 * except fentry/fexit. The reason is the following.
20389 			 * The fentry/fexit programs are used for performance
20390 			 * analysis, stats and can be attached to any program
20391 			 * type except themselves. When extension program is
20392 			 * replacing XDP function it is necessary to allow
20393 			 * performance analysis of all functions. Both original
20394 			 * XDP program and its program extension. Hence
20395 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
20396 			 * allowed. If extending of fentry/fexit was allowed it
20397 			 * would be possible to create long call chain
20398 			 * fentry->extension->fentry->extension beyond
20399 			 * reasonable stack size. Hence extending fentry is not
20400 			 * allowed.
20401 			 */
20402 			bpf_log(log, "Cannot extend fentry/fexit\n");
20403 			return -EINVAL;
20404 		}
20405 	} else {
20406 		if (prog_extension) {
20407 			bpf_log(log, "Cannot replace kernel functions\n");
20408 			return -EINVAL;
20409 		}
20410 	}
20411 
20412 	switch (prog->expected_attach_type) {
20413 	case BPF_TRACE_RAW_TP:
20414 		if (tgt_prog) {
20415 			bpf_log(log,
20416 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
20417 			return -EINVAL;
20418 		}
20419 		if (!btf_type_is_typedef(t)) {
20420 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
20421 				btf_id);
20422 			return -EINVAL;
20423 		}
20424 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
20425 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
20426 				btf_id, tname);
20427 			return -EINVAL;
20428 		}
20429 		tname += sizeof(prefix) - 1;
20430 		t = btf_type_by_id(btf, t->type);
20431 		if (!btf_type_is_ptr(t))
20432 			/* should never happen in valid vmlinux build */
20433 			return -EINVAL;
20434 		t = btf_type_by_id(btf, t->type);
20435 		if (!btf_type_is_func_proto(t))
20436 			/* should never happen in valid vmlinux build */
20437 			return -EINVAL;
20438 
20439 		break;
20440 	case BPF_TRACE_ITER:
20441 		if (!btf_type_is_func(t)) {
20442 			bpf_log(log, "attach_btf_id %u is not a function\n",
20443 				btf_id);
20444 			return -EINVAL;
20445 		}
20446 		t = btf_type_by_id(btf, t->type);
20447 		if (!btf_type_is_func_proto(t))
20448 			return -EINVAL;
20449 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20450 		if (ret)
20451 			return ret;
20452 		break;
20453 	default:
20454 		if (!prog_extension)
20455 			return -EINVAL;
20456 		fallthrough;
20457 	case BPF_MODIFY_RETURN:
20458 	case BPF_LSM_MAC:
20459 	case BPF_LSM_CGROUP:
20460 	case BPF_TRACE_FENTRY:
20461 	case BPF_TRACE_FEXIT:
20462 		if (!btf_type_is_func(t)) {
20463 			bpf_log(log, "attach_btf_id %u is not a function\n",
20464 				btf_id);
20465 			return -EINVAL;
20466 		}
20467 		if (prog_extension &&
20468 		    btf_check_type_match(log, prog, btf, t))
20469 			return -EINVAL;
20470 		t = btf_type_by_id(btf, t->type);
20471 		if (!btf_type_is_func_proto(t))
20472 			return -EINVAL;
20473 
20474 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
20475 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
20476 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
20477 			return -EINVAL;
20478 
20479 		if (tgt_prog && conservative)
20480 			t = NULL;
20481 
20482 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20483 		if (ret < 0)
20484 			return ret;
20485 
20486 		if (tgt_prog) {
20487 			if (subprog == 0)
20488 				addr = (long) tgt_prog->bpf_func;
20489 			else
20490 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20491 		} else {
20492 			if (btf_is_module(btf)) {
20493 				mod = btf_try_get_module(btf);
20494 				if (mod)
20495 					addr = find_kallsyms_symbol_value(mod, tname);
20496 				else
20497 					addr = 0;
20498 			} else {
20499 				addr = kallsyms_lookup_name(tname);
20500 			}
20501 			if (!addr) {
20502 				module_put(mod);
20503 				bpf_log(log,
20504 					"The address of function %s cannot be found\n",
20505 					tname);
20506 				return -ENOENT;
20507 			}
20508 		}
20509 
20510 		if (prog->aux->sleepable) {
20511 			ret = -EINVAL;
20512 			switch (prog->type) {
20513 			case BPF_PROG_TYPE_TRACING:
20514 
20515 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
20516 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20517 				 */
20518 				if (!check_non_sleepable_error_inject(btf_id) &&
20519 				    within_error_injection_list(addr))
20520 					ret = 0;
20521 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
20522 				 * in the fmodret id set with the KF_SLEEPABLE flag.
20523 				 */
20524 				else {
20525 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20526 										prog);
20527 
20528 					if (flags && (*flags & KF_SLEEPABLE))
20529 						ret = 0;
20530 				}
20531 				break;
20532 			case BPF_PROG_TYPE_LSM:
20533 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
20534 				 * Only some of them are sleepable.
20535 				 */
20536 				if (bpf_lsm_is_sleepable_hook(btf_id))
20537 					ret = 0;
20538 				break;
20539 			default:
20540 				break;
20541 			}
20542 			if (ret) {
20543 				module_put(mod);
20544 				bpf_log(log, "%s is not sleepable\n", tname);
20545 				return ret;
20546 			}
20547 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20548 			if (tgt_prog) {
20549 				module_put(mod);
20550 				bpf_log(log, "can't modify return codes of BPF programs\n");
20551 				return -EINVAL;
20552 			}
20553 			ret = -EINVAL;
20554 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20555 			    !check_attach_modify_return(addr, tname))
20556 				ret = 0;
20557 			if (ret) {
20558 				module_put(mod);
20559 				bpf_log(log, "%s() is not modifiable\n", tname);
20560 				return ret;
20561 			}
20562 		}
20563 
20564 		break;
20565 	}
20566 	tgt_info->tgt_addr = addr;
20567 	tgt_info->tgt_name = tname;
20568 	tgt_info->tgt_type = t;
20569 	tgt_info->tgt_mod = mod;
20570 	return 0;
20571 }
20572 
20573 BTF_SET_START(btf_id_deny)
20574 BTF_ID_UNUSED
20575 #ifdef CONFIG_SMP
20576 BTF_ID(func, migrate_disable)
20577 BTF_ID(func, migrate_enable)
20578 #endif
20579 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20580 BTF_ID(func, rcu_read_unlock_strict)
20581 #endif
20582 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20583 BTF_ID(func, preempt_count_add)
20584 BTF_ID(func, preempt_count_sub)
20585 #endif
20586 #ifdef CONFIG_PREEMPT_RCU
20587 BTF_ID(func, __rcu_read_lock)
20588 BTF_ID(func, __rcu_read_unlock)
20589 #endif
20590 BTF_SET_END(btf_id_deny)
20591 
20592 static bool can_be_sleepable(struct bpf_prog *prog)
20593 {
20594 	if (prog->type == BPF_PROG_TYPE_TRACING) {
20595 		switch (prog->expected_attach_type) {
20596 		case BPF_TRACE_FENTRY:
20597 		case BPF_TRACE_FEXIT:
20598 		case BPF_MODIFY_RETURN:
20599 		case BPF_TRACE_ITER:
20600 			return true;
20601 		default:
20602 			return false;
20603 		}
20604 	}
20605 	return prog->type == BPF_PROG_TYPE_LSM ||
20606 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20607 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20608 }
20609 
20610 static int check_attach_btf_id(struct bpf_verifier_env *env)
20611 {
20612 	struct bpf_prog *prog = env->prog;
20613 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20614 	struct bpf_attach_target_info tgt_info = {};
20615 	u32 btf_id = prog->aux->attach_btf_id;
20616 	struct bpf_trampoline *tr;
20617 	int ret;
20618 	u64 key;
20619 
20620 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20621 		if (prog->aux->sleepable)
20622 			/* attach_btf_id checked to be zero already */
20623 			return 0;
20624 		verbose(env, "Syscall programs can only be sleepable\n");
20625 		return -EINVAL;
20626 	}
20627 
20628 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20629 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20630 		return -EINVAL;
20631 	}
20632 
20633 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20634 		return check_struct_ops_btf_id(env);
20635 
20636 	if (prog->type != BPF_PROG_TYPE_TRACING &&
20637 	    prog->type != BPF_PROG_TYPE_LSM &&
20638 	    prog->type != BPF_PROG_TYPE_EXT)
20639 		return 0;
20640 
20641 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20642 	if (ret)
20643 		return ret;
20644 
20645 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20646 		/* to make freplace equivalent to their targets, they need to
20647 		 * inherit env->ops and expected_attach_type for the rest of the
20648 		 * verification
20649 		 */
20650 		env->ops = bpf_verifier_ops[tgt_prog->type];
20651 		prog->expected_attach_type = tgt_prog->expected_attach_type;
20652 	}
20653 
20654 	/* store info about the attachment target that will be used later */
20655 	prog->aux->attach_func_proto = tgt_info.tgt_type;
20656 	prog->aux->attach_func_name = tgt_info.tgt_name;
20657 	prog->aux->mod = tgt_info.tgt_mod;
20658 
20659 	if (tgt_prog) {
20660 		prog->aux->saved_dst_prog_type = tgt_prog->type;
20661 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20662 	}
20663 
20664 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20665 		prog->aux->attach_btf_trace = true;
20666 		return 0;
20667 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20668 		if (!bpf_iter_prog_supported(prog))
20669 			return -EINVAL;
20670 		return 0;
20671 	}
20672 
20673 	if (prog->type == BPF_PROG_TYPE_LSM) {
20674 		ret = bpf_lsm_verify_prog(&env->log, prog);
20675 		if (ret < 0)
20676 			return ret;
20677 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
20678 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
20679 		return -EINVAL;
20680 	}
20681 
20682 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20683 	tr = bpf_trampoline_get(key, &tgt_info);
20684 	if (!tr)
20685 		return -ENOMEM;
20686 
20687 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20688 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20689 
20690 	prog->aux->dst_trampoline = tr;
20691 	return 0;
20692 }
20693 
20694 struct btf *bpf_get_btf_vmlinux(void)
20695 {
20696 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20697 		mutex_lock(&bpf_verifier_lock);
20698 		if (!btf_vmlinux)
20699 			btf_vmlinux = btf_parse_vmlinux();
20700 		mutex_unlock(&bpf_verifier_lock);
20701 	}
20702 	return btf_vmlinux;
20703 }
20704 
20705 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20706 {
20707 	u64 start_time = ktime_get_ns();
20708 	struct bpf_verifier_env *env;
20709 	int i, len, ret = -EINVAL, err;
20710 	u32 log_true_size;
20711 	bool is_priv;
20712 
20713 	/* no program is valid */
20714 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20715 		return -EINVAL;
20716 
20717 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
20718 	 * allocate/free it every time bpf_check() is called
20719 	 */
20720 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20721 	if (!env)
20722 		return -ENOMEM;
20723 
20724 	env->bt.env = env;
20725 
20726 	len = (*prog)->len;
20727 	env->insn_aux_data =
20728 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20729 	ret = -ENOMEM;
20730 	if (!env->insn_aux_data)
20731 		goto err_free_env;
20732 	for (i = 0; i < len; i++)
20733 		env->insn_aux_data[i].orig_idx = i;
20734 	env->prog = *prog;
20735 	env->ops = bpf_verifier_ops[env->prog->type];
20736 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20737 	is_priv = bpf_capable();
20738 
20739 	bpf_get_btf_vmlinux();
20740 
20741 	/* grab the mutex to protect few globals used by verifier */
20742 	if (!is_priv)
20743 		mutex_lock(&bpf_verifier_lock);
20744 
20745 	/* user could have requested verbose verifier output
20746 	 * and supplied buffer to store the verification trace
20747 	 */
20748 	ret = bpf_vlog_init(&env->log, attr->log_level,
20749 			    (char __user *) (unsigned long) attr->log_buf,
20750 			    attr->log_size);
20751 	if (ret)
20752 		goto err_unlock;
20753 
20754 	mark_verifier_state_clean(env);
20755 
20756 	if (IS_ERR(btf_vmlinux)) {
20757 		/* Either gcc or pahole or kernel are broken. */
20758 		verbose(env, "in-kernel BTF is malformed\n");
20759 		ret = PTR_ERR(btf_vmlinux);
20760 		goto skip_full_check;
20761 	}
20762 
20763 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20764 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20765 		env->strict_alignment = true;
20766 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20767 		env->strict_alignment = false;
20768 
20769 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20770 	env->allow_uninit_stack = bpf_allow_uninit_stack();
20771 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
20772 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
20773 	env->bpf_capable = bpf_capable();
20774 
20775 	if (is_priv)
20776 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20777 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
20778 
20779 	env->explored_states = kvcalloc(state_htab_size(env),
20780 				       sizeof(struct bpf_verifier_state_list *),
20781 				       GFP_USER);
20782 	ret = -ENOMEM;
20783 	if (!env->explored_states)
20784 		goto skip_full_check;
20785 
20786 	ret = check_btf_info_early(env, attr, uattr);
20787 	if (ret < 0)
20788 		goto skip_full_check;
20789 
20790 	ret = add_subprog_and_kfunc(env);
20791 	if (ret < 0)
20792 		goto skip_full_check;
20793 
20794 	ret = check_subprogs(env);
20795 	if (ret < 0)
20796 		goto skip_full_check;
20797 
20798 	ret = check_btf_info(env, attr, uattr);
20799 	if (ret < 0)
20800 		goto skip_full_check;
20801 
20802 	ret = check_attach_btf_id(env);
20803 	if (ret)
20804 		goto skip_full_check;
20805 
20806 	ret = resolve_pseudo_ldimm64(env);
20807 	if (ret < 0)
20808 		goto skip_full_check;
20809 
20810 	if (bpf_prog_is_offloaded(env->prog->aux)) {
20811 		ret = bpf_prog_offload_verifier_prep(env->prog);
20812 		if (ret)
20813 			goto skip_full_check;
20814 	}
20815 
20816 	ret = check_cfg(env);
20817 	if (ret < 0)
20818 		goto skip_full_check;
20819 
20820 	ret = do_check_main(env);
20821 	ret = ret ?: do_check_subprogs(env);
20822 
20823 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20824 		ret = bpf_prog_offload_finalize(env);
20825 
20826 skip_full_check:
20827 	kvfree(env->explored_states);
20828 
20829 	if (ret == 0)
20830 		ret = check_max_stack_depth(env);
20831 
20832 	/* instruction rewrites happen after this point */
20833 	if (ret == 0)
20834 		ret = optimize_bpf_loop(env);
20835 
20836 	if (is_priv) {
20837 		if (ret == 0)
20838 			opt_hard_wire_dead_code_branches(env);
20839 		if (ret == 0)
20840 			ret = opt_remove_dead_code(env);
20841 		if (ret == 0)
20842 			ret = opt_remove_nops(env);
20843 	} else {
20844 		if (ret == 0)
20845 			sanitize_dead_code(env);
20846 	}
20847 
20848 	if (ret == 0)
20849 		/* program is valid, convert *(u32*)(ctx + off) accesses */
20850 		ret = convert_ctx_accesses(env);
20851 
20852 	if (ret == 0)
20853 		ret = do_misc_fixups(env);
20854 
20855 	/* do 32-bit optimization after insn patching has done so those patched
20856 	 * insns could be handled correctly.
20857 	 */
20858 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20859 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20860 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20861 								     : false;
20862 	}
20863 
20864 	if (ret == 0)
20865 		ret = fixup_call_args(env);
20866 
20867 	env->verification_time = ktime_get_ns() - start_time;
20868 	print_verification_stats(env);
20869 	env->prog->aux->verified_insns = env->insn_processed;
20870 
20871 	/* preserve original error even if log finalization is successful */
20872 	err = bpf_vlog_finalize(&env->log, &log_true_size);
20873 	if (err)
20874 		ret = err;
20875 
20876 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20877 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20878 				  &log_true_size, sizeof(log_true_size))) {
20879 		ret = -EFAULT;
20880 		goto err_release_maps;
20881 	}
20882 
20883 	if (ret)
20884 		goto err_release_maps;
20885 
20886 	if (env->used_map_cnt) {
20887 		/* if program passed verifier, update used_maps in bpf_prog_info */
20888 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20889 							  sizeof(env->used_maps[0]),
20890 							  GFP_KERNEL);
20891 
20892 		if (!env->prog->aux->used_maps) {
20893 			ret = -ENOMEM;
20894 			goto err_release_maps;
20895 		}
20896 
20897 		memcpy(env->prog->aux->used_maps, env->used_maps,
20898 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
20899 		env->prog->aux->used_map_cnt = env->used_map_cnt;
20900 	}
20901 	if (env->used_btf_cnt) {
20902 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
20903 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20904 							  sizeof(env->used_btfs[0]),
20905 							  GFP_KERNEL);
20906 		if (!env->prog->aux->used_btfs) {
20907 			ret = -ENOMEM;
20908 			goto err_release_maps;
20909 		}
20910 
20911 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
20912 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20913 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20914 	}
20915 	if (env->used_map_cnt || env->used_btf_cnt) {
20916 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
20917 		 * bpf_ld_imm64 instructions
20918 		 */
20919 		convert_pseudo_ld_imm64(env);
20920 	}
20921 
20922 	adjust_btf_func(env);
20923 
20924 err_release_maps:
20925 	if (!env->prog->aux->used_maps)
20926 		/* if we didn't copy map pointers into bpf_prog_info, release
20927 		 * them now. Otherwise free_used_maps() will release them.
20928 		 */
20929 		release_maps(env);
20930 	if (!env->prog->aux->used_btfs)
20931 		release_btfs(env);
20932 
20933 	/* extension progs temporarily inherit the attach_type of their targets
20934 	   for verification purposes, so set it back to zero before returning
20935 	 */
20936 	if (env->prog->type == BPF_PROG_TYPE_EXT)
20937 		env->prog->expected_attach_type = 0;
20938 
20939 	*prog = env->prog;
20940 err_unlock:
20941 	if (!is_priv)
20942 		mutex_unlock(&bpf_verifier_lock);
20943 	vfree(env->insn_aux_data);
20944 err_free_env:
20945 	kfree(env);
20946 	return ret;
20947 }
20948