xref: /linux/kernel/bpf/verifier.c (revision e91c37f1)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <linux/bpf_mem_alloc.h>
30 #include <net/xdp.h>
31 
32 #include "disasm.h"
33 
34 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
35 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
36 	[_id] = & _name ## _verifier_ops,
37 #define BPF_MAP_TYPE(_id, _ops)
38 #define BPF_LINK_TYPE(_id, _name)
39 #include <linux/bpf_types.h>
40 #undef BPF_PROG_TYPE
41 #undef BPF_MAP_TYPE
42 #undef BPF_LINK_TYPE
43 };
44 
45 struct bpf_mem_alloc bpf_global_percpu_ma;
46 static bool bpf_global_percpu_ma_set;
47 
48 /* bpf_check() is a static code analyzer that walks eBPF program
49  * instruction by instruction and updates register/stack state.
50  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
51  *
52  * The first pass is depth-first-search to check that the program is a DAG.
53  * It rejects the following programs:
54  * - larger than BPF_MAXINSNS insns
55  * - if loop is present (detected via back-edge)
56  * - unreachable insns exist (shouldn't be a forest. program = one function)
57  * - out of bounds or malformed jumps
58  * The second pass is all possible path descent from the 1st insn.
59  * Since it's analyzing all paths through the program, the length of the
60  * analysis is limited to 64k insn, which may be hit even if total number of
61  * insn is less then 4K, but there are too many branches that change stack/regs.
62  * Number of 'branches to be analyzed' is limited to 1k
63  *
64  * On entry to each instruction, each register has a type, and the instruction
65  * changes the types of the registers depending on instruction semantics.
66  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
67  * copied to R1.
68  *
69  * All registers are 64-bit.
70  * R0 - return register
71  * R1-R5 argument passing registers
72  * R6-R9 callee saved registers
73  * R10 - frame pointer read-only
74  *
75  * At the start of BPF program the register R1 contains a pointer to bpf_context
76  * and has type PTR_TO_CTX.
77  *
78  * Verifier tracks arithmetic operations on pointers in case:
79  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
80  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
81  * 1st insn copies R10 (which has FRAME_PTR) type into R1
82  * and 2nd arithmetic instruction is pattern matched to recognize
83  * that it wants to construct a pointer to some element within stack.
84  * So after 2nd insn, the register R1 has type PTR_TO_STACK
85  * (and -20 constant is saved for further stack bounds checking).
86  * Meaning that this reg is a pointer to stack plus known immediate constant.
87  *
88  * Most of the time the registers have SCALAR_VALUE type, which
89  * means the register has some value, but it's not a valid pointer.
90  * (like pointer plus pointer becomes SCALAR_VALUE type)
91  *
92  * When verifier sees load or store instructions the type of base register
93  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
94  * four pointer types recognized by check_mem_access() function.
95  *
96  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
97  * and the range of [ptr, ptr + map's value_size) is accessible.
98  *
99  * registers used to pass values to function calls are checked against
100  * function argument constraints.
101  *
102  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
103  * It means that the register type passed to this function must be
104  * PTR_TO_STACK and it will be used inside the function as
105  * 'pointer to map element key'
106  *
107  * For example the argument constraints for bpf_map_lookup_elem():
108  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
109  *   .arg1_type = ARG_CONST_MAP_PTR,
110  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
111  *
112  * ret_type says that this function returns 'pointer to map elem value or null'
113  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
114  * 2nd argument should be a pointer to stack, which will be used inside
115  * the helper function as a pointer to map element key.
116  *
117  * On the kernel side the helper function looks like:
118  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
119  * {
120  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
121  *    void *key = (void *) (unsigned long) r2;
122  *    void *value;
123  *
124  *    here kernel can access 'key' and 'map' pointers safely, knowing that
125  *    [key, key + map->key_size) bytes are valid and were initialized on
126  *    the stack of eBPF program.
127  * }
128  *
129  * Corresponding eBPF program may look like:
130  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
131  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
132  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
133  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
134  * here verifier looks at prototype of map_lookup_elem() and sees:
135  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
136  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
137  *
138  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
139  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
140  * and were initialized prior to this call.
141  * If it's ok, then verifier allows this BPF_CALL insn and looks at
142  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
143  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
144  * returns either pointer to map value or NULL.
145  *
146  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
147  * insn, the register holding that pointer in the true branch changes state to
148  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
149  * branch. See check_cond_jmp_op().
150  *
151  * After the call R0 is set to return type of the function and registers R1-R5
152  * are set to NOT_INIT to indicate that they are no longer readable.
153  *
154  * The following reference types represent a potential reference to a kernel
155  * resource which, after first being allocated, must be checked and freed by
156  * the BPF program:
157  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
158  *
159  * When the verifier sees a helper call return a reference type, it allocates a
160  * pointer id for the reference and stores it in the current function state.
161  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
162  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
163  * passes through a NULL-check conditional. For the branch wherein the state is
164  * changed to CONST_IMM, the verifier releases the reference.
165  *
166  * For each helper function that allocates a reference, such as
167  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
168  * bpf_sk_release(). When a reference type passes into the release function,
169  * the verifier also releases the reference. If any unchecked or unreleased
170  * reference remains at the end of the program, the verifier rejects it.
171  */
172 
173 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
174 struct bpf_verifier_stack_elem {
175 	/* verifer state is 'st'
176 	 * before processing instruction 'insn_idx'
177 	 * and after processing instruction 'prev_insn_idx'
178 	 */
179 	struct bpf_verifier_state st;
180 	int insn_idx;
181 	int prev_insn_idx;
182 	struct bpf_verifier_stack_elem *next;
183 	/* length of verifier log at the time this state was pushed on stack */
184 	u32 log_pos;
185 };
186 
187 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
188 #define BPF_COMPLEXITY_LIMIT_STATES	64
189 
190 #define BPF_MAP_KEY_POISON	(1ULL << 63)
191 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
192 
193 #define BPF_MAP_PTR_UNPRIV	1UL
194 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
195 					  POISON_POINTER_DELTA))
196 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
197 
198 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
199 
200 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
201 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
202 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
203 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
204 static int ref_set_non_owning(struct bpf_verifier_env *env,
205 			      struct bpf_reg_state *reg);
206 static void specialize_kfunc(struct bpf_verifier_env *env,
207 			     u32 func_id, u16 offset, unsigned long *addr);
208 static bool is_trusted_reg(const struct bpf_reg_state *reg);
209 
210 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
211 {
212 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
213 }
214 
215 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
216 {
217 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
218 }
219 
220 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
221 			      const struct bpf_map *map, bool unpriv)
222 {
223 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
224 	unpriv |= bpf_map_ptr_unpriv(aux);
225 	aux->map_ptr_state = (unsigned long)map |
226 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
227 }
228 
229 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
230 {
231 	return aux->map_key_state & BPF_MAP_KEY_POISON;
232 }
233 
234 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
235 {
236 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
237 }
238 
239 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
240 {
241 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
242 }
243 
244 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
245 {
246 	bool poisoned = bpf_map_key_poisoned(aux);
247 
248 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
249 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
250 }
251 
252 static bool bpf_helper_call(const struct bpf_insn *insn)
253 {
254 	return insn->code == (BPF_JMP | BPF_CALL) &&
255 	       insn->src_reg == 0;
256 }
257 
258 static bool bpf_pseudo_call(const struct bpf_insn *insn)
259 {
260 	return insn->code == (BPF_JMP | BPF_CALL) &&
261 	       insn->src_reg == BPF_PSEUDO_CALL;
262 }
263 
264 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
265 {
266 	return insn->code == (BPF_JMP | BPF_CALL) &&
267 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
268 }
269 
270 struct bpf_call_arg_meta {
271 	struct bpf_map *map_ptr;
272 	bool raw_mode;
273 	bool pkt_access;
274 	u8 release_regno;
275 	int regno;
276 	int access_size;
277 	int mem_size;
278 	u64 msize_max_value;
279 	int ref_obj_id;
280 	int dynptr_id;
281 	int map_uid;
282 	int func_id;
283 	struct btf *btf;
284 	u32 btf_id;
285 	struct btf *ret_btf;
286 	u32 ret_btf_id;
287 	u32 subprogno;
288 	struct btf_field *kptr_field;
289 };
290 
291 struct bpf_kfunc_call_arg_meta {
292 	/* In parameters */
293 	struct btf *btf;
294 	u32 func_id;
295 	u32 kfunc_flags;
296 	const struct btf_type *func_proto;
297 	const char *func_name;
298 	/* Out parameters */
299 	u32 ref_obj_id;
300 	u8 release_regno;
301 	bool r0_rdonly;
302 	u32 ret_btf_id;
303 	u64 r0_size;
304 	u32 subprogno;
305 	struct {
306 		u64 value;
307 		bool found;
308 	} arg_constant;
309 
310 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
311 	 * generally to pass info about user-defined local kptr types to later
312 	 * verification logic
313 	 *   bpf_obj_drop/bpf_percpu_obj_drop
314 	 *     Record the local kptr type to be drop'd
315 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
316 	 *     Record the local kptr type to be refcount_incr'd and use
317 	 *     arg_owning_ref to determine whether refcount_acquire should be
318 	 *     fallible
319 	 */
320 	struct btf *arg_btf;
321 	u32 arg_btf_id;
322 	bool arg_owning_ref;
323 
324 	struct {
325 		struct btf_field *field;
326 	} arg_list_head;
327 	struct {
328 		struct btf_field *field;
329 	} arg_rbtree_root;
330 	struct {
331 		enum bpf_dynptr_type type;
332 		u32 id;
333 		u32 ref_obj_id;
334 	} initialized_dynptr;
335 	struct {
336 		u8 spi;
337 		u8 frameno;
338 	} iter;
339 	u64 mem_size;
340 };
341 
342 struct btf *btf_vmlinux;
343 
344 static const char *btf_type_name(const struct btf *btf, u32 id)
345 {
346 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
347 }
348 
349 static DEFINE_MUTEX(bpf_verifier_lock);
350 static DEFINE_MUTEX(bpf_percpu_ma_lock);
351 
352 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
353 {
354 	struct bpf_verifier_env *env = private_data;
355 	va_list args;
356 
357 	if (!bpf_verifier_log_needed(&env->log))
358 		return;
359 
360 	va_start(args, fmt);
361 	bpf_verifier_vlog(&env->log, fmt, args);
362 	va_end(args);
363 }
364 
365 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
366 				   struct bpf_reg_state *reg,
367 				   struct bpf_retval_range range, const char *ctx,
368 				   const char *reg_name)
369 {
370 	bool unknown = true;
371 
372 	verbose(env, "%s the register %s has", ctx, reg_name);
373 	if (reg->smin_value > S64_MIN) {
374 		verbose(env, " smin=%lld", reg->smin_value);
375 		unknown = false;
376 	}
377 	if (reg->smax_value < S64_MAX) {
378 		verbose(env, " smax=%lld", reg->smax_value);
379 		unknown = false;
380 	}
381 	if (unknown)
382 		verbose(env, " unknown scalar value");
383 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
384 }
385 
386 static bool type_may_be_null(u32 type)
387 {
388 	return type & PTR_MAYBE_NULL;
389 }
390 
391 static bool reg_not_null(const struct bpf_reg_state *reg)
392 {
393 	enum bpf_reg_type type;
394 
395 	type = reg->type;
396 	if (type_may_be_null(type))
397 		return false;
398 
399 	type = base_type(type);
400 	return type == PTR_TO_SOCKET ||
401 		type == PTR_TO_TCP_SOCK ||
402 		type == PTR_TO_MAP_VALUE ||
403 		type == PTR_TO_MAP_KEY ||
404 		type == PTR_TO_SOCK_COMMON ||
405 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
406 		type == PTR_TO_MEM;
407 }
408 
409 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
410 {
411 	struct btf_record *rec = NULL;
412 	struct btf_struct_meta *meta;
413 
414 	if (reg->type == PTR_TO_MAP_VALUE) {
415 		rec = reg->map_ptr->record;
416 	} else if (type_is_ptr_alloc_obj(reg->type)) {
417 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
418 		if (meta)
419 			rec = meta->record;
420 	}
421 	return rec;
422 }
423 
424 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
425 {
426 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
427 
428 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
429 }
430 
431 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
432 {
433 	struct bpf_func_info *info;
434 
435 	if (!env->prog->aux->func_info)
436 		return "";
437 
438 	info = &env->prog->aux->func_info[subprog];
439 	return btf_type_name(env->prog->aux->btf, info->type_id);
440 }
441 
442 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
443 {
444 	struct bpf_subprog_info *info = subprog_info(env, subprog);
445 
446 	info->is_cb = true;
447 	info->is_async_cb = true;
448 	info->is_exception_cb = true;
449 }
450 
451 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
452 {
453 	return subprog_info(env, subprog)->is_exception_cb;
454 }
455 
456 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
457 {
458 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
459 }
460 
461 static bool type_is_rdonly_mem(u32 type)
462 {
463 	return type & MEM_RDONLY;
464 }
465 
466 static bool is_acquire_function(enum bpf_func_id func_id,
467 				const struct bpf_map *map)
468 {
469 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
470 
471 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
472 	    func_id == BPF_FUNC_sk_lookup_udp ||
473 	    func_id == BPF_FUNC_skc_lookup_tcp ||
474 	    func_id == BPF_FUNC_ringbuf_reserve ||
475 	    func_id == BPF_FUNC_kptr_xchg)
476 		return true;
477 
478 	if (func_id == BPF_FUNC_map_lookup_elem &&
479 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
480 	     map_type == BPF_MAP_TYPE_SOCKHASH))
481 		return true;
482 
483 	return false;
484 }
485 
486 static bool is_ptr_cast_function(enum bpf_func_id func_id)
487 {
488 	return func_id == BPF_FUNC_tcp_sock ||
489 		func_id == BPF_FUNC_sk_fullsock ||
490 		func_id == BPF_FUNC_skc_to_tcp_sock ||
491 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
492 		func_id == BPF_FUNC_skc_to_udp6_sock ||
493 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
494 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
495 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
496 }
497 
498 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
499 {
500 	return func_id == BPF_FUNC_dynptr_data;
501 }
502 
503 static bool is_sync_callback_calling_kfunc(u32 btf_id);
504 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
505 
506 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
507 {
508 	return func_id == BPF_FUNC_for_each_map_elem ||
509 	       func_id == BPF_FUNC_find_vma ||
510 	       func_id == BPF_FUNC_loop ||
511 	       func_id == BPF_FUNC_user_ringbuf_drain;
512 }
513 
514 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
515 {
516 	return func_id == BPF_FUNC_timer_set_callback;
517 }
518 
519 static bool is_callback_calling_function(enum bpf_func_id func_id)
520 {
521 	return is_sync_callback_calling_function(func_id) ||
522 	       is_async_callback_calling_function(func_id);
523 }
524 
525 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
526 {
527 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
528 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
529 }
530 
531 static bool is_storage_get_function(enum bpf_func_id func_id)
532 {
533 	return func_id == BPF_FUNC_sk_storage_get ||
534 	       func_id == BPF_FUNC_inode_storage_get ||
535 	       func_id == BPF_FUNC_task_storage_get ||
536 	       func_id == BPF_FUNC_cgrp_storage_get;
537 }
538 
539 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
540 					const struct bpf_map *map)
541 {
542 	int ref_obj_uses = 0;
543 
544 	if (is_ptr_cast_function(func_id))
545 		ref_obj_uses++;
546 	if (is_acquire_function(func_id, map))
547 		ref_obj_uses++;
548 	if (is_dynptr_ref_function(func_id))
549 		ref_obj_uses++;
550 
551 	return ref_obj_uses > 1;
552 }
553 
554 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
555 {
556 	return BPF_CLASS(insn->code) == BPF_STX &&
557 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
558 	       insn->imm == BPF_CMPXCHG;
559 }
560 
561 static int __get_spi(s32 off)
562 {
563 	return (-off - 1) / BPF_REG_SIZE;
564 }
565 
566 static struct bpf_func_state *func(struct bpf_verifier_env *env,
567 				   const struct bpf_reg_state *reg)
568 {
569 	struct bpf_verifier_state *cur = env->cur_state;
570 
571 	return cur->frame[reg->frameno];
572 }
573 
574 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
575 {
576        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
577 
578        /* We need to check that slots between [spi - nr_slots + 1, spi] are
579 	* within [0, allocated_stack).
580 	*
581 	* Please note that the spi grows downwards. For example, a dynptr
582 	* takes the size of two stack slots; the first slot will be at
583 	* spi and the second slot will be at spi - 1.
584 	*/
585        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
586 }
587 
588 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
589 			          const char *obj_kind, int nr_slots)
590 {
591 	int off, spi;
592 
593 	if (!tnum_is_const(reg->var_off)) {
594 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
595 		return -EINVAL;
596 	}
597 
598 	off = reg->off + reg->var_off.value;
599 	if (off % BPF_REG_SIZE) {
600 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
601 		return -EINVAL;
602 	}
603 
604 	spi = __get_spi(off);
605 	if (spi + 1 < nr_slots) {
606 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
607 		return -EINVAL;
608 	}
609 
610 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
611 		return -ERANGE;
612 	return spi;
613 }
614 
615 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
616 {
617 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
618 }
619 
620 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
621 {
622 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
623 }
624 
625 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
626 {
627 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
628 	case DYNPTR_TYPE_LOCAL:
629 		return BPF_DYNPTR_TYPE_LOCAL;
630 	case DYNPTR_TYPE_RINGBUF:
631 		return BPF_DYNPTR_TYPE_RINGBUF;
632 	case DYNPTR_TYPE_SKB:
633 		return BPF_DYNPTR_TYPE_SKB;
634 	case DYNPTR_TYPE_XDP:
635 		return BPF_DYNPTR_TYPE_XDP;
636 	default:
637 		return BPF_DYNPTR_TYPE_INVALID;
638 	}
639 }
640 
641 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
642 {
643 	switch (type) {
644 	case BPF_DYNPTR_TYPE_LOCAL:
645 		return DYNPTR_TYPE_LOCAL;
646 	case BPF_DYNPTR_TYPE_RINGBUF:
647 		return DYNPTR_TYPE_RINGBUF;
648 	case BPF_DYNPTR_TYPE_SKB:
649 		return DYNPTR_TYPE_SKB;
650 	case BPF_DYNPTR_TYPE_XDP:
651 		return DYNPTR_TYPE_XDP;
652 	default:
653 		return 0;
654 	}
655 }
656 
657 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
658 {
659 	return type == BPF_DYNPTR_TYPE_RINGBUF;
660 }
661 
662 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
663 			      enum bpf_dynptr_type type,
664 			      bool first_slot, int dynptr_id);
665 
666 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
667 				struct bpf_reg_state *reg);
668 
669 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
670 				   struct bpf_reg_state *sreg1,
671 				   struct bpf_reg_state *sreg2,
672 				   enum bpf_dynptr_type type)
673 {
674 	int id = ++env->id_gen;
675 
676 	__mark_dynptr_reg(sreg1, type, true, id);
677 	__mark_dynptr_reg(sreg2, type, false, id);
678 }
679 
680 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
681 			       struct bpf_reg_state *reg,
682 			       enum bpf_dynptr_type type)
683 {
684 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
685 }
686 
687 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
688 				        struct bpf_func_state *state, int spi);
689 
690 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
691 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
692 {
693 	struct bpf_func_state *state = func(env, reg);
694 	enum bpf_dynptr_type type;
695 	int spi, i, err;
696 
697 	spi = dynptr_get_spi(env, reg);
698 	if (spi < 0)
699 		return spi;
700 
701 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
702 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
703 	 * to ensure that for the following example:
704 	 *	[d1][d1][d2][d2]
705 	 * spi    3   2   1   0
706 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
707 	 * case they do belong to same dynptr, second call won't see slot_type
708 	 * as STACK_DYNPTR and will simply skip destruction.
709 	 */
710 	err = destroy_if_dynptr_stack_slot(env, state, spi);
711 	if (err)
712 		return err;
713 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
714 	if (err)
715 		return err;
716 
717 	for (i = 0; i < BPF_REG_SIZE; i++) {
718 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
719 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
720 	}
721 
722 	type = arg_to_dynptr_type(arg_type);
723 	if (type == BPF_DYNPTR_TYPE_INVALID)
724 		return -EINVAL;
725 
726 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
727 			       &state->stack[spi - 1].spilled_ptr, type);
728 
729 	if (dynptr_type_refcounted(type)) {
730 		/* The id is used to track proper releasing */
731 		int id;
732 
733 		if (clone_ref_obj_id)
734 			id = clone_ref_obj_id;
735 		else
736 			id = acquire_reference_state(env, insn_idx);
737 
738 		if (id < 0)
739 			return id;
740 
741 		state->stack[spi].spilled_ptr.ref_obj_id = id;
742 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
743 	}
744 
745 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
746 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
747 
748 	return 0;
749 }
750 
751 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
752 {
753 	int i;
754 
755 	for (i = 0; i < BPF_REG_SIZE; i++) {
756 		state->stack[spi].slot_type[i] = STACK_INVALID;
757 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
758 	}
759 
760 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
761 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
762 
763 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
764 	 *
765 	 * While we don't allow reading STACK_INVALID, it is still possible to
766 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
767 	 * helpers or insns can do partial read of that part without failing,
768 	 * but check_stack_range_initialized, check_stack_read_var_off, and
769 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
770 	 * the slot conservatively. Hence we need to prevent those liveness
771 	 * marking walks.
772 	 *
773 	 * This was not a problem before because STACK_INVALID is only set by
774 	 * default (where the default reg state has its reg->parent as NULL), or
775 	 * in clean_live_states after REG_LIVE_DONE (at which point
776 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
777 	 * verifier state exploration (like we did above). Hence, for our case
778 	 * parentage chain will still be live (i.e. reg->parent may be
779 	 * non-NULL), while earlier reg->parent was NULL, so we need
780 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
781 	 * done later on reads or by mark_dynptr_read as well to unnecessary
782 	 * mark registers in verifier state.
783 	 */
784 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
785 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
786 }
787 
788 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
789 {
790 	struct bpf_func_state *state = func(env, reg);
791 	int spi, ref_obj_id, i;
792 
793 	spi = dynptr_get_spi(env, reg);
794 	if (spi < 0)
795 		return spi;
796 
797 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
798 		invalidate_dynptr(env, state, spi);
799 		return 0;
800 	}
801 
802 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
803 
804 	/* If the dynptr has a ref_obj_id, then we need to invalidate
805 	 * two things:
806 	 *
807 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
808 	 * 2) Any slices derived from this dynptr.
809 	 */
810 
811 	/* Invalidate any slices associated with this dynptr */
812 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
813 
814 	/* Invalidate any dynptr clones */
815 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
816 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
817 			continue;
818 
819 		/* it should always be the case that if the ref obj id
820 		 * matches then the stack slot also belongs to a
821 		 * dynptr
822 		 */
823 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
824 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
825 			return -EFAULT;
826 		}
827 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
828 			invalidate_dynptr(env, state, i);
829 	}
830 
831 	return 0;
832 }
833 
834 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
835 			       struct bpf_reg_state *reg);
836 
837 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
838 {
839 	if (!env->allow_ptr_leaks)
840 		__mark_reg_not_init(env, reg);
841 	else
842 		__mark_reg_unknown(env, reg);
843 }
844 
845 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
846 				        struct bpf_func_state *state, int spi)
847 {
848 	struct bpf_func_state *fstate;
849 	struct bpf_reg_state *dreg;
850 	int i, dynptr_id;
851 
852 	/* We always ensure that STACK_DYNPTR is never set partially,
853 	 * hence just checking for slot_type[0] is enough. This is
854 	 * different for STACK_SPILL, where it may be only set for
855 	 * 1 byte, so code has to use is_spilled_reg.
856 	 */
857 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
858 		return 0;
859 
860 	/* Reposition spi to first slot */
861 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
862 		spi = spi + 1;
863 
864 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
865 		verbose(env, "cannot overwrite referenced dynptr\n");
866 		return -EINVAL;
867 	}
868 
869 	mark_stack_slot_scratched(env, spi);
870 	mark_stack_slot_scratched(env, spi - 1);
871 
872 	/* Writing partially to one dynptr stack slot destroys both. */
873 	for (i = 0; i < BPF_REG_SIZE; i++) {
874 		state->stack[spi].slot_type[i] = STACK_INVALID;
875 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
876 	}
877 
878 	dynptr_id = state->stack[spi].spilled_ptr.id;
879 	/* Invalidate any slices associated with this dynptr */
880 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
881 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
882 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
883 			continue;
884 		if (dreg->dynptr_id == dynptr_id)
885 			mark_reg_invalid(env, dreg);
886 	}));
887 
888 	/* Do not release reference state, we are destroying dynptr on stack,
889 	 * not using some helper to release it. Just reset register.
890 	 */
891 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
892 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
893 
894 	/* Same reason as unmark_stack_slots_dynptr above */
895 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
896 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
897 
898 	return 0;
899 }
900 
901 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
902 {
903 	int spi;
904 
905 	if (reg->type == CONST_PTR_TO_DYNPTR)
906 		return false;
907 
908 	spi = dynptr_get_spi(env, reg);
909 
910 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
911 	 * error because this just means the stack state hasn't been updated yet.
912 	 * We will do check_mem_access to check and update stack bounds later.
913 	 */
914 	if (spi < 0 && spi != -ERANGE)
915 		return false;
916 
917 	/* We don't need to check if the stack slots are marked by previous
918 	 * dynptr initializations because we allow overwriting existing unreferenced
919 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
920 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
921 	 * touching are completely destructed before we reinitialize them for a new
922 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
923 	 * instead of delaying it until the end where the user will get "Unreleased
924 	 * reference" error.
925 	 */
926 	return true;
927 }
928 
929 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
930 {
931 	struct bpf_func_state *state = func(env, reg);
932 	int i, spi;
933 
934 	/* This already represents first slot of initialized bpf_dynptr.
935 	 *
936 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
937 	 * check_func_arg_reg_off's logic, so we don't need to check its
938 	 * offset and alignment.
939 	 */
940 	if (reg->type == CONST_PTR_TO_DYNPTR)
941 		return true;
942 
943 	spi = dynptr_get_spi(env, reg);
944 	if (spi < 0)
945 		return false;
946 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
947 		return false;
948 
949 	for (i = 0; i < BPF_REG_SIZE; i++) {
950 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
951 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
952 			return false;
953 	}
954 
955 	return true;
956 }
957 
958 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
959 				    enum bpf_arg_type arg_type)
960 {
961 	struct bpf_func_state *state = func(env, reg);
962 	enum bpf_dynptr_type dynptr_type;
963 	int spi;
964 
965 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
966 	if (arg_type == ARG_PTR_TO_DYNPTR)
967 		return true;
968 
969 	dynptr_type = arg_to_dynptr_type(arg_type);
970 	if (reg->type == CONST_PTR_TO_DYNPTR) {
971 		return reg->dynptr.type == dynptr_type;
972 	} else {
973 		spi = dynptr_get_spi(env, reg);
974 		if (spi < 0)
975 			return false;
976 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
977 	}
978 }
979 
980 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
981 
982 static bool in_rcu_cs(struct bpf_verifier_env *env);
983 
984 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
985 
986 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
987 				 struct bpf_kfunc_call_arg_meta *meta,
988 				 struct bpf_reg_state *reg, int insn_idx,
989 				 struct btf *btf, u32 btf_id, int nr_slots)
990 {
991 	struct bpf_func_state *state = func(env, reg);
992 	int spi, i, j, id;
993 
994 	spi = iter_get_spi(env, reg, nr_slots);
995 	if (spi < 0)
996 		return spi;
997 
998 	id = acquire_reference_state(env, insn_idx);
999 	if (id < 0)
1000 		return id;
1001 
1002 	for (i = 0; i < nr_slots; i++) {
1003 		struct bpf_stack_state *slot = &state->stack[spi - i];
1004 		struct bpf_reg_state *st = &slot->spilled_ptr;
1005 
1006 		__mark_reg_known_zero(st);
1007 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1008 		if (is_kfunc_rcu_protected(meta)) {
1009 			if (in_rcu_cs(env))
1010 				st->type |= MEM_RCU;
1011 			else
1012 				st->type |= PTR_UNTRUSTED;
1013 		}
1014 		st->live |= REG_LIVE_WRITTEN;
1015 		st->ref_obj_id = i == 0 ? id : 0;
1016 		st->iter.btf = btf;
1017 		st->iter.btf_id = btf_id;
1018 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1019 		st->iter.depth = 0;
1020 
1021 		for (j = 0; j < BPF_REG_SIZE; j++)
1022 			slot->slot_type[j] = STACK_ITER;
1023 
1024 		mark_stack_slot_scratched(env, spi - i);
1025 	}
1026 
1027 	return 0;
1028 }
1029 
1030 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1031 				   struct bpf_reg_state *reg, int nr_slots)
1032 {
1033 	struct bpf_func_state *state = func(env, reg);
1034 	int spi, i, j;
1035 
1036 	spi = iter_get_spi(env, reg, nr_slots);
1037 	if (spi < 0)
1038 		return spi;
1039 
1040 	for (i = 0; i < nr_slots; i++) {
1041 		struct bpf_stack_state *slot = &state->stack[spi - i];
1042 		struct bpf_reg_state *st = &slot->spilled_ptr;
1043 
1044 		if (i == 0)
1045 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1046 
1047 		__mark_reg_not_init(env, st);
1048 
1049 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1050 		st->live |= REG_LIVE_WRITTEN;
1051 
1052 		for (j = 0; j < BPF_REG_SIZE; j++)
1053 			slot->slot_type[j] = STACK_INVALID;
1054 
1055 		mark_stack_slot_scratched(env, spi - i);
1056 	}
1057 
1058 	return 0;
1059 }
1060 
1061 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1062 				     struct bpf_reg_state *reg, int nr_slots)
1063 {
1064 	struct bpf_func_state *state = func(env, reg);
1065 	int spi, i, j;
1066 
1067 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1068 	 * will do check_mem_access to check and update stack bounds later, so
1069 	 * return true for that case.
1070 	 */
1071 	spi = iter_get_spi(env, reg, nr_slots);
1072 	if (spi == -ERANGE)
1073 		return true;
1074 	if (spi < 0)
1075 		return false;
1076 
1077 	for (i = 0; i < nr_slots; i++) {
1078 		struct bpf_stack_state *slot = &state->stack[spi - i];
1079 
1080 		for (j = 0; j < BPF_REG_SIZE; j++)
1081 			if (slot->slot_type[j] == STACK_ITER)
1082 				return false;
1083 	}
1084 
1085 	return true;
1086 }
1087 
1088 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1089 				   struct btf *btf, u32 btf_id, int nr_slots)
1090 {
1091 	struct bpf_func_state *state = func(env, reg);
1092 	int spi, i, j;
1093 
1094 	spi = iter_get_spi(env, reg, nr_slots);
1095 	if (spi < 0)
1096 		return -EINVAL;
1097 
1098 	for (i = 0; i < nr_slots; i++) {
1099 		struct bpf_stack_state *slot = &state->stack[spi - i];
1100 		struct bpf_reg_state *st = &slot->spilled_ptr;
1101 
1102 		if (st->type & PTR_UNTRUSTED)
1103 			return -EPROTO;
1104 		/* only main (first) slot has ref_obj_id set */
1105 		if (i == 0 && !st->ref_obj_id)
1106 			return -EINVAL;
1107 		if (i != 0 && st->ref_obj_id)
1108 			return -EINVAL;
1109 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1110 			return -EINVAL;
1111 
1112 		for (j = 0; j < BPF_REG_SIZE; j++)
1113 			if (slot->slot_type[j] != STACK_ITER)
1114 				return -EINVAL;
1115 	}
1116 
1117 	return 0;
1118 }
1119 
1120 /* Check if given stack slot is "special":
1121  *   - spilled register state (STACK_SPILL);
1122  *   - dynptr state (STACK_DYNPTR);
1123  *   - iter state (STACK_ITER).
1124  */
1125 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1126 {
1127 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1128 
1129 	switch (type) {
1130 	case STACK_SPILL:
1131 	case STACK_DYNPTR:
1132 	case STACK_ITER:
1133 		return true;
1134 	case STACK_INVALID:
1135 	case STACK_MISC:
1136 	case STACK_ZERO:
1137 		return false;
1138 	default:
1139 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1140 		return true;
1141 	}
1142 }
1143 
1144 /* The reg state of a pointer or a bounded scalar was saved when
1145  * it was spilled to the stack.
1146  */
1147 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1148 {
1149 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1150 }
1151 
1152 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1153 {
1154 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1155 	       stack->spilled_ptr.type == SCALAR_VALUE;
1156 }
1157 
1158 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1159  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1160  * more precise STACK_ZERO.
1161  * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take
1162  * env->allow_ptr_leaks into account and force STACK_MISC, if necessary.
1163  */
1164 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1165 {
1166 	if (*stype == STACK_ZERO)
1167 		return;
1168 	if (env->allow_ptr_leaks && *stype == STACK_INVALID)
1169 		return;
1170 	*stype = STACK_MISC;
1171 }
1172 
1173 static void scrub_spilled_slot(u8 *stype)
1174 {
1175 	if (*stype != STACK_INVALID)
1176 		*stype = STACK_MISC;
1177 }
1178 
1179 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1180  * small to hold src. This is different from krealloc since we don't want to preserve
1181  * the contents of dst.
1182  *
1183  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1184  * not be allocated.
1185  */
1186 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1187 {
1188 	size_t alloc_bytes;
1189 	void *orig = dst;
1190 	size_t bytes;
1191 
1192 	if (ZERO_OR_NULL_PTR(src))
1193 		goto out;
1194 
1195 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1196 		return NULL;
1197 
1198 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1199 	dst = krealloc(orig, alloc_bytes, flags);
1200 	if (!dst) {
1201 		kfree(orig);
1202 		return NULL;
1203 	}
1204 
1205 	memcpy(dst, src, bytes);
1206 out:
1207 	return dst ? dst : ZERO_SIZE_PTR;
1208 }
1209 
1210 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1211  * small to hold new_n items. new items are zeroed out if the array grows.
1212  *
1213  * Contrary to krealloc_array, does not free arr if new_n is zero.
1214  */
1215 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1216 {
1217 	size_t alloc_size;
1218 	void *new_arr;
1219 
1220 	if (!new_n || old_n == new_n)
1221 		goto out;
1222 
1223 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1224 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1225 	if (!new_arr) {
1226 		kfree(arr);
1227 		return NULL;
1228 	}
1229 	arr = new_arr;
1230 
1231 	if (new_n > old_n)
1232 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1233 
1234 out:
1235 	return arr ? arr : ZERO_SIZE_PTR;
1236 }
1237 
1238 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1239 {
1240 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1241 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1242 	if (!dst->refs)
1243 		return -ENOMEM;
1244 
1245 	dst->acquired_refs = src->acquired_refs;
1246 	return 0;
1247 }
1248 
1249 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1250 {
1251 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1252 
1253 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1254 				GFP_KERNEL);
1255 	if (!dst->stack)
1256 		return -ENOMEM;
1257 
1258 	dst->allocated_stack = src->allocated_stack;
1259 	return 0;
1260 }
1261 
1262 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1263 {
1264 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1265 				    sizeof(struct bpf_reference_state));
1266 	if (!state->refs)
1267 		return -ENOMEM;
1268 
1269 	state->acquired_refs = n;
1270 	return 0;
1271 }
1272 
1273 /* Possibly update state->allocated_stack to be at least size bytes. Also
1274  * possibly update the function's high-water mark in its bpf_subprog_info.
1275  */
1276 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1277 {
1278 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1279 
1280 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1281 	size = round_up(size, BPF_REG_SIZE);
1282 	n = size / BPF_REG_SIZE;
1283 
1284 	if (old_n >= n)
1285 		return 0;
1286 
1287 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1288 	if (!state->stack)
1289 		return -ENOMEM;
1290 
1291 	state->allocated_stack = size;
1292 
1293 	/* update known max for given subprogram */
1294 	if (env->subprog_info[state->subprogno].stack_depth < size)
1295 		env->subprog_info[state->subprogno].stack_depth = size;
1296 
1297 	return 0;
1298 }
1299 
1300 /* Acquire a pointer id from the env and update the state->refs to include
1301  * this new pointer reference.
1302  * On success, returns a valid pointer id to associate with the register
1303  * On failure, returns a negative errno.
1304  */
1305 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1306 {
1307 	struct bpf_func_state *state = cur_func(env);
1308 	int new_ofs = state->acquired_refs;
1309 	int id, err;
1310 
1311 	err = resize_reference_state(state, state->acquired_refs + 1);
1312 	if (err)
1313 		return err;
1314 	id = ++env->id_gen;
1315 	state->refs[new_ofs].id = id;
1316 	state->refs[new_ofs].insn_idx = insn_idx;
1317 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1318 
1319 	return id;
1320 }
1321 
1322 /* release function corresponding to acquire_reference_state(). Idempotent. */
1323 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1324 {
1325 	int i, last_idx;
1326 
1327 	last_idx = state->acquired_refs - 1;
1328 	for (i = 0; i < state->acquired_refs; i++) {
1329 		if (state->refs[i].id == ptr_id) {
1330 			/* Cannot release caller references in callbacks */
1331 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1332 				return -EINVAL;
1333 			if (last_idx && i != last_idx)
1334 				memcpy(&state->refs[i], &state->refs[last_idx],
1335 				       sizeof(*state->refs));
1336 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1337 			state->acquired_refs--;
1338 			return 0;
1339 		}
1340 	}
1341 	return -EINVAL;
1342 }
1343 
1344 static void free_func_state(struct bpf_func_state *state)
1345 {
1346 	if (!state)
1347 		return;
1348 	kfree(state->refs);
1349 	kfree(state->stack);
1350 	kfree(state);
1351 }
1352 
1353 static void clear_jmp_history(struct bpf_verifier_state *state)
1354 {
1355 	kfree(state->jmp_history);
1356 	state->jmp_history = NULL;
1357 	state->jmp_history_cnt = 0;
1358 }
1359 
1360 static void free_verifier_state(struct bpf_verifier_state *state,
1361 				bool free_self)
1362 {
1363 	int i;
1364 
1365 	for (i = 0; i <= state->curframe; i++) {
1366 		free_func_state(state->frame[i]);
1367 		state->frame[i] = NULL;
1368 	}
1369 	clear_jmp_history(state);
1370 	if (free_self)
1371 		kfree(state);
1372 }
1373 
1374 /* copy verifier state from src to dst growing dst stack space
1375  * when necessary to accommodate larger src stack
1376  */
1377 static int copy_func_state(struct bpf_func_state *dst,
1378 			   const struct bpf_func_state *src)
1379 {
1380 	int err;
1381 
1382 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1383 	err = copy_reference_state(dst, src);
1384 	if (err)
1385 		return err;
1386 	return copy_stack_state(dst, src);
1387 }
1388 
1389 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1390 			       const struct bpf_verifier_state *src)
1391 {
1392 	struct bpf_func_state *dst;
1393 	int i, err;
1394 
1395 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1396 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1397 					  GFP_USER);
1398 	if (!dst_state->jmp_history)
1399 		return -ENOMEM;
1400 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1401 
1402 	/* if dst has more stack frames then src frame, free them, this is also
1403 	 * necessary in case of exceptional exits using bpf_throw.
1404 	 */
1405 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1406 		free_func_state(dst_state->frame[i]);
1407 		dst_state->frame[i] = NULL;
1408 	}
1409 	dst_state->speculative = src->speculative;
1410 	dst_state->active_rcu_lock = src->active_rcu_lock;
1411 	dst_state->curframe = src->curframe;
1412 	dst_state->active_lock.ptr = src->active_lock.ptr;
1413 	dst_state->active_lock.id = src->active_lock.id;
1414 	dst_state->branches = src->branches;
1415 	dst_state->parent = src->parent;
1416 	dst_state->first_insn_idx = src->first_insn_idx;
1417 	dst_state->last_insn_idx = src->last_insn_idx;
1418 	dst_state->dfs_depth = src->dfs_depth;
1419 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1420 	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1421 	for (i = 0; i <= src->curframe; i++) {
1422 		dst = dst_state->frame[i];
1423 		if (!dst) {
1424 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1425 			if (!dst)
1426 				return -ENOMEM;
1427 			dst_state->frame[i] = dst;
1428 		}
1429 		err = copy_func_state(dst, src->frame[i]);
1430 		if (err)
1431 			return err;
1432 	}
1433 	return 0;
1434 }
1435 
1436 static u32 state_htab_size(struct bpf_verifier_env *env)
1437 {
1438 	return env->prog->len;
1439 }
1440 
1441 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1442 {
1443 	struct bpf_verifier_state *cur = env->cur_state;
1444 	struct bpf_func_state *state = cur->frame[cur->curframe];
1445 
1446 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1447 }
1448 
1449 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1450 {
1451 	int fr;
1452 
1453 	if (a->curframe != b->curframe)
1454 		return false;
1455 
1456 	for (fr = a->curframe; fr >= 0; fr--)
1457 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1458 			return false;
1459 
1460 	return true;
1461 }
1462 
1463 /* Open coded iterators allow back-edges in the state graph in order to
1464  * check unbounded loops that iterators.
1465  *
1466  * In is_state_visited() it is necessary to know if explored states are
1467  * part of some loops in order to decide whether non-exact states
1468  * comparison could be used:
1469  * - non-exact states comparison establishes sub-state relation and uses
1470  *   read and precision marks to do so, these marks are propagated from
1471  *   children states and thus are not guaranteed to be final in a loop;
1472  * - exact states comparison just checks if current and explored states
1473  *   are identical (and thus form a back-edge).
1474  *
1475  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1476  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1477  * algorithm for loop structure detection and gives an overview of
1478  * relevant terminology. It also has helpful illustrations.
1479  *
1480  * [1] https://api.semanticscholar.org/CorpusID:15784067
1481  *
1482  * We use a similar algorithm but because loop nested structure is
1483  * irrelevant for verifier ours is significantly simpler and resembles
1484  * strongly connected components algorithm from Sedgewick's textbook.
1485  *
1486  * Define topmost loop entry as a first node of the loop traversed in a
1487  * depth first search starting from initial state. The goal of the loop
1488  * tracking algorithm is to associate topmost loop entries with states
1489  * derived from these entries.
1490  *
1491  * For each step in the DFS states traversal algorithm needs to identify
1492  * the following situations:
1493  *
1494  *          initial                     initial                   initial
1495  *            |                           |                         |
1496  *            V                           V                         V
1497  *           ...                         ...           .---------> hdr
1498  *            |                           |            |            |
1499  *            V                           V            |            V
1500  *           cur                     .-> succ          |    .------...
1501  *            |                      |    |            |    |       |
1502  *            V                      |    V            |    V       V
1503  *           succ                    '-- cur           |   ...     ...
1504  *                                                     |    |       |
1505  *                                                     |    V       V
1506  *                                                     |   succ <- cur
1507  *                                                     |    |
1508  *                                                     |    V
1509  *                                                     |   ...
1510  *                                                     |    |
1511  *                                                     '----'
1512  *
1513  *  (A) successor state of cur   (B) successor state of cur or it's entry
1514  *      not yet traversed            are in current DFS path, thus cur and succ
1515  *                                   are members of the same outermost loop
1516  *
1517  *                      initial                  initial
1518  *                        |                        |
1519  *                        V                        V
1520  *                       ...                      ...
1521  *                        |                        |
1522  *                        V                        V
1523  *                .------...               .------...
1524  *                |       |                |       |
1525  *                V       V                V       V
1526  *           .-> hdr     ...              ...     ...
1527  *           |    |       |                |       |
1528  *           |    V       V                V       V
1529  *           |   succ <- cur              succ <- cur
1530  *           |    |                        |
1531  *           |    V                        V
1532  *           |   ...                      ...
1533  *           |    |                        |
1534  *           '----'                       exit
1535  *
1536  * (C) successor state of cur is a part of some loop but this loop
1537  *     does not include cur or successor state is not in a loop at all.
1538  *
1539  * Algorithm could be described as the following python code:
1540  *
1541  *     traversed = set()   # Set of traversed nodes
1542  *     entries = {}        # Mapping from node to loop entry
1543  *     depths = {}         # Depth level assigned to graph node
1544  *     path = set()        # Current DFS path
1545  *
1546  *     # Find outermost loop entry known for n
1547  *     def get_loop_entry(n):
1548  *         h = entries.get(n, None)
1549  *         while h in entries and entries[h] != h:
1550  *             h = entries[h]
1551  *         return h
1552  *
1553  *     # Update n's loop entry if h's outermost entry comes
1554  *     # before n's outermost entry in current DFS path.
1555  *     def update_loop_entry(n, h):
1556  *         n1 = get_loop_entry(n) or n
1557  *         h1 = get_loop_entry(h) or h
1558  *         if h1 in path and depths[h1] <= depths[n1]:
1559  *             entries[n] = h1
1560  *
1561  *     def dfs(n, depth):
1562  *         traversed.add(n)
1563  *         path.add(n)
1564  *         depths[n] = depth
1565  *         for succ in G.successors(n):
1566  *             if succ not in traversed:
1567  *                 # Case A: explore succ and update cur's loop entry
1568  *                 #         only if succ's entry is in current DFS path.
1569  *                 dfs(succ, depth + 1)
1570  *                 h = get_loop_entry(succ)
1571  *                 update_loop_entry(n, h)
1572  *             else:
1573  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1574  *                 update_loop_entry(n, succ)
1575  *         path.remove(n)
1576  *
1577  * To adapt this algorithm for use with verifier:
1578  * - use st->branch == 0 as a signal that DFS of succ had been finished
1579  *   and cur's loop entry has to be updated (case A), handle this in
1580  *   update_branch_counts();
1581  * - use st->branch > 0 as a signal that st is in the current DFS path;
1582  * - handle cases B and C in is_state_visited();
1583  * - update topmost loop entry for intermediate states in get_loop_entry().
1584  */
1585 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1586 {
1587 	struct bpf_verifier_state *topmost = st->loop_entry, *old;
1588 
1589 	while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1590 		topmost = topmost->loop_entry;
1591 	/* Update loop entries for intermediate states to avoid this
1592 	 * traversal in future get_loop_entry() calls.
1593 	 */
1594 	while (st && st->loop_entry != topmost) {
1595 		old = st->loop_entry;
1596 		st->loop_entry = topmost;
1597 		st = old;
1598 	}
1599 	return topmost;
1600 }
1601 
1602 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1603 {
1604 	struct bpf_verifier_state *cur1, *hdr1;
1605 
1606 	cur1 = get_loop_entry(cur) ?: cur;
1607 	hdr1 = get_loop_entry(hdr) ?: hdr;
1608 	/* The head1->branches check decides between cases B and C in
1609 	 * comment for get_loop_entry(). If hdr1->branches == 0 then
1610 	 * head's topmost loop entry is not in current DFS path,
1611 	 * hence 'cur' and 'hdr' are not in the same loop and there is
1612 	 * no need to update cur->loop_entry.
1613 	 */
1614 	if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1615 		cur->loop_entry = hdr;
1616 		hdr->used_as_loop_entry = true;
1617 	}
1618 }
1619 
1620 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1621 {
1622 	while (st) {
1623 		u32 br = --st->branches;
1624 
1625 		/* br == 0 signals that DFS exploration for 'st' is finished,
1626 		 * thus it is necessary to update parent's loop entry if it
1627 		 * turned out that st is a part of some loop.
1628 		 * This is a part of 'case A' in get_loop_entry() comment.
1629 		 */
1630 		if (br == 0 && st->parent && st->loop_entry)
1631 			update_loop_entry(st->parent, st->loop_entry);
1632 
1633 		/* WARN_ON(br > 1) technically makes sense here,
1634 		 * but see comment in push_stack(), hence:
1635 		 */
1636 		WARN_ONCE((int)br < 0,
1637 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1638 			  br);
1639 		if (br)
1640 			break;
1641 		st = st->parent;
1642 	}
1643 }
1644 
1645 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1646 		     int *insn_idx, bool pop_log)
1647 {
1648 	struct bpf_verifier_state *cur = env->cur_state;
1649 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1650 	int err;
1651 
1652 	if (env->head == NULL)
1653 		return -ENOENT;
1654 
1655 	if (cur) {
1656 		err = copy_verifier_state(cur, &head->st);
1657 		if (err)
1658 			return err;
1659 	}
1660 	if (pop_log)
1661 		bpf_vlog_reset(&env->log, head->log_pos);
1662 	if (insn_idx)
1663 		*insn_idx = head->insn_idx;
1664 	if (prev_insn_idx)
1665 		*prev_insn_idx = head->prev_insn_idx;
1666 	elem = head->next;
1667 	free_verifier_state(&head->st, false);
1668 	kfree(head);
1669 	env->head = elem;
1670 	env->stack_size--;
1671 	return 0;
1672 }
1673 
1674 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1675 					     int insn_idx, int prev_insn_idx,
1676 					     bool speculative)
1677 {
1678 	struct bpf_verifier_state *cur = env->cur_state;
1679 	struct bpf_verifier_stack_elem *elem;
1680 	int err;
1681 
1682 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1683 	if (!elem)
1684 		goto err;
1685 
1686 	elem->insn_idx = insn_idx;
1687 	elem->prev_insn_idx = prev_insn_idx;
1688 	elem->next = env->head;
1689 	elem->log_pos = env->log.end_pos;
1690 	env->head = elem;
1691 	env->stack_size++;
1692 	err = copy_verifier_state(&elem->st, cur);
1693 	if (err)
1694 		goto err;
1695 	elem->st.speculative |= speculative;
1696 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1697 		verbose(env, "The sequence of %d jumps is too complex.\n",
1698 			env->stack_size);
1699 		goto err;
1700 	}
1701 	if (elem->st.parent) {
1702 		++elem->st.parent->branches;
1703 		/* WARN_ON(branches > 2) technically makes sense here,
1704 		 * but
1705 		 * 1. speculative states will bump 'branches' for non-branch
1706 		 * instructions
1707 		 * 2. is_state_visited() heuristics may decide not to create
1708 		 * a new state for a sequence of branches and all such current
1709 		 * and cloned states will be pointing to a single parent state
1710 		 * which might have large 'branches' count.
1711 		 */
1712 	}
1713 	return &elem->st;
1714 err:
1715 	free_verifier_state(env->cur_state, true);
1716 	env->cur_state = NULL;
1717 	/* pop all elements and return */
1718 	while (!pop_stack(env, NULL, NULL, false));
1719 	return NULL;
1720 }
1721 
1722 #define CALLER_SAVED_REGS 6
1723 static const int caller_saved[CALLER_SAVED_REGS] = {
1724 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1725 };
1726 
1727 /* This helper doesn't clear reg->id */
1728 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1729 {
1730 	reg->var_off = tnum_const(imm);
1731 	reg->smin_value = (s64)imm;
1732 	reg->smax_value = (s64)imm;
1733 	reg->umin_value = imm;
1734 	reg->umax_value = imm;
1735 
1736 	reg->s32_min_value = (s32)imm;
1737 	reg->s32_max_value = (s32)imm;
1738 	reg->u32_min_value = (u32)imm;
1739 	reg->u32_max_value = (u32)imm;
1740 }
1741 
1742 /* Mark the unknown part of a register (variable offset or scalar value) as
1743  * known to have the value @imm.
1744  */
1745 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1746 {
1747 	/* Clear off and union(map_ptr, range) */
1748 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1749 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1750 	reg->id = 0;
1751 	reg->ref_obj_id = 0;
1752 	___mark_reg_known(reg, imm);
1753 }
1754 
1755 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1756 {
1757 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1758 	reg->s32_min_value = (s32)imm;
1759 	reg->s32_max_value = (s32)imm;
1760 	reg->u32_min_value = (u32)imm;
1761 	reg->u32_max_value = (u32)imm;
1762 }
1763 
1764 /* Mark the 'variable offset' part of a register as zero.  This should be
1765  * used only on registers holding a pointer type.
1766  */
1767 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1768 {
1769 	__mark_reg_known(reg, 0);
1770 }
1771 
1772 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1773 {
1774 	__mark_reg_known(reg, 0);
1775 	reg->type = SCALAR_VALUE;
1776 	/* all scalars are assumed imprecise initially (unless unprivileged,
1777 	 * in which case everything is forced to be precise)
1778 	 */
1779 	reg->precise = !env->bpf_capable;
1780 }
1781 
1782 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1783 				struct bpf_reg_state *regs, u32 regno)
1784 {
1785 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1786 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1787 		/* Something bad happened, let's kill all regs */
1788 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1789 			__mark_reg_not_init(env, regs + regno);
1790 		return;
1791 	}
1792 	__mark_reg_known_zero(regs + regno);
1793 }
1794 
1795 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1796 			      bool first_slot, int dynptr_id)
1797 {
1798 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1799 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1800 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1801 	 */
1802 	__mark_reg_known_zero(reg);
1803 	reg->type = CONST_PTR_TO_DYNPTR;
1804 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1805 	reg->id = dynptr_id;
1806 	reg->dynptr.type = type;
1807 	reg->dynptr.first_slot = first_slot;
1808 }
1809 
1810 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1811 {
1812 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1813 		const struct bpf_map *map = reg->map_ptr;
1814 
1815 		if (map->inner_map_meta) {
1816 			reg->type = CONST_PTR_TO_MAP;
1817 			reg->map_ptr = map->inner_map_meta;
1818 			/* transfer reg's id which is unique for every map_lookup_elem
1819 			 * as UID of the inner map.
1820 			 */
1821 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1822 				reg->map_uid = reg->id;
1823 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1824 			reg->type = PTR_TO_XDP_SOCK;
1825 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1826 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1827 			reg->type = PTR_TO_SOCKET;
1828 		} else {
1829 			reg->type = PTR_TO_MAP_VALUE;
1830 		}
1831 		return;
1832 	}
1833 
1834 	reg->type &= ~PTR_MAYBE_NULL;
1835 }
1836 
1837 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1838 				struct btf_field_graph_root *ds_head)
1839 {
1840 	__mark_reg_known_zero(&regs[regno]);
1841 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1842 	regs[regno].btf = ds_head->btf;
1843 	regs[regno].btf_id = ds_head->value_btf_id;
1844 	regs[regno].off = ds_head->node_offset;
1845 }
1846 
1847 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1848 {
1849 	return type_is_pkt_pointer(reg->type);
1850 }
1851 
1852 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1853 {
1854 	return reg_is_pkt_pointer(reg) ||
1855 	       reg->type == PTR_TO_PACKET_END;
1856 }
1857 
1858 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1859 {
1860 	return base_type(reg->type) == PTR_TO_MEM &&
1861 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1862 }
1863 
1864 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1865 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1866 				    enum bpf_reg_type which)
1867 {
1868 	/* The register can already have a range from prior markings.
1869 	 * This is fine as long as it hasn't been advanced from its
1870 	 * origin.
1871 	 */
1872 	return reg->type == which &&
1873 	       reg->id == 0 &&
1874 	       reg->off == 0 &&
1875 	       tnum_equals_const(reg->var_off, 0);
1876 }
1877 
1878 /* Reset the min/max bounds of a register */
1879 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1880 {
1881 	reg->smin_value = S64_MIN;
1882 	reg->smax_value = S64_MAX;
1883 	reg->umin_value = 0;
1884 	reg->umax_value = U64_MAX;
1885 
1886 	reg->s32_min_value = S32_MIN;
1887 	reg->s32_max_value = S32_MAX;
1888 	reg->u32_min_value = 0;
1889 	reg->u32_max_value = U32_MAX;
1890 }
1891 
1892 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1893 {
1894 	reg->smin_value = S64_MIN;
1895 	reg->smax_value = S64_MAX;
1896 	reg->umin_value = 0;
1897 	reg->umax_value = U64_MAX;
1898 }
1899 
1900 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1901 {
1902 	reg->s32_min_value = S32_MIN;
1903 	reg->s32_max_value = S32_MAX;
1904 	reg->u32_min_value = 0;
1905 	reg->u32_max_value = U32_MAX;
1906 }
1907 
1908 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1909 {
1910 	struct tnum var32_off = tnum_subreg(reg->var_off);
1911 
1912 	/* min signed is max(sign bit) | min(other bits) */
1913 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1914 			var32_off.value | (var32_off.mask & S32_MIN));
1915 	/* max signed is min(sign bit) | max(other bits) */
1916 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1917 			var32_off.value | (var32_off.mask & S32_MAX));
1918 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1919 	reg->u32_max_value = min(reg->u32_max_value,
1920 				 (u32)(var32_off.value | var32_off.mask));
1921 }
1922 
1923 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1924 {
1925 	/* min signed is max(sign bit) | min(other bits) */
1926 	reg->smin_value = max_t(s64, reg->smin_value,
1927 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1928 	/* max signed is min(sign bit) | max(other bits) */
1929 	reg->smax_value = min_t(s64, reg->smax_value,
1930 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1931 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1932 	reg->umax_value = min(reg->umax_value,
1933 			      reg->var_off.value | reg->var_off.mask);
1934 }
1935 
1936 static void __update_reg_bounds(struct bpf_reg_state *reg)
1937 {
1938 	__update_reg32_bounds(reg);
1939 	__update_reg64_bounds(reg);
1940 }
1941 
1942 /* Uses signed min/max values to inform unsigned, and vice-versa */
1943 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1944 {
1945 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
1946 	 * bits to improve our u32/s32 boundaries.
1947 	 *
1948 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
1949 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
1950 	 * [10, 20] range. But this property holds for any 64-bit range as
1951 	 * long as upper 32 bits in that entire range of values stay the same.
1952 	 *
1953 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
1954 	 * in decimal) has the same upper 32 bits throughout all the values in
1955 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
1956 	 * range.
1957 	 *
1958 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
1959 	 * following the rules outlined below about u64/s64 correspondence
1960 	 * (which equally applies to u32 vs s32 correspondence). In general it
1961 	 * depends on actual hexadecimal values of 32-bit range. They can form
1962 	 * only valid u32, or only valid s32 ranges in some cases.
1963 	 *
1964 	 * So we use all these insights to derive bounds for subregisters here.
1965 	 */
1966 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
1967 		/* u64 to u32 casting preserves validity of low 32 bits as
1968 		 * a range, if upper 32 bits are the same
1969 		 */
1970 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
1971 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
1972 
1973 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
1974 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
1975 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
1976 		}
1977 	}
1978 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
1979 		/* low 32 bits should form a proper u32 range */
1980 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
1981 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
1982 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
1983 		}
1984 		/* low 32 bits should form a proper s32 range */
1985 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
1986 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
1987 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
1988 		}
1989 	}
1990 	/* Special case where upper bits form a small sequence of two
1991 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
1992 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
1993 	 * going from negative numbers to positive numbers. E.g., let's say we
1994 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
1995 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
1996 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
1997 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
1998 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
1999 	 * upper 32 bits. As a random example, s64 range
2000 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2001 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2002 	 */
2003 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2004 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2005 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2006 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2007 	}
2008 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2009 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2010 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2011 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2012 	}
2013 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2014 	 * try to learn from that
2015 	 */
2016 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2017 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2018 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2019 	}
2020 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2021 	 * are the same, so combine.  This works even in the negative case, e.g.
2022 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2023 	 */
2024 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2025 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2026 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2027 	}
2028 }
2029 
2030 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2031 {
2032 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2033 	 * try to learn from that. Let's do a bit of ASCII art to see when
2034 	 * this is happening. Let's take u64 range first:
2035 	 *
2036 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2037 	 * |-------------------------------|--------------------------------|
2038 	 *
2039 	 * Valid u64 range is formed when umin and umax are anywhere in the
2040 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2041 	 * straightforward. Let's see how s64 range maps onto the same range
2042 	 * of values, annotated below the line for comparison:
2043 	 *
2044 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2045 	 * |-------------------------------|--------------------------------|
2046 	 * 0                        S64_MAX S64_MIN                        -1
2047 	 *
2048 	 * So s64 values basically start in the middle and they are logically
2049 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2050 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2051 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2052 	 * more visually as mapped to sign-agnostic range of hex values.
2053 	 *
2054 	 *  u64 start                                               u64 end
2055 	 *  _______________________________________________________________
2056 	 * /                                                               \
2057 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2058 	 * |-------------------------------|--------------------------------|
2059 	 * 0                        S64_MAX S64_MIN                        -1
2060 	 *                                / \
2061 	 * >------------------------------   ------------------------------->
2062 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2063 	 *
2064 	 * What this means is that, in general, we can't always derive
2065 	 * something new about u64 from any random s64 range, and vice versa.
2066 	 *
2067 	 * But we can do that in two particular cases. One is when entire
2068 	 * u64/s64 range is *entirely* contained within left half of the above
2069 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2070 	 *
2071 	 * |-------------------------------|--------------------------------|
2072 	 *     ^                   ^            ^                 ^
2073 	 *     A                   B            C                 D
2074 	 *
2075 	 * [A, B] and [C, D] are contained entirely in their respective halves
2076 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2077 	 * will be non-negative both as u64 and s64 (and in fact it will be
2078 	 * identical ranges no matter the signedness). [C, D] treated as s64
2079 	 * will be a range of negative values, while in u64 it will be
2080 	 * non-negative range of values larger than 0x8000000000000000.
2081 	 *
2082 	 * Now, any other range here can't be represented in both u64 and s64
2083 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2084 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2085 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2086 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2087 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2088 	 * ranges as u64. Currently reg_state can't represent two segments per
2089 	 * numeric domain, so in such situations we can only derive maximal
2090 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2091 	 *
2092 	 * So we use these facts to derive umin/umax from smin/smax and vice
2093 	 * versa only if they stay within the same "half". This is equivalent
2094 	 * to checking sign bit: lower half will have sign bit as zero, upper
2095 	 * half have sign bit 1. Below in code we simplify this by just
2096 	 * casting umin/umax as smin/smax and checking if they form valid
2097 	 * range, and vice versa. Those are equivalent checks.
2098 	 */
2099 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2100 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2101 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2102 	}
2103 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2104 	 * are the same, so combine.  This works even in the negative case, e.g.
2105 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2106 	 */
2107 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2108 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2109 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2110 	}
2111 }
2112 
2113 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2114 {
2115 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2116 	 * values on both sides of 64-bit range in hope to have tigher range.
2117 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2118 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2119 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2120 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2121 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2122 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2123 	 * We just need to make sure that derived bounds we are intersecting
2124 	 * with are well-formed ranges in respecitve s64 or u64 domain, just
2125 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2126 	 */
2127 	__u64 new_umin, new_umax;
2128 	__s64 new_smin, new_smax;
2129 
2130 	/* u32 -> u64 tightening, it's always well-formed */
2131 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2132 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2133 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2134 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2135 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2136 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2137 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2138 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2139 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2140 
2141 	/* if s32 can be treated as valid u32 range, we can use it as well */
2142 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2143 		/* s32 -> u64 tightening */
2144 		new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2145 		new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2146 		reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2147 		reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2148 		/* s32 -> s64 tightening */
2149 		new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2150 		new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2151 		reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2152 		reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2153 	}
2154 }
2155 
2156 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2157 {
2158 	__reg32_deduce_bounds(reg);
2159 	__reg64_deduce_bounds(reg);
2160 	__reg_deduce_mixed_bounds(reg);
2161 }
2162 
2163 /* Attempts to improve var_off based on unsigned min/max information */
2164 static void __reg_bound_offset(struct bpf_reg_state *reg)
2165 {
2166 	struct tnum var64_off = tnum_intersect(reg->var_off,
2167 					       tnum_range(reg->umin_value,
2168 							  reg->umax_value));
2169 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2170 					       tnum_range(reg->u32_min_value,
2171 							  reg->u32_max_value));
2172 
2173 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2174 }
2175 
2176 static void reg_bounds_sync(struct bpf_reg_state *reg)
2177 {
2178 	/* We might have learned new bounds from the var_off. */
2179 	__update_reg_bounds(reg);
2180 	/* We might have learned something about the sign bit. */
2181 	__reg_deduce_bounds(reg);
2182 	__reg_deduce_bounds(reg);
2183 	/* We might have learned some bits from the bounds. */
2184 	__reg_bound_offset(reg);
2185 	/* Intersecting with the old var_off might have improved our bounds
2186 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2187 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2188 	 */
2189 	__update_reg_bounds(reg);
2190 }
2191 
2192 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2193 				   struct bpf_reg_state *reg, const char *ctx)
2194 {
2195 	const char *msg;
2196 
2197 	if (reg->umin_value > reg->umax_value ||
2198 	    reg->smin_value > reg->smax_value ||
2199 	    reg->u32_min_value > reg->u32_max_value ||
2200 	    reg->s32_min_value > reg->s32_max_value) {
2201 		    msg = "range bounds violation";
2202 		    goto out;
2203 	}
2204 
2205 	if (tnum_is_const(reg->var_off)) {
2206 		u64 uval = reg->var_off.value;
2207 		s64 sval = (s64)uval;
2208 
2209 		if (reg->umin_value != uval || reg->umax_value != uval ||
2210 		    reg->smin_value != sval || reg->smax_value != sval) {
2211 			msg = "const tnum out of sync with range bounds";
2212 			goto out;
2213 		}
2214 	}
2215 
2216 	if (tnum_subreg_is_const(reg->var_off)) {
2217 		u32 uval32 = tnum_subreg(reg->var_off).value;
2218 		s32 sval32 = (s32)uval32;
2219 
2220 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2221 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2222 			msg = "const subreg tnum out of sync with range bounds";
2223 			goto out;
2224 		}
2225 	}
2226 
2227 	return 0;
2228 out:
2229 	verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2230 		"s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n",
2231 		ctx, msg, reg->umin_value, reg->umax_value,
2232 		reg->smin_value, reg->smax_value,
2233 		reg->u32_min_value, reg->u32_max_value,
2234 		reg->s32_min_value, reg->s32_max_value,
2235 		reg->var_off.value, reg->var_off.mask);
2236 	if (env->test_reg_invariants)
2237 		return -EFAULT;
2238 	__mark_reg_unbounded(reg);
2239 	return 0;
2240 }
2241 
2242 static bool __reg32_bound_s64(s32 a)
2243 {
2244 	return a >= 0 && a <= S32_MAX;
2245 }
2246 
2247 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2248 {
2249 	reg->umin_value = reg->u32_min_value;
2250 	reg->umax_value = reg->u32_max_value;
2251 
2252 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2253 	 * be positive otherwise set to worse case bounds and refine later
2254 	 * from tnum.
2255 	 */
2256 	if (__reg32_bound_s64(reg->s32_min_value) &&
2257 	    __reg32_bound_s64(reg->s32_max_value)) {
2258 		reg->smin_value = reg->s32_min_value;
2259 		reg->smax_value = reg->s32_max_value;
2260 	} else {
2261 		reg->smin_value = 0;
2262 		reg->smax_value = U32_MAX;
2263 	}
2264 }
2265 
2266 /* Mark a register as having a completely unknown (scalar) value. */
2267 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2268 			       struct bpf_reg_state *reg)
2269 {
2270 	/*
2271 	 * Clear type, off, and union(map_ptr, range) and
2272 	 * padding between 'type' and union
2273 	 */
2274 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2275 	reg->type = SCALAR_VALUE;
2276 	reg->id = 0;
2277 	reg->ref_obj_id = 0;
2278 	reg->var_off = tnum_unknown;
2279 	reg->frameno = 0;
2280 	reg->precise = !env->bpf_capable;
2281 	__mark_reg_unbounded(reg);
2282 }
2283 
2284 static void mark_reg_unknown(struct bpf_verifier_env *env,
2285 			     struct bpf_reg_state *regs, u32 regno)
2286 {
2287 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2288 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2289 		/* Something bad happened, let's kill all regs except FP */
2290 		for (regno = 0; regno < BPF_REG_FP; regno++)
2291 			__mark_reg_not_init(env, regs + regno);
2292 		return;
2293 	}
2294 	__mark_reg_unknown(env, regs + regno);
2295 }
2296 
2297 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2298 				struct bpf_reg_state *reg)
2299 {
2300 	__mark_reg_unknown(env, reg);
2301 	reg->type = NOT_INIT;
2302 }
2303 
2304 static void mark_reg_not_init(struct bpf_verifier_env *env,
2305 			      struct bpf_reg_state *regs, u32 regno)
2306 {
2307 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2308 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2309 		/* Something bad happened, let's kill all regs except FP */
2310 		for (regno = 0; regno < BPF_REG_FP; regno++)
2311 			__mark_reg_not_init(env, regs + regno);
2312 		return;
2313 	}
2314 	__mark_reg_not_init(env, regs + regno);
2315 }
2316 
2317 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2318 			    struct bpf_reg_state *regs, u32 regno,
2319 			    enum bpf_reg_type reg_type,
2320 			    struct btf *btf, u32 btf_id,
2321 			    enum bpf_type_flag flag)
2322 {
2323 	if (reg_type == SCALAR_VALUE) {
2324 		mark_reg_unknown(env, regs, regno);
2325 		return;
2326 	}
2327 	mark_reg_known_zero(env, regs, regno);
2328 	regs[regno].type = PTR_TO_BTF_ID | flag;
2329 	regs[regno].btf = btf;
2330 	regs[regno].btf_id = btf_id;
2331 }
2332 
2333 #define DEF_NOT_SUBREG	(0)
2334 static void init_reg_state(struct bpf_verifier_env *env,
2335 			   struct bpf_func_state *state)
2336 {
2337 	struct bpf_reg_state *regs = state->regs;
2338 	int i;
2339 
2340 	for (i = 0; i < MAX_BPF_REG; i++) {
2341 		mark_reg_not_init(env, regs, i);
2342 		regs[i].live = REG_LIVE_NONE;
2343 		regs[i].parent = NULL;
2344 		regs[i].subreg_def = DEF_NOT_SUBREG;
2345 	}
2346 
2347 	/* frame pointer */
2348 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2349 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2350 	regs[BPF_REG_FP].frameno = state->frameno;
2351 }
2352 
2353 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2354 {
2355 	return (struct bpf_retval_range){ minval, maxval };
2356 }
2357 
2358 #define BPF_MAIN_FUNC (-1)
2359 static void init_func_state(struct bpf_verifier_env *env,
2360 			    struct bpf_func_state *state,
2361 			    int callsite, int frameno, int subprogno)
2362 {
2363 	state->callsite = callsite;
2364 	state->frameno = frameno;
2365 	state->subprogno = subprogno;
2366 	state->callback_ret_range = retval_range(0, 0);
2367 	init_reg_state(env, state);
2368 	mark_verifier_state_scratched(env);
2369 }
2370 
2371 /* Similar to push_stack(), but for async callbacks */
2372 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2373 						int insn_idx, int prev_insn_idx,
2374 						int subprog)
2375 {
2376 	struct bpf_verifier_stack_elem *elem;
2377 	struct bpf_func_state *frame;
2378 
2379 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2380 	if (!elem)
2381 		goto err;
2382 
2383 	elem->insn_idx = insn_idx;
2384 	elem->prev_insn_idx = prev_insn_idx;
2385 	elem->next = env->head;
2386 	elem->log_pos = env->log.end_pos;
2387 	env->head = elem;
2388 	env->stack_size++;
2389 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2390 		verbose(env,
2391 			"The sequence of %d jumps is too complex for async cb.\n",
2392 			env->stack_size);
2393 		goto err;
2394 	}
2395 	/* Unlike push_stack() do not copy_verifier_state().
2396 	 * The caller state doesn't matter.
2397 	 * This is async callback. It starts in a fresh stack.
2398 	 * Initialize it similar to do_check_common().
2399 	 */
2400 	elem->st.branches = 1;
2401 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2402 	if (!frame)
2403 		goto err;
2404 	init_func_state(env, frame,
2405 			BPF_MAIN_FUNC /* callsite */,
2406 			0 /* frameno within this callchain */,
2407 			subprog /* subprog number within this prog */);
2408 	elem->st.frame[0] = frame;
2409 	return &elem->st;
2410 err:
2411 	free_verifier_state(env->cur_state, true);
2412 	env->cur_state = NULL;
2413 	/* pop all elements and return */
2414 	while (!pop_stack(env, NULL, NULL, false));
2415 	return NULL;
2416 }
2417 
2418 
2419 enum reg_arg_type {
2420 	SRC_OP,		/* register is used as source operand */
2421 	DST_OP,		/* register is used as destination operand */
2422 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2423 };
2424 
2425 static int cmp_subprogs(const void *a, const void *b)
2426 {
2427 	return ((struct bpf_subprog_info *)a)->start -
2428 	       ((struct bpf_subprog_info *)b)->start;
2429 }
2430 
2431 static int find_subprog(struct bpf_verifier_env *env, int off)
2432 {
2433 	struct bpf_subprog_info *p;
2434 
2435 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2436 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2437 	if (!p)
2438 		return -ENOENT;
2439 	return p - env->subprog_info;
2440 
2441 }
2442 
2443 static int add_subprog(struct bpf_verifier_env *env, int off)
2444 {
2445 	int insn_cnt = env->prog->len;
2446 	int ret;
2447 
2448 	if (off >= insn_cnt || off < 0) {
2449 		verbose(env, "call to invalid destination\n");
2450 		return -EINVAL;
2451 	}
2452 	ret = find_subprog(env, off);
2453 	if (ret >= 0)
2454 		return ret;
2455 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2456 		verbose(env, "too many subprograms\n");
2457 		return -E2BIG;
2458 	}
2459 	/* determine subprog starts. The end is one before the next starts */
2460 	env->subprog_info[env->subprog_cnt++].start = off;
2461 	sort(env->subprog_info, env->subprog_cnt,
2462 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2463 	return env->subprog_cnt - 1;
2464 }
2465 
2466 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2467 {
2468 	struct bpf_prog_aux *aux = env->prog->aux;
2469 	struct btf *btf = aux->btf;
2470 	const struct btf_type *t;
2471 	u32 main_btf_id, id;
2472 	const char *name;
2473 	int ret, i;
2474 
2475 	/* Non-zero func_info_cnt implies valid btf */
2476 	if (!aux->func_info_cnt)
2477 		return 0;
2478 	main_btf_id = aux->func_info[0].type_id;
2479 
2480 	t = btf_type_by_id(btf, main_btf_id);
2481 	if (!t) {
2482 		verbose(env, "invalid btf id for main subprog in func_info\n");
2483 		return -EINVAL;
2484 	}
2485 
2486 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2487 	if (IS_ERR(name)) {
2488 		ret = PTR_ERR(name);
2489 		/* If there is no tag present, there is no exception callback */
2490 		if (ret == -ENOENT)
2491 			ret = 0;
2492 		else if (ret == -EEXIST)
2493 			verbose(env, "multiple exception callback tags for main subprog\n");
2494 		return ret;
2495 	}
2496 
2497 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2498 	if (ret < 0) {
2499 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2500 		return ret;
2501 	}
2502 	id = ret;
2503 	t = btf_type_by_id(btf, id);
2504 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2505 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2506 		return -EINVAL;
2507 	}
2508 	ret = 0;
2509 	for (i = 0; i < aux->func_info_cnt; i++) {
2510 		if (aux->func_info[i].type_id != id)
2511 			continue;
2512 		ret = aux->func_info[i].insn_off;
2513 		/* Further func_info and subprog checks will also happen
2514 		 * later, so assume this is the right insn_off for now.
2515 		 */
2516 		if (!ret) {
2517 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2518 			ret = -EINVAL;
2519 		}
2520 	}
2521 	if (!ret) {
2522 		verbose(env, "exception callback type id not found in func_info\n");
2523 		ret = -EINVAL;
2524 	}
2525 	return ret;
2526 }
2527 
2528 #define MAX_KFUNC_DESCS 256
2529 #define MAX_KFUNC_BTFS	256
2530 
2531 struct bpf_kfunc_desc {
2532 	struct btf_func_model func_model;
2533 	u32 func_id;
2534 	s32 imm;
2535 	u16 offset;
2536 	unsigned long addr;
2537 };
2538 
2539 struct bpf_kfunc_btf {
2540 	struct btf *btf;
2541 	struct module *module;
2542 	u16 offset;
2543 };
2544 
2545 struct bpf_kfunc_desc_tab {
2546 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2547 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2548 	 * available, therefore at the end of verification do_misc_fixups()
2549 	 * sorts this by imm and offset.
2550 	 */
2551 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2552 	u32 nr_descs;
2553 };
2554 
2555 struct bpf_kfunc_btf_tab {
2556 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2557 	u32 nr_descs;
2558 };
2559 
2560 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2561 {
2562 	const struct bpf_kfunc_desc *d0 = a;
2563 	const struct bpf_kfunc_desc *d1 = b;
2564 
2565 	/* func_id is not greater than BTF_MAX_TYPE */
2566 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2567 }
2568 
2569 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2570 {
2571 	const struct bpf_kfunc_btf *d0 = a;
2572 	const struct bpf_kfunc_btf *d1 = b;
2573 
2574 	return d0->offset - d1->offset;
2575 }
2576 
2577 static const struct bpf_kfunc_desc *
2578 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2579 {
2580 	struct bpf_kfunc_desc desc = {
2581 		.func_id = func_id,
2582 		.offset = offset,
2583 	};
2584 	struct bpf_kfunc_desc_tab *tab;
2585 
2586 	tab = prog->aux->kfunc_tab;
2587 	return bsearch(&desc, tab->descs, tab->nr_descs,
2588 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2589 }
2590 
2591 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2592 		       u16 btf_fd_idx, u8 **func_addr)
2593 {
2594 	const struct bpf_kfunc_desc *desc;
2595 
2596 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2597 	if (!desc)
2598 		return -EFAULT;
2599 
2600 	*func_addr = (u8 *)desc->addr;
2601 	return 0;
2602 }
2603 
2604 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2605 					 s16 offset)
2606 {
2607 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2608 	struct bpf_kfunc_btf_tab *tab;
2609 	struct bpf_kfunc_btf *b;
2610 	struct module *mod;
2611 	struct btf *btf;
2612 	int btf_fd;
2613 
2614 	tab = env->prog->aux->kfunc_btf_tab;
2615 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2616 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2617 	if (!b) {
2618 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2619 			verbose(env, "too many different module BTFs\n");
2620 			return ERR_PTR(-E2BIG);
2621 		}
2622 
2623 		if (bpfptr_is_null(env->fd_array)) {
2624 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2625 			return ERR_PTR(-EPROTO);
2626 		}
2627 
2628 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2629 					    offset * sizeof(btf_fd),
2630 					    sizeof(btf_fd)))
2631 			return ERR_PTR(-EFAULT);
2632 
2633 		btf = btf_get_by_fd(btf_fd);
2634 		if (IS_ERR(btf)) {
2635 			verbose(env, "invalid module BTF fd specified\n");
2636 			return btf;
2637 		}
2638 
2639 		if (!btf_is_module(btf)) {
2640 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2641 			btf_put(btf);
2642 			return ERR_PTR(-EINVAL);
2643 		}
2644 
2645 		mod = btf_try_get_module(btf);
2646 		if (!mod) {
2647 			btf_put(btf);
2648 			return ERR_PTR(-ENXIO);
2649 		}
2650 
2651 		b = &tab->descs[tab->nr_descs++];
2652 		b->btf = btf;
2653 		b->module = mod;
2654 		b->offset = offset;
2655 
2656 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2657 		     kfunc_btf_cmp_by_off, NULL);
2658 	}
2659 	return b->btf;
2660 }
2661 
2662 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2663 {
2664 	if (!tab)
2665 		return;
2666 
2667 	while (tab->nr_descs--) {
2668 		module_put(tab->descs[tab->nr_descs].module);
2669 		btf_put(tab->descs[tab->nr_descs].btf);
2670 	}
2671 	kfree(tab);
2672 }
2673 
2674 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2675 {
2676 	if (offset) {
2677 		if (offset < 0) {
2678 			/* In the future, this can be allowed to increase limit
2679 			 * of fd index into fd_array, interpreted as u16.
2680 			 */
2681 			verbose(env, "negative offset disallowed for kernel module function call\n");
2682 			return ERR_PTR(-EINVAL);
2683 		}
2684 
2685 		return __find_kfunc_desc_btf(env, offset);
2686 	}
2687 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2688 }
2689 
2690 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2691 {
2692 	const struct btf_type *func, *func_proto;
2693 	struct bpf_kfunc_btf_tab *btf_tab;
2694 	struct bpf_kfunc_desc_tab *tab;
2695 	struct bpf_prog_aux *prog_aux;
2696 	struct bpf_kfunc_desc *desc;
2697 	const char *func_name;
2698 	struct btf *desc_btf;
2699 	unsigned long call_imm;
2700 	unsigned long addr;
2701 	int err;
2702 
2703 	prog_aux = env->prog->aux;
2704 	tab = prog_aux->kfunc_tab;
2705 	btf_tab = prog_aux->kfunc_btf_tab;
2706 	if (!tab) {
2707 		if (!btf_vmlinux) {
2708 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2709 			return -ENOTSUPP;
2710 		}
2711 
2712 		if (!env->prog->jit_requested) {
2713 			verbose(env, "JIT is required for calling kernel function\n");
2714 			return -ENOTSUPP;
2715 		}
2716 
2717 		if (!bpf_jit_supports_kfunc_call()) {
2718 			verbose(env, "JIT does not support calling kernel function\n");
2719 			return -ENOTSUPP;
2720 		}
2721 
2722 		if (!env->prog->gpl_compatible) {
2723 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2724 			return -EINVAL;
2725 		}
2726 
2727 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2728 		if (!tab)
2729 			return -ENOMEM;
2730 		prog_aux->kfunc_tab = tab;
2731 	}
2732 
2733 	/* func_id == 0 is always invalid, but instead of returning an error, be
2734 	 * conservative and wait until the code elimination pass before returning
2735 	 * error, so that invalid calls that get pruned out can be in BPF programs
2736 	 * loaded from userspace.  It is also required that offset be untouched
2737 	 * for such calls.
2738 	 */
2739 	if (!func_id && !offset)
2740 		return 0;
2741 
2742 	if (!btf_tab && offset) {
2743 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2744 		if (!btf_tab)
2745 			return -ENOMEM;
2746 		prog_aux->kfunc_btf_tab = btf_tab;
2747 	}
2748 
2749 	desc_btf = find_kfunc_desc_btf(env, offset);
2750 	if (IS_ERR(desc_btf)) {
2751 		verbose(env, "failed to find BTF for kernel function\n");
2752 		return PTR_ERR(desc_btf);
2753 	}
2754 
2755 	if (find_kfunc_desc(env->prog, func_id, offset))
2756 		return 0;
2757 
2758 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2759 		verbose(env, "too many different kernel function calls\n");
2760 		return -E2BIG;
2761 	}
2762 
2763 	func = btf_type_by_id(desc_btf, func_id);
2764 	if (!func || !btf_type_is_func(func)) {
2765 		verbose(env, "kernel btf_id %u is not a function\n",
2766 			func_id);
2767 		return -EINVAL;
2768 	}
2769 	func_proto = btf_type_by_id(desc_btf, func->type);
2770 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2771 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2772 			func_id);
2773 		return -EINVAL;
2774 	}
2775 
2776 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2777 	addr = kallsyms_lookup_name(func_name);
2778 	if (!addr) {
2779 		verbose(env, "cannot find address for kernel function %s\n",
2780 			func_name);
2781 		return -EINVAL;
2782 	}
2783 	specialize_kfunc(env, func_id, offset, &addr);
2784 
2785 	if (bpf_jit_supports_far_kfunc_call()) {
2786 		call_imm = func_id;
2787 	} else {
2788 		call_imm = BPF_CALL_IMM(addr);
2789 		/* Check whether the relative offset overflows desc->imm */
2790 		if ((unsigned long)(s32)call_imm != call_imm) {
2791 			verbose(env, "address of kernel function %s is out of range\n",
2792 				func_name);
2793 			return -EINVAL;
2794 		}
2795 	}
2796 
2797 	if (bpf_dev_bound_kfunc_id(func_id)) {
2798 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2799 		if (err)
2800 			return err;
2801 	}
2802 
2803 	desc = &tab->descs[tab->nr_descs++];
2804 	desc->func_id = func_id;
2805 	desc->imm = call_imm;
2806 	desc->offset = offset;
2807 	desc->addr = addr;
2808 	err = btf_distill_func_proto(&env->log, desc_btf,
2809 				     func_proto, func_name,
2810 				     &desc->func_model);
2811 	if (!err)
2812 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2813 		     kfunc_desc_cmp_by_id_off, NULL);
2814 	return err;
2815 }
2816 
2817 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2818 {
2819 	const struct bpf_kfunc_desc *d0 = a;
2820 	const struct bpf_kfunc_desc *d1 = b;
2821 
2822 	if (d0->imm != d1->imm)
2823 		return d0->imm < d1->imm ? -1 : 1;
2824 	if (d0->offset != d1->offset)
2825 		return d0->offset < d1->offset ? -1 : 1;
2826 	return 0;
2827 }
2828 
2829 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2830 {
2831 	struct bpf_kfunc_desc_tab *tab;
2832 
2833 	tab = prog->aux->kfunc_tab;
2834 	if (!tab)
2835 		return;
2836 
2837 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2838 	     kfunc_desc_cmp_by_imm_off, NULL);
2839 }
2840 
2841 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2842 {
2843 	return !!prog->aux->kfunc_tab;
2844 }
2845 
2846 const struct btf_func_model *
2847 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2848 			 const struct bpf_insn *insn)
2849 {
2850 	const struct bpf_kfunc_desc desc = {
2851 		.imm = insn->imm,
2852 		.offset = insn->off,
2853 	};
2854 	const struct bpf_kfunc_desc *res;
2855 	struct bpf_kfunc_desc_tab *tab;
2856 
2857 	tab = prog->aux->kfunc_tab;
2858 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2859 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2860 
2861 	return res ? &res->func_model : NULL;
2862 }
2863 
2864 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2865 {
2866 	struct bpf_subprog_info *subprog = env->subprog_info;
2867 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
2868 	struct bpf_insn *insn = env->prog->insnsi;
2869 
2870 	/* Add entry function. */
2871 	ret = add_subprog(env, 0);
2872 	if (ret)
2873 		return ret;
2874 
2875 	for (i = 0; i < insn_cnt; i++, insn++) {
2876 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2877 		    !bpf_pseudo_kfunc_call(insn))
2878 			continue;
2879 
2880 		if (!env->bpf_capable) {
2881 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2882 			return -EPERM;
2883 		}
2884 
2885 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2886 			ret = add_subprog(env, i + insn->imm + 1);
2887 		else
2888 			ret = add_kfunc_call(env, insn->imm, insn->off);
2889 
2890 		if (ret < 0)
2891 			return ret;
2892 	}
2893 
2894 	ret = bpf_find_exception_callback_insn_off(env);
2895 	if (ret < 0)
2896 		return ret;
2897 	ex_cb_insn = ret;
2898 
2899 	/* If ex_cb_insn > 0, this means that the main program has a subprog
2900 	 * marked using BTF decl tag to serve as the exception callback.
2901 	 */
2902 	if (ex_cb_insn) {
2903 		ret = add_subprog(env, ex_cb_insn);
2904 		if (ret < 0)
2905 			return ret;
2906 		for (i = 1; i < env->subprog_cnt; i++) {
2907 			if (env->subprog_info[i].start != ex_cb_insn)
2908 				continue;
2909 			env->exception_callback_subprog = i;
2910 			mark_subprog_exc_cb(env, i);
2911 			break;
2912 		}
2913 	}
2914 
2915 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2916 	 * logic. 'subprog_cnt' should not be increased.
2917 	 */
2918 	subprog[env->subprog_cnt].start = insn_cnt;
2919 
2920 	if (env->log.level & BPF_LOG_LEVEL2)
2921 		for (i = 0; i < env->subprog_cnt; i++)
2922 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2923 
2924 	return 0;
2925 }
2926 
2927 static int check_subprogs(struct bpf_verifier_env *env)
2928 {
2929 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2930 	struct bpf_subprog_info *subprog = env->subprog_info;
2931 	struct bpf_insn *insn = env->prog->insnsi;
2932 	int insn_cnt = env->prog->len;
2933 
2934 	/* now check that all jumps are within the same subprog */
2935 	subprog_start = subprog[cur_subprog].start;
2936 	subprog_end = subprog[cur_subprog + 1].start;
2937 	for (i = 0; i < insn_cnt; i++) {
2938 		u8 code = insn[i].code;
2939 
2940 		if (code == (BPF_JMP | BPF_CALL) &&
2941 		    insn[i].src_reg == 0 &&
2942 		    insn[i].imm == BPF_FUNC_tail_call)
2943 			subprog[cur_subprog].has_tail_call = true;
2944 		if (BPF_CLASS(code) == BPF_LD &&
2945 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2946 			subprog[cur_subprog].has_ld_abs = true;
2947 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2948 			goto next;
2949 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2950 			goto next;
2951 		if (code == (BPF_JMP32 | BPF_JA))
2952 			off = i + insn[i].imm + 1;
2953 		else
2954 			off = i + insn[i].off + 1;
2955 		if (off < subprog_start || off >= subprog_end) {
2956 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2957 			return -EINVAL;
2958 		}
2959 next:
2960 		if (i == subprog_end - 1) {
2961 			/* to avoid fall-through from one subprog into another
2962 			 * the last insn of the subprog should be either exit
2963 			 * or unconditional jump back or bpf_throw call
2964 			 */
2965 			if (code != (BPF_JMP | BPF_EXIT) &&
2966 			    code != (BPF_JMP32 | BPF_JA) &&
2967 			    code != (BPF_JMP | BPF_JA)) {
2968 				verbose(env, "last insn is not an exit or jmp\n");
2969 				return -EINVAL;
2970 			}
2971 			subprog_start = subprog_end;
2972 			cur_subprog++;
2973 			if (cur_subprog < env->subprog_cnt)
2974 				subprog_end = subprog[cur_subprog + 1].start;
2975 		}
2976 	}
2977 	return 0;
2978 }
2979 
2980 /* Parentage chain of this register (or stack slot) should take care of all
2981  * issues like callee-saved registers, stack slot allocation time, etc.
2982  */
2983 static int mark_reg_read(struct bpf_verifier_env *env,
2984 			 const struct bpf_reg_state *state,
2985 			 struct bpf_reg_state *parent, u8 flag)
2986 {
2987 	bool writes = parent == state->parent; /* Observe write marks */
2988 	int cnt = 0;
2989 
2990 	while (parent) {
2991 		/* if read wasn't screened by an earlier write ... */
2992 		if (writes && state->live & REG_LIVE_WRITTEN)
2993 			break;
2994 		if (parent->live & REG_LIVE_DONE) {
2995 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2996 				reg_type_str(env, parent->type),
2997 				parent->var_off.value, parent->off);
2998 			return -EFAULT;
2999 		}
3000 		/* The first condition is more likely to be true than the
3001 		 * second, checked it first.
3002 		 */
3003 		if ((parent->live & REG_LIVE_READ) == flag ||
3004 		    parent->live & REG_LIVE_READ64)
3005 			/* The parentage chain never changes and
3006 			 * this parent was already marked as LIVE_READ.
3007 			 * There is no need to keep walking the chain again and
3008 			 * keep re-marking all parents as LIVE_READ.
3009 			 * This case happens when the same register is read
3010 			 * multiple times without writes into it in-between.
3011 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3012 			 * then no need to set the weak REG_LIVE_READ32.
3013 			 */
3014 			break;
3015 		/* ... then we depend on parent's value */
3016 		parent->live |= flag;
3017 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3018 		if (flag == REG_LIVE_READ64)
3019 			parent->live &= ~REG_LIVE_READ32;
3020 		state = parent;
3021 		parent = state->parent;
3022 		writes = true;
3023 		cnt++;
3024 	}
3025 
3026 	if (env->longest_mark_read_walk < cnt)
3027 		env->longest_mark_read_walk = cnt;
3028 	return 0;
3029 }
3030 
3031 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3032 {
3033 	struct bpf_func_state *state = func(env, reg);
3034 	int spi, ret;
3035 
3036 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3037 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3038 	 * check_kfunc_call.
3039 	 */
3040 	if (reg->type == CONST_PTR_TO_DYNPTR)
3041 		return 0;
3042 	spi = dynptr_get_spi(env, reg);
3043 	if (spi < 0)
3044 		return spi;
3045 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3046 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3047 	 * read.
3048 	 */
3049 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3050 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3051 	if (ret)
3052 		return ret;
3053 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3054 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3055 }
3056 
3057 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3058 			  int spi, int nr_slots)
3059 {
3060 	struct bpf_func_state *state = func(env, reg);
3061 	int err, i;
3062 
3063 	for (i = 0; i < nr_slots; i++) {
3064 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3065 
3066 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3067 		if (err)
3068 			return err;
3069 
3070 		mark_stack_slot_scratched(env, spi - i);
3071 	}
3072 
3073 	return 0;
3074 }
3075 
3076 /* This function is supposed to be used by the following 32-bit optimization
3077  * code only. It returns TRUE if the source or destination register operates
3078  * on 64-bit, otherwise return FALSE.
3079  */
3080 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3081 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3082 {
3083 	u8 code, class, op;
3084 
3085 	code = insn->code;
3086 	class = BPF_CLASS(code);
3087 	op = BPF_OP(code);
3088 	if (class == BPF_JMP) {
3089 		/* BPF_EXIT for "main" will reach here. Return TRUE
3090 		 * conservatively.
3091 		 */
3092 		if (op == BPF_EXIT)
3093 			return true;
3094 		if (op == BPF_CALL) {
3095 			/* BPF to BPF call will reach here because of marking
3096 			 * caller saved clobber with DST_OP_NO_MARK for which we
3097 			 * don't care the register def because they are anyway
3098 			 * marked as NOT_INIT already.
3099 			 */
3100 			if (insn->src_reg == BPF_PSEUDO_CALL)
3101 				return false;
3102 			/* Helper call will reach here because of arg type
3103 			 * check, conservatively return TRUE.
3104 			 */
3105 			if (t == SRC_OP)
3106 				return true;
3107 
3108 			return false;
3109 		}
3110 	}
3111 
3112 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3113 		return false;
3114 
3115 	if (class == BPF_ALU64 || class == BPF_JMP ||
3116 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3117 		return true;
3118 
3119 	if (class == BPF_ALU || class == BPF_JMP32)
3120 		return false;
3121 
3122 	if (class == BPF_LDX) {
3123 		if (t != SRC_OP)
3124 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3125 		/* LDX source must be ptr. */
3126 		return true;
3127 	}
3128 
3129 	if (class == BPF_STX) {
3130 		/* BPF_STX (including atomic variants) has multiple source
3131 		 * operands, one of which is a ptr. Check whether the caller is
3132 		 * asking about it.
3133 		 */
3134 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3135 			return true;
3136 		return BPF_SIZE(code) == BPF_DW;
3137 	}
3138 
3139 	if (class == BPF_LD) {
3140 		u8 mode = BPF_MODE(code);
3141 
3142 		/* LD_IMM64 */
3143 		if (mode == BPF_IMM)
3144 			return true;
3145 
3146 		/* Both LD_IND and LD_ABS return 32-bit data. */
3147 		if (t != SRC_OP)
3148 			return  false;
3149 
3150 		/* Implicit ctx ptr. */
3151 		if (regno == BPF_REG_6)
3152 			return true;
3153 
3154 		/* Explicit source could be any width. */
3155 		return true;
3156 	}
3157 
3158 	if (class == BPF_ST)
3159 		/* The only source register for BPF_ST is a ptr. */
3160 		return true;
3161 
3162 	/* Conservatively return true at default. */
3163 	return true;
3164 }
3165 
3166 /* Return the regno defined by the insn, or -1. */
3167 static int insn_def_regno(const struct bpf_insn *insn)
3168 {
3169 	switch (BPF_CLASS(insn->code)) {
3170 	case BPF_JMP:
3171 	case BPF_JMP32:
3172 	case BPF_ST:
3173 		return -1;
3174 	case BPF_STX:
3175 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3176 		    (insn->imm & BPF_FETCH)) {
3177 			if (insn->imm == BPF_CMPXCHG)
3178 				return BPF_REG_0;
3179 			else
3180 				return insn->src_reg;
3181 		} else {
3182 			return -1;
3183 		}
3184 	default:
3185 		return insn->dst_reg;
3186 	}
3187 }
3188 
3189 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3190 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3191 {
3192 	int dst_reg = insn_def_regno(insn);
3193 
3194 	if (dst_reg == -1)
3195 		return false;
3196 
3197 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3198 }
3199 
3200 static void mark_insn_zext(struct bpf_verifier_env *env,
3201 			   struct bpf_reg_state *reg)
3202 {
3203 	s32 def_idx = reg->subreg_def;
3204 
3205 	if (def_idx == DEF_NOT_SUBREG)
3206 		return;
3207 
3208 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3209 	/* The dst will be zero extended, so won't be sub-register anymore. */
3210 	reg->subreg_def = DEF_NOT_SUBREG;
3211 }
3212 
3213 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3214 			   enum reg_arg_type t)
3215 {
3216 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3217 	struct bpf_reg_state *reg;
3218 	bool rw64;
3219 
3220 	if (regno >= MAX_BPF_REG) {
3221 		verbose(env, "R%d is invalid\n", regno);
3222 		return -EINVAL;
3223 	}
3224 
3225 	mark_reg_scratched(env, regno);
3226 
3227 	reg = &regs[regno];
3228 	rw64 = is_reg64(env, insn, regno, reg, t);
3229 	if (t == SRC_OP) {
3230 		/* check whether register used as source operand can be read */
3231 		if (reg->type == NOT_INIT) {
3232 			verbose(env, "R%d !read_ok\n", regno);
3233 			return -EACCES;
3234 		}
3235 		/* We don't need to worry about FP liveness because it's read-only */
3236 		if (regno == BPF_REG_FP)
3237 			return 0;
3238 
3239 		if (rw64)
3240 			mark_insn_zext(env, reg);
3241 
3242 		return mark_reg_read(env, reg, reg->parent,
3243 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3244 	} else {
3245 		/* check whether register used as dest operand can be written to */
3246 		if (regno == BPF_REG_FP) {
3247 			verbose(env, "frame pointer is read only\n");
3248 			return -EACCES;
3249 		}
3250 		reg->live |= REG_LIVE_WRITTEN;
3251 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3252 		if (t == DST_OP)
3253 			mark_reg_unknown(env, regs, regno);
3254 	}
3255 	return 0;
3256 }
3257 
3258 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3259 			 enum reg_arg_type t)
3260 {
3261 	struct bpf_verifier_state *vstate = env->cur_state;
3262 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3263 
3264 	return __check_reg_arg(env, state->regs, regno, t);
3265 }
3266 
3267 static int insn_stack_access_flags(int frameno, int spi)
3268 {
3269 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3270 }
3271 
3272 static int insn_stack_access_spi(int insn_flags)
3273 {
3274 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3275 }
3276 
3277 static int insn_stack_access_frameno(int insn_flags)
3278 {
3279 	return insn_flags & INSN_F_FRAMENO_MASK;
3280 }
3281 
3282 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3283 {
3284 	env->insn_aux_data[idx].jmp_point = true;
3285 }
3286 
3287 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3288 {
3289 	return env->insn_aux_data[insn_idx].jmp_point;
3290 }
3291 
3292 /* for any branch, call, exit record the history of jmps in the given state */
3293 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3294 			    int insn_flags)
3295 {
3296 	u32 cnt = cur->jmp_history_cnt;
3297 	struct bpf_jmp_history_entry *p;
3298 	size_t alloc_size;
3299 
3300 	/* combine instruction flags if we already recorded this instruction */
3301 	if (env->cur_hist_ent) {
3302 		/* atomic instructions push insn_flags twice, for READ and
3303 		 * WRITE sides, but they should agree on stack slot
3304 		 */
3305 		WARN_ONCE((env->cur_hist_ent->flags & insn_flags) &&
3306 			  (env->cur_hist_ent->flags & insn_flags) != insn_flags,
3307 			  "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n",
3308 			  env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3309 		env->cur_hist_ent->flags |= insn_flags;
3310 		return 0;
3311 	}
3312 
3313 	cnt++;
3314 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3315 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3316 	if (!p)
3317 		return -ENOMEM;
3318 	cur->jmp_history = p;
3319 
3320 	p = &cur->jmp_history[cnt - 1];
3321 	p->idx = env->insn_idx;
3322 	p->prev_idx = env->prev_insn_idx;
3323 	p->flags = insn_flags;
3324 	cur->jmp_history_cnt = cnt;
3325 	env->cur_hist_ent = p;
3326 
3327 	return 0;
3328 }
3329 
3330 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3331 						        u32 hist_end, int insn_idx)
3332 {
3333 	if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3334 		return &st->jmp_history[hist_end - 1];
3335 	return NULL;
3336 }
3337 
3338 /* Backtrack one insn at a time. If idx is not at the top of recorded
3339  * history then previous instruction came from straight line execution.
3340  * Return -ENOENT if we exhausted all instructions within given state.
3341  *
3342  * It's legal to have a bit of a looping with the same starting and ending
3343  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3344  * instruction index is the same as state's first_idx doesn't mean we are
3345  * done. If there is still some jump history left, we should keep going. We
3346  * need to take into account that we might have a jump history between given
3347  * state's parent and itself, due to checkpointing. In this case, we'll have
3348  * history entry recording a jump from last instruction of parent state and
3349  * first instruction of given state.
3350  */
3351 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3352 			     u32 *history)
3353 {
3354 	u32 cnt = *history;
3355 
3356 	if (i == st->first_insn_idx) {
3357 		if (cnt == 0)
3358 			return -ENOENT;
3359 		if (cnt == 1 && st->jmp_history[0].idx == i)
3360 			return -ENOENT;
3361 	}
3362 
3363 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3364 		i = st->jmp_history[cnt - 1].prev_idx;
3365 		(*history)--;
3366 	} else {
3367 		i--;
3368 	}
3369 	return i;
3370 }
3371 
3372 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3373 {
3374 	const struct btf_type *func;
3375 	struct btf *desc_btf;
3376 
3377 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3378 		return NULL;
3379 
3380 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3381 	if (IS_ERR(desc_btf))
3382 		return "<error>";
3383 
3384 	func = btf_type_by_id(desc_btf, insn->imm);
3385 	return btf_name_by_offset(desc_btf, func->name_off);
3386 }
3387 
3388 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3389 {
3390 	bt->frame = frame;
3391 }
3392 
3393 static inline void bt_reset(struct backtrack_state *bt)
3394 {
3395 	struct bpf_verifier_env *env = bt->env;
3396 
3397 	memset(bt, 0, sizeof(*bt));
3398 	bt->env = env;
3399 }
3400 
3401 static inline u32 bt_empty(struct backtrack_state *bt)
3402 {
3403 	u64 mask = 0;
3404 	int i;
3405 
3406 	for (i = 0; i <= bt->frame; i++)
3407 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3408 
3409 	return mask == 0;
3410 }
3411 
3412 static inline int bt_subprog_enter(struct backtrack_state *bt)
3413 {
3414 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3415 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3416 		WARN_ONCE(1, "verifier backtracking bug");
3417 		return -EFAULT;
3418 	}
3419 	bt->frame++;
3420 	return 0;
3421 }
3422 
3423 static inline int bt_subprog_exit(struct backtrack_state *bt)
3424 {
3425 	if (bt->frame == 0) {
3426 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3427 		WARN_ONCE(1, "verifier backtracking bug");
3428 		return -EFAULT;
3429 	}
3430 	bt->frame--;
3431 	return 0;
3432 }
3433 
3434 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3435 {
3436 	bt->reg_masks[frame] |= 1 << reg;
3437 }
3438 
3439 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3440 {
3441 	bt->reg_masks[frame] &= ~(1 << reg);
3442 }
3443 
3444 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3445 {
3446 	bt_set_frame_reg(bt, bt->frame, reg);
3447 }
3448 
3449 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3450 {
3451 	bt_clear_frame_reg(bt, bt->frame, reg);
3452 }
3453 
3454 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3455 {
3456 	bt->stack_masks[frame] |= 1ull << slot;
3457 }
3458 
3459 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3460 {
3461 	bt->stack_masks[frame] &= ~(1ull << slot);
3462 }
3463 
3464 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3465 {
3466 	return bt->reg_masks[frame];
3467 }
3468 
3469 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3470 {
3471 	return bt->reg_masks[bt->frame];
3472 }
3473 
3474 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3475 {
3476 	return bt->stack_masks[frame];
3477 }
3478 
3479 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3480 {
3481 	return bt->stack_masks[bt->frame];
3482 }
3483 
3484 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3485 {
3486 	return bt->reg_masks[bt->frame] & (1 << reg);
3487 }
3488 
3489 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
3490 {
3491 	return bt->stack_masks[frame] & (1ull << slot);
3492 }
3493 
3494 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3495 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3496 {
3497 	DECLARE_BITMAP(mask, 64);
3498 	bool first = true;
3499 	int i, n;
3500 
3501 	buf[0] = '\0';
3502 
3503 	bitmap_from_u64(mask, reg_mask);
3504 	for_each_set_bit(i, mask, 32) {
3505 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3506 		first = false;
3507 		buf += n;
3508 		buf_sz -= n;
3509 		if (buf_sz < 0)
3510 			break;
3511 	}
3512 }
3513 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3514 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3515 {
3516 	DECLARE_BITMAP(mask, 64);
3517 	bool first = true;
3518 	int i, n;
3519 
3520 	buf[0] = '\0';
3521 
3522 	bitmap_from_u64(mask, stack_mask);
3523 	for_each_set_bit(i, mask, 64) {
3524 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3525 		first = false;
3526 		buf += n;
3527 		buf_sz -= n;
3528 		if (buf_sz < 0)
3529 			break;
3530 	}
3531 }
3532 
3533 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3534 
3535 /* For given verifier state backtrack_insn() is called from the last insn to
3536  * the first insn. Its purpose is to compute a bitmask of registers and
3537  * stack slots that needs precision in the parent verifier state.
3538  *
3539  * @idx is an index of the instruction we are currently processing;
3540  * @subseq_idx is an index of the subsequent instruction that:
3541  *   - *would be* executed next, if jump history is viewed in forward order;
3542  *   - *was* processed previously during backtracking.
3543  */
3544 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3545 			  struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
3546 {
3547 	const struct bpf_insn_cbs cbs = {
3548 		.cb_call	= disasm_kfunc_name,
3549 		.cb_print	= verbose,
3550 		.private_data	= env,
3551 	};
3552 	struct bpf_insn *insn = env->prog->insnsi + idx;
3553 	u8 class = BPF_CLASS(insn->code);
3554 	u8 opcode = BPF_OP(insn->code);
3555 	u8 mode = BPF_MODE(insn->code);
3556 	u32 dreg = insn->dst_reg;
3557 	u32 sreg = insn->src_reg;
3558 	u32 spi, i, fr;
3559 
3560 	if (insn->code == 0)
3561 		return 0;
3562 	if (env->log.level & BPF_LOG_LEVEL2) {
3563 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3564 		verbose(env, "mark_precise: frame%d: regs=%s ",
3565 			bt->frame, env->tmp_str_buf);
3566 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3567 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3568 		verbose(env, "%d: ", idx);
3569 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3570 	}
3571 
3572 	if (class == BPF_ALU || class == BPF_ALU64) {
3573 		if (!bt_is_reg_set(bt, dreg))
3574 			return 0;
3575 		if (opcode == BPF_END || opcode == BPF_NEG) {
3576 			/* sreg is reserved and unused
3577 			 * dreg still need precision before this insn
3578 			 */
3579 			return 0;
3580 		} else if (opcode == BPF_MOV) {
3581 			if (BPF_SRC(insn->code) == BPF_X) {
3582 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3583 				 * dreg needs precision after this insn
3584 				 * sreg needs precision before this insn
3585 				 */
3586 				bt_clear_reg(bt, dreg);
3587 				bt_set_reg(bt, sreg);
3588 			} else {
3589 				/* dreg = K
3590 				 * dreg needs precision after this insn.
3591 				 * Corresponding register is already marked
3592 				 * as precise=true in this verifier state.
3593 				 * No further markings in parent are necessary
3594 				 */
3595 				bt_clear_reg(bt, dreg);
3596 			}
3597 		} else {
3598 			if (BPF_SRC(insn->code) == BPF_X) {
3599 				/* dreg += sreg
3600 				 * both dreg and sreg need precision
3601 				 * before this insn
3602 				 */
3603 				bt_set_reg(bt, sreg);
3604 			} /* else dreg += K
3605 			   * dreg still needs precision before this insn
3606 			   */
3607 		}
3608 	} else if (class == BPF_LDX) {
3609 		if (!bt_is_reg_set(bt, dreg))
3610 			return 0;
3611 		bt_clear_reg(bt, dreg);
3612 
3613 		/* scalars can only be spilled into stack w/o losing precision.
3614 		 * Load from any other memory can be zero extended.
3615 		 * The desire to keep that precision is already indicated
3616 		 * by 'precise' mark in corresponding register of this state.
3617 		 * No further tracking necessary.
3618 		 */
3619 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3620 			return 0;
3621 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3622 		 * that [fp - off] slot contains scalar that needs to be
3623 		 * tracked with precision
3624 		 */
3625 		spi = insn_stack_access_spi(hist->flags);
3626 		fr = insn_stack_access_frameno(hist->flags);
3627 		bt_set_frame_slot(bt, fr, spi);
3628 	} else if (class == BPF_STX || class == BPF_ST) {
3629 		if (bt_is_reg_set(bt, dreg))
3630 			/* stx & st shouldn't be using _scalar_ dst_reg
3631 			 * to access memory. It means backtracking
3632 			 * encountered a case of pointer subtraction.
3633 			 */
3634 			return -ENOTSUPP;
3635 		/* scalars can only be spilled into stack */
3636 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3637 			return 0;
3638 		spi = insn_stack_access_spi(hist->flags);
3639 		fr = insn_stack_access_frameno(hist->flags);
3640 		if (!bt_is_frame_slot_set(bt, fr, spi))
3641 			return 0;
3642 		bt_clear_frame_slot(bt, fr, spi);
3643 		if (class == BPF_STX)
3644 			bt_set_reg(bt, sreg);
3645 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3646 		if (bpf_pseudo_call(insn)) {
3647 			int subprog_insn_idx, subprog;
3648 
3649 			subprog_insn_idx = idx + insn->imm + 1;
3650 			subprog = find_subprog(env, subprog_insn_idx);
3651 			if (subprog < 0)
3652 				return -EFAULT;
3653 
3654 			if (subprog_is_global(env, subprog)) {
3655 				/* check that jump history doesn't have any
3656 				 * extra instructions from subprog; the next
3657 				 * instruction after call to global subprog
3658 				 * should be literally next instruction in
3659 				 * caller program
3660 				 */
3661 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3662 				/* r1-r5 are invalidated after subprog call,
3663 				 * so for global func call it shouldn't be set
3664 				 * anymore
3665 				 */
3666 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3667 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3668 					WARN_ONCE(1, "verifier backtracking bug");
3669 					return -EFAULT;
3670 				}
3671 				/* global subprog always sets R0 */
3672 				bt_clear_reg(bt, BPF_REG_0);
3673 				return 0;
3674 			} else {
3675 				/* static subprog call instruction, which
3676 				 * means that we are exiting current subprog,
3677 				 * so only r1-r5 could be still requested as
3678 				 * precise, r0 and r6-r10 or any stack slot in
3679 				 * the current frame should be zero by now
3680 				 */
3681 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3682 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3683 					WARN_ONCE(1, "verifier backtracking bug");
3684 					return -EFAULT;
3685 				}
3686 				/* we are now tracking register spills correctly,
3687 				 * so any instance of leftover slots is a bug
3688 				 */
3689 				if (bt_stack_mask(bt) != 0) {
3690 					verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3691 					WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)");
3692 					return -EFAULT;
3693 				}
3694 				/* propagate r1-r5 to the caller */
3695 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3696 					if (bt_is_reg_set(bt, i)) {
3697 						bt_clear_reg(bt, i);
3698 						bt_set_frame_reg(bt, bt->frame - 1, i);
3699 					}
3700 				}
3701 				if (bt_subprog_exit(bt))
3702 					return -EFAULT;
3703 				return 0;
3704 			}
3705 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3706 			/* exit from callback subprog to callback-calling helper or
3707 			 * kfunc call. Use idx/subseq_idx check to discern it from
3708 			 * straight line code backtracking.
3709 			 * Unlike the subprog call handling above, we shouldn't
3710 			 * propagate precision of r1-r5 (if any requested), as they are
3711 			 * not actually arguments passed directly to callback subprogs
3712 			 */
3713 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3714 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3715 				WARN_ONCE(1, "verifier backtracking bug");
3716 				return -EFAULT;
3717 			}
3718 			if (bt_stack_mask(bt) != 0) {
3719 				verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3720 				WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)");
3721 				return -EFAULT;
3722 			}
3723 			/* clear r1-r5 in callback subprog's mask */
3724 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3725 				bt_clear_reg(bt, i);
3726 			if (bt_subprog_exit(bt))
3727 				return -EFAULT;
3728 			return 0;
3729 		} else if (opcode == BPF_CALL) {
3730 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3731 			 * catch this error later. Make backtracking conservative
3732 			 * with ENOTSUPP.
3733 			 */
3734 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3735 				return -ENOTSUPP;
3736 			/* regular helper call sets R0 */
3737 			bt_clear_reg(bt, BPF_REG_0);
3738 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3739 				/* if backtracing was looking for registers R1-R5
3740 				 * they should have been found already.
3741 				 */
3742 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3743 				WARN_ONCE(1, "verifier backtracking bug");
3744 				return -EFAULT;
3745 			}
3746 		} else if (opcode == BPF_EXIT) {
3747 			bool r0_precise;
3748 
3749 			/* Backtracking to a nested function call, 'idx' is a part of
3750 			 * the inner frame 'subseq_idx' is a part of the outer frame.
3751 			 * In case of a regular function call, instructions giving
3752 			 * precision to registers R1-R5 should have been found already.
3753 			 * In case of a callback, it is ok to have R1-R5 marked for
3754 			 * backtracking, as these registers are set by the function
3755 			 * invoking callback.
3756 			 */
3757 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3758 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3759 					bt_clear_reg(bt, i);
3760 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3761 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3762 				WARN_ONCE(1, "verifier backtracking bug");
3763 				return -EFAULT;
3764 			}
3765 
3766 			/* BPF_EXIT in subprog or callback always returns
3767 			 * right after the call instruction, so by checking
3768 			 * whether the instruction at subseq_idx-1 is subprog
3769 			 * call or not we can distinguish actual exit from
3770 			 * *subprog* from exit from *callback*. In the former
3771 			 * case, we need to propagate r0 precision, if
3772 			 * necessary. In the former we never do that.
3773 			 */
3774 			r0_precise = subseq_idx - 1 >= 0 &&
3775 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3776 				     bt_is_reg_set(bt, BPF_REG_0);
3777 
3778 			bt_clear_reg(bt, BPF_REG_0);
3779 			if (bt_subprog_enter(bt))
3780 				return -EFAULT;
3781 
3782 			if (r0_precise)
3783 				bt_set_reg(bt, BPF_REG_0);
3784 			/* r6-r9 and stack slots will stay set in caller frame
3785 			 * bitmasks until we return back from callee(s)
3786 			 */
3787 			return 0;
3788 		} else if (BPF_SRC(insn->code) == BPF_X) {
3789 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3790 				return 0;
3791 			/* dreg <cond> sreg
3792 			 * Both dreg and sreg need precision before
3793 			 * this insn. If only sreg was marked precise
3794 			 * before it would be equally necessary to
3795 			 * propagate it to dreg.
3796 			 */
3797 			bt_set_reg(bt, dreg);
3798 			bt_set_reg(bt, sreg);
3799 			 /* else dreg <cond> K
3800 			  * Only dreg still needs precision before
3801 			  * this insn, so for the K-based conditional
3802 			  * there is nothing new to be marked.
3803 			  */
3804 		}
3805 	} else if (class == BPF_LD) {
3806 		if (!bt_is_reg_set(bt, dreg))
3807 			return 0;
3808 		bt_clear_reg(bt, dreg);
3809 		/* It's ld_imm64 or ld_abs or ld_ind.
3810 		 * For ld_imm64 no further tracking of precision
3811 		 * into parent is necessary
3812 		 */
3813 		if (mode == BPF_IND || mode == BPF_ABS)
3814 			/* to be analyzed */
3815 			return -ENOTSUPP;
3816 	}
3817 	return 0;
3818 }
3819 
3820 /* the scalar precision tracking algorithm:
3821  * . at the start all registers have precise=false.
3822  * . scalar ranges are tracked as normal through alu and jmp insns.
3823  * . once precise value of the scalar register is used in:
3824  *   .  ptr + scalar alu
3825  *   . if (scalar cond K|scalar)
3826  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3827  *   backtrack through the verifier states and mark all registers and
3828  *   stack slots with spilled constants that these scalar regisers
3829  *   should be precise.
3830  * . during state pruning two registers (or spilled stack slots)
3831  *   are equivalent if both are not precise.
3832  *
3833  * Note the verifier cannot simply walk register parentage chain,
3834  * since many different registers and stack slots could have been
3835  * used to compute single precise scalar.
3836  *
3837  * The approach of starting with precise=true for all registers and then
3838  * backtrack to mark a register as not precise when the verifier detects
3839  * that program doesn't care about specific value (e.g., when helper
3840  * takes register as ARG_ANYTHING parameter) is not safe.
3841  *
3842  * It's ok to walk single parentage chain of the verifier states.
3843  * It's possible that this backtracking will go all the way till 1st insn.
3844  * All other branches will be explored for needing precision later.
3845  *
3846  * The backtracking needs to deal with cases like:
3847  *   R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
3848  * r9 -= r8
3849  * r5 = r9
3850  * if r5 > 0x79f goto pc+7
3851  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3852  * r5 += 1
3853  * ...
3854  * call bpf_perf_event_output#25
3855  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3856  *
3857  * and this case:
3858  * r6 = 1
3859  * call foo // uses callee's r6 inside to compute r0
3860  * r0 += r6
3861  * if r0 == 0 goto
3862  *
3863  * to track above reg_mask/stack_mask needs to be independent for each frame.
3864  *
3865  * Also if parent's curframe > frame where backtracking started,
3866  * the verifier need to mark registers in both frames, otherwise callees
3867  * may incorrectly prune callers. This is similar to
3868  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3869  *
3870  * For now backtracking falls back into conservative marking.
3871  */
3872 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3873 				     struct bpf_verifier_state *st)
3874 {
3875 	struct bpf_func_state *func;
3876 	struct bpf_reg_state *reg;
3877 	int i, j;
3878 
3879 	if (env->log.level & BPF_LOG_LEVEL2) {
3880 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3881 			st->curframe);
3882 	}
3883 
3884 	/* big hammer: mark all scalars precise in this path.
3885 	 * pop_stack may still get !precise scalars.
3886 	 * We also skip current state and go straight to first parent state,
3887 	 * because precision markings in current non-checkpointed state are
3888 	 * not needed. See why in the comment in __mark_chain_precision below.
3889 	 */
3890 	for (st = st->parent; st; st = st->parent) {
3891 		for (i = 0; i <= st->curframe; i++) {
3892 			func = st->frame[i];
3893 			for (j = 0; j < BPF_REG_FP; j++) {
3894 				reg = &func->regs[j];
3895 				if (reg->type != SCALAR_VALUE || reg->precise)
3896 					continue;
3897 				reg->precise = true;
3898 				if (env->log.level & BPF_LOG_LEVEL2) {
3899 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3900 						i, j);
3901 				}
3902 			}
3903 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3904 				if (!is_spilled_reg(&func->stack[j]))
3905 					continue;
3906 				reg = &func->stack[j].spilled_ptr;
3907 				if (reg->type != SCALAR_VALUE || reg->precise)
3908 					continue;
3909 				reg->precise = true;
3910 				if (env->log.level & BPF_LOG_LEVEL2) {
3911 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3912 						i, -(j + 1) * 8);
3913 				}
3914 			}
3915 		}
3916 	}
3917 }
3918 
3919 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3920 {
3921 	struct bpf_func_state *func;
3922 	struct bpf_reg_state *reg;
3923 	int i, j;
3924 
3925 	for (i = 0; i <= st->curframe; i++) {
3926 		func = st->frame[i];
3927 		for (j = 0; j < BPF_REG_FP; j++) {
3928 			reg = &func->regs[j];
3929 			if (reg->type != SCALAR_VALUE)
3930 				continue;
3931 			reg->precise = false;
3932 		}
3933 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3934 			if (!is_spilled_reg(&func->stack[j]))
3935 				continue;
3936 			reg = &func->stack[j].spilled_ptr;
3937 			if (reg->type != SCALAR_VALUE)
3938 				continue;
3939 			reg->precise = false;
3940 		}
3941 	}
3942 }
3943 
3944 static bool idset_contains(struct bpf_idset *s, u32 id)
3945 {
3946 	u32 i;
3947 
3948 	for (i = 0; i < s->count; ++i)
3949 		if (s->ids[i] == id)
3950 			return true;
3951 
3952 	return false;
3953 }
3954 
3955 static int idset_push(struct bpf_idset *s, u32 id)
3956 {
3957 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3958 		return -EFAULT;
3959 	s->ids[s->count++] = id;
3960 	return 0;
3961 }
3962 
3963 static void idset_reset(struct bpf_idset *s)
3964 {
3965 	s->count = 0;
3966 }
3967 
3968 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3969  * Mark all registers with these IDs as precise.
3970  */
3971 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3972 {
3973 	struct bpf_idset *precise_ids = &env->idset_scratch;
3974 	struct backtrack_state *bt = &env->bt;
3975 	struct bpf_func_state *func;
3976 	struct bpf_reg_state *reg;
3977 	DECLARE_BITMAP(mask, 64);
3978 	int i, fr;
3979 
3980 	idset_reset(precise_ids);
3981 
3982 	for (fr = bt->frame; fr >= 0; fr--) {
3983 		func = st->frame[fr];
3984 
3985 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3986 		for_each_set_bit(i, mask, 32) {
3987 			reg = &func->regs[i];
3988 			if (!reg->id || reg->type != SCALAR_VALUE)
3989 				continue;
3990 			if (idset_push(precise_ids, reg->id))
3991 				return -EFAULT;
3992 		}
3993 
3994 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3995 		for_each_set_bit(i, mask, 64) {
3996 			if (i >= func->allocated_stack / BPF_REG_SIZE)
3997 				break;
3998 			if (!is_spilled_scalar_reg(&func->stack[i]))
3999 				continue;
4000 			reg = &func->stack[i].spilled_ptr;
4001 			if (!reg->id)
4002 				continue;
4003 			if (idset_push(precise_ids, reg->id))
4004 				return -EFAULT;
4005 		}
4006 	}
4007 
4008 	for (fr = 0; fr <= st->curframe; ++fr) {
4009 		func = st->frame[fr];
4010 
4011 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4012 			reg = &func->regs[i];
4013 			if (!reg->id)
4014 				continue;
4015 			if (!idset_contains(precise_ids, reg->id))
4016 				continue;
4017 			bt_set_frame_reg(bt, fr, i);
4018 		}
4019 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4020 			if (!is_spilled_scalar_reg(&func->stack[i]))
4021 				continue;
4022 			reg = &func->stack[i].spilled_ptr;
4023 			if (!reg->id)
4024 				continue;
4025 			if (!idset_contains(precise_ids, reg->id))
4026 				continue;
4027 			bt_set_frame_slot(bt, fr, i);
4028 		}
4029 	}
4030 
4031 	return 0;
4032 }
4033 
4034 /*
4035  * __mark_chain_precision() backtracks BPF program instruction sequence and
4036  * chain of verifier states making sure that register *regno* (if regno >= 0)
4037  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4038  * SCALARS, as well as any other registers and slots that contribute to
4039  * a tracked state of given registers/stack slots, depending on specific BPF
4040  * assembly instructions (see backtrack_insns() for exact instruction handling
4041  * logic). This backtracking relies on recorded jmp_history and is able to
4042  * traverse entire chain of parent states. This process ends only when all the
4043  * necessary registers/slots and their transitive dependencies are marked as
4044  * precise.
4045  *
4046  * One important and subtle aspect is that precise marks *do not matter* in
4047  * the currently verified state (current state). It is important to understand
4048  * why this is the case.
4049  *
4050  * First, note that current state is the state that is not yet "checkpointed",
4051  * i.e., it is not yet put into env->explored_states, and it has no children
4052  * states as well. It's ephemeral, and can end up either a) being discarded if
4053  * compatible explored state is found at some point or BPF_EXIT instruction is
4054  * reached or b) checkpointed and put into env->explored_states, branching out
4055  * into one or more children states.
4056  *
4057  * In the former case, precise markings in current state are completely
4058  * ignored by state comparison code (see regsafe() for details). Only
4059  * checkpointed ("old") state precise markings are important, and if old
4060  * state's register/slot is precise, regsafe() assumes current state's
4061  * register/slot as precise and checks value ranges exactly and precisely. If
4062  * states turn out to be compatible, current state's necessary precise
4063  * markings and any required parent states' precise markings are enforced
4064  * after the fact with propagate_precision() logic, after the fact. But it's
4065  * important to realize that in this case, even after marking current state
4066  * registers/slots as precise, we immediately discard current state. So what
4067  * actually matters is any of the precise markings propagated into current
4068  * state's parent states, which are always checkpointed (due to b) case above).
4069  * As such, for scenario a) it doesn't matter if current state has precise
4070  * markings set or not.
4071  *
4072  * Now, for the scenario b), checkpointing and forking into child(ren)
4073  * state(s). Note that before current state gets to checkpointing step, any
4074  * processed instruction always assumes precise SCALAR register/slot
4075  * knowledge: if precise value or range is useful to prune jump branch, BPF
4076  * verifier takes this opportunity enthusiastically. Similarly, when
4077  * register's value is used to calculate offset or memory address, exact
4078  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4079  * what we mentioned above about state comparison ignoring precise markings
4080  * during state comparison, BPF verifier ignores and also assumes precise
4081  * markings *at will* during instruction verification process. But as verifier
4082  * assumes precision, it also propagates any precision dependencies across
4083  * parent states, which are not yet finalized, so can be further restricted
4084  * based on new knowledge gained from restrictions enforced by their children
4085  * states. This is so that once those parent states are finalized, i.e., when
4086  * they have no more active children state, state comparison logic in
4087  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4088  * required for correctness.
4089  *
4090  * To build a bit more intuition, note also that once a state is checkpointed,
4091  * the path we took to get to that state is not important. This is crucial
4092  * property for state pruning. When state is checkpointed and finalized at
4093  * some instruction index, it can be correctly and safely used to "short
4094  * circuit" any *compatible* state that reaches exactly the same instruction
4095  * index. I.e., if we jumped to that instruction from a completely different
4096  * code path than original finalized state was derived from, it doesn't
4097  * matter, current state can be discarded because from that instruction
4098  * forward having a compatible state will ensure we will safely reach the
4099  * exit. States describe preconditions for further exploration, but completely
4100  * forget the history of how we got here.
4101  *
4102  * This also means that even if we needed precise SCALAR range to get to
4103  * finalized state, but from that point forward *that same* SCALAR register is
4104  * never used in a precise context (i.e., it's precise value is not needed for
4105  * correctness), it's correct and safe to mark such register as "imprecise"
4106  * (i.e., precise marking set to false). This is what we rely on when we do
4107  * not set precise marking in current state. If no child state requires
4108  * precision for any given SCALAR register, it's safe to dictate that it can
4109  * be imprecise. If any child state does require this register to be precise,
4110  * we'll mark it precise later retroactively during precise markings
4111  * propagation from child state to parent states.
4112  *
4113  * Skipping precise marking setting in current state is a mild version of
4114  * relying on the above observation. But we can utilize this property even
4115  * more aggressively by proactively forgetting any precise marking in the
4116  * current state (which we inherited from the parent state), right before we
4117  * checkpoint it and branch off into new child state. This is done by
4118  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4119  * finalized states which help in short circuiting more future states.
4120  */
4121 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4122 {
4123 	struct backtrack_state *bt = &env->bt;
4124 	struct bpf_verifier_state *st = env->cur_state;
4125 	int first_idx = st->first_insn_idx;
4126 	int last_idx = env->insn_idx;
4127 	int subseq_idx = -1;
4128 	struct bpf_func_state *func;
4129 	struct bpf_reg_state *reg;
4130 	bool skip_first = true;
4131 	int i, fr, err;
4132 
4133 	if (!env->bpf_capable)
4134 		return 0;
4135 
4136 	/* set frame number from which we are starting to backtrack */
4137 	bt_init(bt, env->cur_state->curframe);
4138 
4139 	/* Do sanity checks against current state of register and/or stack
4140 	 * slot, but don't set precise flag in current state, as precision
4141 	 * tracking in the current state is unnecessary.
4142 	 */
4143 	func = st->frame[bt->frame];
4144 	if (regno >= 0) {
4145 		reg = &func->regs[regno];
4146 		if (reg->type != SCALAR_VALUE) {
4147 			WARN_ONCE(1, "backtracing misuse");
4148 			return -EFAULT;
4149 		}
4150 		bt_set_reg(bt, regno);
4151 	}
4152 
4153 	if (bt_empty(bt))
4154 		return 0;
4155 
4156 	for (;;) {
4157 		DECLARE_BITMAP(mask, 64);
4158 		u32 history = st->jmp_history_cnt;
4159 		struct bpf_jmp_history_entry *hist;
4160 
4161 		if (env->log.level & BPF_LOG_LEVEL2) {
4162 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4163 				bt->frame, last_idx, first_idx, subseq_idx);
4164 		}
4165 
4166 		/* If some register with scalar ID is marked as precise,
4167 		 * make sure that all registers sharing this ID are also precise.
4168 		 * This is needed to estimate effect of find_equal_scalars().
4169 		 * Do this at the last instruction of each state,
4170 		 * bpf_reg_state::id fields are valid for these instructions.
4171 		 *
4172 		 * Allows to track precision in situation like below:
4173 		 *
4174 		 *     r2 = unknown value
4175 		 *     ...
4176 		 *   --- state #0 ---
4177 		 *     ...
4178 		 *     r1 = r2                 // r1 and r2 now share the same ID
4179 		 *     ...
4180 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4181 		 *     ...
4182 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4183 		 *     ...
4184 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4185 		 *     r3 = r10
4186 		 *     r3 += r1                // need to mark both r1 and r2
4187 		 */
4188 		if (mark_precise_scalar_ids(env, st))
4189 			return -EFAULT;
4190 
4191 		if (last_idx < 0) {
4192 			/* we are at the entry into subprog, which
4193 			 * is expected for global funcs, but only if
4194 			 * requested precise registers are R1-R5
4195 			 * (which are global func's input arguments)
4196 			 */
4197 			if (st->curframe == 0 &&
4198 			    st->frame[0]->subprogno > 0 &&
4199 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4200 			    bt_stack_mask(bt) == 0 &&
4201 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4202 				bitmap_from_u64(mask, bt_reg_mask(bt));
4203 				for_each_set_bit(i, mask, 32) {
4204 					reg = &st->frame[0]->regs[i];
4205 					bt_clear_reg(bt, i);
4206 					if (reg->type == SCALAR_VALUE)
4207 						reg->precise = true;
4208 				}
4209 				return 0;
4210 			}
4211 
4212 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4213 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4214 			WARN_ONCE(1, "verifier backtracking bug");
4215 			return -EFAULT;
4216 		}
4217 
4218 		for (i = last_idx;;) {
4219 			if (skip_first) {
4220 				err = 0;
4221 				skip_first = false;
4222 			} else {
4223 				hist = get_jmp_hist_entry(st, history, i);
4224 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4225 			}
4226 			if (err == -ENOTSUPP) {
4227 				mark_all_scalars_precise(env, env->cur_state);
4228 				bt_reset(bt);
4229 				return 0;
4230 			} else if (err) {
4231 				return err;
4232 			}
4233 			if (bt_empty(bt))
4234 				/* Found assignment(s) into tracked register in this state.
4235 				 * Since this state is already marked, just return.
4236 				 * Nothing to be tracked further in the parent state.
4237 				 */
4238 				return 0;
4239 			subseq_idx = i;
4240 			i = get_prev_insn_idx(st, i, &history);
4241 			if (i == -ENOENT)
4242 				break;
4243 			if (i >= env->prog->len) {
4244 				/* This can happen if backtracking reached insn 0
4245 				 * and there are still reg_mask or stack_mask
4246 				 * to backtrack.
4247 				 * It means the backtracking missed the spot where
4248 				 * particular register was initialized with a constant.
4249 				 */
4250 				verbose(env, "BUG backtracking idx %d\n", i);
4251 				WARN_ONCE(1, "verifier backtracking bug");
4252 				return -EFAULT;
4253 			}
4254 		}
4255 		st = st->parent;
4256 		if (!st)
4257 			break;
4258 
4259 		for (fr = bt->frame; fr >= 0; fr--) {
4260 			func = st->frame[fr];
4261 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4262 			for_each_set_bit(i, mask, 32) {
4263 				reg = &func->regs[i];
4264 				if (reg->type != SCALAR_VALUE) {
4265 					bt_clear_frame_reg(bt, fr, i);
4266 					continue;
4267 				}
4268 				if (reg->precise)
4269 					bt_clear_frame_reg(bt, fr, i);
4270 				else
4271 					reg->precise = true;
4272 			}
4273 
4274 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4275 			for_each_set_bit(i, mask, 64) {
4276 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4277 					verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n",
4278 						i, func->allocated_stack / BPF_REG_SIZE);
4279 					WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)");
4280 					return -EFAULT;
4281 				}
4282 
4283 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4284 					bt_clear_frame_slot(bt, fr, i);
4285 					continue;
4286 				}
4287 				reg = &func->stack[i].spilled_ptr;
4288 				if (reg->precise)
4289 					bt_clear_frame_slot(bt, fr, i);
4290 				else
4291 					reg->precise = true;
4292 			}
4293 			if (env->log.level & BPF_LOG_LEVEL2) {
4294 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4295 					     bt_frame_reg_mask(bt, fr));
4296 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4297 					fr, env->tmp_str_buf);
4298 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4299 					       bt_frame_stack_mask(bt, fr));
4300 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4301 				print_verifier_state(env, func, true);
4302 			}
4303 		}
4304 
4305 		if (bt_empty(bt))
4306 			return 0;
4307 
4308 		subseq_idx = first_idx;
4309 		last_idx = st->last_insn_idx;
4310 		first_idx = st->first_insn_idx;
4311 	}
4312 
4313 	/* if we still have requested precise regs or slots, we missed
4314 	 * something (e.g., stack access through non-r10 register), so
4315 	 * fallback to marking all precise
4316 	 */
4317 	if (!bt_empty(bt)) {
4318 		mark_all_scalars_precise(env, env->cur_state);
4319 		bt_reset(bt);
4320 	}
4321 
4322 	return 0;
4323 }
4324 
4325 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4326 {
4327 	return __mark_chain_precision(env, regno);
4328 }
4329 
4330 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4331  * desired reg and stack masks across all relevant frames
4332  */
4333 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4334 {
4335 	return __mark_chain_precision(env, -1);
4336 }
4337 
4338 static bool is_spillable_regtype(enum bpf_reg_type type)
4339 {
4340 	switch (base_type(type)) {
4341 	case PTR_TO_MAP_VALUE:
4342 	case PTR_TO_STACK:
4343 	case PTR_TO_CTX:
4344 	case PTR_TO_PACKET:
4345 	case PTR_TO_PACKET_META:
4346 	case PTR_TO_PACKET_END:
4347 	case PTR_TO_FLOW_KEYS:
4348 	case CONST_PTR_TO_MAP:
4349 	case PTR_TO_SOCKET:
4350 	case PTR_TO_SOCK_COMMON:
4351 	case PTR_TO_TCP_SOCK:
4352 	case PTR_TO_XDP_SOCK:
4353 	case PTR_TO_BTF_ID:
4354 	case PTR_TO_BUF:
4355 	case PTR_TO_MEM:
4356 	case PTR_TO_FUNC:
4357 	case PTR_TO_MAP_KEY:
4358 		return true;
4359 	default:
4360 		return false;
4361 	}
4362 }
4363 
4364 /* Does this register contain a constant zero? */
4365 static bool register_is_null(struct bpf_reg_state *reg)
4366 {
4367 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4368 }
4369 
4370 /* check if register is a constant scalar value */
4371 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4372 {
4373 	return reg->type == SCALAR_VALUE &&
4374 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4375 }
4376 
4377 /* assuming is_reg_const() is true, return constant value of a register */
4378 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4379 {
4380 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4381 }
4382 
4383 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4384 {
4385 	return tnum_is_unknown(reg->var_off) &&
4386 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4387 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4388 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4389 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4390 }
4391 
4392 static bool register_is_bounded(struct bpf_reg_state *reg)
4393 {
4394 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4395 }
4396 
4397 static bool __is_pointer_value(bool allow_ptr_leaks,
4398 			       const struct bpf_reg_state *reg)
4399 {
4400 	if (allow_ptr_leaks)
4401 		return false;
4402 
4403 	return reg->type != SCALAR_VALUE;
4404 }
4405 
4406 /* Copy src state preserving dst->parent and dst->live fields */
4407 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4408 {
4409 	struct bpf_reg_state *parent = dst->parent;
4410 	enum bpf_reg_liveness live = dst->live;
4411 
4412 	*dst = *src;
4413 	dst->parent = parent;
4414 	dst->live = live;
4415 }
4416 
4417 static void save_register_state(struct bpf_verifier_env *env,
4418 				struct bpf_func_state *state,
4419 				int spi, struct bpf_reg_state *reg,
4420 				int size)
4421 {
4422 	int i;
4423 
4424 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4425 	if (size == BPF_REG_SIZE)
4426 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4427 
4428 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4429 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4430 
4431 	/* size < 8 bytes spill */
4432 	for (; i; i--)
4433 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4434 }
4435 
4436 static bool is_bpf_st_mem(struct bpf_insn *insn)
4437 {
4438 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4439 }
4440 
4441 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4442  * stack boundary and alignment are checked in check_mem_access()
4443  */
4444 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4445 				       /* stack frame we're writing to */
4446 				       struct bpf_func_state *state,
4447 				       int off, int size, int value_regno,
4448 				       int insn_idx)
4449 {
4450 	struct bpf_func_state *cur; /* state of the current function */
4451 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4452 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4453 	struct bpf_reg_state *reg = NULL;
4454 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
4455 
4456 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4457 	 * so it's aligned access and [off, off + size) are within stack limits
4458 	 */
4459 	if (!env->allow_ptr_leaks &&
4460 	    is_spilled_reg(&state->stack[spi]) &&
4461 	    size != BPF_REG_SIZE) {
4462 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4463 		return -EACCES;
4464 	}
4465 
4466 	cur = env->cur_state->frame[env->cur_state->curframe];
4467 	if (value_regno >= 0)
4468 		reg = &cur->regs[value_regno];
4469 	if (!env->bypass_spec_v4) {
4470 		bool sanitize = reg && is_spillable_regtype(reg->type);
4471 
4472 		for (i = 0; i < size; i++) {
4473 			u8 type = state->stack[spi].slot_type[i];
4474 
4475 			if (type != STACK_MISC && type != STACK_ZERO) {
4476 				sanitize = true;
4477 				break;
4478 			}
4479 		}
4480 
4481 		if (sanitize)
4482 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4483 	}
4484 
4485 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4486 	if (err)
4487 		return err;
4488 
4489 	mark_stack_slot_scratched(env, spi);
4490 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && env->bpf_capable) {
4491 		save_register_state(env, state, spi, reg, size);
4492 		/* Break the relation on a narrowing spill. */
4493 		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4494 			state->stack[spi].spilled_ptr.id = 0;
4495 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4496 		   insn->imm != 0 && env->bpf_capable) {
4497 		struct bpf_reg_state fake_reg = {};
4498 
4499 		__mark_reg_known(&fake_reg, insn->imm);
4500 		fake_reg.type = SCALAR_VALUE;
4501 		save_register_state(env, state, spi, &fake_reg, size);
4502 	} else if (reg && is_spillable_regtype(reg->type)) {
4503 		/* register containing pointer is being spilled into stack */
4504 		if (size != BPF_REG_SIZE) {
4505 			verbose_linfo(env, insn_idx, "; ");
4506 			verbose(env, "invalid size of register spill\n");
4507 			return -EACCES;
4508 		}
4509 		if (state != cur && reg->type == PTR_TO_STACK) {
4510 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4511 			return -EINVAL;
4512 		}
4513 		save_register_state(env, state, spi, reg, size);
4514 	} else {
4515 		u8 type = STACK_MISC;
4516 
4517 		/* regular write of data into stack destroys any spilled ptr */
4518 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4519 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4520 		if (is_stack_slot_special(&state->stack[spi]))
4521 			for (i = 0; i < BPF_REG_SIZE; i++)
4522 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4523 
4524 		/* only mark the slot as written if all 8 bytes were written
4525 		 * otherwise read propagation may incorrectly stop too soon
4526 		 * when stack slots are partially written.
4527 		 * This heuristic means that read propagation will be
4528 		 * conservative, since it will add reg_live_read marks
4529 		 * to stack slots all the way to first state when programs
4530 		 * writes+reads less than 8 bytes
4531 		 */
4532 		if (size == BPF_REG_SIZE)
4533 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4534 
4535 		/* when we zero initialize stack slots mark them as such */
4536 		if ((reg && register_is_null(reg)) ||
4537 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4538 			/* STACK_ZERO case happened because register spill
4539 			 * wasn't properly aligned at the stack slot boundary,
4540 			 * so it's not a register spill anymore; force
4541 			 * originating register to be precise to make
4542 			 * STACK_ZERO correct for subsequent states
4543 			 */
4544 			err = mark_chain_precision(env, value_regno);
4545 			if (err)
4546 				return err;
4547 			type = STACK_ZERO;
4548 		}
4549 
4550 		/* Mark slots affected by this stack write. */
4551 		for (i = 0; i < size; i++)
4552 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
4553 		insn_flags = 0; /* not a register spill */
4554 	}
4555 
4556 	if (insn_flags)
4557 		return push_jmp_history(env, env->cur_state, insn_flags);
4558 	return 0;
4559 }
4560 
4561 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4562  * known to contain a variable offset.
4563  * This function checks whether the write is permitted and conservatively
4564  * tracks the effects of the write, considering that each stack slot in the
4565  * dynamic range is potentially written to.
4566  *
4567  * 'off' includes 'regno->off'.
4568  * 'value_regno' can be -1, meaning that an unknown value is being written to
4569  * the stack.
4570  *
4571  * Spilled pointers in range are not marked as written because we don't know
4572  * what's going to be actually written. This means that read propagation for
4573  * future reads cannot be terminated by this write.
4574  *
4575  * For privileged programs, uninitialized stack slots are considered
4576  * initialized by this write (even though we don't know exactly what offsets
4577  * are going to be written to). The idea is that we don't want the verifier to
4578  * reject future reads that access slots written to through variable offsets.
4579  */
4580 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4581 				     /* func where register points to */
4582 				     struct bpf_func_state *state,
4583 				     int ptr_regno, int off, int size,
4584 				     int value_regno, int insn_idx)
4585 {
4586 	struct bpf_func_state *cur; /* state of the current function */
4587 	int min_off, max_off;
4588 	int i, err;
4589 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4590 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4591 	bool writing_zero = false;
4592 	/* set if the fact that we're writing a zero is used to let any
4593 	 * stack slots remain STACK_ZERO
4594 	 */
4595 	bool zero_used = false;
4596 
4597 	cur = env->cur_state->frame[env->cur_state->curframe];
4598 	ptr_reg = &cur->regs[ptr_regno];
4599 	min_off = ptr_reg->smin_value + off;
4600 	max_off = ptr_reg->smax_value + off + size;
4601 	if (value_regno >= 0)
4602 		value_reg = &cur->regs[value_regno];
4603 	if ((value_reg && register_is_null(value_reg)) ||
4604 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4605 		writing_zero = true;
4606 
4607 	for (i = min_off; i < max_off; i++) {
4608 		int spi;
4609 
4610 		spi = __get_spi(i);
4611 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4612 		if (err)
4613 			return err;
4614 	}
4615 
4616 	/* Variable offset writes destroy any spilled pointers in range. */
4617 	for (i = min_off; i < max_off; i++) {
4618 		u8 new_type, *stype;
4619 		int slot, spi;
4620 
4621 		slot = -i - 1;
4622 		spi = slot / BPF_REG_SIZE;
4623 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4624 		mark_stack_slot_scratched(env, spi);
4625 
4626 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4627 			/* Reject the write if range we may write to has not
4628 			 * been initialized beforehand. If we didn't reject
4629 			 * here, the ptr status would be erased below (even
4630 			 * though not all slots are actually overwritten),
4631 			 * possibly opening the door to leaks.
4632 			 *
4633 			 * We do however catch STACK_INVALID case below, and
4634 			 * only allow reading possibly uninitialized memory
4635 			 * later for CAP_PERFMON, as the write may not happen to
4636 			 * that slot.
4637 			 */
4638 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4639 				insn_idx, i);
4640 			return -EINVAL;
4641 		}
4642 
4643 		/* Erase all spilled pointers. */
4644 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4645 
4646 		/* Update the slot type. */
4647 		new_type = STACK_MISC;
4648 		if (writing_zero && *stype == STACK_ZERO) {
4649 			new_type = STACK_ZERO;
4650 			zero_used = true;
4651 		}
4652 		/* If the slot is STACK_INVALID, we check whether it's OK to
4653 		 * pretend that it will be initialized by this write. The slot
4654 		 * might not actually be written to, and so if we mark it as
4655 		 * initialized future reads might leak uninitialized memory.
4656 		 * For privileged programs, we will accept such reads to slots
4657 		 * that may or may not be written because, if we're reject
4658 		 * them, the error would be too confusing.
4659 		 */
4660 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4661 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4662 					insn_idx, i);
4663 			return -EINVAL;
4664 		}
4665 		*stype = new_type;
4666 	}
4667 	if (zero_used) {
4668 		/* backtracking doesn't work for STACK_ZERO yet. */
4669 		err = mark_chain_precision(env, value_regno);
4670 		if (err)
4671 			return err;
4672 	}
4673 	return 0;
4674 }
4675 
4676 /* When register 'dst_regno' is assigned some values from stack[min_off,
4677  * max_off), we set the register's type according to the types of the
4678  * respective stack slots. If all the stack values are known to be zeros, then
4679  * so is the destination reg. Otherwise, the register is considered to be
4680  * SCALAR. This function does not deal with register filling; the caller must
4681  * ensure that all spilled registers in the stack range have been marked as
4682  * read.
4683  */
4684 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4685 				/* func where src register points to */
4686 				struct bpf_func_state *ptr_state,
4687 				int min_off, int max_off, int dst_regno)
4688 {
4689 	struct bpf_verifier_state *vstate = env->cur_state;
4690 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4691 	int i, slot, spi;
4692 	u8 *stype;
4693 	int zeros = 0;
4694 
4695 	for (i = min_off; i < max_off; i++) {
4696 		slot = -i - 1;
4697 		spi = slot / BPF_REG_SIZE;
4698 		mark_stack_slot_scratched(env, spi);
4699 		stype = ptr_state->stack[spi].slot_type;
4700 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4701 			break;
4702 		zeros++;
4703 	}
4704 	if (zeros == max_off - min_off) {
4705 		/* Any access_size read into register is zero extended,
4706 		 * so the whole register == const_zero.
4707 		 */
4708 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
4709 	} else {
4710 		/* have read misc data from the stack */
4711 		mark_reg_unknown(env, state->regs, dst_regno);
4712 	}
4713 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4714 }
4715 
4716 /* Read the stack at 'off' and put the results into the register indicated by
4717  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4718  * spilled reg.
4719  *
4720  * 'dst_regno' can be -1, meaning that the read value is not going to a
4721  * register.
4722  *
4723  * The access is assumed to be within the current stack bounds.
4724  */
4725 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4726 				      /* func where src register points to */
4727 				      struct bpf_func_state *reg_state,
4728 				      int off, int size, int dst_regno)
4729 {
4730 	struct bpf_verifier_state *vstate = env->cur_state;
4731 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4732 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4733 	struct bpf_reg_state *reg;
4734 	u8 *stype, type;
4735 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
4736 
4737 	stype = reg_state->stack[spi].slot_type;
4738 	reg = &reg_state->stack[spi].spilled_ptr;
4739 
4740 	mark_stack_slot_scratched(env, spi);
4741 
4742 	if (is_spilled_reg(&reg_state->stack[spi])) {
4743 		u8 spill_size = 1;
4744 
4745 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4746 			spill_size++;
4747 
4748 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4749 			if (reg->type != SCALAR_VALUE) {
4750 				verbose_linfo(env, env->insn_idx, "; ");
4751 				verbose(env, "invalid size of register fill\n");
4752 				return -EACCES;
4753 			}
4754 
4755 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4756 			if (dst_regno < 0)
4757 				return 0;
4758 
4759 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4760 				/* The earlier check_reg_arg() has decided the
4761 				 * subreg_def for this insn.  Save it first.
4762 				 */
4763 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4764 
4765 				copy_register_state(&state->regs[dst_regno], reg);
4766 				state->regs[dst_regno].subreg_def = subreg_def;
4767 			} else {
4768 				int spill_cnt = 0, zero_cnt = 0;
4769 
4770 				for (i = 0; i < size; i++) {
4771 					type = stype[(slot - i) % BPF_REG_SIZE];
4772 					if (type == STACK_SPILL) {
4773 						spill_cnt++;
4774 						continue;
4775 					}
4776 					if (type == STACK_MISC)
4777 						continue;
4778 					if (type == STACK_ZERO) {
4779 						zero_cnt++;
4780 						continue;
4781 					}
4782 					if (type == STACK_INVALID && env->allow_uninit_stack)
4783 						continue;
4784 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4785 						off, i, size);
4786 					return -EACCES;
4787 				}
4788 
4789 				if (spill_cnt == size &&
4790 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
4791 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4792 					/* this IS register fill, so keep insn_flags */
4793 				} else if (zero_cnt == size) {
4794 					/* similarly to mark_reg_stack_read(), preserve zeroes */
4795 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4796 					insn_flags = 0; /* not restoring original register state */
4797 				} else {
4798 					mark_reg_unknown(env, state->regs, dst_regno);
4799 					insn_flags = 0; /* not restoring original register state */
4800 				}
4801 			}
4802 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4803 		} else if (dst_regno >= 0) {
4804 			/* restore register state from stack */
4805 			copy_register_state(&state->regs[dst_regno], reg);
4806 			/* mark reg as written since spilled pointer state likely
4807 			 * has its liveness marks cleared by is_state_visited()
4808 			 * which resets stack/reg liveness for state transitions
4809 			 */
4810 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4811 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4812 			/* If dst_regno==-1, the caller is asking us whether
4813 			 * it is acceptable to use this value as a SCALAR_VALUE
4814 			 * (e.g. for XADD).
4815 			 * We must not allow unprivileged callers to do that
4816 			 * with spilled pointers.
4817 			 */
4818 			verbose(env, "leaking pointer from stack off %d\n",
4819 				off);
4820 			return -EACCES;
4821 		}
4822 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4823 	} else {
4824 		for (i = 0; i < size; i++) {
4825 			type = stype[(slot - i) % BPF_REG_SIZE];
4826 			if (type == STACK_MISC)
4827 				continue;
4828 			if (type == STACK_ZERO)
4829 				continue;
4830 			if (type == STACK_INVALID && env->allow_uninit_stack)
4831 				continue;
4832 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4833 				off, i, size);
4834 			return -EACCES;
4835 		}
4836 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4837 		if (dst_regno >= 0)
4838 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4839 		insn_flags = 0; /* we are not restoring spilled register */
4840 	}
4841 	if (insn_flags)
4842 		return push_jmp_history(env, env->cur_state, insn_flags);
4843 	return 0;
4844 }
4845 
4846 enum bpf_access_src {
4847 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4848 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4849 };
4850 
4851 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4852 					 int regno, int off, int access_size,
4853 					 bool zero_size_allowed,
4854 					 enum bpf_access_src type,
4855 					 struct bpf_call_arg_meta *meta);
4856 
4857 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4858 {
4859 	return cur_regs(env) + regno;
4860 }
4861 
4862 /* Read the stack at 'ptr_regno + off' and put the result into the register
4863  * 'dst_regno'.
4864  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4865  * but not its variable offset.
4866  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4867  *
4868  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4869  * filling registers (i.e. reads of spilled register cannot be detected when
4870  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4871  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4872  * offset; for a fixed offset check_stack_read_fixed_off should be used
4873  * instead.
4874  */
4875 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4876 				    int ptr_regno, int off, int size, int dst_regno)
4877 {
4878 	/* The state of the source register. */
4879 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4880 	struct bpf_func_state *ptr_state = func(env, reg);
4881 	int err;
4882 	int min_off, max_off;
4883 
4884 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4885 	 */
4886 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4887 					    false, ACCESS_DIRECT, NULL);
4888 	if (err)
4889 		return err;
4890 
4891 	min_off = reg->smin_value + off;
4892 	max_off = reg->smax_value + off;
4893 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4894 	return 0;
4895 }
4896 
4897 /* check_stack_read dispatches to check_stack_read_fixed_off or
4898  * check_stack_read_var_off.
4899  *
4900  * The caller must ensure that the offset falls within the allocated stack
4901  * bounds.
4902  *
4903  * 'dst_regno' is a register which will receive the value from the stack. It
4904  * can be -1, meaning that the read value is not going to a register.
4905  */
4906 static int check_stack_read(struct bpf_verifier_env *env,
4907 			    int ptr_regno, int off, int size,
4908 			    int dst_regno)
4909 {
4910 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4911 	struct bpf_func_state *state = func(env, reg);
4912 	int err;
4913 	/* Some accesses are only permitted with a static offset. */
4914 	bool var_off = !tnum_is_const(reg->var_off);
4915 
4916 	/* The offset is required to be static when reads don't go to a
4917 	 * register, in order to not leak pointers (see
4918 	 * check_stack_read_fixed_off).
4919 	 */
4920 	if (dst_regno < 0 && var_off) {
4921 		char tn_buf[48];
4922 
4923 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4924 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4925 			tn_buf, off, size);
4926 		return -EACCES;
4927 	}
4928 	/* Variable offset is prohibited for unprivileged mode for simplicity
4929 	 * since it requires corresponding support in Spectre masking for stack
4930 	 * ALU. See also retrieve_ptr_limit(). The check in
4931 	 * check_stack_access_for_ptr_arithmetic() called by
4932 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4933 	 * with variable offsets, therefore no check is required here. Further,
4934 	 * just checking it here would be insufficient as speculative stack
4935 	 * writes could still lead to unsafe speculative behaviour.
4936 	 */
4937 	if (!var_off) {
4938 		off += reg->var_off.value;
4939 		err = check_stack_read_fixed_off(env, state, off, size,
4940 						 dst_regno);
4941 	} else {
4942 		/* Variable offset stack reads need more conservative handling
4943 		 * than fixed offset ones. Note that dst_regno >= 0 on this
4944 		 * branch.
4945 		 */
4946 		err = check_stack_read_var_off(env, ptr_regno, off, size,
4947 					       dst_regno);
4948 	}
4949 	return err;
4950 }
4951 
4952 
4953 /* check_stack_write dispatches to check_stack_write_fixed_off or
4954  * check_stack_write_var_off.
4955  *
4956  * 'ptr_regno' is the register used as a pointer into the stack.
4957  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4958  * 'value_regno' is the register whose value we're writing to the stack. It can
4959  * be -1, meaning that we're not writing from a register.
4960  *
4961  * The caller must ensure that the offset falls within the maximum stack size.
4962  */
4963 static int check_stack_write(struct bpf_verifier_env *env,
4964 			     int ptr_regno, int off, int size,
4965 			     int value_regno, int insn_idx)
4966 {
4967 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4968 	struct bpf_func_state *state = func(env, reg);
4969 	int err;
4970 
4971 	if (tnum_is_const(reg->var_off)) {
4972 		off += reg->var_off.value;
4973 		err = check_stack_write_fixed_off(env, state, off, size,
4974 						  value_regno, insn_idx);
4975 	} else {
4976 		/* Variable offset stack reads need more conservative handling
4977 		 * than fixed offset ones.
4978 		 */
4979 		err = check_stack_write_var_off(env, state,
4980 						ptr_regno, off, size,
4981 						value_regno, insn_idx);
4982 	}
4983 	return err;
4984 }
4985 
4986 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4987 				 int off, int size, enum bpf_access_type type)
4988 {
4989 	struct bpf_reg_state *regs = cur_regs(env);
4990 	struct bpf_map *map = regs[regno].map_ptr;
4991 	u32 cap = bpf_map_flags_to_cap(map);
4992 
4993 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4994 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4995 			map->value_size, off, size);
4996 		return -EACCES;
4997 	}
4998 
4999 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5000 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5001 			map->value_size, off, size);
5002 		return -EACCES;
5003 	}
5004 
5005 	return 0;
5006 }
5007 
5008 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5009 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5010 			      int off, int size, u32 mem_size,
5011 			      bool zero_size_allowed)
5012 {
5013 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5014 	struct bpf_reg_state *reg;
5015 
5016 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5017 		return 0;
5018 
5019 	reg = &cur_regs(env)[regno];
5020 	switch (reg->type) {
5021 	case PTR_TO_MAP_KEY:
5022 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5023 			mem_size, off, size);
5024 		break;
5025 	case PTR_TO_MAP_VALUE:
5026 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5027 			mem_size, off, size);
5028 		break;
5029 	case PTR_TO_PACKET:
5030 	case PTR_TO_PACKET_META:
5031 	case PTR_TO_PACKET_END:
5032 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5033 			off, size, regno, reg->id, off, mem_size);
5034 		break;
5035 	case PTR_TO_MEM:
5036 	default:
5037 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5038 			mem_size, off, size);
5039 	}
5040 
5041 	return -EACCES;
5042 }
5043 
5044 /* check read/write into a memory region with possible variable offset */
5045 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5046 				   int off, int size, u32 mem_size,
5047 				   bool zero_size_allowed)
5048 {
5049 	struct bpf_verifier_state *vstate = env->cur_state;
5050 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5051 	struct bpf_reg_state *reg = &state->regs[regno];
5052 	int err;
5053 
5054 	/* We may have adjusted the register pointing to memory region, so we
5055 	 * need to try adding each of min_value and max_value to off
5056 	 * to make sure our theoretical access will be safe.
5057 	 *
5058 	 * The minimum value is only important with signed
5059 	 * comparisons where we can't assume the floor of a
5060 	 * value is 0.  If we are using signed variables for our
5061 	 * index'es we need to make sure that whatever we use
5062 	 * will have a set floor within our range.
5063 	 */
5064 	if (reg->smin_value < 0 &&
5065 	    (reg->smin_value == S64_MIN ||
5066 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5067 	      reg->smin_value + off < 0)) {
5068 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5069 			regno);
5070 		return -EACCES;
5071 	}
5072 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5073 				 mem_size, zero_size_allowed);
5074 	if (err) {
5075 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5076 			regno);
5077 		return err;
5078 	}
5079 
5080 	/* If we haven't set a max value then we need to bail since we can't be
5081 	 * sure we won't do bad things.
5082 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5083 	 */
5084 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5085 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5086 			regno);
5087 		return -EACCES;
5088 	}
5089 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5090 				 mem_size, zero_size_allowed);
5091 	if (err) {
5092 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5093 			regno);
5094 		return err;
5095 	}
5096 
5097 	return 0;
5098 }
5099 
5100 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5101 			       const struct bpf_reg_state *reg, int regno,
5102 			       bool fixed_off_ok)
5103 {
5104 	/* Access to this pointer-typed register or passing it to a helper
5105 	 * is only allowed in its original, unmodified form.
5106 	 */
5107 
5108 	if (reg->off < 0) {
5109 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5110 			reg_type_str(env, reg->type), regno, reg->off);
5111 		return -EACCES;
5112 	}
5113 
5114 	if (!fixed_off_ok && reg->off) {
5115 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5116 			reg_type_str(env, reg->type), regno, reg->off);
5117 		return -EACCES;
5118 	}
5119 
5120 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5121 		char tn_buf[48];
5122 
5123 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5124 		verbose(env, "variable %s access var_off=%s disallowed\n",
5125 			reg_type_str(env, reg->type), tn_buf);
5126 		return -EACCES;
5127 	}
5128 
5129 	return 0;
5130 }
5131 
5132 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5133 		             const struct bpf_reg_state *reg, int regno)
5134 {
5135 	return __check_ptr_off_reg(env, reg, regno, false);
5136 }
5137 
5138 static int map_kptr_match_type(struct bpf_verifier_env *env,
5139 			       struct btf_field *kptr_field,
5140 			       struct bpf_reg_state *reg, u32 regno)
5141 {
5142 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5143 	int perm_flags;
5144 	const char *reg_name = "";
5145 
5146 	if (btf_is_kernel(reg->btf)) {
5147 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5148 
5149 		/* Only unreferenced case accepts untrusted pointers */
5150 		if (kptr_field->type == BPF_KPTR_UNREF)
5151 			perm_flags |= PTR_UNTRUSTED;
5152 	} else {
5153 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5154 		if (kptr_field->type == BPF_KPTR_PERCPU)
5155 			perm_flags |= MEM_PERCPU;
5156 	}
5157 
5158 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5159 		goto bad_type;
5160 
5161 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5162 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5163 
5164 	/* For ref_ptr case, release function check should ensure we get one
5165 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5166 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5167 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5168 	 * reg->off and reg->ref_obj_id are not needed here.
5169 	 */
5170 	if (__check_ptr_off_reg(env, reg, regno, true))
5171 		return -EACCES;
5172 
5173 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5174 	 * we also need to take into account the reg->off.
5175 	 *
5176 	 * We want to support cases like:
5177 	 *
5178 	 * struct foo {
5179 	 *         struct bar br;
5180 	 *         struct baz bz;
5181 	 * };
5182 	 *
5183 	 * struct foo *v;
5184 	 * v = func();	      // PTR_TO_BTF_ID
5185 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5186 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5187 	 *                    // first member type of struct after comparison fails
5188 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5189 	 *                    // to match type
5190 	 *
5191 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5192 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5193 	 * the struct to match type against first member of struct, i.e. reject
5194 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5195 	 * strict mode to true for type match.
5196 	 */
5197 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5198 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5199 				  kptr_field->type != BPF_KPTR_UNREF))
5200 		goto bad_type;
5201 	return 0;
5202 bad_type:
5203 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5204 		reg_type_str(env, reg->type), reg_name);
5205 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5206 	if (kptr_field->type == BPF_KPTR_UNREF)
5207 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5208 			targ_name);
5209 	else
5210 		verbose(env, "\n");
5211 	return -EINVAL;
5212 }
5213 
5214 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5215  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5216  */
5217 static bool in_rcu_cs(struct bpf_verifier_env *env)
5218 {
5219 	return env->cur_state->active_rcu_lock ||
5220 	       env->cur_state->active_lock.ptr ||
5221 	       !env->prog->aux->sleepable;
5222 }
5223 
5224 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5225 BTF_SET_START(rcu_protected_types)
5226 BTF_ID(struct, prog_test_ref_kfunc)
5227 #ifdef CONFIG_CGROUPS
5228 BTF_ID(struct, cgroup)
5229 #endif
5230 BTF_ID(struct, bpf_cpumask)
5231 BTF_ID(struct, task_struct)
5232 BTF_SET_END(rcu_protected_types)
5233 
5234 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5235 {
5236 	if (!btf_is_kernel(btf))
5237 		return true;
5238 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5239 }
5240 
5241 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5242 {
5243 	struct btf_struct_meta *meta;
5244 
5245 	if (btf_is_kernel(kptr_field->kptr.btf))
5246 		return NULL;
5247 
5248 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5249 				    kptr_field->kptr.btf_id);
5250 
5251 	return meta ? meta->record : NULL;
5252 }
5253 
5254 static bool rcu_safe_kptr(const struct btf_field *field)
5255 {
5256 	const struct btf_field_kptr *kptr = &field->kptr;
5257 
5258 	return field->type == BPF_KPTR_PERCPU ||
5259 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5260 }
5261 
5262 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5263 {
5264 	struct btf_record *rec;
5265 	u32 ret;
5266 
5267 	ret = PTR_MAYBE_NULL;
5268 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5269 		ret |= MEM_RCU;
5270 		if (kptr_field->type == BPF_KPTR_PERCPU)
5271 			ret |= MEM_PERCPU;
5272 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5273 			ret |= MEM_ALLOC;
5274 
5275 		rec = kptr_pointee_btf_record(kptr_field);
5276 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5277 			ret |= NON_OWN_REF;
5278 	} else {
5279 		ret |= PTR_UNTRUSTED;
5280 	}
5281 
5282 	return ret;
5283 }
5284 
5285 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5286 				 int value_regno, int insn_idx,
5287 				 struct btf_field *kptr_field)
5288 {
5289 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5290 	int class = BPF_CLASS(insn->code);
5291 	struct bpf_reg_state *val_reg;
5292 
5293 	/* Things we already checked for in check_map_access and caller:
5294 	 *  - Reject cases where variable offset may touch kptr
5295 	 *  - size of access (must be BPF_DW)
5296 	 *  - tnum_is_const(reg->var_off)
5297 	 *  - kptr_field->offset == off + reg->var_off.value
5298 	 */
5299 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5300 	if (BPF_MODE(insn->code) != BPF_MEM) {
5301 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5302 		return -EACCES;
5303 	}
5304 
5305 	/* We only allow loading referenced kptr, since it will be marked as
5306 	 * untrusted, similar to unreferenced kptr.
5307 	 */
5308 	if (class != BPF_LDX &&
5309 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5310 		verbose(env, "store to referenced kptr disallowed\n");
5311 		return -EACCES;
5312 	}
5313 
5314 	if (class == BPF_LDX) {
5315 		val_reg = reg_state(env, value_regno);
5316 		/* We can simply mark the value_regno receiving the pointer
5317 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5318 		 */
5319 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5320 				kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5321 		/* For mark_ptr_or_null_reg */
5322 		val_reg->id = ++env->id_gen;
5323 	} else if (class == BPF_STX) {
5324 		val_reg = reg_state(env, value_regno);
5325 		if (!register_is_null(val_reg) &&
5326 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5327 			return -EACCES;
5328 	} else if (class == BPF_ST) {
5329 		if (insn->imm) {
5330 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5331 				kptr_field->offset);
5332 			return -EACCES;
5333 		}
5334 	} else {
5335 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5336 		return -EACCES;
5337 	}
5338 	return 0;
5339 }
5340 
5341 /* check read/write into a map element with possible variable offset */
5342 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5343 			    int off, int size, bool zero_size_allowed,
5344 			    enum bpf_access_src src)
5345 {
5346 	struct bpf_verifier_state *vstate = env->cur_state;
5347 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5348 	struct bpf_reg_state *reg = &state->regs[regno];
5349 	struct bpf_map *map = reg->map_ptr;
5350 	struct btf_record *rec;
5351 	int err, i;
5352 
5353 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5354 				      zero_size_allowed);
5355 	if (err)
5356 		return err;
5357 
5358 	if (IS_ERR_OR_NULL(map->record))
5359 		return 0;
5360 	rec = map->record;
5361 	for (i = 0; i < rec->cnt; i++) {
5362 		struct btf_field *field = &rec->fields[i];
5363 		u32 p = field->offset;
5364 
5365 		/* If any part of a field  can be touched by load/store, reject
5366 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5367 		 * it is sufficient to check x1 < y2 && y1 < x2.
5368 		 */
5369 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5370 		    p < reg->umax_value + off + size) {
5371 			switch (field->type) {
5372 			case BPF_KPTR_UNREF:
5373 			case BPF_KPTR_REF:
5374 			case BPF_KPTR_PERCPU:
5375 				if (src != ACCESS_DIRECT) {
5376 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5377 					return -EACCES;
5378 				}
5379 				if (!tnum_is_const(reg->var_off)) {
5380 					verbose(env, "kptr access cannot have variable offset\n");
5381 					return -EACCES;
5382 				}
5383 				if (p != off + reg->var_off.value) {
5384 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5385 						p, off + reg->var_off.value);
5386 					return -EACCES;
5387 				}
5388 				if (size != bpf_size_to_bytes(BPF_DW)) {
5389 					verbose(env, "kptr access size must be BPF_DW\n");
5390 					return -EACCES;
5391 				}
5392 				break;
5393 			default:
5394 				verbose(env, "%s cannot be accessed directly by load/store\n",
5395 					btf_field_type_name(field->type));
5396 				return -EACCES;
5397 			}
5398 		}
5399 	}
5400 	return 0;
5401 }
5402 
5403 #define MAX_PACKET_OFF 0xffff
5404 
5405 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5406 				       const struct bpf_call_arg_meta *meta,
5407 				       enum bpf_access_type t)
5408 {
5409 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5410 
5411 	switch (prog_type) {
5412 	/* Program types only with direct read access go here! */
5413 	case BPF_PROG_TYPE_LWT_IN:
5414 	case BPF_PROG_TYPE_LWT_OUT:
5415 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5416 	case BPF_PROG_TYPE_SK_REUSEPORT:
5417 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5418 	case BPF_PROG_TYPE_CGROUP_SKB:
5419 		if (t == BPF_WRITE)
5420 			return false;
5421 		fallthrough;
5422 
5423 	/* Program types with direct read + write access go here! */
5424 	case BPF_PROG_TYPE_SCHED_CLS:
5425 	case BPF_PROG_TYPE_SCHED_ACT:
5426 	case BPF_PROG_TYPE_XDP:
5427 	case BPF_PROG_TYPE_LWT_XMIT:
5428 	case BPF_PROG_TYPE_SK_SKB:
5429 	case BPF_PROG_TYPE_SK_MSG:
5430 		if (meta)
5431 			return meta->pkt_access;
5432 
5433 		env->seen_direct_write = true;
5434 		return true;
5435 
5436 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5437 		if (t == BPF_WRITE)
5438 			env->seen_direct_write = true;
5439 
5440 		return true;
5441 
5442 	default:
5443 		return false;
5444 	}
5445 }
5446 
5447 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5448 			       int size, bool zero_size_allowed)
5449 {
5450 	struct bpf_reg_state *regs = cur_regs(env);
5451 	struct bpf_reg_state *reg = &regs[regno];
5452 	int err;
5453 
5454 	/* We may have added a variable offset to the packet pointer; but any
5455 	 * reg->range we have comes after that.  We are only checking the fixed
5456 	 * offset.
5457 	 */
5458 
5459 	/* We don't allow negative numbers, because we aren't tracking enough
5460 	 * detail to prove they're safe.
5461 	 */
5462 	if (reg->smin_value < 0) {
5463 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5464 			regno);
5465 		return -EACCES;
5466 	}
5467 
5468 	err = reg->range < 0 ? -EINVAL :
5469 	      __check_mem_access(env, regno, off, size, reg->range,
5470 				 zero_size_allowed);
5471 	if (err) {
5472 		verbose(env, "R%d offset is outside of the packet\n", regno);
5473 		return err;
5474 	}
5475 
5476 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5477 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5478 	 * otherwise find_good_pkt_pointers would have refused to set range info
5479 	 * that __check_mem_access would have rejected this pkt access.
5480 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5481 	 */
5482 	env->prog->aux->max_pkt_offset =
5483 		max_t(u32, env->prog->aux->max_pkt_offset,
5484 		      off + reg->umax_value + size - 1);
5485 
5486 	return err;
5487 }
5488 
5489 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5490 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5491 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5492 			    struct btf **btf, u32 *btf_id)
5493 {
5494 	struct bpf_insn_access_aux info = {
5495 		.reg_type = *reg_type,
5496 		.log = &env->log,
5497 	};
5498 
5499 	if (env->ops->is_valid_access &&
5500 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5501 		/* A non zero info.ctx_field_size indicates that this field is a
5502 		 * candidate for later verifier transformation to load the whole
5503 		 * field and then apply a mask when accessed with a narrower
5504 		 * access than actual ctx access size. A zero info.ctx_field_size
5505 		 * will only allow for whole field access and rejects any other
5506 		 * type of narrower access.
5507 		 */
5508 		*reg_type = info.reg_type;
5509 
5510 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5511 			*btf = info.btf;
5512 			*btf_id = info.btf_id;
5513 		} else {
5514 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5515 		}
5516 		/* remember the offset of last byte accessed in ctx */
5517 		if (env->prog->aux->max_ctx_offset < off + size)
5518 			env->prog->aux->max_ctx_offset = off + size;
5519 		return 0;
5520 	}
5521 
5522 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5523 	return -EACCES;
5524 }
5525 
5526 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5527 				  int size)
5528 {
5529 	if (size < 0 || off < 0 ||
5530 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5531 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5532 			off, size);
5533 		return -EACCES;
5534 	}
5535 	return 0;
5536 }
5537 
5538 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5539 			     u32 regno, int off, int size,
5540 			     enum bpf_access_type t)
5541 {
5542 	struct bpf_reg_state *regs = cur_regs(env);
5543 	struct bpf_reg_state *reg = &regs[regno];
5544 	struct bpf_insn_access_aux info = {};
5545 	bool valid;
5546 
5547 	if (reg->smin_value < 0) {
5548 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5549 			regno);
5550 		return -EACCES;
5551 	}
5552 
5553 	switch (reg->type) {
5554 	case PTR_TO_SOCK_COMMON:
5555 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5556 		break;
5557 	case PTR_TO_SOCKET:
5558 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5559 		break;
5560 	case PTR_TO_TCP_SOCK:
5561 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5562 		break;
5563 	case PTR_TO_XDP_SOCK:
5564 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5565 		break;
5566 	default:
5567 		valid = false;
5568 	}
5569 
5570 
5571 	if (valid) {
5572 		env->insn_aux_data[insn_idx].ctx_field_size =
5573 			info.ctx_field_size;
5574 		return 0;
5575 	}
5576 
5577 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5578 		regno, reg_type_str(env, reg->type), off, size);
5579 
5580 	return -EACCES;
5581 }
5582 
5583 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5584 {
5585 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5586 }
5587 
5588 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5589 {
5590 	const struct bpf_reg_state *reg = reg_state(env, regno);
5591 
5592 	return reg->type == PTR_TO_CTX;
5593 }
5594 
5595 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5596 {
5597 	const struct bpf_reg_state *reg = reg_state(env, regno);
5598 
5599 	return type_is_sk_pointer(reg->type);
5600 }
5601 
5602 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5603 {
5604 	const struct bpf_reg_state *reg = reg_state(env, regno);
5605 
5606 	return type_is_pkt_pointer(reg->type);
5607 }
5608 
5609 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5610 {
5611 	const struct bpf_reg_state *reg = reg_state(env, regno);
5612 
5613 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5614 	return reg->type == PTR_TO_FLOW_KEYS;
5615 }
5616 
5617 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5618 #ifdef CONFIG_NET
5619 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5620 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5621 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5622 #endif
5623 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5624 };
5625 
5626 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5627 {
5628 	/* A referenced register is always trusted. */
5629 	if (reg->ref_obj_id)
5630 		return true;
5631 
5632 	/* Types listed in the reg2btf_ids are always trusted */
5633 	if (reg2btf_ids[base_type(reg->type)])
5634 		return true;
5635 
5636 	/* If a register is not referenced, it is trusted if it has the
5637 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5638 	 * other type modifiers may be safe, but we elect to take an opt-in
5639 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5640 	 * not.
5641 	 *
5642 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5643 	 * for whether a register is trusted.
5644 	 */
5645 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5646 	       !bpf_type_has_unsafe_modifiers(reg->type);
5647 }
5648 
5649 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5650 {
5651 	return reg->type & MEM_RCU;
5652 }
5653 
5654 static void clear_trusted_flags(enum bpf_type_flag *flag)
5655 {
5656 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5657 }
5658 
5659 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5660 				   const struct bpf_reg_state *reg,
5661 				   int off, int size, bool strict)
5662 {
5663 	struct tnum reg_off;
5664 	int ip_align;
5665 
5666 	/* Byte size accesses are always allowed. */
5667 	if (!strict || size == 1)
5668 		return 0;
5669 
5670 	/* For platforms that do not have a Kconfig enabling
5671 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5672 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5673 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5674 	 * to this code only in strict mode where we want to emulate
5675 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5676 	 * unconditional IP align value of '2'.
5677 	 */
5678 	ip_align = 2;
5679 
5680 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5681 	if (!tnum_is_aligned(reg_off, size)) {
5682 		char tn_buf[48];
5683 
5684 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5685 		verbose(env,
5686 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5687 			ip_align, tn_buf, reg->off, off, size);
5688 		return -EACCES;
5689 	}
5690 
5691 	return 0;
5692 }
5693 
5694 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5695 				       const struct bpf_reg_state *reg,
5696 				       const char *pointer_desc,
5697 				       int off, int size, bool strict)
5698 {
5699 	struct tnum reg_off;
5700 
5701 	/* Byte size accesses are always allowed. */
5702 	if (!strict || size == 1)
5703 		return 0;
5704 
5705 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5706 	if (!tnum_is_aligned(reg_off, size)) {
5707 		char tn_buf[48];
5708 
5709 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5710 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5711 			pointer_desc, tn_buf, reg->off, off, size);
5712 		return -EACCES;
5713 	}
5714 
5715 	return 0;
5716 }
5717 
5718 static int check_ptr_alignment(struct bpf_verifier_env *env,
5719 			       const struct bpf_reg_state *reg, int off,
5720 			       int size, bool strict_alignment_once)
5721 {
5722 	bool strict = env->strict_alignment || strict_alignment_once;
5723 	const char *pointer_desc = "";
5724 
5725 	switch (reg->type) {
5726 	case PTR_TO_PACKET:
5727 	case PTR_TO_PACKET_META:
5728 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5729 		 * right in front, treat it the very same way.
5730 		 */
5731 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5732 	case PTR_TO_FLOW_KEYS:
5733 		pointer_desc = "flow keys ";
5734 		break;
5735 	case PTR_TO_MAP_KEY:
5736 		pointer_desc = "key ";
5737 		break;
5738 	case PTR_TO_MAP_VALUE:
5739 		pointer_desc = "value ";
5740 		break;
5741 	case PTR_TO_CTX:
5742 		pointer_desc = "context ";
5743 		break;
5744 	case PTR_TO_STACK:
5745 		pointer_desc = "stack ";
5746 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5747 		 * and check_stack_read_fixed_off() relies on stack accesses being
5748 		 * aligned.
5749 		 */
5750 		strict = true;
5751 		break;
5752 	case PTR_TO_SOCKET:
5753 		pointer_desc = "sock ";
5754 		break;
5755 	case PTR_TO_SOCK_COMMON:
5756 		pointer_desc = "sock_common ";
5757 		break;
5758 	case PTR_TO_TCP_SOCK:
5759 		pointer_desc = "tcp_sock ";
5760 		break;
5761 	case PTR_TO_XDP_SOCK:
5762 		pointer_desc = "xdp_sock ";
5763 		break;
5764 	default:
5765 		break;
5766 	}
5767 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5768 					   strict);
5769 }
5770 
5771 /* starting from main bpf function walk all instructions of the function
5772  * and recursively walk all callees that given function can call.
5773  * Ignore jump and exit insns.
5774  * Since recursion is prevented by check_cfg() this algorithm
5775  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5776  */
5777 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5778 {
5779 	struct bpf_subprog_info *subprog = env->subprog_info;
5780 	struct bpf_insn *insn = env->prog->insnsi;
5781 	int depth = 0, frame = 0, i, subprog_end;
5782 	bool tail_call_reachable = false;
5783 	int ret_insn[MAX_CALL_FRAMES];
5784 	int ret_prog[MAX_CALL_FRAMES];
5785 	int j;
5786 
5787 	i = subprog[idx].start;
5788 process_func:
5789 	/* protect against potential stack overflow that might happen when
5790 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5791 	 * depth for such case down to 256 so that the worst case scenario
5792 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5793 	 * 8k).
5794 	 *
5795 	 * To get the idea what might happen, see an example:
5796 	 * func1 -> sub rsp, 128
5797 	 *  subfunc1 -> sub rsp, 256
5798 	 *  tailcall1 -> add rsp, 256
5799 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5800 	 *   subfunc2 -> sub rsp, 64
5801 	 *   subfunc22 -> sub rsp, 128
5802 	 *   tailcall2 -> add rsp, 128
5803 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5804 	 *
5805 	 * tailcall will unwind the current stack frame but it will not get rid
5806 	 * of caller's stack as shown on the example above.
5807 	 */
5808 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5809 		verbose(env,
5810 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5811 			depth);
5812 		return -EACCES;
5813 	}
5814 	/* round up to 32-bytes, since this is granularity
5815 	 * of interpreter stack size
5816 	 */
5817 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5818 	if (depth > MAX_BPF_STACK) {
5819 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5820 			frame + 1, depth);
5821 		return -EACCES;
5822 	}
5823 continue_func:
5824 	subprog_end = subprog[idx + 1].start;
5825 	for (; i < subprog_end; i++) {
5826 		int next_insn, sidx;
5827 
5828 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
5829 			bool err = false;
5830 
5831 			if (!is_bpf_throw_kfunc(insn + i))
5832 				continue;
5833 			if (subprog[idx].is_cb)
5834 				err = true;
5835 			for (int c = 0; c < frame && !err; c++) {
5836 				if (subprog[ret_prog[c]].is_cb) {
5837 					err = true;
5838 					break;
5839 				}
5840 			}
5841 			if (!err)
5842 				continue;
5843 			verbose(env,
5844 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5845 				i, idx);
5846 			return -EINVAL;
5847 		}
5848 
5849 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5850 			continue;
5851 		/* remember insn and function to return to */
5852 		ret_insn[frame] = i + 1;
5853 		ret_prog[frame] = idx;
5854 
5855 		/* find the callee */
5856 		next_insn = i + insn[i].imm + 1;
5857 		sidx = find_subprog(env, next_insn);
5858 		if (sidx < 0) {
5859 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5860 				  next_insn);
5861 			return -EFAULT;
5862 		}
5863 		if (subprog[sidx].is_async_cb) {
5864 			if (subprog[sidx].has_tail_call) {
5865 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5866 				return -EFAULT;
5867 			}
5868 			/* async callbacks don't increase bpf prog stack size unless called directly */
5869 			if (!bpf_pseudo_call(insn + i))
5870 				continue;
5871 			if (subprog[sidx].is_exception_cb) {
5872 				verbose(env, "insn %d cannot call exception cb directly\n", i);
5873 				return -EINVAL;
5874 			}
5875 		}
5876 		i = next_insn;
5877 		idx = sidx;
5878 
5879 		if (subprog[idx].has_tail_call)
5880 			tail_call_reachable = true;
5881 
5882 		frame++;
5883 		if (frame >= MAX_CALL_FRAMES) {
5884 			verbose(env, "the call stack of %d frames is too deep !\n",
5885 				frame);
5886 			return -E2BIG;
5887 		}
5888 		goto process_func;
5889 	}
5890 	/* if tail call got detected across bpf2bpf calls then mark each of the
5891 	 * currently present subprog frames as tail call reachable subprogs;
5892 	 * this info will be utilized by JIT so that we will be preserving the
5893 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5894 	 */
5895 	if (tail_call_reachable)
5896 		for (j = 0; j < frame; j++) {
5897 			if (subprog[ret_prog[j]].is_exception_cb) {
5898 				verbose(env, "cannot tail call within exception cb\n");
5899 				return -EINVAL;
5900 			}
5901 			subprog[ret_prog[j]].tail_call_reachable = true;
5902 		}
5903 	if (subprog[0].tail_call_reachable)
5904 		env->prog->aux->tail_call_reachable = true;
5905 
5906 	/* end of for() loop means the last insn of the 'subprog'
5907 	 * was reached. Doesn't matter whether it was JA or EXIT
5908 	 */
5909 	if (frame == 0)
5910 		return 0;
5911 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5912 	frame--;
5913 	i = ret_insn[frame];
5914 	idx = ret_prog[frame];
5915 	goto continue_func;
5916 }
5917 
5918 static int check_max_stack_depth(struct bpf_verifier_env *env)
5919 {
5920 	struct bpf_subprog_info *si = env->subprog_info;
5921 	int ret;
5922 
5923 	for (int i = 0; i < env->subprog_cnt; i++) {
5924 		if (!i || si[i].is_async_cb) {
5925 			ret = check_max_stack_depth_subprog(env, i);
5926 			if (ret < 0)
5927 				return ret;
5928 		}
5929 		continue;
5930 	}
5931 	return 0;
5932 }
5933 
5934 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5935 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5936 				  const struct bpf_insn *insn, int idx)
5937 {
5938 	int start = idx + insn->imm + 1, subprog;
5939 
5940 	subprog = find_subprog(env, start);
5941 	if (subprog < 0) {
5942 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5943 			  start);
5944 		return -EFAULT;
5945 	}
5946 	return env->subprog_info[subprog].stack_depth;
5947 }
5948 #endif
5949 
5950 static int __check_buffer_access(struct bpf_verifier_env *env,
5951 				 const char *buf_info,
5952 				 const struct bpf_reg_state *reg,
5953 				 int regno, int off, int size)
5954 {
5955 	if (off < 0) {
5956 		verbose(env,
5957 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5958 			regno, buf_info, off, size);
5959 		return -EACCES;
5960 	}
5961 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5962 		char tn_buf[48];
5963 
5964 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5965 		verbose(env,
5966 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5967 			regno, off, tn_buf);
5968 		return -EACCES;
5969 	}
5970 
5971 	return 0;
5972 }
5973 
5974 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5975 				  const struct bpf_reg_state *reg,
5976 				  int regno, int off, int size)
5977 {
5978 	int err;
5979 
5980 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5981 	if (err)
5982 		return err;
5983 
5984 	if (off + size > env->prog->aux->max_tp_access)
5985 		env->prog->aux->max_tp_access = off + size;
5986 
5987 	return 0;
5988 }
5989 
5990 static int check_buffer_access(struct bpf_verifier_env *env,
5991 			       const struct bpf_reg_state *reg,
5992 			       int regno, int off, int size,
5993 			       bool zero_size_allowed,
5994 			       u32 *max_access)
5995 {
5996 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5997 	int err;
5998 
5999 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6000 	if (err)
6001 		return err;
6002 
6003 	if (off + size > *max_access)
6004 		*max_access = off + size;
6005 
6006 	return 0;
6007 }
6008 
6009 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6010 static void zext_32_to_64(struct bpf_reg_state *reg)
6011 {
6012 	reg->var_off = tnum_subreg(reg->var_off);
6013 	__reg_assign_32_into_64(reg);
6014 }
6015 
6016 /* truncate register to smaller size (in bytes)
6017  * must be called with size < BPF_REG_SIZE
6018  */
6019 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6020 {
6021 	u64 mask;
6022 
6023 	/* clear high bits in bit representation */
6024 	reg->var_off = tnum_cast(reg->var_off, size);
6025 
6026 	/* fix arithmetic bounds */
6027 	mask = ((u64)1 << (size * 8)) - 1;
6028 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6029 		reg->umin_value &= mask;
6030 		reg->umax_value &= mask;
6031 	} else {
6032 		reg->umin_value = 0;
6033 		reg->umax_value = mask;
6034 	}
6035 	reg->smin_value = reg->umin_value;
6036 	reg->smax_value = reg->umax_value;
6037 
6038 	/* If size is smaller than 32bit register the 32bit register
6039 	 * values are also truncated so we push 64-bit bounds into
6040 	 * 32-bit bounds. Above were truncated < 32-bits already.
6041 	 */
6042 	if (size < 4) {
6043 		__mark_reg32_unbounded(reg);
6044 		reg_bounds_sync(reg);
6045 	}
6046 }
6047 
6048 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6049 {
6050 	if (size == 1) {
6051 		reg->smin_value = reg->s32_min_value = S8_MIN;
6052 		reg->smax_value = reg->s32_max_value = S8_MAX;
6053 	} else if (size == 2) {
6054 		reg->smin_value = reg->s32_min_value = S16_MIN;
6055 		reg->smax_value = reg->s32_max_value = S16_MAX;
6056 	} else {
6057 		/* size == 4 */
6058 		reg->smin_value = reg->s32_min_value = S32_MIN;
6059 		reg->smax_value = reg->s32_max_value = S32_MAX;
6060 	}
6061 	reg->umin_value = reg->u32_min_value = 0;
6062 	reg->umax_value = U64_MAX;
6063 	reg->u32_max_value = U32_MAX;
6064 	reg->var_off = tnum_unknown;
6065 }
6066 
6067 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6068 {
6069 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6070 	u64 top_smax_value, top_smin_value;
6071 	u64 num_bits = size * 8;
6072 
6073 	if (tnum_is_const(reg->var_off)) {
6074 		u64_cval = reg->var_off.value;
6075 		if (size == 1)
6076 			reg->var_off = tnum_const((s8)u64_cval);
6077 		else if (size == 2)
6078 			reg->var_off = tnum_const((s16)u64_cval);
6079 		else
6080 			/* size == 4 */
6081 			reg->var_off = tnum_const((s32)u64_cval);
6082 
6083 		u64_cval = reg->var_off.value;
6084 		reg->smax_value = reg->smin_value = u64_cval;
6085 		reg->umax_value = reg->umin_value = u64_cval;
6086 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6087 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6088 		return;
6089 	}
6090 
6091 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6092 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6093 
6094 	if (top_smax_value != top_smin_value)
6095 		goto out;
6096 
6097 	/* find the s64_min and s64_min after sign extension */
6098 	if (size == 1) {
6099 		init_s64_max = (s8)reg->smax_value;
6100 		init_s64_min = (s8)reg->smin_value;
6101 	} else if (size == 2) {
6102 		init_s64_max = (s16)reg->smax_value;
6103 		init_s64_min = (s16)reg->smin_value;
6104 	} else {
6105 		init_s64_max = (s32)reg->smax_value;
6106 		init_s64_min = (s32)reg->smin_value;
6107 	}
6108 
6109 	s64_max = max(init_s64_max, init_s64_min);
6110 	s64_min = min(init_s64_max, init_s64_min);
6111 
6112 	/* both of s64_max/s64_min positive or negative */
6113 	if ((s64_max >= 0) == (s64_min >= 0)) {
6114 		reg->smin_value = reg->s32_min_value = s64_min;
6115 		reg->smax_value = reg->s32_max_value = s64_max;
6116 		reg->umin_value = reg->u32_min_value = s64_min;
6117 		reg->umax_value = reg->u32_max_value = s64_max;
6118 		reg->var_off = tnum_range(s64_min, s64_max);
6119 		return;
6120 	}
6121 
6122 out:
6123 	set_sext64_default_val(reg, size);
6124 }
6125 
6126 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6127 {
6128 	if (size == 1) {
6129 		reg->s32_min_value = S8_MIN;
6130 		reg->s32_max_value = S8_MAX;
6131 	} else {
6132 		/* size == 2 */
6133 		reg->s32_min_value = S16_MIN;
6134 		reg->s32_max_value = S16_MAX;
6135 	}
6136 	reg->u32_min_value = 0;
6137 	reg->u32_max_value = U32_MAX;
6138 }
6139 
6140 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6141 {
6142 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6143 	u32 top_smax_value, top_smin_value;
6144 	u32 num_bits = size * 8;
6145 
6146 	if (tnum_is_const(reg->var_off)) {
6147 		u32_val = reg->var_off.value;
6148 		if (size == 1)
6149 			reg->var_off = tnum_const((s8)u32_val);
6150 		else
6151 			reg->var_off = tnum_const((s16)u32_val);
6152 
6153 		u32_val = reg->var_off.value;
6154 		reg->s32_min_value = reg->s32_max_value = u32_val;
6155 		reg->u32_min_value = reg->u32_max_value = u32_val;
6156 		return;
6157 	}
6158 
6159 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6160 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6161 
6162 	if (top_smax_value != top_smin_value)
6163 		goto out;
6164 
6165 	/* find the s32_min and s32_min after sign extension */
6166 	if (size == 1) {
6167 		init_s32_max = (s8)reg->s32_max_value;
6168 		init_s32_min = (s8)reg->s32_min_value;
6169 	} else {
6170 		/* size == 2 */
6171 		init_s32_max = (s16)reg->s32_max_value;
6172 		init_s32_min = (s16)reg->s32_min_value;
6173 	}
6174 	s32_max = max(init_s32_max, init_s32_min);
6175 	s32_min = min(init_s32_max, init_s32_min);
6176 
6177 	if ((s32_min >= 0) == (s32_max >= 0)) {
6178 		reg->s32_min_value = s32_min;
6179 		reg->s32_max_value = s32_max;
6180 		reg->u32_min_value = (u32)s32_min;
6181 		reg->u32_max_value = (u32)s32_max;
6182 		return;
6183 	}
6184 
6185 out:
6186 	set_sext32_default_val(reg, size);
6187 }
6188 
6189 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6190 {
6191 	/* A map is considered read-only if the following condition are true:
6192 	 *
6193 	 * 1) BPF program side cannot change any of the map content. The
6194 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6195 	 *    and was set at map creation time.
6196 	 * 2) The map value(s) have been initialized from user space by a
6197 	 *    loader and then "frozen", such that no new map update/delete
6198 	 *    operations from syscall side are possible for the rest of
6199 	 *    the map's lifetime from that point onwards.
6200 	 * 3) Any parallel/pending map update/delete operations from syscall
6201 	 *    side have been completed. Only after that point, it's safe to
6202 	 *    assume that map value(s) are immutable.
6203 	 */
6204 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6205 	       READ_ONCE(map->frozen) &&
6206 	       !bpf_map_write_active(map);
6207 }
6208 
6209 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6210 			       bool is_ldsx)
6211 {
6212 	void *ptr;
6213 	u64 addr;
6214 	int err;
6215 
6216 	err = map->ops->map_direct_value_addr(map, &addr, off);
6217 	if (err)
6218 		return err;
6219 	ptr = (void *)(long)addr + off;
6220 
6221 	switch (size) {
6222 	case sizeof(u8):
6223 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6224 		break;
6225 	case sizeof(u16):
6226 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6227 		break;
6228 	case sizeof(u32):
6229 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6230 		break;
6231 	case sizeof(u64):
6232 		*val = *(u64 *)ptr;
6233 		break;
6234 	default:
6235 		return -EINVAL;
6236 	}
6237 	return 0;
6238 }
6239 
6240 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6241 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6242 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6243 
6244 /*
6245  * Allow list few fields as RCU trusted or full trusted.
6246  * This logic doesn't allow mix tagging and will be removed once GCC supports
6247  * btf_type_tag.
6248  */
6249 
6250 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6251 BTF_TYPE_SAFE_RCU(struct task_struct) {
6252 	const cpumask_t *cpus_ptr;
6253 	struct css_set __rcu *cgroups;
6254 	struct task_struct __rcu *real_parent;
6255 	struct task_struct *group_leader;
6256 };
6257 
6258 BTF_TYPE_SAFE_RCU(struct cgroup) {
6259 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6260 	struct kernfs_node *kn;
6261 };
6262 
6263 BTF_TYPE_SAFE_RCU(struct css_set) {
6264 	struct cgroup *dfl_cgrp;
6265 };
6266 
6267 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6268 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6269 	struct file __rcu *exe_file;
6270 };
6271 
6272 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6273  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6274  */
6275 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6276 	struct sock *sk;
6277 };
6278 
6279 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6280 	struct sock *sk;
6281 };
6282 
6283 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6284 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6285 	struct seq_file *seq;
6286 };
6287 
6288 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6289 	struct bpf_iter_meta *meta;
6290 	struct task_struct *task;
6291 };
6292 
6293 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6294 	struct file *file;
6295 };
6296 
6297 BTF_TYPE_SAFE_TRUSTED(struct file) {
6298 	struct inode *f_inode;
6299 };
6300 
6301 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6302 	/* no negative dentry-s in places where bpf can see it */
6303 	struct inode *d_inode;
6304 };
6305 
6306 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6307 	struct sock *sk;
6308 };
6309 
6310 static bool type_is_rcu(struct bpf_verifier_env *env,
6311 			struct bpf_reg_state *reg,
6312 			const char *field_name, u32 btf_id)
6313 {
6314 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6315 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6316 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6317 
6318 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6319 }
6320 
6321 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6322 				struct bpf_reg_state *reg,
6323 				const char *field_name, u32 btf_id)
6324 {
6325 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6326 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6327 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6328 
6329 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6330 }
6331 
6332 static bool type_is_trusted(struct bpf_verifier_env *env,
6333 			    struct bpf_reg_state *reg,
6334 			    const char *field_name, u32 btf_id)
6335 {
6336 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6337 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6338 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6339 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6340 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6341 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6342 
6343 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6344 }
6345 
6346 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6347 				   struct bpf_reg_state *regs,
6348 				   int regno, int off, int size,
6349 				   enum bpf_access_type atype,
6350 				   int value_regno)
6351 {
6352 	struct bpf_reg_state *reg = regs + regno;
6353 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6354 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6355 	const char *field_name = NULL;
6356 	enum bpf_type_flag flag = 0;
6357 	u32 btf_id = 0;
6358 	int ret;
6359 
6360 	if (!env->allow_ptr_leaks) {
6361 		verbose(env,
6362 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6363 			tname);
6364 		return -EPERM;
6365 	}
6366 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6367 		verbose(env,
6368 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6369 			tname);
6370 		return -EINVAL;
6371 	}
6372 	if (off < 0) {
6373 		verbose(env,
6374 			"R%d is ptr_%s invalid negative access: off=%d\n",
6375 			regno, tname, off);
6376 		return -EACCES;
6377 	}
6378 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6379 		char tn_buf[48];
6380 
6381 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6382 		verbose(env,
6383 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6384 			regno, tname, off, tn_buf);
6385 		return -EACCES;
6386 	}
6387 
6388 	if (reg->type & MEM_USER) {
6389 		verbose(env,
6390 			"R%d is ptr_%s access user memory: off=%d\n",
6391 			regno, tname, off);
6392 		return -EACCES;
6393 	}
6394 
6395 	if (reg->type & MEM_PERCPU) {
6396 		verbose(env,
6397 			"R%d is ptr_%s access percpu memory: off=%d\n",
6398 			regno, tname, off);
6399 		return -EACCES;
6400 	}
6401 
6402 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6403 		if (!btf_is_kernel(reg->btf)) {
6404 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6405 			return -EFAULT;
6406 		}
6407 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6408 	} else {
6409 		/* Writes are permitted with default btf_struct_access for
6410 		 * program allocated objects (which always have ref_obj_id > 0),
6411 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6412 		 */
6413 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6414 			verbose(env, "only read is supported\n");
6415 			return -EACCES;
6416 		}
6417 
6418 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6419 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
6420 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6421 			return -EFAULT;
6422 		}
6423 
6424 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6425 	}
6426 
6427 	if (ret < 0)
6428 		return ret;
6429 
6430 	if (ret != PTR_TO_BTF_ID) {
6431 		/* just mark; */
6432 
6433 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6434 		/* If this is an untrusted pointer, all pointers formed by walking it
6435 		 * also inherit the untrusted flag.
6436 		 */
6437 		flag = PTR_UNTRUSTED;
6438 
6439 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6440 		/* By default any pointer obtained from walking a trusted pointer is no
6441 		 * longer trusted, unless the field being accessed has explicitly been
6442 		 * marked as inheriting its parent's state of trust (either full or RCU).
6443 		 * For example:
6444 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6445 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6446 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6447 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6448 		 *
6449 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6450 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6451 		 */
6452 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6453 			flag |= PTR_TRUSTED;
6454 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6455 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6456 				/* ignore __rcu tag and mark it MEM_RCU */
6457 				flag |= MEM_RCU;
6458 			} else if (flag & MEM_RCU ||
6459 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6460 				/* __rcu tagged pointers can be NULL */
6461 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6462 
6463 				/* We always trust them */
6464 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6465 				    flag & PTR_UNTRUSTED)
6466 					flag &= ~PTR_UNTRUSTED;
6467 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6468 				/* keep as-is */
6469 			} else {
6470 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6471 				clear_trusted_flags(&flag);
6472 			}
6473 		} else {
6474 			/*
6475 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6476 			 * aggressively mark as untrusted otherwise such
6477 			 * pointers will be plain PTR_TO_BTF_ID without flags
6478 			 * and will be allowed to be passed into helpers for
6479 			 * compat reasons.
6480 			 */
6481 			flag = PTR_UNTRUSTED;
6482 		}
6483 	} else {
6484 		/* Old compat. Deprecated */
6485 		clear_trusted_flags(&flag);
6486 	}
6487 
6488 	if (atype == BPF_READ && value_regno >= 0)
6489 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6490 
6491 	return 0;
6492 }
6493 
6494 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6495 				   struct bpf_reg_state *regs,
6496 				   int regno, int off, int size,
6497 				   enum bpf_access_type atype,
6498 				   int value_regno)
6499 {
6500 	struct bpf_reg_state *reg = regs + regno;
6501 	struct bpf_map *map = reg->map_ptr;
6502 	struct bpf_reg_state map_reg;
6503 	enum bpf_type_flag flag = 0;
6504 	const struct btf_type *t;
6505 	const char *tname;
6506 	u32 btf_id;
6507 	int ret;
6508 
6509 	if (!btf_vmlinux) {
6510 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6511 		return -ENOTSUPP;
6512 	}
6513 
6514 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6515 		verbose(env, "map_ptr access not supported for map type %d\n",
6516 			map->map_type);
6517 		return -ENOTSUPP;
6518 	}
6519 
6520 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6521 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6522 
6523 	if (!env->allow_ptr_leaks) {
6524 		verbose(env,
6525 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6526 			tname);
6527 		return -EPERM;
6528 	}
6529 
6530 	if (off < 0) {
6531 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6532 			regno, tname, off);
6533 		return -EACCES;
6534 	}
6535 
6536 	if (atype != BPF_READ) {
6537 		verbose(env, "only read from %s is supported\n", tname);
6538 		return -EACCES;
6539 	}
6540 
6541 	/* Simulate access to a PTR_TO_BTF_ID */
6542 	memset(&map_reg, 0, sizeof(map_reg));
6543 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6544 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6545 	if (ret < 0)
6546 		return ret;
6547 
6548 	if (value_regno >= 0)
6549 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6550 
6551 	return 0;
6552 }
6553 
6554 /* Check that the stack access at the given offset is within bounds. The
6555  * maximum valid offset is -1.
6556  *
6557  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6558  * -state->allocated_stack for reads.
6559  */
6560 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6561                                           s64 off,
6562                                           struct bpf_func_state *state,
6563                                           enum bpf_access_type t)
6564 {
6565 	int min_valid_off;
6566 
6567 	if (t == BPF_WRITE || env->allow_uninit_stack)
6568 		min_valid_off = -MAX_BPF_STACK;
6569 	else
6570 		min_valid_off = -state->allocated_stack;
6571 
6572 	if (off < min_valid_off || off > -1)
6573 		return -EACCES;
6574 	return 0;
6575 }
6576 
6577 /* Check that the stack access at 'regno + off' falls within the maximum stack
6578  * bounds.
6579  *
6580  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6581  */
6582 static int check_stack_access_within_bounds(
6583 		struct bpf_verifier_env *env,
6584 		int regno, int off, int access_size,
6585 		enum bpf_access_src src, enum bpf_access_type type)
6586 {
6587 	struct bpf_reg_state *regs = cur_regs(env);
6588 	struct bpf_reg_state *reg = regs + regno;
6589 	struct bpf_func_state *state = func(env, reg);
6590 	s64 min_off, max_off;
6591 	int err;
6592 	char *err_extra;
6593 
6594 	if (src == ACCESS_HELPER)
6595 		/* We don't know if helpers are reading or writing (or both). */
6596 		err_extra = " indirect access to";
6597 	else if (type == BPF_READ)
6598 		err_extra = " read from";
6599 	else
6600 		err_extra = " write to";
6601 
6602 	if (tnum_is_const(reg->var_off)) {
6603 		min_off = (s64)reg->var_off.value + off;
6604 		max_off = min_off + access_size;
6605 	} else {
6606 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6607 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6608 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6609 				err_extra, regno);
6610 			return -EACCES;
6611 		}
6612 		min_off = reg->smin_value + off;
6613 		max_off = reg->smax_value + off + access_size;
6614 	}
6615 
6616 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6617 	if (!err && max_off > 0)
6618 		err = -EINVAL; /* out of stack access into non-negative offsets */
6619 
6620 	if (err) {
6621 		if (tnum_is_const(reg->var_off)) {
6622 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6623 				err_extra, regno, off, access_size);
6624 		} else {
6625 			char tn_buf[48];
6626 
6627 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6628 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
6629 				err_extra, regno, tn_buf, off, access_size);
6630 		}
6631 		return err;
6632 	}
6633 
6634 	/* Note that there is no stack access with offset zero, so the needed stack
6635 	 * size is -min_off, not -min_off+1.
6636 	 */
6637 	return grow_stack_state(env, state, -min_off /* size */);
6638 }
6639 
6640 /* check whether memory at (regno + off) is accessible for t = (read | write)
6641  * if t==write, value_regno is a register which value is stored into memory
6642  * if t==read, value_regno is a register which will receive the value from memory
6643  * if t==write && value_regno==-1, some unknown value is stored into memory
6644  * if t==read && value_regno==-1, don't care what we read from memory
6645  */
6646 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6647 			    int off, int bpf_size, enum bpf_access_type t,
6648 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6649 {
6650 	struct bpf_reg_state *regs = cur_regs(env);
6651 	struct bpf_reg_state *reg = regs + regno;
6652 	int size, err = 0;
6653 
6654 	size = bpf_size_to_bytes(bpf_size);
6655 	if (size < 0)
6656 		return size;
6657 
6658 	/* alignment checks will add in reg->off themselves */
6659 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6660 	if (err)
6661 		return err;
6662 
6663 	/* for access checks, reg->off is just part of off */
6664 	off += reg->off;
6665 
6666 	if (reg->type == PTR_TO_MAP_KEY) {
6667 		if (t == BPF_WRITE) {
6668 			verbose(env, "write to change key R%d not allowed\n", regno);
6669 			return -EACCES;
6670 		}
6671 
6672 		err = check_mem_region_access(env, regno, off, size,
6673 					      reg->map_ptr->key_size, false);
6674 		if (err)
6675 			return err;
6676 		if (value_regno >= 0)
6677 			mark_reg_unknown(env, regs, value_regno);
6678 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6679 		struct btf_field *kptr_field = NULL;
6680 
6681 		if (t == BPF_WRITE && value_regno >= 0 &&
6682 		    is_pointer_value(env, value_regno)) {
6683 			verbose(env, "R%d leaks addr into map\n", value_regno);
6684 			return -EACCES;
6685 		}
6686 		err = check_map_access_type(env, regno, off, size, t);
6687 		if (err)
6688 			return err;
6689 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6690 		if (err)
6691 			return err;
6692 		if (tnum_is_const(reg->var_off))
6693 			kptr_field = btf_record_find(reg->map_ptr->record,
6694 						     off + reg->var_off.value, BPF_KPTR);
6695 		if (kptr_field) {
6696 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6697 		} else if (t == BPF_READ && value_regno >= 0) {
6698 			struct bpf_map *map = reg->map_ptr;
6699 
6700 			/* if map is read-only, track its contents as scalars */
6701 			if (tnum_is_const(reg->var_off) &&
6702 			    bpf_map_is_rdonly(map) &&
6703 			    map->ops->map_direct_value_addr) {
6704 				int map_off = off + reg->var_off.value;
6705 				u64 val = 0;
6706 
6707 				err = bpf_map_direct_read(map, map_off, size,
6708 							  &val, is_ldsx);
6709 				if (err)
6710 					return err;
6711 
6712 				regs[value_regno].type = SCALAR_VALUE;
6713 				__mark_reg_known(&regs[value_regno], val);
6714 			} else {
6715 				mark_reg_unknown(env, regs, value_regno);
6716 			}
6717 		}
6718 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6719 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6720 
6721 		if (type_may_be_null(reg->type)) {
6722 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6723 				reg_type_str(env, reg->type));
6724 			return -EACCES;
6725 		}
6726 
6727 		if (t == BPF_WRITE && rdonly_mem) {
6728 			verbose(env, "R%d cannot write into %s\n",
6729 				regno, reg_type_str(env, reg->type));
6730 			return -EACCES;
6731 		}
6732 
6733 		if (t == BPF_WRITE && value_regno >= 0 &&
6734 		    is_pointer_value(env, value_regno)) {
6735 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6736 			return -EACCES;
6737 		}
6738 
6739 		err = check_mem_region_access(env, regno, off, size,
6740 					      reg->mem_size, false);
6741 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6742 			mark_reg_unknown(env, regs, value_regno);
6743 	} else if (reg->type == PTR_TO_CTX) {
6744 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6745 		struct btf *btf = NULL;
6746 		u32 btf_id = 0;
6747 
6748 		if (t == BPF_WRITE && value_regno >= 0 &&
6749 		    is_pointer_value(env, value_regno)) {
6750 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6751 			return -EACCES;
6752 		}
6753 
6754 		err = check_ptr_off_reg(env, reg, regno);
6755 		if (err < 0)
6756 			return err;
6757 
6758 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6759 				       &btf_id);
6760 		if (err)
6761 			verbose_linfo(env, insn_idx, "; ");
6762 		if (!err && t == BPF_READ && value_regno >= 0) {
6763 			/* ctx access returns either a scalar, or a
6764 			 * PTR_TO_PACKET[_META,_END]. In the latter
6765 			 * case, we know the offset is zero.
6766 			 */
6767 			if (reg_type == SCALAR_VALUE) {
6768 				mark_reg_unknown(env, regs, value_regno);
6769 			} else {
6770 				mark_reg_known_zero(env, regs,
6771 						    value_regno);
6772 				if (type_may_be_null(reg_type))
6773 					regs[value_regno].id = ++env->id_gen;
6774 				/* A load of ctx field could have different
6775 				 * actual load size with the one encoded in the
6776 				 * insn. When the dst is PTR, it is for sure not
6777 				 * a sub-register.
6778 				 */
6779 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6780 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6781 					regs[value_regno].btf = btf;
6782 					regs[value_regno].btf_id = btf_id;
6783 				}
6784 			}
6785 			regs[value_regno].type = reg_type;
6786 		}
6787 
6788 	} else if (reg->type == PTR_TO_STACK) {
6789 		/* Basic bounds checks. */
6790 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6791 		if (err)
6792 			return err;
6793 
6794 		if (t == BPF_READ)
6795 			err = check_stack_read(env, regno, off, size,
6796 					       value_regno);
6797 		else
6798 			err = check_stack_write(env, regno, off, size,
6799 						value_regno, insn_idx);
6800 	} else if (reg_is_pkt_pointer(reg)) {
6801 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6802 			verbose(env, "cannot write into packet\n");
6803 			return -EACCES;
6804 		}
6805 		if (t == BPF_WRITE && value_regno >= 0 &&
6806 		    is_pointer_value(env, value_regno)) {
6807 			verbose(env, "R%d leaks addr into packet\n",
6808 				value_regno);
6809 			return -EACCES;
6810 		}
6811 		err = check_packet_access(env, regno, off, size, false);
6812 		if (!err && t == BPF_READ && value_regno >= 0)
6813 			mark_reg_unknown(env, regs, value_regno);
6814 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6815 		if (t == BPF_WRITE && value_regno >= 0 &&
6816 		    is_pointer_value(env, value_regno)) {
6817 			verbose(env, "R%d leaks addr into flow keys\n",
6818 				value_regno);
6819 			return -EACCES;
6820 		}
6821 
6822 		err = check_flow_keys_access(env, off, size);
6823 		if (!err && t == BPF_READ && value_regno >= 0)
6824 			mark_reg_unknown(env, regs, value_regno);
6825 	} else if (type_is_sk_pointer(reg->type)) {
6826 		if (t == BPF_WRITE) {
6827 			verbose(env, "R%d cannot write into %s\n",
6828 				regno, reg_type_str(env, reg->type));
6829 			return -EACCES;
6830 		}
6831 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6832 		if (!err && value_regno >= 0)
6833 			mark_reg_unknown(env, regs, value_regno);
6834 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6835 		err = check_tp_buffer_access(env, reg, regno, off, size);
6836 		if (!err && t == BPF_READ && value_regno >= 0)
6837 			mark_reg_unknown(env, regs, value_regno);
6838 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6839 		   !type_may_be_null(reg->type)) {
6840 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6841 					      value_regno);
6842 	} else if (reg->type == CONST_PTR_TO_MAP) {
6843 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6844 					      value_regno);
6845 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6846 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6847 		u32 *max_access;
6848 
6849 		if (rdonly_mem) {
6850 			if (t == BPF_WRITE) {
6851 				verbose(env, "R%d cannot write into %s\n",
6852 					regno, reg_type_str(env, reg->type));
6853 				return -EACCES;
6854 			}
6855 			max_access = &env->prog->aux->max_rdonly_access;
6856 		} else {
6857 			max_access = &env->prog->aux->max_rdwr_access;
6858 		}
6859 
6860 		err = check_buffer_access(env, reg, regno, off, size, false,
6861 					  max_access);
6862 
6863 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6864 			mark_reg_unknown(env, regs, value_regno);
6865 	} else {
6866 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6867 			reg_type_str(env, reg->type));
6868 		return -EACCES;
6869 	}
6870 
6871 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6872 	    regs[value_regno].type == SCALAR_VALUE) {
6873 		if (!is_ldsx)
6874 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6875 			coerce_reg_to_size(&regs[value_regno], size);
6876 		else
6877 			coerce_reg_to_size_sx(&regs[value_regno], size);
6878 	}
6879 	return err;
6880 }
6881 
6882 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6883 {
6884 	int load_reg;
6885 	int err;
6886 
6887 	switch (insn->imm) {
6888 	case BPF_ADD:
6889 	case BPF_ADD | BPF_FETCH:
6890 	case BPF_AND:
6891 	case BPF_AND | BPF_FETCH:
6892 	case BPF_OR:
6893 	case BPF_OR | BPF_FETCH:
6894 	case BPF_XOR:
6895 	case BPF_XOR | BPF_FETCH:
6896 	case BPF_XCHG:
6897 	case BPF_CMPXCHG:
6898 		break;
6899 	default:
6900 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6901 		return -EINVAL;
6902 	}
6903 
6904 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6905 		verbose(env, "invalid atomic operand size\n");
6906 		return -EINVAL;
6907 	}
6908 
6909 	/* check src1 operand */
6910 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6911 	if (err)
6912 		return err;
6913 
6914 	/* check src2 operand */
6915 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6916 	if (err)
6917 		return err;
6918 
6919 	if (insn->imm == BPF_CMPXCHG) {
6920 		/* Check comparison of R0 with memory location */
6921 		const u32 aux_reg = BPF_REG_0;
6922 
6923 		err = check_reg_arg(env, aux_reg, SRC_OP);
6924 		if (err)
6925 			return err;
6926 
6927 		if (is_pointer_value(env, aux_reg)) {
6928 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6929 			return -EACCES;
6930 		}
6931 	}
6932 
6933 	if (is_pointer_value(env, insn->src_reg)) {
6934 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6935 		return -EACCES;
6936 	}
6937 
6938 	if (is_ctx_reg(env, insn->dst_reg) ||
6939 	    is_pkt_reg(env, insn->dst_reg) ||
6940 	    is_flow_key_reg(env, insn->dst_reg) ||
6941 	    is_sk_reg(env, insn->dst_reg)) {
6942 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6943 			insn->dst_reg,
6944 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6945 		return -EACCES;
6946 	}
6947 
6948 	if (insn->imm & BPF_FETCH) {
6949 		if (insn->imm == BPF_CMPXCHG)
6950 			load_reg = BPF_REG_0;
6951 		else
6952 			load_reg = insn->src_reg;
6953 
6954 		/* check and record load of old value */
6955 		err = check_reg_arg(env, load_reg, DST_OP);
6956 		if (err)
6957 			return err;
6958 	} else {
6959 		/* This instruction accesses a memory location but doesn't
6960 		 * actually load it into a register.
6961 		 */
6962 		load_reg = -1;
6963 	}
6964 
6965 	/* Check whether we can read the memory, with second call for fetch
6966 	 * case to simulate the register fill.
6967 	 */
6968 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6969 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6970 	if (!err && load_reg >= 0)
6971 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6972 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
6973 				       true, false);
6974 	if (err)
6975 		return err;
6976 
6977 	/* Check whether we can write into the same memory. */
6978 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6979 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6980 	if (err)
6981 		return err;
6982 	return 0;
6983 }
6984 
6985 /* When register 'regno' is used to read the stack (either directly or through
6986  * a helper function) make sure that it's within stack boundary and, depending
6987  * on the access type and privileges, that all elements of the stack are
6988  * initialized.
6989  *
6990  * 'off' includes 'regno->off', but not its dynamic part (if any).
6991  *
6992  * All registers that have been spilled on the stack in the slots within the
6993  * read offsets are marked as read.
6994  */
6995 static int check_stack_range_initialized(
6996 		struct bpf_verifier_env *env, int regno, int off,
6997 		int access_size, bool zero_size_allowed,
6998 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6999 {
7000 	struct bpf_reg_state *reg = reg_state(env, regno);
7001 	struct bpf_func_state *state = func(env, reg);
7002 	int err, min_off, max_off, i, j, slot, spi;
7003 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7004 	enum bpf_access_type bounds_check_type;
7005 	/* Some accesses can write anything into the stack, others are
7006 	 * read-only.
7007 	 */
7008 	bool clobber = false;
7009 
7010 	if (access_size == 0 && !zero_size_allowed) {
7011 		verbose(env, "invalid zero-sized read\n");
7012 		return -EACCES;
7013 	}
7014 
7015 	if (type == ACCESS_HELPER) {
7016 		/* The bounds checks for writes are more permissive than for
7017 		 * reads. However, if raw_mode is not set, we'll do extra
7018 		 * checks below.
7019 		 */
7020 		bounds_check_type = BPF_WRITE;
7021 		clobber = true;
7022 	} else {
7023 		bounds_check_type = BPF_READ;
7024 	}
7025 	err = check_stack_access_within_bounds(env, regno, off, access_size,
7026 					       type, bounds_check_type);
7027 	if (err)
7028 		return err;
7029 
7030 
7031 	if (tnum_is_const(reg->var_off)) {
7032 		min_off = max_off = reg->var_off.value + off;
7033 	} else {
7034 		/* Variable offset is prohibited for unprivileged mode for
7035 		 * simplicity since it requires corresponding support in
7036 		 * Spectre masking for stack ALU.
7037 		 * See also retrieve_ptr_limit().
7038 		 */
7039 		if (!env->bypass_spec_v1) {
7040 			char tn_buf[48];
7041 
7042 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7043 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7044 				regno, err_extra, tn_buf);
7045 			return -EACCES;
7046 		}
7047 		/* Only initialized buffer on stack is allowed to be accessed
7048 		 * with variable offset. With uninitialized buffer it's hard to
7049 		 * guarantee that whole memory is marked as initialized on
7050 		 * helper return since specific bounds are unknown what may
7051 		 * cause uninitialized stack leaking.
7052 		 */
7053 		if (meta && meta->raw_mode)
7054 			meta = NULL;
7055 
7056 		min_off = reg->smin_value + off;
7057 		max_off = reg->smax_value + off;
7058 	}
7059 
7060 	if (meta && meta->raw_mode) {
7061 		/* Ensure we won't be overwriting dynptrs when simulating byte
7062 		 * by byte access in check_helper_call using meta.access_size.
7063 		 * This would be a problem if we have a helper in the future
7064 		 * which takes:
7065 		 *
7066 		 *	helper(uninit_mem, len, dynptr)
7067 		 *
7068 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7069 		 * may end up writing to dynptr itself when touching memory from
7070 		 * arg 1. This can be relaxed on a case by case basis for known
7071 		 * safe cases, but reject due to the possibilitiy of aliasing by
7072 		 * default.
7073 		 */
7074 		for (i = min_off; i < max_off + access_size; i++) {
7075 			int stack_off = -i - 1;
7076 
7077 			spi = __get_spi(i);
7078 			/* raw_mode may write past allocated_stack */
7079 			if (state->allocated_stack <= stack_off)
7080 				continue;
7081 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7082 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7083 				return -EACCES;
7084 			}
7085 		}
7086 		meta->access_size = access_size;
7087 		meta->regno = regno;
7088 		return 0;
7089 	}
7090 
7091 	for (i = min_off; i < max_off + access_size; i++) {
7092 		u8 *stype;
7093 
7094 		slot = -i - 1;
7095 		spi = slot / BPF_REG_SIZE;
7096 		if (state->allocated_stack <= slot) {
7097 			verbose(env, "verifier bug: allocated_stack too small");
7098 			return -EFAULT;
7099 		}
7100 
7101 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7102 		if (*stype == STACK_MISC)
7103 			goto mark;
7104 		if ((*stype == STACK_ZERO) ||
7105 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7106 			if (clobber) {
7107 				/* helper can write anything into the stack */
7108 				*stype = STACK_MISC;
7109 			}
7110 			goto mark;
7111 		}
7112 
7113 		if (is_spilled_reg(&state->stack[spi]) &&
7114 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7115 		     env->allow_ptr_leaks)) {
7116 			if (clobber) {
7117 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7118 				for (j = 0; j < BPF_REG_SIZE; j++)
7119 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7120 			}
7121 			goto mark;
7122 		}
7123 
7124 		if (tnum_is_const(reg->var_off)) {
7125 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7126 				err_extra, regno, min_off, i - min_off, access_size);
7127 		} else {
7128 			char tn_buf[48];
7129 
7130 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7131 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7132 				err_extra, regno, tn_buf, i - min_off, access_size);
7133 		}
7134 		return -EACCES;
7135 mark:
7136 		/* reading any byte out of 8-byte 'spill_slot' will cause
7137 		 * the whole slot to be marked as 'read'
7138 		 */
7139 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7140 			      state->stack[spi].spilled_ptr.parent,
7141 			      REG_LIVE_READ64);
7142 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7143 		 * be sure that whether stack slot is written to or not. Hence,
7144 		 * we must still conservatively propagate reads upwards even if
7145 		 * helper may write to the entire memory range.
7146 		 */
7147 	}
7148 	return 0;
7149 }
7150 
7151 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7152 				   int access_size, bool zero_size_allowed,
7153 				   struct bpf_call_arg_meta *meta)
7154 {
7155 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7156 	u32 *max_access;
7157 
7158 	switch (base_type(reg->type)) {
7159 	case PTR_TO_PACKET:
7160 	case PTR_TO_PACKET_META:
7161 		return check_packet_access(env, regno, reg->off, access_size,
7162 					   zero_size_allowed);
7163 	case PTR_TO_MAP_KEY:
7164 		if (meta && meta->raw_mode) {
7165 			verbose(env, "R%d cannot write into %s\n", regno,
7166 				reg_type_str(env, reg->type));
7167 			return -EACCES;
7168 		}
7169 		return check_mem_region_access(env, regno, reg->off, access_size,
7170 					       reg->map_ptr->key_size, false);
7171 	case PTR_TO_MAP_VALUE:
7172 		if (check_map_access_type(env, regno, reg->off, access_size,
7173 					  meta && meta->raw_mode ? BPF_WRITE :
7174 					  BPF_READ))
7175 			return -EACCES;
7176 		return check_map_access(env, regno, reg->off, access_size,
7177 					zero_size_allowed, ACCESS_HELPER);
7178 	case PTR_TO_MEM:
7179 		if (type_is_rdonly_mem(reg->type)) {
7180 			if (meta && meta->raw_mode) {
7181 				verbose(env, "R%d cannot write into %s\n", regno,
7182 					reg_type_str(env, reg->type));
7183 				return -EACCES;
7184 			}
7185 		}
7186 		return check_mem_region_access(env, regno, reg->off,
7187 					       access_size, reg->mem_size,
7188 					       zero_size_allowed);
7189 	case PTR_TO_BUF:
7190 		if (type_is_rdonly_mem(reg->type)) {
7191 			if (meta && meta->raw_mode) {
7192 				verbose(env, "R%d cannot write into %s\n", regno,
7193 					reg_type_str(env, reg->type));
7194 				return -EACCES;
7195 			}
7196 
7197 			max_access = &env->prog->aux->max_rdonly_access;
7198 		} else {
7199 			max_access = &env->prog->aux->max_rdwr_access;
7200 		}
7201 		return check_buffer_access(env, reg, regno, reg->off,
7202 					   access_size, zero_size_allowed,
7203 					   max_access);
7204 	case PTR_TO_STACK:
7205 		return check_stack_range_initialized(
7206 				env,
7207 				regno, reg->off, access_size,
7208 				zero_size_allowed, ACCESS_HELPER, meta);
7209 	case PTR_TO_BTF_ID:
7210 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7211 					       access_size, BPF_READ, -1);
7212 	case PTR_TO_CTX:
7213 		/* in case the function doesn't know how to access the context,
7214 		 * (because we are in a program of type SYSCALL for example), we
7215 		 * can not statically check its size.
7216 		 * Dynamically check it now.
7217 		 */
7218 		if (!env->ops->convert_ctx_access) {
7219 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7220 			int offset = access_size - 1;
7221 
7222 			/* Allow zero-byte read from PTR_TO_CTX */
7223 			if (access_size == 0)
7224 				return zero_size_allowed ? 0 : -EACCES;
7225 
7226 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7227 						atype, -1, false, false);
7228 		}
7229 
7230 		fallthrough;
7231 	default: /* scalar_value or invalid ptr */
7232 		/* Allow zero-byte read from NULL, regardless of pointer type */
7233 		if (zero_size_allowed && access_size == 0 &&
7234 		    register_is_null(reg))
7235 			return 0;
7236 
7237 		verbose(env, "R%d type=%s ", regno,
7238 			reg_type_str(env, reg->type));
7239 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7240 		return -EACCES;
7241 	}
7242 }
7243 
7244 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7245  * size.
7246  *
7247  * @regno is the register containing the access size. regno-1 is the register
7248  * containing the pointer.
7249  */
7250 static int check_mem_size_reg(struct bpf_verifier_env *env,
7251 			      struct bpf_reg_state *reg, u32 regno,
7252 			      bool zero_size_allowed,
7253 			      struct bpf_call_arg_meta *meta)
7254 {
7255 	int err;
7256 
7257 	/* This is used to refine r0 return value bounds for helpers
7258 	 * that enforce this value as an upper bound on return values.
7259 	 * See do_refine_retval_range() for helpers that can refine
7260 	 * the return value. C type of helper is u32 so we pull register
7261 	 * bound from umax_value however, if negative verifier errors
7262 	 * out. Only upper bounds can be learned because retval is an
7263 	 * int type and negative retvals are allowed.
7264 	 */
7265 	meta->msize_max_value = reg->umax_value;
7266 
7267 	/* The register is SCALAR_VALUE; the access check
7268 	 * happens using its boundaries.
7269 	 */
7270 	if (!tnum_is_const(reg->var_off))
7271 		/* For unprivileged variable accesses, disable raw
7272 		 * mode so that the program is required to
7273 		 * initialize all the memory that the helper could
7274 		 * just partially fill up.
7275 		 */
7276 		meta = NULL;
7277 
7278 	if (reg->smin_value < 0) {
7279 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7280 			regno);
7281 		return -EACCES;
7282 	}
7283 
7284 	if (reg->umin_value == 0 && !zero_size_allowed) {
7285 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7286 			regno, reg->umin_value, reg->umax_value);
7287 		return -EACCES;
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 (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
12145 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12146 					return -EINVAL;
12147 				}
12148 
12149 				ret_btf = env->prog->aux->btf;
12150 				ret_btf_id = meta.arg_constant.value;
12151 
12152 				/* This may be NULL due to user not supplying a BTF */
12153 				if (!ret_btf) {
12154 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12155 					return -EINVAL;
12156 				}
12157 
12158 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12159 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
12160 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12161 					return -EINVAL;
12162 				}
12163 
12164 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12165 					if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
12166 						verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
12167 							ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
12168 						return -EINVAL;
12169 					}
12170 
12171 					if (!bpf_global_percpu_ma_set) {
12172 						mutex_lock(&bpf_percpu_ma_lock);
12173 						if (!bpf_global_percpu_ma_set) {
12174 							/* Charge memory allocated with bpf_global_percpu_ma to
12175 							 * root memcg. The obj_cgroup for root memcg is NULL.
12176 							 */
12177 							err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
12178 							if (!err)
12179 								bpf_global_percpu_ma_set = true;
12180 						}
12181 						mutex_unlock(&bpf_percpu_ma_lock);
12182 						if (err)
12183 							return err;
12184 					}
12185 
12186 					mutex_lock(&bpf_percpu_ma_lock);
12187 					err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
12188 					mutex_unlock(&bpf_percpu_ma_lock);
12189 					if (err)
12190 						return err;
12191 				}
12192 
12193 				struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12194 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12195 					if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12196 						verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12197 						return -EINVAL;
12198 					}
12199 
12200 					if (struct_meta) {
12201 						verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12202 						return -EINVAL;
12203 					}
12204 				}
12205 
12206 				mark_reg_known_zero(env, regs, BPF_REG_0);
12207 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12208 				regs[BPF_REG_0].btf = ret_btf;
12209 				regs[BPF_REG_0].btf_id = ret_btf_id;
12210 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12211 					regs[BPF_REG_0].type |= MEM_PERCPU;
12212 
12213 				insn_aux->obj_new_size = ret_t->size;
12214 				insn_aux->kptr_struct_meta = struct_meta;
12215 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12216 				mark_reg_known_zero(env, regs, BPF_REG_0);
12217 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12218 				regs[BPF_REG_0].btf = meta.arg_btf;
12219 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
12220 
12221 				insn_aux->kptr_struct_meta =
12222 					btf_find_struct_meta(meta.arg_btf,
12223 							     meta.arg_btf_id);
12224 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12225 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12226 				struct btf_field *field = meta.arg_list_head.field;
12227 
12228 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12229 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12230 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12231 				struct btf_field *field = meta.arg_rbtree_root.field;
12232 
12233 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12234 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12235 				mark_reg_known_zero(env, regs, BPF_REG_0);
12236 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12237 				regs[BPF_REG_0].btf = desc_btf;
12238 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12239 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12240 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12241 				if (!ret_t || !btf_type_is_struct(ret_t)) {
12242 					verbose(env,
12243 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
12244 					return -EINVAL;
12245 				}
12246 
12247 				mark_reg_known_zero(env, regs, BPF_REG_0);
12248 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12249 				regs[BPF_REG_0].btf = desc_btf;
12250 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
12251 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12252 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12253 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
12254 
12255 				mark_reg_known_zero(env, regs, BPF_REG_0);
12256 
12257 				if (!meta.arg_constant.found) {
12258 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
12259 					return -EFAULT;
12260 				}
12261 
12262 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
12263 
12264 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12265 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12266 
12267 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12268 					regs[BPF_REG_0].type |= MEM_RDONLY;
12269 				} else {
12270 					/* this will set env->seen_direct_write to true */
12271 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12272 						verbose(env, "the prog does not allow writes to packet data\n");
12273 						return -EINVAL;
12274 					}
12275 				}
12276 
12277 				if (!meta.initialized_dynptr.id) {
12278 					verbose(env, "verifier internal error: no dynptr id\n");
12279 					return -EFAULT;
12280 				}
12281 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
12282 
12283 				/* we don't need to set BPF_REG_0's ref obj id
12284 				 * because packet slices are not refcounted (see
12285 				 * dynptr_type_refcounted)
12286 				 */
12287 			} else {
12288 				verbose(env, "kernel function %s unhandled dynamic return type\n",
12289 					meta.func_name);
12290 				return -EFAULT;
12291 			}
12292 		} else if (!__btf_type_is_struct(ptr_type)) {
12293 			if (!meta.r0_size) {
12294 				__u32 sz;
12295 
12296 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
12297 					meta.r0_size = sz;
12298 					meta.r0_rdonly = true;
12299 				}
12300 			}
12301 			if (!meta.r0_size) {
12302 				ptr_type_name = btf_name_by_offset(desc_btf,
12303 								   ptr_type->name_off);
12304 				verbose(env,
12305 					"kernel function %s returns pointer type %s %s is not supported\n",
12306 					func_name,
12307 					btf_type_str(ptr_type),
12308 					ptr_type_name);
12309 				return -EINVAL;
12310 			}
12311 
12312 			mark_reg_known_zero(env, regs, BPF_REG_0);
12313 			regs[BPF_REG_0].type = PTR_TO_MEM;
12314 			regs[BPF_REG_0].mem_size = meta.r0_size;
12315 
12316 			if (meta.r0_rdonly)
12317 				regs[BPF_REG_0].type |= MEM_RDONLY;
12318 
12319 			/* Ensures we don't access the memory after a release_reference() */
12320 			if (meta.ref_obj_id)
12321 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12322 		} else {
12323 			mark_reg_known_zero(env, regs, BPF_REG_0);
12324 			regs[BPF_REG_0].btf = desc_btf;
12325 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12326 			regs[BPF_REG_0].btf_id = ptr_type_id;
12327 		}
12328 
12329 		if (is_kfunc_ret_null(&meta)) {
12330 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12331 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12332 			regs[BPF_REG_0].id = ++env->id_gen;
12333 		}
12334 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12335 		if (is_kfunc_acquire(&meta)) {
12336 			int id = acquire_reference_state(env, insn_idx);
12337 
12338 			if (id < 0)
12339 				return id;
12340 			if (is_kfunc_ret_null(&meta))
12341 				regs[BPF_REG_0].id = id;
12342 			regs[BPF_REG_0].ref_obj_id = id;
12343 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12344 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12345 		}
12346 
12347 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12348 			regs[BPF_REG_0].id = ++env->id_gen;
12349 	} else if (btf_type_is_void(t)) {
12350 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12351 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
12352 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12353 				insn_aux->kptr_struct_meta =
12354 					btf_find_struct_meta(meta.arg_btf,
12355 							     meta.arg_btf_id);
12356 			}
12357 		}
12358 	}
12359 
12360 	nargs = btf_type_vlen(meta.func_proto);
12361 	args = (const struct btf_param *)(meta.func_proto + 1);
12362 	for (i = 0; i < nargs; i++) {
12363 		u32 regno = i + 1;
12364 
12365 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12366 		if (btf_type_is_ptr(t))
12367 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12368 		else
12369 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12370 			mark_btf_func_reg_size(env, regno, t->size);
12371 	}
12372 
12373 	if (is_iter_next_kfunc(&meta)) {
12374 		err = process_iter_next_call(env, insn_idx, &meta);
12375 		if (err)
12376 			return err;
12377 	}
12378 
12379 	return 0;
12380 }
12381 
12382 static bool signed_add_overflows(s64 a, s64 b)
12383 {
12384 	/* Do the add in u64, where overflow is well-defined */
12385 	s64 res = (s64)((u64)a + (u64)b);
12386 
12387 	if (b < 0)
12388 		return res > a;
12389 	return res < a;
12390 }
12391 
12392 static bool signed_add32_overflows(s32 a, s32 b)
12393 {
12394 	/* Do the add in u32, where overflow is well-defined */
12395 	s32 res = (s32)((u32)a + (u32)b);
12396 
12397 	if (b < 0)
12398 		return res > a;
12399 	return res < a;
12400 }
12401 
12402 static bool signed_sub_overflows(s64 a, s64 b)
12403 {
12404 	/* Do the sub in u64, where overflow is well-defined */
12405 	s64 res = (s64)((u64)a - (u64)b);
12406 
12407 	if (b < 0)
12408 		return res < a;
12409 	return res > a;
12410 }
12411 
12412 static bool signed_sub32_overflows(s32 a, s32 b)
12413 {
12414 	/* Do the sub in u32, where overflow is well-defined */
12415 	s32 res = (s32)((u32)a - (u32)b);
12416 
12417 	if (b < 0)
12418 		return res < a;
12419 	return res > a;
12420 }
12421 
12422 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12423 				  const struct bpf_reg_state *reg,
12424 				  enum bpf_reg_type type)
12425 {
12426 	bool known = tnum_is_const(reg->var_off);
12427 	s64 val = reg->var_off.value;
12428 	s64 smin = reg->smin_value;
12429 
12430 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12431 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12432 			reg_type_str(env, type), val);
12433 		return false;
12434 	}
12435 
12436 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12437 		verbose(env, "%s pointer offset %d is not allowed\n",
12438 			reg_type_str(env, type), reg->off);
12439 		return false;
12440 	}
12441 
12442 	if (smin == S64_MIN) {
12443 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12444 			reg_type_str(env, type));
12445 		return false;
12446 	}
12447 
12448 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12449 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12450 			smin, reg_type_str(env, type));
12451 		return false;
12452 	}
12453 
12454 	return true;
12455 }
12456 
12457 enum {
12458 	REASON_BOUNDS	= -1,
12459 	REASON_TYPE	= -2,
12460 	REASON_PATHS	= -3,
12461 	REASON_LIMIT	= -4,
12462 	REASON_STACK	= -5,
12463 };
12464 
12465 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12466 			      u32 *alu_limit, bool mask_to_left)
12467 {
12468 	u32 max = 0, ptr_limit = 0;
12469 
12470 	switch (ptr_reg->type) {
12471 	case PTR_TO_STACK:
12472 		/* Offset 0 is out-of-bounds, but acceptable start for the
12473 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12474 		 * offset where we would need to deal with min/max bounds is
12475 		 * currently prohibited for unprivileged.
12476 		 */
12477 		max = MAX_BPF_STACK + mask_to_left;
12478 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12479 		break;
12480 	case PTR_TO_MAP_VALUE:
12481 		max = ptr_reg->map_ptr->value_size;
12482 		ptr_limit = (mask_to_left ?
12483 			     ptr_reg->smin_value :
12484 			     ptr_reg->umax_value) + ptr_reg->off;
12485 		break;
12486 	default:
12487 		return REASON_TYPE;
12488 	}
12489 
12490 	if (ptr_limit >= max)
12491 		return REASON_LIMIT;
12492 	*alu_limit = ptr_limit;
12493 	return 0;
12494 }
12495 
12496 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12497 				    const struct bpf_insn *insn)
12498 {
12499 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12500 }
12501 
12502 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12503 				       u32 alu_state, u32 alu_limit)
12504 {
12505 	/* If we arrived here from different branches with different
12506 	 * state or limits to sanitize, then this won't work.
12507 	 */
12508 	if (aux->alu_state &&
12509 	    (aux->alu_state != alu_state ||
12510 	     aux->alu_limit != alu_limit))
12511 		return REASON_PATHS;
12512 
12513 	/* Corresponding fixup done in do_misc_fixups(). */
12514 	aux->alu_state = alu_state;
12515 	aux->alu_limit = alu_limit;
12516 	return 0;
12517 }
12518 
12519 static int sanitize_val_alu(struct bpf_verifier_env *env,
12520 			    struct bpf_insn *insn)
12521 {
12522 	struct bpf_insn_aux_data *aux = cur_aux(env);
12523 
12524 	if (can_skip_alu_sanitation(env, insn))
12525 		return 0;
12526 
12527 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12528 }
12529 
12530 static bool sanitize_needed(u8 opcode)
12531 {
12532 	return opcode == BPF_ADD || opcode == BPF_SUB;
12533 }
12534 
12535 struct bpf_sanitize_info {
12536 	struct bpf_insn_aux_data aux;
12537 	bool mask_to_left;
12538 };
12539 
12540 static struct bpf_verifier_state *
12541 sanitize_speculative_path(struct bpf_verifier_env *env,
12542 			  const struct bpf_insn *insn,
12543 			  u32 next_idx, u32 curr_idx)
12544 {
12545 	struct bpf_verifier_state *branch;
12546 	struct bpf_reg_state *regs;
12547 
12548 	branch = push_stack(env, next_idx, curr_idx, true);
12549 	if (branch && insn) {
12550 		regs = branch->frame[branch->curframe]->regs;
12551 		if (BPF_SRC(insn->code) == BPF_K) {
12552 			mark_reg_unknown(env, regs, insn->dst_reg);
12553 		} else if (BPF_SRC(insn->code) == BPF_X) {
12554 			mark_reg_unknown(env, regs, insn->dst_reg);
12555 			mark_reg_unknown(env, regs, insn->src_reg);
12556 		}
12557 	}
12558 	return branch;
12559 }
12560 
12561 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12562 			    struct bpf_insn *insn,
12563 			    const struct bpf_reg_state *ptr_reg,
12564 			    const struct bpf_reg_state *off_reg,
12565 			    struct bpf_reg_state *dst_reg,
12566 			    struct bpf_sanitize_info *info,
12567 			    const bool commit_window)
12568 {
12569 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12570 	struct bpf_verifier_state *vstate = env->cur_state;
12571 	bool off_is_imm = tnum_is_const(off_reg->var_off);
12572 	bool off_is_neg = off_reg->smin_value < 0;
12573 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12574 	u8 opcode = BPF_OP(insn->code);
12575 	u32 alu_state, alu_limit;
12576 	struct bpf_reg_state tmp;
12577 	bool ret;
12578 	int err;
12579 
12580 	if (can_skip_alu_sanitation(env, insn))
12581 		return 0;
12582 
12583 	/* We already marked aux for masking from non-speculative
12584 	 * paths, thus we got here in the first place. We only care
12585 	 * to explore bad access from here.
12586 	 */
12587 	if (vstate->speculative)
12588 		goto do_sim;
12589 
12590 	if (!commit_window) {
12591 		if (!tnum_is_const(off_reg->var_off) &&
12592 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12593 			return REASON_BOUNDS;
12594 
12595 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12596 				     (opcode == BPF_SUB && !off_is_neg);
12597 	}
12598 
12599 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12600 	if (err < 0)
12601 		return err;
12602 
12603 	if (commit_window) {
12604 		/* In commit phase we narrow the masking window based on
12605 		 * the observed pointer move after the simulated operation.
12606 		 */
12607 		alu_state = info->aux.alu_state;
12608 		alu_limit = abs(info->aux.alu_limit - alu_limit);
12609 	} else {
12610 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12611 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12612 		alu_state |= ptr_is_dst_reg ?
12613 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12614 
12615 		/* Limit pruning on unknown scalars to enable deep search for
12616 		 * potential masking differences from other program paths.
12617 		 */
12618 		if (!off_is_imm)
12619 			env->explore_alu_limits = true;
12620 	}
12621 
12622 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12623 	if (err < 0)
12624 		return err;
12625 do_sim:
12626 	/* If we're in commit phase, we're done here given we already
12627 	 * pushed the truncated dst_reg into the speculative verification
12628 	 * stack.
12629 	 *
12630 	 * Also, when register is a known constant, we rewrite register-based
12631 	 * operation to immediate-based, and thus do not need masking (and as
12632 	 * a consequence, do not need to simulate the zero-truncation either).
12633 	 */
12634 	if (commit_window || off_is_imm)
12635 		return 0;
12636 
12637 	/* Simulate and find potential out-of-bounds access under
12638 	 * speculative execution from truncation as a result of
12639 	 * masking when off was not within expected range. If off
12640 	 * sits in dst, then we temporarily need to move ptr there
12641 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12642 	 * for cases where we use K-based arithmetic in one direction
12643 	 * and truncated reg-based in the other in order to explore
12644 	 * bad access.
12645 	 */
12646 	if (!ptr_is_dst_reg) {
12647 		tmp = *dst_reg;
12648 		copy_register_state(dst_reg, ptr_reg);
12649 	}
12650 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12651 					env->insn_idx);
12652 	if (!ptr_is_dst_reg && ret)
12653 		*dst_reg = tmp;
12654 	return !ret ? REASON_STACK : 0;
12655 }
12656 
12657 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12658 {
12659 	struct bpf_verifier_state *vstate = env->cur_state;
12660 
12661 	/* If we simulate paths under speculation, we don't update the
12662 	 * insn as 'seen' such that when we verify unreachable paths in
12663 	 * the non-speculative domain, sanitize_dead_code() can still
12664 	 * rewrite/sanitize them.
12665 	 */
12666 	if (!vstate->speculative)
12667 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12668 }
12669 
12670 static int sanitize_err(struct bpf_verifier_env *env,
12671 			const struct bpf_insn *insn, int reason,
12672 			const struct bpf_reg_state *off_reg,
12673 			const struct bpf_reg_state *dst_reg)
12674 {
12675 	static const char *err = "pointer arithmetic with it prohibited for !root";
12676 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12677 	u32 dst = insn->dst_reg, src = insn->src_reg;
12678 
12679 	switch (reason) {
12680 	case REASON_BOUNDS:
12681 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12682 			off_reg == dst_reg ? dst : src, err);
12683 		break;
12684 	case REASON_TYPE:
12685 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12686 			off_reg == dst_reg ? src : dst, err);
12687 		break;
12688 	case REASON_PATHS:
12689 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12690 			dst, op, err);
12691 		break;
12692 	case REASON_LIMIT:
12693 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12694 			dst, op, err);
12695 		break;
12696 	case REASON_STACK:
12697 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12698 			dst, err);
12699 		break;
12700 	default:
12701 		verbose(env, "verifier internal error: unknown reason (%d)\n",
12702 			reason);
12703 		break;
12704 	}
12705 
12706 	return -EACCES;
12707 }
12708 
12709 /* check that stack access falls within stack limits and that 'reg' doesn't
12710  * have a variable offset.
12711  *
12712  * Variable offset is prohibited for unprivileged mode for simplicity since it
12713  * requires corresponding support in Spectre masking for stack ALU.  See also
12714  * retrieve_ptr_limit().
12715  *
12716  *
12717  * 'off' includes 'reg->off'.
12718  */
12719 static int check_stack_access_for_ptr_arithmetic(
12720 				struct bpf_verifier_env *env,
12721 				int regno,
12722 				const struct bpf_reg_state *reg,
12723 				int off)
12724 {
12725 	if (!tnum_is_const(reg->var_off)) {
12726 		char tn_buf[48];
12727 
12728 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12729 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12730 			regno, tn_buf, off);
12731 		return -EACCES;
12732 	}
12733 
12734 	if (off >= 0 || off < -MAX_BPF_STACK) {
12735 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
12736 			"prohibited for !root; off=%d\n", regno, off);
12737 		return -EACCES;
12738 	}
12739 
12740 	return 0;
12741 }
12742 
12743 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12744 				 const struct bpf_insn *insn,
12745 				 const struct bpf_reg_state *dst_reg)
12746 {
12747 	u32 dst = insn->dst_reg;
12748 
12749 	/* For unprivileged we require that resulting offset must be in bounds
12750 	 * in order to be able to sanitize access later on.
12751 	 */
12752 	if (env->bypass_spec_v1)
12753 		return 0;
12754 
12755 	switch (dst_reg->type) {
12756 	case PTR_TO_STACK:
12757 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12758 					dst_reg->off + dst_reg->var_off.value))
12759 			return -EACCES;
12760 		break;
12761 	case PTR_TO_MAP_VALUE:
12762 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12763 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12764 				"prohibited for !root\n", dst);
12765 			return -EACCES;
12766 		}
12767 		break;
12768 	default:
12769 		break;
12770 	}
12771 
12772 	return 0;
12773 }
12774 
12775 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12776  * Caller should also handle BPF_MOV case separately.
12777  * If we return -EACCES, caller may want to try again treating pointer as a
12778  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12779  */
12780 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12781 				   struct bpf_insn *insn,
12782 				   const struct bpf_reg_state *ptr_reg,
12783 				   const struct bpf_reg_state *off_reg)
12784 {
12785 	struct bpf_verifier_state *vstate = env->cur_state;
12786 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12787 	struct bpf_reg_state *regs = state->regs, *dst_reg;
12788 	bool known = tnum_is_const(off_reg->var_off);
12789 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12790 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12791 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12792 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12793 	struct bpf_sanitize_info info = {};
12794 	u8 opcode = BPF_OP(insn->code);
12795 	u32 dst = insn->dst_reg;
12796 	int ret;
12797 
12798 	dst_reg = &regs[dst];
12799 
12800 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12801 	    smin_val > smax_val || umin_val > umax_val) {
12802 		/* Taint dst register if offset had invalid bounds derived from
12803 		 * e.g. dead branches.
12804 		 */
12805 		__mark_reg_unknown(env, dst_reg);
12806 		return 0;
12807 	}
12808 
12809 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
12810 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
12811 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12812 			__mark_reg_unknown(env, dst_reg);
12813 			return 0;
12814 		}
12815 
12816 		verbose(env,
12817 			"R%d 32-bit pointer arithmetic prohibited\n",
12818 			dst);
12819 		return -EACCES;
12820 	}
12821 
12822 	if (ptr_reg->type & PTR_MAYBE_NULL) {
12823 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12824 			dst, reg_type_str(env, ptr_reg->type));
12825 		return -EACCES;
12826 	}
12827 
12828 	switch (base_type(ptr_reg->type)) {
12829 	case PTR_TO_FLOW_KEYS:
12830 		if (known)
12831 			break;
12832 		fallthrough;
12833 	case CONST_PTR_TO_MAP:
12834 		/* smin_val represents the known value */
12835 		if (known && smin_val == 0 && opcode == BPF_ADD)
12836 			break;
12837 		fallthrough;
12838 	case PTR_TO_PACKET_END:
12839 	case PTR_TO_SOCKET:
12840 	case PTR_TO_SOCK_COMMON:
12841 	case PTR_TO_TCP_SOCK:
12842 	case PTR_TO_XDP_SOCK:
12843 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12844 			dst, reg_type_str(env, ptr_reg->type));
12845 		return -EACCES;
12846 	default:
12847 		break;
12848 	}
12849 
12850 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12851 	 * The id may be overwritten later if we create a new variable offset.
12852 	 */
12853 	dst_reg->type = ptr_reg->type;
12854 	dst_reg->id = ptr_reg->id;
12855 
12856 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12857 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12858 		return -EINVAL;
12859 
12860 	/* pointer types do not carry 32-bit bounds at the moment. */
12861 	__mark_reg32_unbounded(dst_reg);
12862 
12863 	if (sanitize_needed(opcode)) {
12864 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12865 				       &info, false);
12866 		if (ret < 0)
12867 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12868 	}
12869 
12870 	switch (opcode) {
12871 	case BPF_ADD:
12872 		/* We can take a fixed offset as long as it doesn't overflow
12873 		 * the s32 'off' field
12874 		 */
12875 		if (known && (ptr_reg->off + smin_val ==
12876 			      (s64)(s32)(ptr_reg->off + smin_val))) {
12877 			/* pointer += K.  Accumulate it into fixed offset */
12878 			dst_reg->smin_value = smin_ptr;
12879 			dst_reg->smax_value = smax_ptr;
12880 			dst_reg->umin_value = umin_ptr;
12881 			dst_reg->umax_value = umax_ptr;
12882 			dst_reg->var_off = ptr_reg->var_off;
12883 			dst_reg->off = ptr_reg->off + smin_val;
12884 			dst_reg->raw = ptr_reg->raw;
12885 			break;
12886 		}
12887 		/* A new variable offset is created.  Note that off_reg->off
12888 		 * == 0, since it's a scalar.
12889 		 * dst_reg gets the pointer type and since some positive
12890 		 * integer value was added to the pointer, give it a new 'id'
12891 		 * if it's a PTR_TO_PACKET.
12892 		 * this creates a new 'base' pointer, off_reg (variable) gets
12893 		 * added into the variable offset, and we copy the fixed offset
12894 		 * from ptr_reg.
12895 		 */
12896 		if (signed_add_overflows(smin_ptr, smin_val) ||
12897 		    signed_add_overflows(smax_ptr, smax_val)) {
12898 			dst_reg->smin_value = S64_MIN;
12899 			dst_reg->smax_value = S64_MAX;
12900 		} else {
12901 			dst_reg->smin_value = smin_ptr + smin_val;
12902 			dst_reg->smax_value = smax_ptr + smax_val;
12903 		}
12904 		if (umin_ptr + umin_val < umin_ptr ||
12905 		    umax_ptr + umax_val < umax_ptr) {
12906 			dst_reg->umin_value = 0;
12907 			dst_reg->umax_value = U64_MAX;
12908 		} else {
12909 			dst_reg->umin_value = umin_ptr + umin_val;
12910 			dst_reg->umax_value = umax_ptr + umax_val;
12911 		}
12912 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12913 		dst_reg->off = ptr_reg->off;
12914 		dst_reg->raw = ptr_reg->raw;
12915 		if (reg_is_pkt_pointer(ptr_reg)) {
12916 			dst_reg->id = ++env->id_gen;
12917 			/* something was added to pkt_ptr, set range to zero */
12918 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12919 		}
12920 		break;
12921 	case BPF_SUB:
12922 		if (dst_reg == off_reg) {
12923 			/* scalar -= pointer.  Creates an unknown scalar */
12924 			verbose(env, "R%d tried to subtract pointer from scalar\n",
12925 				dst);
12926 			return -EACCES;
12927 		}
12928 		/* We don't allow subtraction from FP, because (according to
12929 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
12930 		 * be able to deal with it.
12931 		 */
12932 		if (ptr_reg->type == PTR_TO_STACK) {
12933 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
12934 				dst);
12935 			return -EACCES;
12936 		}
12937 		if (known && (ptr_reg->off - smin_val ==
12938 			      (s64)(s32)(ptr_reg->off - smin_val))) {
12939 			/* pointer -= K.  Subtract it from fixed offset */
12940 			dst_reg->smin_value = smin_ptr;
12941 			dst_reg->smax_value = smax_ptr;
12942 			dst_reg->umin_value = umin_ptr;
12943 			dst_reg->umax_value = umax_ptr;
12944 			dst_reg->var_off = ptr_reg->var_off;
12945 			dst_reg->id = ptr_reg->id;
12946 			dst_reg->off = ptr_reg->off - smin_val;
12947 			dst_reg->raw = ptr_reg->raw;
12948 			break;
12949 		}
12950 		/* A new variable offset is created.  If the subtrahend is known
12951 		 * nonnegative, then any reg->range we had before is still good.
12952 		 */
12953 		if (signed_sub_overflows(smin_ptr, smax_val) ||
12954 		    signed_sub_overflows(smax_ptr, smin_val)) {
12955 			/* Overflow possible, we know nothing */
12956 			dst_reg->smin_value = S64_MIN;
12957 			dst_reg->smax_value = S64_MAX;
12958 		} else {
12959 			dst_reg->smin_value = smin_ptr - smax_val;
12960 			dst_reg->smax_value = smax_ptr - smin_val;
12961 		}
12962 		if (umin_ptr < umax_val) {
12963 			/* Overflow possible, we know nothing */
12964 			dst_reg->umin_value = 0;
12965 			dst_reg->umax_value = U64_MAX;
12966 		} else {
12967 			/* Cannot overflow (as long as bounds are consistent) */
12968 			dst_reg->umin_value = umin_ptr - umax_val;
12969 			dst_reg->umax_value = umax_ptr - umin_val;
12970 		}
12971 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12972 		dst_reg->off = ptr_reg->off;
12973 		dst_reg->raw = ptr_reg->raw;
12974 		if (reg_is_pkt_pointer(ptr_reg)) {
12975 			dst_reg->id = ++env->id_gen;
12976 			/* something was added to pkt_ptr, set range to zero */
12977 			if (smin_val < 0)
12978 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12979 		}
12980 		break;
12981 	case BPF_AND:
12982 	case BPF_OR:
12983 	case BPF_XOR:
12984 		/* bitwise ops on pointers are troublesome, prohibit. */
12985 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12986 			dst, bpf_alu_string[opcode >> 4]);
12987 		return -EACCES;
12988 	default:
12989 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
12990 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12991 			dst, bpf_alu_string[opcode >> 4]);
12992 		return -EACCES;
12993 	}
12994 
12995 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12996 		return -EINVAL;
12997 	reg_bounds_sync(dst_reg);
12998 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12999 		return -EACCES;
13000 	if (sanitize_needed(opcode)) {
13001 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
13002 				       &info, true);
13003 		if (ret < 0)
13004 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13005 	}
13006 
13007 	return 0;
13008 }
13009 
13010 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
13011 				 struct bpf_reg_state *src_reg)
13012 {
13013 	s32 smin_val = src_reg->s32_min_value;
13014 	s32 smax_val = src_reg->s32_max_value;
13015 	u32 umin_val = src_reg->u32_min_value;
13016 	u32 umax_val = src_reg->u32_max_value;
13017 
13018 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
13019 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
13020 		dst_reg->s32_min_value = S32_MIN;
13021 		dst_reg->s32_max_value = S32_MAX;
13022 	} else {
13023 		dst_reg->s32_min_value += smin_val;
13024 		dst_reg->s32_max_value += smax_val;
13025 	}
13026 	if (dst_reg->u32_min_value + umin_val < umin_val ||
13027 	    dst_reg->u32_max_value + umax_val < umax_val) {
13028 		dst_reg->u32_min_value = 0;
13029 		dst_reg->u32_max_value = U32_MAX;
13030 	} else {
13031 		dst_reg->u32_min_value += umin_val;
13032 		dst_reg->u32_max_value += umax_val;
13033 	}
13034 }
13035 
13036 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
13037 			       struct bpf_reg_state *src_reg)
13038 {
13039 	s64 smin_val = src_reg->smin_value;
13040 	s64 smax_val = src_reg->smax_value;
13041 	u64 umin_val = src_reg->umin_value;
13042 	u64 umax_val = src_reg->umax_value;
13043 
13044 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
13045 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
13046 		dst_reg->smin_value = S64_MIN;
13047 		dst_reg->smax_value = S64_MAX;
13048 	} else {
13049 		dst_reg->smin_value += smin_val;
13050 		dst_reg->smax_value += smax_val;
13051 	}
13052 	if (dst_reg->umin_value + umin_val < umin_val ||
13053 	    dst_reg->umax_value + umax_val < umax_val) {
13054 		dst_reg->umin_value = 0;
13055 		dst_reg->umax_value = U64_MAX;
13056 	} else {
13057 		dst_reg->umin_value += umin_val;
13058 		dst_reg->umax_value += umax_val;
13059 	}
13060 }
13061 
13062 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
13063 				 struct bpf_reg_state *src_reg)
13064 {
13065 	s32 smin_val = src_reg->s32_min_value;
13066 	s32 smax_val = src_reg->s32_max_value;
13067 	u32 umin_val = src_reg->u32_min_value;
13068 	u32 umax_val = src_reg->u32_max_value;
13069 
13070 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
13071 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
13072 		/* Overflow possible, we know nothing */
13073 		dst_reg->s32_min_value = S32_MIN;
13074 		dst_reg->s32_max_value = S32_MAX;
13075 	} else {
13076 		dst_reg->s32_min_value -= smax_val;
13077 		dst_reg->s32_max_value -= smin_val;
13078 	}
13079 	if (dst_reg->u32_min_value < umax_val) {
13080 		/* Overflow possible, we know nothing */
13081 		dst_reg->u32_min_value = 0;
13082 		dst_reg->u32_max_value = U32_MAX;
13083 	} else {
13084 		/* Cannot overflow (as long as bounds are consistent) */
13085 		dst_reg->u32_min_value -= umax_val;
13086 		dst_reg->u32_max_value -= umin_val;
13087 	}
13088 }
13089 
13090 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
13091 			       struct bpf_reg_state *src_reg)
13092 {
13093 	s64 smin_val = src_reg->smin_value;
13094 	s64 smax_val = src_reg->smax_value;
13095 	u64 umin_val = src_reg->umin_value;
13096 	u64 umax_val = src_reg->umax_value;
13097 
13098 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
13099 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
13100 		/* Overflow possible, we know nothing */
13101 		dst_reg->smin_value = S64_MIN;
13102 		dst_reg->smax_value = S64_MAX;
13103 	} else {
13104 		dst_reg->smin_value -= smax_val;
13105 		dst_reg->smax_value -= smin_val;
13106 	}
13107 	if (dst_reg->umin_value < umax_val) {
13108 		/* Overflow possible, we know nothing */
13109 		dst_reg->umin_value = 0;
13110 		dst_reg->umax_value = U64_MAX;
13111 	} else {
13112 		/* Cannot overflow (as long as bounds are consistent) */
13113 		dst_reg->umin_value -= umax_val;
13114 		dst_reg->umax_value -= umin_val;
13115 	}
13116 }
13117 
13118 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13119 				 struct bpf_reg_state *src_reg)
13120 {
13121 	s32 smin_val = src_reg->s32_min_value;
13122 	u32 umin_val = src_reg->u32_min_value;
13123 	u32 umax_val = src_reg->u32_max_value;
13124 
13125 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
13126 		/* Ain't nobody got time to multiply that sign */
13127 		__mark_reg32_unbounded(dst_reg);
13128 		return;
13129 	}
13130 	/* Both values are positive, so we can work with unsigned and
13131 	 * copy the result to signed (unless it exceeds S32_MAX).
13132 	 */
13133 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
13134 		/* Potential overflow, we know nothing */
13135 		__mark_reg32_unbounded(dst_reg);
13136 		return;
13137 	}
13138 	dst_reg->u32_min_value *= umin_val;
13139 	dst_reg->u32_max_value *= umax_val;
13140 	if (dst_reg->u32_max_value > S32_MAX) {
13141 		/* Overflow possible, we know nothing */
13142 		dst_reg->s32_min_value = S32_MIN;
13143 		dst_reg->s32_max_value = S32_MAX;
13144 	} else {
13145 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13146 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13147 	}
13148 }
13149 
13150 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13151 			       struct bpf_reg_state *src_reg)
13152 {
13153 	s64 smin_val = src_reg->smin_value;
13154 	u64 umin_val = src_reg->umin_value;
13155 	u64 umax_val = src_reg->umax_value;
13156 
13157 	if (smin_val < 0 || dst_reg->smin_value < 0) {
13158 		/* Ain't nobody got time to multiply that sign */
13159 		__mark_reg64_unbounded(dst_reg);
13160 		return;
13161 	}
13162 	/* Both values are positive, so we can work with unsigned and
13163 	 * copy the result to signed (unless it exceeds S64_MAX).
13164 	 */
13165 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
13166 		/* Potential overflow, we know nothing */
13167 		__mark_reg64_unbounded(dst_reg);
13168 		return;
13169 	}
13170 	dst_reg->umin_value *= umin_val;
13171 	dst_reg->umax_value *= umax_val;
13172 	if (dst_reg->umax_value > S64_MAX) {
13173 		/* Overflow possible, we know nothing */
13174 		dst_reg->smin_value = S64_MIN;
13175 		dst_reg->smax_value = S64_MAX;
13176 	} else {
13177 		dst_reg->smin_value = dst_reg->umin_value;
13178 		dst_reg->smax_value = dst_reg->umax_value;
13179 	}
13180 }
13181 
13182 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13183 				 struct bpf_reg_state *src_reg)
13184 {
13185 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13186 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13187 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13188 	s32 smin_val = src_reg->s32_min_value;
13189 	u32 umax_val = src_reg->u32_max_value;
13190 
13191 	if (src_known && dst_known) {
13192 		__mark_reg32_known(dst_reg, var32_off.value);
13193 		return;
13194 	}
13195 
13196 	/* We get our minimum from the var_off, since that's inherently
13197 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13198 	 */
13199 	dst_reg->u32_min_value = var32_off.value;
13200 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13201 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13202 		/* Lose signed bounds when ANDing negative numbers,
13203 		 * ain't nobody got time for that.
13204 		 */
13205 		dst_reg->s32_min_value = S32_MIN;
13206 		dst_reg->s32_max_value = S32_MAX;
13207 	} else {
13208 		/* ANDing two positives gives a positive, so safe to
13209 		 * cast result into s64.
13210 		 */
13211 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13212 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13213 	}
13214 }
13215 
13216 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
13217 			       struct bpf_reg_state *src_reg)
13218 {
13219 	bool src_known = tnum_is_const(src_reg->var_off);
13220 	bool dst_known = tnum_is_const(dst_reg->var_off);
13221 	s64 smin_val = src_reg->smin_value;
13222 	u64 umax_val = src_reg->umax_value;
13223 
13224 	if (src_known && dst_known) {
13225 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13226 		return;
13227 	}
13228 
13229 	/* We get our minimum from the var_off, since that's inherently
13230 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13231 	 */
13232 	dst_reg->umin_value = dst_reg->var_off.value;
13233 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13234 	if (dst_reg->smin_value < 0 || smin_val < 0) {
13235 		/* Lose signed bounds when ANDing negative numbers,
13236 		 * ain't nobody got time for that.
13237 		 */
13238 		dst_reg->smin_value = S64_MIN;
13239 		dst_reg->smax_value = S64_MAX;
13240 	} else {
13241 		/* ANDing two positives gives a positive, so safe to
13242 		 * cast result into s64.
13243 		 */
13244 		dst_reg->smin_value = dst_reg->umin_value;
13245 		dst_reg->smax_value = dst_reg->umax_value;
13246 	}
13247 	/* We may learn something more from the var_off */
13248 	__update_reg_bounds(dst_reg);
13249 }
13250 
13251 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13252 				struct bpf_reg_state *src_reg)
13253 {
13254 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13255 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13256 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13257 	s32 smin_val = src_reg->s32_min_value;
13258 	u32 umin_val = src_reg->u32_min_value;
13259 
13260 	if (src_known && dst_known) {
13261 		__mark_reg32_known(dst_reg, var32_off.value);
13262 		return;
13263 	}
13264 
13265 	/* We get our maximum from the var_off, and our minimum is the
13266 	 * maximum of the operands' minima
13267 	 */
13268 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13269 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13270 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13271 		/* Lose signed bounds when ORing negative numbers,
13272 		 * ain't nobody got time for that.
13273 		 */
13274 		dst_reg->s32_min_value = S32_MIN;
13275 		dst_reg->s32_max_value = S32_MAX;
13276 	} else {
13277 		/* ORing two positives gives a positive, so safe to
13278 		 * cast result into s64.
13279 		 */
13280 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13281 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13282 	}
13283 }
13284 
13285 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13286 			      struct bpf_reg_state *src_reg)
13287 {
13288 	bool src_known = tnum_is_const(src_reg->var_off);
13289 	bool dst_known = tnum_is_const(dst_reg->var_off);
13290 	s64 smin_val = src_reg->smin_value;
13291 	u64 umin_val = src_reg->umin_value;
13292 
13293 	if (src_known && dst_known) {
13294 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13295 		return;
13296 	}
13297 
13298 	/* We get our maximum from the var_off, and our minimum is the
13299 	 * maximum of the operands' minima
13300 	 */
13301 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13302 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13303 	if (dst_reg->smin_value < 0 || smin_val < 0) {
13304 		/* Lose signed bounds when ORing negative numbers,
13305 		 * ain't nobody got time for that.
13306 		 */
13307 		dst_reg->smin_value = S64_MIN;
13308 		dst_reg->smax_value = S64_MAX;
13309 	} else {
13310 		/* ORing two positives gives a positive, so safe to
13311 		 * cast result into s64.
13312 		 */
13313 		dst_reg->smin_value = dst_reg->umin_value;
13314 		dst_reg->smax_value = dst_reg->umax_value;
13315 	}
13316 	/* We may learn something more from the var_off */
13317 	__update_reg_bounds(dst_reg);
13318 }
13319 
13320 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13321 				 struct bpf_reg_state *src_reg)
13322 {
13323 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13324 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13325 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13326 	s32 smin_val = src_reg->s32_min_value;
13327 
13328 	if (src_known && dst_known) {
13329 		__mark_reg32_known(dst_reg, var32_off.value);
13330 		return;
13331 	}
13332 
13333 	/* We get both minimum and maximum from the var32_off. */
13334 	dst_reg->u32_min_value = var32_off.value;
13335 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13336 
13337 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13338 		/* XORing two positive sign numbers gives a positive,
13339 		 * so safe to cast u32 result into s32.
13340 		 */
13341 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13342 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13343 	} else {
13344 		dst_reg->s32_min_value = S32_MIN;
13345 		dst_reg->s32_max_value = S32_MAX;
13346 	}
13347 }
13348 
13349 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13350 			       struct bpf_reg_state *src_reg)
13351 {
13352 	bool src_known = tnum_is_const(src_reg->var_off);
13353 	bool dst_known = tnum_is_const(dst_reg->var_off);
13354 	s64 smin_val = src_reg->smin_value;
13355 
13356 	if (src_known && dst_known) {
13357 		/* dst_reg->var_off.value has been updated earlier */
13358 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13359 		return;
13360 	}
13361 
13362 	/* We get both minimum and maximum from the var_off. */
13363 	dst_reg->umin_value = dst_reg->var_off.value;
13364 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13365 
13366 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13367 		/* XORing two positive sign numbers gives a positive,
13368 		 * so safe to cast u64 result into s64.
13369 		 */
13370 		dst_reg->smin_value = dst_reg->umin_value;
13371 		dst_reg->smax_value = dst_reg->umax_value;
13372 	} else {
13373 		dst_reg->smin_value = S64_MIN;
13374 		dst_reg->smax_value = S64_MAX;
13375 	}
13376 
13377 	__update_reg_bounds(dst_reg);
13378 }
13379 
13380 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13381 				   u64 umin_val, u64 umax_val)
13382 {
13383 	/* We lose all sign bit information (except what we can pick
13384 	 * up from var_off)
13385 	 */
13386 	dst_reg->s32_min_value = S32_MIN;
13387 	dst_reg->s32_max_value = S32_MAX;
13388 	/* If we might shift our top bit out, then we know nothing */
13389 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13390 		dst_reg->u32_min_value = 0;
13391 		dst_reg->u32_max_value = U32_MAX;
13392 	} else {
13393 		dst_reg->u32_min_value <<= umin_val;
13394 		dst_reg->u32_max_value <<= umax_val;
13395 	}
13396 }
13397 
13398 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13399 				 struct bpf_reg_state *src_reg)
13400 {
13401 	u32 umax_val = src_reg->u32_max_value;
13402 	u32 umin_val = src_reg->u32_min_value;
13403 	/* u32 alu operation will zext upper bits */
13404 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13405 
13406 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13407 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13408 	/* Not required but being careful mark reg64 bounds as unknown so
13409 	 * that we are forced to pick them up from tnum and zext later and
13410 	 * if some path skips this step we are still safe.
13411 	 */
13412 	__mark_reg64_unbounded(dst_reg);
13413 	__update_reg32_bounds(dst_reg);
13414 }
13415 
13416 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13417 				   u64 umin_val, u64 umax_val)
13418 {
13419 	/* Special case <<32 because it is a common compiler pattern to sign
13420 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13421 	 * positive we know this shift will also be positive so we can track
13422 	 * bounds correctly. Otherwise we lose all sign bit information except
13423 	 * what we can pick up from var_off. Perhaps we can generalize this
13424 	 * later to shifts of any length.
13425 	 */
13426 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13427 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13428 	else
13429 		dst_reg->smax_value = S64_MAX;
13430 
13431 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13432 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13433 	else
13434 		dst_reg->smin_value = S64_MIN;
13435 
13436 	/* If we might shift our top bit out, then we know nothing */
13437 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13438 		dst_reg->umin_value = 0;
13439 		dst_reg->umax_value = U64_MAX;
13440 	} else {
13441 		dst_reg->umin_value <<= umin_val;
13442 		dst_reg->umax_value <<= umax_val;
13443 	}
13444 }
13445 
13446 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13447 			       struct bpf_reg_state *src_reg)
13448 {
13449 	u64 umax_val = src_reg->umax_value;
13450 	u64 umin_val = src_reg->umin_value;
13451 
13452 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13453 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13454 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13455 
13456 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13457 	/* We may learn something more from the var_off */
13458 	__update_reg_bounds(dst_reg);
13459 }
13460 
13461 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13462 				 struct bpf_reg_state *src_reg)
13463 {
13464 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13465 	u32 umax_val = src_reg->u32_max_value;
13466 	u32 umin_val = src_reg->u32_min_value;
13467 
13468 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13469 	 * be negative, then either:
13470 	 * 1) src_reg might be zero, so the sign bit of the result is
13471 	 *    unknown, so we lose our signed bounds
13472 	 * 2) it's known negative, thus the unsigned bounds capture the
13473 	 *    signed bounds
13474 	 * 3) the signed bounds cross zero, so they tell us nothing
13475 	 *    about the result
13476 	 * If the value in dst_reg is known nonnegative, then again the
13477 	 * unsigned bounds capture the signed bounds.
13478 	 * Thus, in all cases it suffices to blow away our signed bounds
13479 	 * and rely on inferring new ones from the unsigned bounds and
13480 	 * var_off of the result.
13481 	 */
13482 	dst_reg->s32_min_value = S32_MIN;
13483 	dst_reg->s32_max_value = S32_MAX;
13484 
13485 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13486 	dst_reg->u32_min_value >>= umax_val;
13487 	dst_reg->u32_max_value >>= umin_val;
13488 
13489 	__mark_reg64_unbounded(dst_reg);
13490 	__update_reg32_bounds(dst_reg);
13491 }
13492 
13493 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13494 			       struct bpf_reg_state *src_reg)
13495 {
13496 	u64 umax_val = src_reg->umax_value;
13497 	u64 umin_val = src_reg->umin_value;
13498 
13499 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13500 	 * be negative, then either:
13501 	 * 1) src_reg might be zero, so the sign bit of the result is
13502 	 *    unknown, so we lose our signed bounds
13503 	 * 2) it's known negative, thus the unsigned bounds capture the
13504 	 *    signed bounds
13505 	 * 3) the signed bounds cross zero, so they tell us nothing
13506 	 *    about the result
13507 	 * If the value in dst_reg is known nonnegative, then again the
13508 	 * unsigned bounds capture the signed bounds.
13509 	 * Thus, in all cases it suffices to blow away our signed bounds
13510 	 * and rely on inferring new ones from the unsigned bounds and
13511 	 * var_off of the result.
13512 	 */
13513 	dst_reg->smin_value = S64_MIN;
13514 	dst_reg->smax_value = S64_MAX;
13515 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13516 	dst_reg->umin_value >>= umax_val;
13517 	dst_reg->umax_value >>= umin_val;
13518 
13519 	/* Its not easy to operate on alu32 bounds here because it depends
13520 	 * on bits being shifted in. Take easy way out and mark unbounded
13521 	 * so we can recalculate later from tnum.
13522 	 */
13523 	__mark_reg32_unbounded(dst_reg);
13524 	__update_reg_bounds(dst_reg);
13525 }
13526 
13527 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13528 				  struct bpf_reg_state *src_reg)
13529 {
13530 	u64 umin_val = src_reg->u32_min_value;
13531 
13532 	/* Upon reaching here, src_known is true and
13533 	 * umax_val is equal to umin_val.
13534 	 */
13535 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13536 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13537 
13538 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13539 
13540 	/* blow away the dst_reg umin_value/umax_value and rely on
13541 	 * dst_reg var_off to refine the result.
13542 	 */
13543 	dst_reg->u32_min_value = 0;
13544 	dst_reg->u32_max_value = U32_MAX;
13545 
13546 	__mark_reg64_unbounded(dst_reg);
13547 	__update_reg32_bounds(dst_reg);
13548 }
13549 
13550 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13551 				struct bpf_reg_state *src_reg)
13552 {
13553 	u64 umin_val = src_reg->umin_value;
13554 
13555 	/* Upon reaching here, src_known is true and umax_val is equal
13556 	 * to umin_val.
13557 	 */
13558 	dst_reg->smin_value >>= umin_val;
13559 	dst_reg->smax_value >>= umin_val;
13560 
13561 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13562 
13563 	/* blow away the dst_reg umin_value/umax_value and rely on
13564 	 * dst_reg var_off to refine the result.
13565 	 */
13566 	dst_reg->umin_value = 0;
13567 	dst_reg->umax_value = U64_MAX;
13568 
13569 	/* Its not easy to operate on alu32 bounds here because it depends
13570 	 * on bits being shifted in from upper 32-bits. Take easy way out
13571 	 * and mark unbounded so we can recalculate later from tnum.
13572 	 */
13573 	__mark_reg32_unbounded(dst_reg);
13574 	__update_reg_bounds(dst_reg);
13575 }
13576 
13577 /* WARNING: This function does calculations on 64-bit values, but the actual
13578  * execution may occur on 32-bit values. Therefore, things like bitshifts
13579  * need extra checks in the 32-bit case.
13580  */
13581 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13582 				      struct bpf_insn *insn,
13583 				      struct bpf_reg_state *dst_reg,
13584 				      struct bpf_reg_state src_reg)
13585 {
13586 	struct bpf_reg_state *regs = cur_regs(env);
13587 	u8 opcode = BPF_OP(insn->code);
13588 	bool src_known;
13589 	s64 smin_val, smax_val;
13590 	u64 umin_val, umax_val;
13591 	s32 s32_min_val, s32_max_val;
13592 	u32 u32_min_val, u32_max_val;
13593 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13594 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13595 	int ret;
13596 
13597 	smin_val = src_reg.smin_value;
13598 	smax_val = src_reg.smax_value;
13599 	umin_val = src_reg.umin_value;
13600 	umax_val = src_reg.umax_value;
13601 
13602 	s32_min_val = src_reg.s32_min_value;
13603 	s32_max_val = src_reg.s32_max_value;
13604 	u32_min_val = src_reg.u32_min_value;
13605 	u32_max_val = src_reg.u32_max_value;
13606 
13607 	if (alu32) {
13608 		src_known = tnum_subreg_is_const(src_reg.var_off);
13609 		if ((src_known &&
13610 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13611 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13612 			/* Taint dst register if offset had invalid bounds
13613 			 * derived from e.g. dead branches.
13614 			 */
13615 			__mark_reg_unknown(env, dst_reg);
13616 			return 0;
13617 		}
13618 	} else {
13619 		src_known = tnum_is_const(src_reg.var_off);
13620 		if ((src_known &&
13621 		     (smin_val != smax_val || umin_val != umax_val)) ||
13622 		    smin_val > smax_val || umin_val > umax_val) {
13623 			/* Taint dst register if offset had invalid bounds
13624 			 * derived from e.g. dead branches.
13625 			 */
13626 			__mark_reg_unknown(env, dst_reg);
13627 			return 0;
13628 		}
13629 	}
13630 
13631 	if (!src_known &&
13632 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13633 		__mark_reg_unknown(env, dst_reg);
13634 		return 0;
13635 	}
13636 
13637 	if (sanitize_needed(opcode)) {
13638 		ret = sanitize_val_alu(env, insn);
13639 		if (ret < 0)
13640 			return sanitize_err(env, insn, ret, NULL, NULL);
13641 	}
13642 
13643 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13644 	 * There are two classes of instructions: The first class we track both
13645 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13646 	 * greatest amount of precision when alu operations are mixed with jmp32
13647 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13648 	 * and BPF_OR. This is possible because these ops have fairly easy to
13649 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13650 	 * See alu32 verifier tests for examples. The second class of
13651 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13652 	 * with regards to tracking sign/unsigned bounds because the bits may
13653 	 * cross subreg boundaries in the alu64 case. When this happens we mark
13654 	 * the reg unbounded in the subreg bound space and use the resulting
13655 	 * tnum to calculate an approximation of the sign/unsigned bounds.
13656 	 */
13657 	switch (opcode) {
13658 	case BPF_ADD:
13659 		scalar32_min_max_add(dst_reg, &src_reg);
13660 		scalar_min_max_add(dst_reg, &src_reg);
13661 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13662 		break;
13663 	case BPF_SUB:
13664 		scalar32_min_max_sub(dst_reg, &src_reg);
13665 		scalar_min_max_sub(dst_reg, &src_reg);
13666 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13667 		break;
13668 	case BPF_MUL:
13669 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13670 		scalar32_min_max_mul(dst_reg, &src_reg);
13671 		scalar_min_max_mul(dst_reg, &src_reg);
13672 		break;
13673 	case BPF_AND:
13674 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13675 		scalar32_min_max_and(dst_reg, &src_reg);
13676 		scalar_min_max_and(dst_reg, &src_reg);
13677 		break;
13678 	case BPF_OR:
13679 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13680 		scalar32_min_max_or(dst_reg, &src_reg);
13681 		scalar_min_max_or(dst_reg, &src_reg);
13682 		break;
13683 	case BPF_XOR:
13684 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13685 		scalar32_min_max_xor(dst_reg, &src_reg);
13686 		scalar_min_max_xor(dst_reg, &src_reg);
13687 		break;
13688 	case BPF_LSH:
13689 		if (umax_val >= insn_bitness) {
13690 			/* Shifts greater than 31 or 63 are undefined.
13691 			 * This includes shifts by a negative number.
13692 			 */
13693 			mark_reg_unknown(env, regs, insn->dst_reg);
13694 			break;
13695 		}
13696 		if (alu32)
13697 			scalar32_min_max_lsh(dst_reg, &src_reg);
13698 		else
13699 			scalar_min_max_lsh(dst_reg, &src_reg);
13700 		break;
13701 	case BPF_RSH:
13702 		if (umax_val >= insn_bitness) {
13703 			/* Shifts greater than 31 or 63 are undefined.
13704 			 * This includes shifts by a negative number.
13705 			 */
13706 			mark_reg_unknown(env, regs, insn->dst_reg);
13707 			break;
13708 		}
13709 		if (alu32)
13710 			scalar32_min_max_rsh(dst_reg, &src_reg);
13711 		else
13712 			scalar_min_max_rsh(dst_reg, &src_reg);
13713 		break;
13714 	case BPF_ARSH:
13715 		if (umax_val >= insn_bitness) {
13716 			/* Shifts greater than 31 or 63 are undefined.
13717 			 * This includes shifts by a negative number.
13718 			 */
13719 			mark_reg_unknown(env, regs, insn->dst_reg);
13720 			break;
13721 		}
13722 		if (alu32)
13723 			scalar32_min_max_arsh(dst_reg, &src_reg);
13724 		else
13725 			scalar_min_max_arsh(dst_reg, &src_reg);
13726 		break;
13727 	default:
13728 		mark_reg_unknown(env, regs, insn->dst_reg);
13729 		break;
13730 	}
13731 
13732 	/* ALU32 ops are zero extended into 64bit register */
13733 	if (alu32)
13734 		zext_32_to_64(dst_reg);
13735 	reg_bounds_sync(dst_reg);
13736 	return 0;
13737 }
13738 
13739 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13740  * and var_off.
13741  */
13742 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13743 				   struct bpf_insn *insn)
13744 {
13745 	struct bpf_verifier_state *vstate = env->cur_state;
13746 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13747 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13748 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13749 	u8 opcode = BPF_OP(insn->code);
13750 	int err;
13751 
13752 	dst_reg = &regs[insn->dst_reg];
13753 	src_reg = NULL;
13754 	if (dst_reg->type != SCALAR_VALUE)
13755 		ptr_reg = dst_reg;
13756 	else
13757 		/* Make sure ID is cleared otherwise dst_reg min/max could be
13758 		 * incorrectly propagated into other registers by find_equal_scalars()
13759 		 */
13760 		dst_reg->id = 0;
13761 	if (BPF_SRC(insn->code) == BPF_X) {
13762 		src_reg = &regs[insn->src_reg];
13763 		if (src_reg->type != SCALAR_VALUE) {
13764 			if (dst_reg->type != SCALAR_VALUE) {
13765 				/* Combining two pointers by any ALU op yields
13766 				 * an arbitrary scalar. Disallow all math except
13767 				 * pointer subtraction
13768 				 */
13769 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13770 					mark_reg_unknown(env, regs, insn->dst_reg);
13771 					return 0;
13772 				}
13773 				verbose(env, "R%d pointer %s pointer prohibited\n",
13774 					insn->dst_reg,
13775 					bpf_alu_string[opcode >> 4]);
13776 				return -EACCES;
13777 			} else {
13778 				/* scalar += pointer
13779 				 * This is legal, but we have to reverse our
13780 				 * src/dest handling in computing the range
13781 				 */
13782 				err = mark_chain_precision(env, insn->dst_reg);
13783 				if (err)
13784 					return err;
13785 				return adjust_ptr_min_max_vals(env, insn,
13786 							       src_reg, dst_reg);
13787 			}
13788 		} else if (ptr_reg) {
13789 			/* pointer += scalar */
13790 			err = mark_chain_precision(env, insn->src_reg);
13791 			if (err)
13792 				return err;
13793 			return adjust_ptr_min_max_vals(env, insn,
13794 						       dst_reg, src_reg);
13795 		} else if (dst_reg->precise) {
13796 			/* if dst_reg is precise, src_reg should be precise as well */
13797 			err = mark_chain_precision(env, insn->src_reg);
13798 			if (err)
13799 				return err;
13800 		}
13801 	} else {
13802 		/* Pretend the src is a reg with a known value, since we only
13803 		 * need to be able to read from this state.
13804 		 */
13805 		off_reg.type = SCALAR_VALUE;
13806 		__mark_reg_known(&off_reg, insn->imm);
13807 		src_reg = &off_reg;
13808 		if (ptr_reg) /* pointer += K */
13809 			return adjust_ptr_min_max_vals(env, insn,
13810 						       ptr_reg, src_reg);
13811 	}
13812 
13813 	/* Got here implies adding two SCALAR_VALUEs */
13814 	if (WARN_ON_ONCE(ptr_reg)) {
13815 		print_verifier_state(env, state, true);
13816 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
13817 		return -EINVAL;
13818 	}
13819 	if (WARN_ON(!src_reg)) {
13820 		print_verifier_state(env, state, true);
13821 		verbose(env, "verifier internal error: no src_reg\n");
13822 		return -EINVAL;
13823 	}
13824 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13825 }
13826 
13827 /* check validity of 32-bit and 64-bit arithmetic operations */
13828 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13829 {
13830 	struct bpf_reg_state *regs = cur_regs(env);
13831 	u8 opcode = BPF_OP(insn->code);
13832 	int err;
13833 
13834 	if (opcode == BPF_END || opcode == BPF_NEG) {
13835 		if (opcode == BPF_NEG) {
13836 			if (BPF_SRC(insn->code) != BPF_K ||
13837 			    insn->src_reg != BPF_REG_0 ||
13838 			    insn->off != 0 || insn->imm != 0) {
13839 				verbose(env, "BPF_NEG uses reserved fields\n");
13840 				return -EINVAL;
13841 			}
13842 		} else {
13843 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13844 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13845 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
13846 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
13847 				verbose(env, "BPF_END uses reserved fields\n");
13848 				return -EINVAL;
13849 			}
13850 		}
13851 
13852 		/* check src operand */
13853 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13854 		if (err)
13855 			return err;
13856 
13857 		if (is_pointer_value(env, insn->dst_reg)) {
13858 			verbose(env, "R%d pointer arithmetic prohibited\n",
13859 				insn->dst_reg);
13860 			return -EACCES;
13861 		}
13862 
13863 		/* check dest operand */
13864 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
13865 		if (err)
13866 			return err;
13867 
13868 	} else if (opcode == BPF_MOV) {
13869 
13870 		if (BPF_SRC(insn->code) == BPF_X) {
13871 			if (insn->imm != 0) {
13872 				verbose(env, "BPF_MOV uses reserved fields\n");
13873 				return -EINVAL;
13874 			}
13875 
13876 			if (BPF_CLASS(insn->code) == BPF_ALU) {
13877 				if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13878 					verbose(env, "BPF_MOV uses reserved fields\n");
13879 					return -EINVAL;
13880 				}
13881 			} else {
13882 				if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13883 				    insn->off != 32) {
13884 					verbose(env, "BPF_MOV uses reserved fields\n");
13885 					return -EINVAL;
13886 				}
13887 			}
13888 
13889 			/* check src operand */
13890 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13891 			if (err)
13892 				return err;
13893 		} else {
13894 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13895 				verbose(env, "BPF_MOV uses reserved fields\n");
13896 				return -EINVAL;
13897 			}
13898 		}
13899 
13900 		/* check dest operand, mark as required later */
13901 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13902 		if (err)
13903 			return err;
13904 
13905 		if (BPF_SRC(insn->code) == BPF_X) {
13906 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
13907 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13908 			bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13909 				       !tnum_is_const(src_reg->var_off);
13910 
13911 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13912 				if (insn->off == 0) {
13913 					/* case: R1 = R2
13914 					 * copy register state to dest reg
13915 					 */
13916 					if (need_id)
13917 						/* Assign src and dst registers the same ID
13918 						 * that will be used by find_equal_scalars()
13919 						 * to propagate min/max range.
13920 						 */
13921 						src_reg->id = ++env->id_gen;
13922 					copy_register_state(dst_reg, src_reg);
13923 					dst_reg->live |= REG_LIVE_WRITTEN;
13924 					dst_reg->subreg_def = DEF_NOT_SUBREG;
13925 				} else {
13926 					/* case: R1 = (s8, s16 s32)R2 */
13927 					if (is_pointer_value(env, insn->src_reg)) {
13928 						verbose(env,
13929 							"R%d sign-extension part of pointer\n",
13930 							insn->src_reg);
13931 						return -EACCES;
13932 					} else if (src_reg->type == SCALAR_VALUE) {
13933 						bool no_sext;
13934 
13935 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13936 						if (no_sext && need_id)
13937 							src_reg->id = ++env->id_gen;
13938 						copy_register_state(dst_reg, src_reg);
13939 						if (!no_sext)
13940 							dst_reg->id = 0;
13941 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13942 						dst_reg->live |= REG_LIVE_WRITTEN;
13943 						dst_reg->subreg_def = DEF_NOT_SUBREG;
13944 					} else {
13945 						mark_reg_unknown(env, regs, insn->dst_reg);
13946 					}
13947 				}
13948 			} else {
13949 				/* R1 = (u32) R2 */
13950 				if (is_pointer_value(env, insn->src_reg)) {
13951 					verbose(env,
13952 						"R%d partial copy of pointer\n",
13953 						insn->src_reg);
13954 					return -EACCES;
13955 				} else if (src_reg->type == SCALAR_VALUE) {
13956 					if (insn->off == 0) {
13957 						bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13958 
13959 						if (is_src_reg_u32 && need_id)
13960 							src_reg->id = ++env->id_gen;
13961 						copy_register_state(dst_reg, src_reg);
13962 						/* Make sure ID is cleared if src_reg is not in u32
13963 						 * range otherwise dst_reg min/max could be incorrectly
13964 						 * propagated into src_reg by find_equal_scalars()
13965 						 */
13966 						if (!is_src_reg_u32)
13967 							dst_reg->id = 0;
13968 						dst_reg->live |= REG_LIVE_WRITTEN;
13969 						dst_reg->subreg_def = env->insn_idx + 1;
13970 					} else {
13971 						/* case: W1 = (s8, s16)W2 */
13972 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13973 
13974 						if (no_sext && need_id)
13975 							src_reg->id = ++env->id_gen;
13976 						copy_register_state(dst_reg, src_reg);
13977 						if (!no_sext)
13978 							dst_reg->id = 0;
13979 						dst_reg->live |= REG_LIVE_WRITTEN;
13980 						dst_reg->subreg_def = env->insn_idx + 1;
13981 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13982 					}
13983 				} else {
13984 					mark_reg_unknown(env, regs,
13985 							 insn->dst_reg);
13986 				}
13987 				zext_32_to_64(dst_reg);
13988 				reg_bounds_sync(dst_reg);
13989 			}
13990 		} else {
13991 			/* case: R = imm
13992 			 * remember the value we stored into this reg
13993 			 */
13994 			/* clear any state __mark_reg_known doesn't set */
13995 			mark_reg_unknown(env, regs, insn->dst_reg);
13996 			regs[insn->dst_reg].type = SCALAR_VALUE;
13997 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13998 				__mark_reg_known(regs + insn->dst_reg,
13999 						 insn->imm);
14000 			} else {
14001 				__mark_reg_known(regs + insn->dst_reg,
14002 						 (u32)insn->imm);
14003 			}
14004 		}
14005 
14006 	} else if (opcode > BPF_END) {
14007 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
14008 		return -EINVAL;
14009 
14010 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
14011 
14012 		if (BPF_SRC(insn->code) == BPF_X) {
14013 			if (insn->imm != 0 || insn->off > 1 ||
14014 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14015 				verbose(env, "BPF_ALU uses reserved fields\n");
14016 				return -EINVAL;
14017 			}
14018 			/* check src1 operand */
14019 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14020 			if (err)
14021 				return err;
14022 		} else {
14023 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
14024 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14025 				verbose(env, "BPF_ALU uses reserved fields\n");
14026 				return -EINVAL;
14027 			}
14028 		}
14029 
14030 		/* check src2 operand */
14031 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14032 		if (err)
14033 			return err;
14034 
14035 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
14036 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
14037 			verbose(env, "div by zero\n");
14038 			return -EINVAL;
14039 		}
14040 
14041 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
14042 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
14043 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
14044 
14045 			if (insn->imm < 0 || insn->imm >= size) {
14046 				verbose(env, "invalid shift %d\n", insn->imm);
14047 				return -EINVAL;
14048 			}
14049 		}
14050 
14051 		/* check dest operand */
14052 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14053 		err = err ?: adjust_reg_min_max_vals(env, insn);
14054 		if (err)
14055 			return err;
14056 	}
14057 
14058 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
14059 }
14060 
14061 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
14062 				   struct bpf_reg_state *dst_reg,
14063 				   enum bpf_reg_type type,
14064 				   bool range_right_open)
14065 {
14066 	struct bpf_func_state *state;
14067 	struct bpf_reg_state *reg;
14068 	int new_range;
14069 
14070 	if (dst_reg->off < 0 ||
14071 	    (dst_reg->off == 0 && range_right_open))
14072 		/* This doesn't give us any range */
14073 		return;
14074 
14075 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
14076 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
14077 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
14078 		 * than pkt_end, but that's because it's also less than pkt.
14079 		 */
14080 		return;
14081 
14082 	new_range = dst_reg->off;
14083 	if (range_right_open)
14084 		new_range++;
14085 
14086 	/* Examples for register markings:
14087 	 *
14088 	 * pkt_data in dst register:
14089 	 *
14090 	 *   r2 = r3;
14091 	 *   r2 += 8;
14092 	 *   if (r2 > pkt_end) goto <handle exception>
14093 	 *   <access okay>
14094 	 *
14095 	 *   r2 = r3;
14096 	 *   r2 += 8;
14097 	 *   if (r2 < pkt_end) goto <access okay>
14098 	 *   <handle exception>
14099 	 *
14100 	 *   Where:
14101 	 *     r2 == dst_reg, pkt_end == src_reg
14102 	 *     r2=pkt(id=n,off=8,r=0)
14103 	 *     r3=pkt(id=n,off=0,r=0)
14104 	 *
14105 	 * pkt_data in src register:
14106 	 *
14107 	 *   r2 = r3;
14108 	 *   r2 += 8;
14109 	 *   if (pkt_end >= r2) goto <access okay>
14110 	 *   <handle exception>
14111 	 *
14112 	 *   r2 = r3;
14113 	 *   r2 += 8;
14114 	 *   if (pkt_end <= r2) goto <handle exception>
14115 	 *   <access okay>
14116 	 *
14117 	 *   Where:
14118 	 *     pkt_end == dst_reg, r2 == src_reg
14119 	 *     r2=pkt(id=n,off=8,r=0)
14120 	 *     r3=pkt(id=n,off=0,r=0)
14121 	 *
14122 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
14123 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
14124 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
14125 	 * the check.
14126 	 */
14127 
14128 	/* If our ids match, then we must have the same max_value.  And we
14129 	 * don't care about the other reg's fixed offset, since if it's too big
14130 	 * the range won't allow anything.
14131 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
14132 	 */
14133 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14134 		if (reg->type == type && reg->id == dst_reg->id)
14135 			/* keep the maximum range already checked */
14136 			reg->range = max(reg->range, new_range);
14137 	}));
14138 }
14139 
14140 /*
14141  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
14142  */
14143 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14144 				  u8 opcode, bool is_jmp32)
14145 {
14146 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
14147 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
14148 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
14149 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
14150 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
14151 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
14152 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
14153 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
14154 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
14155 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
14156 
14157 	switch (opcode) {
14158 	case BPF_JEQ:
14159 		/* constants, umin/umax and smin/smax checks would be
14160 		 * redundant in this case because they all should match
14161 		 */
14162 		if (tnum_is_const(t1) && tnum_is_const(t2))
14163 			return t1.value == t2.value;
14164 		/* non-overlapping ranges */
14165 		if (umin1 > umax2 || umax1 < umin2)
14166 			return 0;
14167 		if (smin1 > smax2 || smax1 < smin2)
14168 			return 0;
14169 		if (!is_jmp32) {
14170 			/* if 64-bit ranges are inconclusive, see if we can
14171 			 * utilize 32-bit subrange knowledge to eliminate
14172 			 * branches that can't be taken a priori
14173 			 */
14174 			if (reg1->u32_min_value > reg2->u32_max_value ||
14175 			    reg1->u32_max_value < reg2->u32_min_value)
14176 				return 0;
14177 			if (reg1->s32_min_value > reg2->s32_max_value ||
14178 			    reg1->s32_max_value < reg2->s32_min_value)
14179 				return 0;
14180 		}
14181 		break;
14182 	case BPF_JNE:
14183 		/* constants, umin/umax and smin/smax checks would be
14184 		 * redundant in this case because they all should match
14185 		 */
14186 		if (tnum_is_const(t1) && tnum_is_const(t2))
14187 			return t1.value != t2.value;
14188 		/* non-overlapping ranges */
14189 		if (umin1 > umax2 || umax1 < umin2)
14190 			return 1;
14191 		if (smin1 > smax2 || smax1 < smin2)
14192 			return 1;
14193 		if (!is_jmp32) {
14194 			/* if 64-bit ranges are inconclusive, see if we can
14195 			 * utilize 32-bit subrange knowledge to eliminate
14196 			 * branches that can't be taken a priori
14197 			 */
14198 			if (reg1->u32_min_value > reg2->u32_max_value ||
14199 			    reg1->u32_max_value < reg2->u32_min_value)
14200 				return 1;
14201 			if (reg1->s32_min_value > reg2->s32_max_value ||
14202 			    reg1->s32_max_value < reg2->s32_min_value)
14203 				return 1;
14204 		}
14205 		break;
14206 	case BPF_JSET:
14207 		if (!is_reg_const(reg2, is_jmp32)) {
14208 			swap(reg1, reg2);
14209 			swap(t1, t2);
14210 		}
14211 		if (!is_reg_const(reg2, is_jmp32))
14212 			return -1;
14213 		if ((~t1.mask & t1.value) & t2.value)
14214 			return 1;
14215 		if (!((t1.mask | t1.value) & t2.value))
14216 			return 0;
14217 		break;
14218 	case BPF_JGT:
14219 		if (umin1 > umax2)
14220 			return 1;
14221 		else if (umax1 <= umin2)
14222 			return 0;
14223 		break;
14224 	case BPF_JSGT:
14225 		if (smin1 > smax2)
14226 			return 1;
14227 		else if (smax1 <= smin2)
14228 			return 0;
14229 		break;
14230 	case BPF_JLT:
14231 		if (umax1 < umin2)
14232 			return 1;
14233 		else if (umin1 >= umax2)
14234 			return 0;
14235 		break;
14236 	case BPF_JSLT:
14237 		if (smax1 < smin2)
14238 			return 1;
14239 		else if (smin1 >= smax2)
14240 			return 0;
14241 		break;
14242 	case BPF_JGE:
14243 		if (umin1 >= umax2)
14244 			return 1;
14245 		else if (umax1 < umin2)
14246 			return 0;
14247 		break;
14248 	case BPF_JSGE:
14249 		if (smin1 >= smax2)
14250 			return 1;
14251 		else if (smax1 < smin2)
14252 			return 0;
14253 		break;
14254 	case BPF_JLE:
14255 		if (umax1 <= umin2)
14256 			return 1;
14257 		else if (umin1 > umax2)
14258 			return 0;
14259 		break;
14260 	case BPF_JSLE:
14261 		if (smax1 <= smin2)
14262 			return 1;
14263 		else if (smin1 > smax2)
14264 			return 0;
14265 		break;
14266 	}
14267 
14268 	return -1;
14269 }
14270 
14271 static int flip_opcode(u32 opcode)
14272 {
14273 	/* How can we transform "a <op> b" into "b <op> a"? */
14274 	static const u8 opcode_flip[16] = {
14275 		/* these stay the same */
14276 		[BPF_JEQ  >> 4] = BPF_JEQ,
14277 		[BPF_JNE  >> 4] = BPF_JNE,
14278 		[BPF_JSET >> 4] = BPF_JSET,
14279 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14280 		[BPF_JGE  >> 4] = BPF_JLE,
14281 		[BPF_JGT  >> 4] = BPF_JLT,
14282 		[BPF_JLE  >> 4] = BPF_JGE,
14283 		[BPF_JLT  >> 4] = BPF_JGT,
14284 		[BPF_JSGE >> 4] = BPF_JSLE,
14285 		[BPF_JSGT >> 4] = BPF_JSLT,
14286 		[BPF_JSLE >> 4] = BPF_JSGE,
14287 		[BPF_JSLT >> 4] = BPF_JSGT
14288 	};
14289 	return opcode_flip[opcode >> 4];
14290 }
14291 
14292 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14293 				   struct bpf_reg_state *src_reg,
14294 				   u8 opcode)
14295 {
14296 	struct bpf_reg_state *pkt;
14297 
14298 	if (src_reg->type == PTR_TO_PACKET_END) {
14299 		pkt = dst_reg;
14300 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14301 		pkt = src_reg;
14302 		opcode = flip_opcode(opcode);
14303 	} else {
14304 		return -1;
14305 	}
14306 
14307 	if (pkt->range >= 0)
14308 		return -1;
14309 
14310 	switch (opcode) {
14311 	case BPF_JLE:
14312 		/* pkt <= pkt_end */
14313 		fallthrough;
14314 	case BPF_JGT:
14315 		/* pkt > pkt_end */
14316 		if (pkt->range == BEYOND_PKT_END)
14317 			/* pkt has at last one extra byte beyond pkt_end */
14318 			return opcode == BPF_JGT;
14319 		break;
14320 	case BPF_JLT:
14321 		/* pkt < pkt_end */
14322 		fallthrough;
14323 	case BPF_JGE:
14324 		/* pkt >= pkt_end */
14325 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14326 			return opcode == BPF_JGE;
14327 		break;
14328 	}
14329 	return -1;
14330 }
14331 
14332 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
14333  * and return:
14334  *  1 - branch will be taken and "goto target" will be executed
14335  *  0 - branch will not be taken and fall-through to next insn
14336  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
14337  *      range [0,10]
14338  */
14339 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14340 			   u8 opcode, bool is_jmp32)
14341 {
14342 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
14343 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
14344 
14345 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
14346 		u64 val;
14347 
14348 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
14349 		if (!is_reg_const(reg2, is_jmp32)) {
14350 			opcode = flip_opcode(opcode);
14351 			swap(reg1, reg2);
14352 		}
14353 		/* and ensure that reg2 is a constant */
14354 		if (!is_reg_const(reg2, is_jmp32))
14355 			return -1;
14356 
14357 		if (!reg_not_null(reg1))
14358 			return -1;
14359 
14360 		/* If pointer is valid tests against zero will fail so we can
14361 		 * use this to direct branch taken.
14362 		 */
14363 		val = reg_const_value(reg2, is_jmp32);
14364 		if (val != 0)
14365 			return -1;
14366 
14367 		switch (opcode) {
14368 		case BPF_JEQ:
14369 			return 0;
14370 		case BPF_JNE:
14371 			return 1;
14372 		default:
14373 			return -1;
14374 		}
14375 	}
14376 
14377 	/* now deal with two scalars, but not necessarily constants */
14378 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
14379 }
14380 
14381 /* Opcode that corresponds to a *false* branch condition.
14382  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
14383  */
14384 static u8 rev_opcode(u8 opcode)
14385 {
14386 	switch (opcode) {
14387 	case BPF_JEQ:		return BPF_JNE;
14388 	case BPF_JNE:		return BPF_JEQ;
14389 	/* JSET doesn't have it's reverse opcode in BPF, so add
14390 	 * BPF_X flag to denote the reverse of that operation
14391 	 */
14392 	case BPF_JSET:		return BPF_JSET | BPF_X;
14393 	case BPF_JSET | BPF_X:	return BPF_JSET;
14394 	case BPF_JGE:		return BPF_JLT;
14395 	case BPF_JGT:		return BPF_JLE;
14396 	case BPF_JLE:		return BPF_JGT;
14397 	case BPF_JLT:		return BPF_JGE;
14398 	case BPF_JSGE:		return BPF_JSLT;
14399 	case BPF_JSGT:		return BPF_JSLE;
14400 	case BPF_JSLE:		return BPF_JSGT;
14401 	case BPF_JSLT:		return BPF_JSGE;
14402 	default:		return 0;
14403 	}
14404 }
14405 
14406 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
14407 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14408 				u8 opcode, bool is_jmp32)
14409 {
14410 	struct tnum t;
14411 	u64 val;
14412 
14413 again:
14414 	switch (opcode) {
14415 	case BPF_JEQ:
14416 		if (is_jmp32) {
14417 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14418 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14419 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14420 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14421 			reg2->u32_min_value = reg1->u32_min_value;
14422 			reg2->u32_max_value = reg1->u32_max_value;
14423 			reg2->s32_min_value = reg1->s32_min_value;
14424 			reg2->s32_max_value = reg1->s32_max_value;
14425 
14426 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
14427 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14428 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
14429 		} else {
14430 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
14431 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14432 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
14433 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14434 			reg2->umin_value = reg1->umin_value;
14435 			reg2->umax_value = reg1->umax_value;
14436 			reg2->smin_value = reg1->smin_value;
14437 			reg2->smax_value = reg1->smax_value;
14438 
14439 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
14440 			reg2->var_off = reg1->var_off;
14441 		}
14442 		break;
14443 	case BPF_JNE:
14444 		if (!is_reg_const(reg2, is_jmp32))
14445 			swap(reg1, reg2);
14446 		if (!is_reg_const(reg2, is_jmp32))
14447 			break;
14448 
14449 		/* try to recompute the bound of reg1 if reg2 is a const and
14450 		 * is exactly the edge of reg1.
14451 		 */
14452 		val = reg_const_value(reg2, is_jmp32);
14453 		if (is_jmp32) {
14454 			/* u32_min_value is not equal to 0xffffffff at this point,
14455 			 * because otherwise u32_max_value is 0xffffffff as well,
14456 			 * in such a case both reg1 and reg2 would be constants,
14457 			 * jump would be predicted and reg_set_min_max() won't
14458 			 * be called.
14459 			 *
14460 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
14461 			 * below.
14462 			 */
14463 			if (reg1->u32_min_value == (u32)val)
14464 				reg1->u32_min_value++;
14465 			if (reg1->u32_max_value == (u32)val)
14466 				reg1->u32_max_value--;
14467 			if (reg1->s32_min_value == (s32)val)
14468 				reg1->s32_min_value++;
14469 			if (reg1->s32_max_value == (s32)val)
14470 				reg1->s32_max_value--;
14471 		} else {
14472 			if (reg1->umin_value == (u64)val)
14473 				reg1->umin_value++;
14474 			if (reg1->umax_value == (u64)val)
14475 				reg1->umax_value--;
14476 			if (reg1->smin_value == (s64)val)
14477 				reg1->smin_value++;
14478 			if (reg1->smax_value == (s64)val)
14479 				reg1->smax_value--;
14480 		}
14481 		break;
14482 	case BPF_JSET:
14483 		if (!is_reg_const(reg2, is_jmp32))
14484 			swap(reg1, reg2);
14485 		if (!is_reg_const(reg2, is_jmp32))
14486 			break;
14487 		val = reg_const_value(reg2, is_jmp32);
14488 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
14489 		 * requires single bit to learn something useful. E.g., if we
14490 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
14491 		 * are actually set? We can learn something definite only if
14492 		 * it's a single-bit value to begin with.
14493 		 *
14494 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
14495 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
14496 		 * bit 1 is set, which we can readily use in adjustments.
14497 		 */
14498 		if (!is_power_of_2(val))
14499 			break;
14500 		if (is_jmp32) {
14501 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
14502 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14503 		} else {
14504 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
14505 		}
14506 		break;
14507 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
14508 		if (!is_reg_const(reg2, is_jmp32))
14509 			swap(reg1, reg2);
14510 		if (!is_reg_const(reg2, is_jmp32))
14511 			break;
14512 		val = reg_const_value(reg2, is_jmp32);
14513 		if (is_jmp32) {
14514 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
14515 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14516 		} else {
14517 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
14518 		}
14519 		break;
14520 	case BPF_JLE:
14521 		if (is_jmp32) {
14522 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14523 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14524 		} else {
14525 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14526 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
14527 		}
14528 		break;
14529 	case BPF_JLT:
14530 		if (is_jmp32) {
14531 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
14532 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
14533 		} else {
14534 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
14535 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
14536 		}
14537 		break;
14538 	case BPF_JSLE:
14539 		if (is_jmp32) {
14540 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14541 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14542 		} else {
14543 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14544 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
14545 		}
14546 		break;
14547 	case BPF_JSLT:
14548 		if (is_jmp32) {
14549 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
14550 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
14551 		} else {
14552 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
14553 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
14554 		}
14555 		break;
14556 	case BPF_JGE:
14557 	case BPF_JGT:
14558 	case BPF_JSGE:
14559 	case BPF_JSGT:
14560 		/* just reuse LE/LT logic above */
14561 		opcode = flip_opcode(opcode);
14562 		swap(reg1, reg2);
14563 		goto again;
14564 	default:
14565 		return;
14566 	}
14567 }
14568 
14569 /* Adjusts the register min/max values in the case that the dst_reg and
14570  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
14571  * check, in which case we havea fake SCALAR_VALUE representing insn->imm).
14572  * Technically we can do similar adjustments for pointers to the same object,
14573  * but we don't support that right now.
14574  */
14575 static int reg_set_min_max(struct bpf_verifier_env *env,
14576 			   struct bpf_reg_state *true_reg1,
14577 			   struct bpf_reg_state *true_reg2,
14578 			   struct bpf_reg_state *false_reg1,
14579 			   struct bpf_reg_state *false_reg2,
14580 			   u8 opcode, bool is_jmp32)
14581 {
14582 	int err;
14583 
14584 	/* If either register is a pointer, we can't learn anything about its
14585 	 * variable offset from the compare (unless they were a pointer into
14586 	 * the same object, but we don't bother with that).
14587 	 */
14588 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
14589 		return 0;
14590 
14591 	/* fallthrough (FALSE) branch */
14592 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
14593 	reg_bounds_sync(false_reg1);
14594 	reg_bounds_sync(false_reg2);
14595 
14596 	/* jump (TRUE) branch */
14597 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
14598 	reg_bounds_sync(true_reg1);
14599 	reg_bounds_sync(true_reg2);
14600 
14601 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
14602 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
14603 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
14604 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
14605 	return err;
14606 }
14607 
14608 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14609 				 struct bpf_reg_state *reg, u32 id,
14610 				 bool is_null)
14611 {
14612 	if (type_may_be_null(reg->type) && reg->id == id &&
14613 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14614 		/* Old offset (both fixed and variable parts) should have been
14615 		 * known-zero, because we don't allow pointer arithmetic on
14616 		 * pointers that might be NULL. If we see this happening, don't
14617 		 * convert the register.
14618 		 *
14619 		 * But in some cases, some helpers that return local kptrs
14620 		 * advance offset for the returned pointer. In those cases, it
14621 		 * is fine to expect to see reg->off.
14622 		 */
14623 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14624 			return;
14625 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14626 		    WARN_ON_ONCE(reg->off))
14627 			return;
14628 
14629 		if (is_null) {
14630 			reg->type = SCALAR_VALUE;
14631 			/* We don't need id and ref_obj_id from this point
14632 			 * onwards anymore, thus we should better reset it,
14633 			 * so that state pruning has chances to take effect.
14634 			 */
14635 			reg->id = 0;
14636 			reg->ref_obj_id = 0;
14637 
14638 			return;
14639 		}
14640 
14641 		mark_ptr_not_null_reg(reg);
14642 
14643 		if (!reg_may_point_to_spin_lock(reg)) {
14644 			/* For not-NULL ptr, reg->ref_obj_id will be reset
14645 			 * in release_reference().
14646 			 *
14647 			 * reg->id is still used by spin_lock ptr. Other
14648 			 * than spin_lock ptr type, reg->id can be reset.
14649 			 */
14650 			reg->id = 0;
14651 		}
14652 	}
14653 }
14654 
14655 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14656  * be folded together at some point.
14657  */
14658 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14659 				  bool is_null)
14660 {
14661 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14662 	struct bpf_reg_state *regs = state->regs, *reg;
14663 	u32 ref_obj_id = regs[regno].ref_obj_id;
14664 	u32 id = regs[regno].id;
14665 
14666 	if (ref_obj_id && ref_obj_id == id && is_null)
14667 		/* regs[regno] is in the " == NULL" branch.
14668 		 * No one could have freed the reference state before
14669 		 * doing the NULL check.
14670 		 */
14671 		WARN_ON_ONCE(release_reference_state(state, id));
14672 
14673 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14674 		mark_ptr_or_null_reg(state, reg, id, is_null);
14675 	}));
14676 }
14677 
14678 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14679 				   struct bpf_reg_state *dst_reg,
14680 				   struct bpf_reg_state *src_reg,
14681 				   struct bpf_verifier_state *this_branch,
14682 				   struct bpf_verifier_state *other_branch)
14683 {
14684 	if (BPF_SRC(insn->code) != BPF_X)
14685 		return false;
14686 
14687 	/* Pointers are always 64-bit. */
14688 	if (BPF_CLASS(insn->code) == BPF_JMP32)
14689 		return false;
14690 
14691 	switch (BPF_OP(insn->code)) {
14692 	case BPF_JGT:
14693 		if ((dst_reg->type == PTR_TO_PACKET &&
14694 		     src_reg->type == PTR_TO_PACKET_END) ||
14695 		    (dst_reg->type == PTR_TO_PACKET_META &&
14696 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14697 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14698 			find_good_pkt_pointers(this_branch, dst_reg,
14699 					       dst_reg->type, false);
14700 			mark_pkt_end(other_branch, insn->dst_reg, true);
14701 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14702 			    src_reg->type == PTR_TO_PACKET) ||
14703 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14704 			    src_reg->type == PTR_TO_PACKET_META)) {
14705 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
14706 			find_good_pkt_pointers(other_branch, src_reg,
14707 					       src_reg->type, true);
14708 			mark_pkt_end(this_branch, insn->src_reg, false);
14709 		} else {
14710 			return false;
14711 		}
14712 		break;
14713 	case BPF_JLT:
14714 		if ((dst_reg->type == PTR_TO_PACKET &&
14715 		     src_reg->type == PTR_TO_PACKET_END) ||
14716 		    (dst_reg->type == PTR_TO_PACKET_META &&
14717 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14718 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14719 			find_good_pkt_pointers(other_branch, dst_reg,
14720 					       dst_reg->type, true);
14721 			mark_pkt_end(this_branch, insn->dst_reg, false);
14722 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14723 			    src_reg->type == PTR_TO_PACKET) ||
14724 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14725 			    src_reg->type == PTR_TO_PACKET_META)) {
14726 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
14727 			find_good_pkt_pointers(this_branch, src_reg,
14728 					       src_reg->type, false);
14729 			mark_pkt_end(other_branch, insn->src_reg, true);
14730 		} else {
14731 			return false;
14732 		}
14733 		break;
14734 	case BPF_JGE:
14735 		if ((dst_reg->type == PTR_TO_PACKET &&
14736 		     src_reg->type == PTR_TO_PACKET_END) ||
14737 		    (dst_reg->type == PTR_TO_PACKET_META &&
14738 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14739 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14740 			find_good_pkt_pointers(this_branch, dst_reg,
14741 					       dst_reg->type, true);
14742 			mark_pkt_end(other_branch, insn->dst_reg, false);
14743 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14744 			    src_reg->type == PTR_TO_PACKET) ||
14745 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14746 			    src_reg->type == PTR_TO_PACKET_META)) {
14747 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14748 			find_good_pkt_pointers(other_branch, src_reg,
14749 					       src_reg->type, false);
14750 			mark_pkt_end(this_branch, insn->src_reg, true);
14751 		} else {
14752 			return false;
14753 		}
14754 		break;
14755 	case BPF_JLE:
14756 		if ((dst_reg->type == PTR_TO_PACKET &&
14757 		     src_reg->type == PTR_TO_PACKET_END) ||
14758 		    (dst_reg->type == PTR_TO_PACKET_META &&
14759 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14760 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14761 			find_good_pkt_pointers(other_branch, dst_reg,
14762 					       dst_reg->type, false);
14763 			mark_pkt_end(this_branch, insn->dst_reg, true);
14764 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14765 			    src_reg->type == PTR_TO_PACKET) ||
14766 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14767 			    src_reg->type == PTR_TO_PACKET_META)) {
14768 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14769 			find_good_pkt_pointers(this_branch, src_reg,
14770 					       src_reg->type, true);
14771 			mark_pkt_end(other_branch, insn->src_reg, false);
14772 		} else {
14773 			return false;
14774 		}
14775 		break;
14776 	default:
14777 		return false;
14778 	}
14779 
14780 	return true;
14781 }
14782 
14783 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14784 			       struct bpf_reg_state *known_reg)
14785 {
14786 	struct bpf_func_state *state;
14787 	struct bpf_reg_state *reg;
14788 
14789 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14790 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14791 			copy_register_state(reg, known_reg);
14792 	}));
14793 }
14794 
14795 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14796 			     struct bpf_insn *insn, int *insn_idx)
14797 {
14798 	struct bpf_verifier_state *this_branch = env->cur_state;
14799 	struct bpf_verifier_state *other_branch;
14800 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14801 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14802 	struct bpf_reg_state *eq_branch_regs;
14803 	struct bpf_reg_state fake_reg = {};
14804 	u8 opcode = BPF_OP(insn->code);
14805 	bool is_jmp32;
14806 	int pred = -1;
14807 	int err;
14808 
14809 	/* Only conditional jumps are expected to reach here. */
14810 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
14811 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14812 		return -EINVAL;
14813 	}
14814 
14815 	/* check src2 operand */
14816 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14817 	if (err)
14818 		return err;
14819 
14820 	dst_reg = &regs[insn->dst_reg];
14821 	if (BPF_SRC(insn->code) == BPF_X) {
14822 		if (insn->imm != 0) {
14823 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14824 			return -EINVAL;
14825 		}
14826 
14827 		/* check src1 operand */
14828 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14829 		if (err)
14830 			return err;
14831 
14832 		src_reg = &regs[insn->src_reg];
14833 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14834 		    is_pointer_value(env, insn->src_reg)) {
14835 			verbose(env, "R%d pointer comparison prohibited\n",
14836 				insn->src_reg);
14837 			return -EACCES;
14838 		}
14839 	} else {
14840 		if (insn->src_reg != BPF_REG_0) {
14841 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14842 			return -EINVAL;
14843 		}
14844 		src_reg = &fake_reg;
14845 		src_reg->type = SCALAR_VALUE;
14846 		__mark_reg_known(src_reg, insn->imm);
14847 	}
14848 
14849 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14850 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
14851 	if (pred >= 0) {
14852 		/* If we get here with a dst_reg pointer type it is because
14853 		 * above is_branch_taken() special cased the 0 comparison.
14854 		 */
14855 		if (!__is_pointer_value(false, dst_reg))
14856 			err = mark_chain_precision(env, insn->dst_reg);
14857 		if (BPF_SRC(insn->code) == BPF_X && !err &&
14858 		    !__is_pointer_value(false, src_reg))
14859 			err = mark_chain_precision(env, insn->src_reg);
14860 		if (err)
14861 			return err;
14862 	}
14863 
14864 	if (pred == 1) {
14865 		/* Only follow the goto, ignore fall-through. If needed, push
14866 		 * the fall-through branch for simulation under speculative
14867 		 * execution.
14868 		 */
14869 		if (!env->bypass_spec_v1 &&
14870 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
14871 					       *insn_idx))
14872 			return -EFAULT;
14873 		if (env->log.level & BPF_LOG_LEVEL)
14874 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14875 		*insn_idx += insn->off;
14876 		return 0;
14877 	} else if (pred == 0) {
14878 		/* Only follow the fall-through branch, since that's where the
14879 		 * program will go. If needed, push the goto branch for
14880 		 * simulation under speculative execution.
14881 		 */
14882 		if (!env->bypass_spec_v1 &&
14883 		    !sanitize_speculative_path(env, insn,
14884 					       *insn_idx + insn->off + 1,
14885 					       *insn_idx))
14886 			return -EFAULT;
14887 		if (env->log.level & BPF_LOG_LEVEL)
14888 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14889 		return 0;
14890 	}
14891 
14892 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14893 				  false);
14894 	if (!other_branch)
14895 		return -EFAULT;
14896 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14897 
14898 	if (BPF_SRC(insn->code) == BPF_X) {
14899 		err = reg_set_min_max(env,
14900 				      &other_branch_regs[insn->dst_reg],
14901 				      &other_branch_regs[insn->src_reg],
14902 				      dst_reg, src_reg, opcode, is_jmp32);
14903 	} else /* BPF_SRC(insn->code) == BPF_K */ {
14904 		err = reg_set_min_max(env,
14905 				      &other_branch_regs[insn->dst_reg],
14906 				      src_reg /* fake one */,
14907 				      dst_reg, src_reg /* same fake one */,
14908 				      opcode, is_jmp32);
14909 	}
14910 	if (err)
14911 		return err;
14912 
14913 	if (BPF_SRC(insn->code) == BPF_X &&
14914 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
14915 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14916 		find_equal_scalars(this_branch, src_reg);
14917 		find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14918 	}
14919 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14920 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14921 		find_equal_scalars(this_branch, dst_reg);
14922 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14923 	}
14924 
14925 	/* if one pointer register is compared to another pointer
14926 	 * register check if PTR_MAYBE_NULL could be lifted.
14927 	 * E.g. register A - maybe null
14928 	 *      register B - not null
14929 	 * for JNE A, B, ... - A is not null in the false branch;
14930 	 * for JEQ A, B, ... - A is not null in the true branch.
14931 	 *
14932 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
14933 	 * not need to be null checked by the BPF program, i.e.,
14934 	 * could be null even without PTR_MAYBE_NULL marking, so
14935 	 * only propagate nullness when neither reg is that type.
14936 	 */
14937 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14938 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14939 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14940 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
14941 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14942 		eq_branch_regs = NULL;
14943 		switch (opcode) {
14944 		case BPF_JEQ:
14945 			eq_branch_regs = other_branch_regs;
14946 			break;
14947 		case BPF_JNE:
14948 			eq_branch_regs = regs;
14949 			break;
14950 		default:
14951 			/* do nothing */
14952 			break;
14953 		}
14954 		if (eq_branch_regs) {
14955 			if (type_may_be_null(src_reg->type))
14956 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14957 			else
14958 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14959 		}
14960 	}
14961 
14962 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14963 	 * NOTE: these optimizations below are related with pointer comparison
14964 	 *       which will never be JMP32.
14965 	 */
14966 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14967 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14968 	    type_may_be_null(dst_reg->type)) {
14969 		/* Mark all identical registers in each branch as either
14970 		 * safe or unknown depending R == 0 or R != 0 conditional.
14971 		 */
14972 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14973 				      opcode == BPF_JNE);
14974 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14975 				      opcode == BPF_JEQ);
14976 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14977 					   this_branch, other_branch) &&
14978 		   is_pointer_value(env, insn->dst_reg)) {
14979 		verbose(env, "R%d pointer comparison prohibited\n",
14980 			insn->dst_reg);
14981 		return -EACCES;
14982 	}
14983 	if (env->log.level & BPF_LOG_LEVEL)
14984 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
14985 	return 0;
14986 }
14987 
14988 /* verify BPF_LD_IMM64 instruction */
14989 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14990 {
14991 	struct bpf_insn_aux_data *aux = cur_aux(env);
14992 	struct bpf_reg_state *regs = cur_regs(env);
14993 	struct bpf_reg_state *dst_reg;
14994 	struct bpf_map *map;
14995 	int err;
14996 
14997 	if (BPF_SIZE(insn->code) != BPF_DW) {
14998 		verbose(env, "invalid BPF_LD_IMM insn\n");
14999 		return -EINVAL;
15000 	}
15001 	if (insn->off != 0) {
15002 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
15003 		return -EINVAL;
15004 	}
15005 
15006 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
15007 	if (err)
15008 		return err;
15009 
15010 	dst_reg = &regs[insn->dst_reg];
15011 	if (insn->src_reg == 0) {
15012 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
15013 
15014 		dst_reg->type = SCALAR_VALUE;
15015 		__mark_reg_known(&regs[insn->dst_reg], imm);
15016 		return 0;
15017 	}
15018 
15019 	/* All special src_reg cases are listed below. From this point onwards
15020 	 * we either succeed and assign a corresponding dst_reg->type after
15021 	 * zeroing the offset, or fail and reject the program.
15022 	 */
15023 	mark_reg_known_zero(env, regs, insn->dst_reg);
15024 
15025 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
15026 		dst_reg->type = aux->btf_var.reg_type;
15027 		switch (base_type(dst_reg->type)) {
15028 		case PTR_TO_MEM:
15029 			dst_reg->mem_size = aux->btf_var.mem_size;
15030 			break;
15031 		case PTR_TO_BTF_ID:
15032 			dst_reg->btf = aux->btf_var.btf;
15033 			dst_reg->btf_id = aux->btf_var.btf_id;
15034 			break;
15035 		default:
15036 			verbose(env, "bpf verifier is misconfigured\n");
15037 			return -EFAULT;
15038 		}
15039 		return 0;
15040 	}
15041 
15042 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
15043 		struct bpf_prog_aux *aux = env->prog->aux;
15044 		u32 subprogno = find_subprog(env,
15045 					     env->insn_idx + insn->imm + 1);
15046 
15047 		if (!aux->func_info) {
15048 			verbose(env, "missing btf func_info\n");
15049 			return -EINVAL;
15050 		}
15051 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
15052 			verbose(env, "callback function not static\n");
15053 			return -EINVAL;
15054 		}
15055 
15056 		dst_reg->type = PTR_TO_FUNC;
15057 		dst_reg->subprogno = subprogno;
15058 		return 0;
15059 	}
15060 
15061 	map = env->used_maps[aux->map_index];
15062 	dst_reg->map_ptr = map;
15063 
15064 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
15065 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
15066 		dst_reg->type = PTR_TO_MAP_VALUE;
15067 		dst_reg->off = aux->map_off;
15068 		WARN_ON_ONCE(map->max_entries != 1);
15069 		/* We want reg->id to be same (0) as map_value is not distinct */
15070 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
15071 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
15072 		dst_reg->type = CONST_PTR_TO_MAP;
15073 	} else {
15074 		verbose(env, "bpf verifier is misconfigured\n");
15075 		return -EINVAL;
15076 	}
15077 
15078 	return 0;
15079 }
15080 
15081 static bool may_access_skb(enum bpf_prog_type type)
15082 {
15083 	switch (type) {
15084 	case BPF_PROG_TYPE_SOCKET_FILTER:
15085 	case BPF_PROG_TYPE_SCHED_CLS:
15086 	case BPF_PROG_TYPE_SCHED_ACT:
15087 		return true;
15088 	default:
15089 		return false;
15090 	}
15091 }
15092 
15093 /* verify safety of LD_ABS|LD_IND instructions:
15094  * - they can only appear in the programs where ctx == skb
15095  * - since they are wrappers of function calls, they scratch R1-R5 registers,
15096  *   preserve R6-R9, and store return value into R0
15097  *
15098  * Implicit input:
15099  *   ctx == skb == R6 == CTX
15100  *
15101  * Explicit input:
15102  *   SRC == any register
15103  *   IMM == 32-bit immediate
15104  *
15105  * Output:
15106  *   R0 - 8/16/32-bit skb data converted to cpu endianness
15107  */
15108 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
15109 {
15110 	struct bpf_reg_state *regs = cur_regs(env);
15111 	static const int ctx_reg = BPF_REG_6;
15112 	u8 mode = BPF_MODE(insn->code);
15113 	int i, err;
15114 
15115 	if (!may_access_skb(resolve_prog_type(env->prog))) {
15116 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
15117 		return -EINVAL;
15118 	}
15119 
15120 	if (!env->ops->gen_ld_abs) {
15121 		verbose(env, "bpf verifier is misconfigured\n");
15122 		return -EINVAL;
15123 	}
15124 
15125 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
15126 	    BPF_SIZE(insn->code) == BPF_DW ||
15127 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
15128 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
15129 		return -EINVAL;
15130 	}
15131 
15132 	/* check whether implicit source operand (register R6) is readable */
15133 	err = check_reg_arg(env, ctx_reg, SRC_OP);
15134 	if (err)
15135 		return err;
15136 
15137 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
15138 	 * gen_ld_abs() may terminate the program at runtime, leading to
15139 	 * reference leak.
15140 	 */
15141 	err = check_reference_leak(env, false);
15142 	if (err) {
15143 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
15144 		return err;
15145 	}
15146 
15147 	if (env->cur_state->active_lock.ptr) {
15148 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
15149 		return -EINVAL;
15150 	}
15151 
15152 	if (env->cur_state->active_rcu_lock) {
15153 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
15154 		return -EINVAL;
15155 	}
15156 
15157 	if (regs[ctx_reg].type != PTR_TO_CTX) {
15158 		verbose(env,
15159 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
15160 		return -EINVAL;
15161 	}
15162 
15163 	if (mode == BPF_IND) {
15164 		/* check explicit source operand */
15165 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
15166 		if (err)
15167 			return err;
15168 	}
15169 
15170 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
15171 	if (err < 0)
15172 		return err;
15173 
15174 	/* reset caller saved regs to unreadable */
15175 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
15176 		mark_reg_not_init(env, regs, caller_saved[i]);
15177 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
15178 	}
15179 
15180 	/* mark destination R0 register as readable, since it contains
15181 	 * the value fetched from the packet.
15182 	 * Already marked as written above.
15183 	 */
15184 	mark_reg_unknown(env, regs, BPF_REG_0);
15185 	/* ld_abs load up to 32-bit skb data. */
15186 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
15187 	return 0;
15188 }
15189 
15190 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
15191 {
15192 	const char *exit_ctx = "At program exit";
15193 	struct tnum enforce_attach_type_range = tnum_unknown;
15194 	const struct bpf_prog *prog = env->prog;
15195 	struct bpf_reg_state *reg;
15196 	struct bpf_retval_range range = retval_range(0, 1);
15197 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15198 	int err;
15199 	struct bpf_func_state *frame = env->cur_state->frame[0];
15200 	const bool is_subprog = frame->subprogno;
15201 
15202 	/* LSM and struct_ops func-ptr's return type could be "void" */
15203 	if (!is_subprog || frame->in_exception_callback_fn) {
15204 		switch (prog_type) {
15205 		case BPF_PROG_TYPE_LSM:
15206 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
15207 				/* See below, can be 0 or 0-1 depending on hook. */
15208 				break;
15209 			fallthrough;
15210 		case BPF_PROG_TYPE_STRUCT_OPS:
15211 			if (!prog->aux->attach_func_proto->type)
15212 				return 0;
15213 			break;
15214 		default:
15215 			break;
15216 		}
15217 	}
15218 
15219 	/* eBPF calling convention is such that R0 is used
15220 	 * to return the value from eBPF program.
15221 	 * Make sure that it's readable at this time
15222 	 * of bpf_exit, which means that program wrote
15223 	 * something into it earlier
15224 	 */
15225 	err = check_reg_arg(env, regno, SRC_OP);
15226 	if (err)
15227 		return err;
15228 
15229 	if (is_pointer_value(env, regno)) {
15230 		verbose(env, "R%d leaks addr as return value\n", regno);
15231 		return -EACCES;
15232 	}
15233 
15234 	reg = cur_regs(env) + regno;
15235 
15236 	if (frame->in_async_callback_fn) {
15237 		/* enforce return zero from async callbacks like timer */
15238 		exit_ctx = "At async callback return";
15239 		range = retval_range(0, 0);
15240 		goto enforce_retval;
15241 	}
15242 
15243 	if (is_subprog && !frame->in_exception_callback_fn) {
15244 		if (reg->type != SCALAR_VALUE) {
15245 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
15246 				regno, reg_type_str(env, reg->type));
15247 			return -EINVAL;
15248 		}
15249 		return 0;
15250 	}
15251 
15252 	switch (prog_type) {
15253 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15254 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15255 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15256 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
15257 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15258 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15259 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
15260 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15261 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
15262 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
15263 			range = retval_range(1, 1);
15264 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15265 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15266 			range = retval_range(0, 3);
15267 		break;
15268 	case BPF_PROG_TYPE_CGROUP_SKB:
15269 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15270 			range = retval_range(0, 3);
15271 			enforce_attach_type_range = tnum_range(2, 3);
15272 		}
15273 		break;
15274 	case BPF_PROG_TYPE_CGROUP_SOCK:
15275 	case BPF_PROG_TYPE_SOCK_OPS:
15276 	case BPF_PROG_TYPE_CGROUP_DEVICE:
15277 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15278 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15279 		break;
15280 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15281 		if (!env->prog->aux->attach_btf_id)
15282 			return 0;
15283 		range = retval_range(0, 0);
15284 		break;
15285 	case BPF_PROG_TYPE_TRACING:
15286 		switch (env->prog->expected_attach_type) {
15287 		case BPF_TRACE_FENTRY:
15288 		case BPF_TRACE_FEXIT:
15289 			range = retval_range(0, 0);
15290 			break;
15291 		case BPF_TRACE_RAW_TP:
15292 		case BPF_MODIFY_RETURN:
15293 			return 0;
15294 		case BPF_TRACE_ITER:
15295 			break;
15296 		default:
15297 			return -ENOTSUPP;
15298 		}
15299 		break;
15300 	case BPF_PROG_TYPE_SK_LOOKUP:
15301 		range = retval_range(SK_DROP, SK_PASS);
15302 		break;
15303 
15304 	case BPF_PROG_TYPE_LSM:
15305 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15306 			/* Regular BPF_PROG_TYPE_LSM programs can return
15307 			 * any value.
15308 			 */
15309 			return 0;
15310 		}
15311 		if (!env->prog->aux->attach_func_proto->type) {
15312 			/* Make sure programs that attach to void
15313 			 * hooks don't try to modify return value.
15314 			 */
15315 			range = retval_range(1, 1);
15316 		}
15317 		break;
15318 
15319 	case BPF_PROG_TYPE_NETFILTER:
15320 		range = retval_range(NF_DROP, NF_ACCEPT);
15321 		break;
15322 	case BPF_PROG_TYPE_EXT:
15323 		/* freplace program can return anything as its return value
15324 		 * depends on the to-be-replaced kernel func or bpf program.
15325 		 */
15326 	default:
15327 		return 0;
15328 	}
15329 
15330 enforce_retval:
15331 	if (reg->type != SCALAR_VALUE) {
15332 		verbose(env, "%s the register R%d is not a known value (%s)\n",
15333 			exit_ctx, regno, reg_type_str(env, reg->type));
15334 		return -EINVAL;
15335 	}
15336 
15337 	err = mark_chain_precision(env, regno);
15338 	if (err)
15339 		return err;
15340 
15341 	if (!retval_range_within(range, reg)) {
15342 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
15343 		if (!is_subprog &&
15344 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
15345 		    prog_type == BPF_PROG_TYPE_LSM &&
15346 		    !prog->aux->attach_func_proto->type)
15347 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15348 		return -EINVAL;
15349 	}
15350 
15351 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15352 	    tnum_in(enforce_attach_type_range, reg->var_off))
15353 		env->prog->enforce_expected_attach_type = 1;
15354 	return 0;
15355 }
15356 
15357 /* non-recursive DFS pseudo code
15358  * 1  procedure DFS-iterative(G,v):
15359  * 2      label v as discovered
15360  * 3      let S be a stack
15361  * 4      S.push(v)
15362  * 5      while S is not empty
15363  * 6            t <- S.peek()
15364  * 7            if t is what we're looking for:
15365  * 8                return t
15366  * 9            for all edges e in G.adjacentEdges(t) do
15367  * 10               if edge e is already labelled
15368  * 11                   continue with the next edge
15369  * 12               w <- G.adjacentVertex(t,e)
15370  * 13               if vertex w is not discovered and not explored
15371  * 14                   label e as tree-edge
15372  * 15                   label w as discovered
15373  * 16                   S.push(w)
15374  * 17                   continue at 5
15375  * 18               else if vertex w is discovered
15376  * 19                   label e as back-edge
15377  * 20               else
15378  * 21                   // vertex w is explored
15379  * 22                   label e as forward- or cross-edge
15380  * 23           label t as explored
15381  * 24           S.pop()
15382  *
15383  * convention:
15384  * 0x10 - discovered
15385  * 0x11 - discovered and fall-through edge labelled
15386  * 0x12 - discovered and fall-through and branch edges labelled
15387  * 0x20 - explored
15388  */
15389 
15390 enum {
15391 	DISCOVERED = 0x10,
15392 	EXPLORED = 0x20,
15393 	FALLTHROUGH = 1,
15394 	BRANCH = 2,
15395 };
15396 
15397 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15398 {
15399 	env->insn_aux_data[idx].prune_point = true;
15400 }
15401 
15402 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15403 {
15404 	return env->insn_aux_data[insn_idx].prune_point;
15405 }
15406 
15407 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15408 {
15409 	env->insn_aux_data[idx].force_checkpoint = true;
15410 }
15411 
15412 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15413 {
15414 	return env->insn_aux_data[insn_idx].force_checkpoint;
15415 }
15416 
15417 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15418 {
15419 	env->insn_aux_data[idx].calls_callback = true;
15420 }
15421 
15422 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15423 {
15424 	return env->insn_aux_data[insn_idx].calls_callback;
15425 }
15426 
15427 enum {
15428 	DONE_EXPLORING = 0,
15429 	KEEP_EXPLORING = 1,
15430 };
15431 
15432 /* t, w, e - match pseudo-code above:
15433  * t - index of current instruction
15434  * w - next instruction
15435  * e - edge
15436  */
15437 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15438 {
15439 	int *insn_stack = env->cfg.insn_stack;
15440 	int *insn_state = env->cfg.insn_state;
15441 
15442 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15443 		return DONE_EXPLORING;
15444 
15445 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15446 		return DONE_EXPLORING;
15447 
15448 	if (w < 0 || w >= env->prog->len) {
15449 		verbose_linfo(env, t, "%d: ", t);
15450 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15451 		return -EINVAL;
15452 	}
15453 
15454 	if (e == BRANCH) {
15455 		/* mark branch target for state pruning */
15456 		mark_prune_point(env, w);
15457 		mark_jmp_point(env, w);
15458 	}
15459 
15460 	if (insn_state[w] == 0) {
15461 		/* tree-edge */
15462 		insn_state[t] = DISCOVERED | e;
15463 		insn_state[w] = DISCOVERED;
15464 		if (env->cfg.cur_stack >= env->prog->len)
15465 			return -E2BIG;
15466 		insn_stack[env->cfg.cur_stack++] = w;
15467 		return KEEP_EXPLORING;
15468 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15469 		if (env->bpf_capable)
15470 			return DONE_EXPLORING;
15471 		verbose_linfo(env, t, "%d: ", t);
15472 		verbose_linfo(env, w, "%d: ", w);
15473 		verbose(env, "back-edge from insn %d to %d\n", t, w);
15474 		return -EINVAL;
15475 	} else if (insn_state[w] == EXPLORED) {
15476 		/* forward- or cross-edge */
15477 		insn_state[t] = DISCOVERED | e;
15478 	} else {
15479 		verbose(env, "insn state internal bug\n");
15480 		return -EFAULT;
15481 	}
15482 	return DONE_EXPLORING;
15483 }
15484 
15485 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15486 				struct bpf_verifier_env *env,
15487 				bool visit_callee)
15488 {
15489 	int ret, insn_sz;
15490 
15491 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15492 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15493 	if (ret)
15494 		return ret;
15495 
15496 	mark_prune_point(env, t + insn_sz);
15497 	/* when we exit from subprog, we need to record non-linear history */
15498 	mark_jmp_point(env, t + insn_sz);
15499 
15500 	if (visit_callee) {
15501 		mark_prune_point(env, t);
15502 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15503 	}
15504 	return ret;
15505 }
15506 
15507 /* Visits the instruction at index t and returns one of the following:
15508  *  < 0 - an error occurred
15509  *  DONE_EXPLORING - the instruction was fully explored
15510  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15511  */
15512 static int visit_insn(int t, struct bpf_verifier_env *env)
15513 {
15514 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15515 	int ret, off, insn_sz;
15516 
15517 	if (bpf_pseudo_func(insn))
15518 		return visit_func_call_insn(t, insns, env, true);
15519 
15520 	/* All non-branch instructions have a single fall-through edge. */
15521 	if (BPF_CLASS(insn->code) != BPF_JMP &&
15522 	    BPF_CLASS(insn->code) != BPF_JMP32) {
15523 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15524 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15525 	}
15526 
15527 	switch (BPF_OP(insn->code)) {
15528 	case BPF_EXIT:
15529 		return DONE_EXPLORING;
15530 
15531 	case BPF_CALL:
15532 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15533 			/* Mark this call insn as a prune point to trigger
15534 			 * is_state_visited() check before call itself is
15535 			 * processed by __check_func_call(). Otherwise new
15536 			 * async state will be pushed for further exploration.
15537 			 */
15538 			mark_prune_point(env, t);
15539 		/* For functions that invoke callbacks it is not known how many times
15540 		 * callback would be called. Verifier models callback calling functions
15541 		 * by repeatedly visiting callback bodies and returning to origin call
15542 		 * instruction.
15543 		 * In order to stop such iteration verifier needs to identify when a
15544 		 * state identical some state from a previous iteration is reached.
15545 		 * Check below forces creation of checkpoint before callback calling
15546 		 * instruction to allow search for such identical states.
15547 		 */
15548 		if (is_sync_callback_calling_insn(insn)) {
15549 			mark_calls_callback(env, t);
15550 			mark_force_checkpoint(env, t);
15551 			mark_prune_point(env, t);
15552 			mark_jmp_point(env, t);
15553 		}
15554 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15555 			struct bpf_kfunc_call_arg_meta meta;
15556 
15557 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15558 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15559 				mark_prune_point(env, t);
15560 				/* Checking and saving state checkpoints at iter_next() call
15561 				 * is crucial for fast convergence of open-coded iterator loop
15562 				 * logic, so we need to force it. If we don't do that,
15563 				 * is_state_visited() might skip saving a checkpoint, causing
15564 				 * unnecessarily long sequence of not checkpointed
15565 				 * instructions and jumps, leading to exhaustion of jump
15566 				 * history buffer, and potentially other undesired outcomes.
15567 				 * It is expected that with correct open-coded iterators
15568 				 * convergence will happen quickly, so we don't run a risk of
15569 				 * exhausting memory.
15570 				 */
15571 				mark_force_checkpoint(env, t);
15572 			}
15573 		}
15574 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15575 
15576 	case BPF_JA:
15577 		if (BPF_SRC(insn->code) != BPF_K)
15578 			return -EINVAL;
15579 
15580 		if (BPF_CLASS(insn->code) == BPF_JMP)
15581 			off = insn->off;
15582 		else
15583 			off = insn->imm;
15584 
15585 		/* unconditional jump with single edge */
15586 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15587 		if (ret)
15588 			return ret;
15589 
15590 		mark_prune_point(env, t + off + 1);
15591 		mark_jmp_point(env, t + off + 1);
15592 
15593 		return ret;
15594 
15595 	default:
15596 		/* conditional jump with two edges */
15597 		mark_prune_point(env, t);
15598 
15599 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15600 		if (ret)
15601 			return ret;
15602 
15603 		return push_insn(t, t + insn->off + 1, BRANCH, env);
15604 	}
15605 }
15606 
15607 /* non-recursive depth-first-search to detect loops in BPF program
15608  * loop == back-edge in directed graph
15609  */
15610 static int check_cfg(struct bpf_verifier_env *env)
15611 {
15612 	int insn_cnt = env->prog->len;
15613 	int *insn_stack, *insn_state;
15614 	int ex_insn_beg, i, ret = 0;
15615 	bool ex_done = false;
15616 
15617 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15618 	if (!insn_state)
15619 		return -ENOMEM;
15620 
15621 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15622 	if (!insn_stack) {
15623 		kvfree(insn_state);
15624 		return -ENOMEM;
15625 	}
15626 
15627 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15628 	insn_stack[0] = 0; /* 0 is the first instruction */
15629 	env->cfg.cur_stack = 1;
15630 
15631 walk_cfg:
15632 	while (env->cfg.cur_stack > 0) {
15633 		int t = insn_stack[env->cfg.cur_stack - 1];
15634 
15635 		ret = visit_insn(t, env);
15636 		switch (ret) {
15637 		case DONE_EXPLORING:
15638 			insn_state[t] = EXPLORED;
15639 			env->cfg.cur_stack--;
15640 			break;
15641 		case KEEP_EXPLORING:
15642 			break;
15643 		default:
15644 			if (ret > 0) {
15645 				verbose(env, "visit_insn internal bug\n");
15646 				ret = -EFAULT;
15647 			}
15648 			goto err_free;
15649 		}
15650 	}
15651 
15652 	if (env->cfg.cur_stack < 0) {
15653 		verbose(env, "pop stack internal bug\n");
15654 		ret = -EFAULT;
15655 		goto err_free;
15656 	}
15657 
15658 	if (env->exception_callback_subprog && !ex_done) {
15659 		ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
15660 
15661 		insn_state[ex_insn_beg] = DISCOVERED;
15662 		insn_stack[0] = ex_insn_beg;
15663 		env->cfg.cur_stack = 1;
15664 		ex_done = true;
15665 		goto walk_cfg;
15666 	}
15667 
15668 	for (i = 0; i < insn_cnt; i++) {
15669 		struct bpf_insn *insn = &env->prog->insnsi[i];
15670 
15671 		if (insn_state[i] != EXPLORED) {
15672 			verbose(env, "unreachable insn %d\n", i);
15673 			ret = -EINVAL;
15674 			goto err_free;
15675 		}
15676 		if (bpf_is_ldimm64(insn)) {
15677 			if (insn_state[i + 1] != 0) {
15678 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15679 				ret = -EINVAL;
15680 				goto err_free;
15681 			}
15682 			i++; /* skip second half of ldimm64 */
15683 		}
15684 	}
15685 	ret = 0; /* cfg looks good */
15686 
15687 err_free:
15688 	kvfree(insn_state);
15689 	kvfree(insn_stack);
15690 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
15691 	return ret;
15692 }
15693 
15694 static int check_abnormal_return(struct bpf_verifier_env *env)
15695 {
15696 	int i;
15697 
15698 	for (i = 1; i < env->subprog_cnt; i++) {
15699 		if (env->subprog_info[i].has_ld_abs) {
15700 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15701 			return -EINVAL;
15702 		}
15703 		if (env->subprog_info[i].has_tail_call) {
15704 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15705 			return -EINVAL;
15706 		}
15707 	}
15708 	return 0;
15709 }
15710 
15711 /* The minimum supported BTF func info size */
15712 #define MIN_BPF_FUNCINFO_SIZE	8
15713 #define MAX_FUNCINFO_REC_SIZE	252
15714 
15715 static int check_btf_func_early(struct bpf_verifier_env *env,
15716 				const union bpf_attr *attr,
15717 				bpfptr_t uattr)
15718 {
15719 	u32 krec_size = sizeof(struct bpf_func_info);
15720 	const struct btf_type *type, *func_proto;
15721 	u32 i, nfuncs, urec_size, min_size;
15722 	struct bpf_func_info *krecord;
15723 	struct bpf_prog *prog;
15724 	const struct btf *btf;
15725 	u32 prev_offset = 0;
15726 	bpfptr_t urecord;
15727 	int ret = -ENOMEM;
15728 
15729 	nfuncs = attr->func_info_cnt;
15730 	if (!nfuncs) {
15731 		if (check_abnormal_return(env))
15732 			return -EINVAL;
15733 		return 0;
15734 	}
15735 
15736 	urec_size = attr->func_info_rec_size;
15737 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15738 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
15739 	    urec_size % sizeof(u32)) {
15740 		verbose(env, "invalid func info rec size %u\n", urec_size);
15741 		return -EINVAL;
15742 	}
15743 
15744 	prog = env->prog;
15745 	btf = prog->aux->btf;
15746 
15747 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15748 	min_size = min_t(u32, krec_size, urec_size);
15749 
15750 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15751 	if (!krecord)
15752 		return -ENOMEM;
15753 
15754 	for (i = 0; i < nfuncs; i++) {
15755 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15756 		if (ret) {
15757 			if (ret == -E2BIG) {
15758 				verbose(env, "nonzero tailing record in func info");
15759 				/* set the size kernel expects so loader can zero
15760 				 * out the rest of the record.
15761 				 */
15762 				if (copy_to_bpfptr_offset(uattr,
15763 							  offsetof(union bpf_attr, func_info_rec_size),
15764 							  &min_size, sizeof(min_size)))
15765 					ret = -EFAULT;
15766 			}
15767 			goto err_free;
15768 		}
15769 
15770 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15771 			ret = -EFAULT;
15772 			goto err_free;
15773 		}
15774 
15775 		/* check insn_off */
15776 		ret = -EINVAL;
15777 		if (i == 0) {
15778 			if (krecord[i].insn_off) {
15779 				verbose(env,
15780 					"nonzero insn_off %u for the first func info record",
15781 					krecord[i].insn_off);
15782 				goto err_free;
15783 			}
15784 		} else if (krecord[i].insn_off <= prev_offset) {
15785 			verbose(env,
15786 				"same or smaller insn offset (%u) than previous func info record (%u)",
15787 				krecord[i].insn_off, prev_offset);
15788 			goto err_free;
15789 		}
15790 
15791 		/* check type_id */
15792 		type = btf_type_by_id(btf, krecord[i].type_id);
15793 		if (!type || !btf_type_is_func(type)) {
15794 			verbose(env, "invalid type id %d in func info",
15795 				krecord[i].type_id);
15796 			goto err_free;
15797 		}
15798 
15799 		func_proto = btf_type_by_id(btf, type->type);
15800 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15801 			/* btf_func_check() already verified it during BTF load */
15802 			goto err_free;
15803 
15804 		prev_offset = krecord[i].insn_off;
15805 		bpfptr_add(&urecord, urec_size);
15806 	}
15807 
15808 	prog->aux->func_info = krecord;
15809 	prog->aux->func_info_cnt = nfuncs;
15810 	return 0;
15811 
15812 err_free:
15813 	kvfree(krecord);
15814 	return ret;
15815 }
15816 
15817 static int check_btf_func(struct bpf_verifier_env *env,
15818 			  const union bpf_attr *attr,
15819 			  bpfptr_t uattr)
15820 {
15821 	const struct btf_type *type, *func_proto, *ret_type;
15822 	u32 i, nfuncs, urec_size;
15823 	struct bpf_func_info *krecord;
15824 	struct bpf_func_info_aux *info_aux = NULL;
15825 	struct bpf_prog *prog;
15826 	const struct btf *btf;
15827 	bpfptr_t urecord;
15828 	bool scalar_return;
15829 	int ret = -ENOMEM;
15830 
15831 	nfuncs = attr->func_info_cnt;
15832 	if (!nfuncs) {
15833 		if (check_abnormal_return(env))
15834 			return -EINVAL;
15835 		return 0;
15836 	}
15837 	if (nfuncs != env->subprog_cnt) {
15838 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15839 		return -EINVAL;
15840 	}
15841 
15842 	urec_size = attr->func_info_rec_size;
15843 
15844 	prog = env->prog;
15845 	btf = prog->aux->btf;
15846 
15847 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15848 
15849 	krecord = prog->aux->func_info;
15850 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15851 	if (!info_aux)
15852 		return -ENOMEM;
15853 
15854 	for (i = 0; i < nfuncs; i++) {
15855 		/* check insn_off */
15856 		ret = -EINVAL;
15857 
15858 		if (env->subprog_info[i].start != krecord[i].insn_off) {
15859 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15860 			goto err_free;
15861 		}
15862 
15863 		/* Already checked type_id */
15864 		type = btf_type_by_id(btf, krecord[i].type_id);
15865 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15866 		/* Already checked func_proto */
15867 		func_proto = btf_type_by_id(btf, type->type);
15868 
15869 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15870 		scalar_return =
15871 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15872 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15873 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15874 			goto err_free;
15875 		}
15876 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15877 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15878 			goto err_free;
15879 		}
15880 
15881 		bpfptr_add(&urecord, urec_size);
15882 	}
15883 
15884 	prog->aux->func_info_aux = info_aux;
15885 	return 0;
15886 
15887 err_free:
15888 	kfree(info_aux);
15889 	return ret;
15890 }
15891 
15892 static void adjust_btf_func(struct bpf_verifier_env *env)
15893 {
15894 	struct bpf_prog_aux *aux = env->prog->aux;
15895 	int i;
15896 
15897 	if (!aux->func_info)
15898 		return;
15899 
15900 	/* func_info is not available for hidden subprogs */
15901 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
15902 		aux->func_info[i].insn_off = env->subprog_info[i].start;
15903 }
15904 
15905 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
15906 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
15907 
15908 static int check_btf_line(struct bpf_verifier_env *env,
15909 			  const union bpf_attr *attr,
15910 			  bpfptr_t uattr)
15911 {
15912 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15913 	struct bpf_subprog_info *sub;
15914 	struct bpf_line_info *linfo;
15915 	struct bpf_prog *prog;
15916 	const struct btf *btf;
15917 	bpfptr_t ulinfo;
15918 	int err;
15919 
15920 	nr_linfo = attr->line_info_cnt;
15921 	if (!nr_linfo)
15922 		return 0;
15923 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15924 		return -EINVAL;
15925 
15926 	rec_size = attr->line_info_rec_size;
15927 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15928 	    rec_size > MAX_LINEINFO_REC_SIZE ||
15929 	    rec_size & (sizeof(u32) - 1))
15930 		return -EINVAL;
15931 
15932 	/* Need to zero it in case the userspace may
15933 	 * pass in a smaller bpf_line_info object.
15934 	 */
15935 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15936 			 GFP_KERNEL | __GFP_NOWARN);
15937 	if (!linfo)
15938 		return -ENOMEM;
15939 
15940 	prog = env->prog;
15941 	btf = prog->aux->btf;
15942 
15943 	s = 0;
15944 	sub = env->subprog_info;
15945 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15946 	expected_size = sizeof(struct bpf_line_info);
15947 	ncopy = min_t(u32, expected_size, rec_size);
15948 	for (i = 0; i < nr_linfo; i++) {
15949 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15950 		if (err) {
15951 			if (err == -E2BIG) {
15952 				verbose(env, "nonzero tailing record in line_info");
15953 				if (copy_to_bpfptr_offset(uattr,
15954 							  offsetof(union bpf_attr, line_info_rec_size),
15955 							  &expected_size, sizeof(expected_size)))
15956 					err = -EFAULT;
15957 			}
15958 			goto err_free;
15959 		}
15960 
15961 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15962 			err = -EFAULT;
15963 			goto err_free;
15964 		}
15965 
15966 		/*
15967 		 * Check insn_off to ensure
15968 		 * 1) strictly increasing AND
15969 		 * 2) bounded by prog->len
15970 		 *
15971 		 * The linfo[0].insn_off == 0 check logically falls into
15972 		 * the later "missing bpf_line_info for func..." case
15973 		 * because the first linfo[0].insn_off must be the
15974 		 * first sub also and the first sub must have
15975 		 * subprog_info[0].start == 0.
15976 		 */
15977 		if ((i && linfo[i].insn_off <= prev_offset) ||
15978 		    linfo[i].insn_off >= prog->len) {
15979 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15980 				i, linfo[i].insn_off, prev_offset,
15981 				prog->len);
15982 			err = -EINVAL;
15983 			goto err_free;
15984 		}
15985 
15986 		if (!prog->insnsi[linfo[i].insn_off].code) {
15987 			verbose(env,
15988 				"Invalid insn code at line_info[%u].insn_off\n",
15989 				i);
15990 			err = -EINVAL;
15991 			goto err_free;
15992 		}
15993 
15994 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15995 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15996 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15997 			err = -EINVAL;
15998 			goto err_free;
15999 		}
16000 
16001 		if (s != env->subprog_cnt) {
16002 			if (linfo[i].insn_off == sub[s].start) {
16003 				sub[s].linfo_idx = i;
16004 				s++;
16005 			} else if (sub[s].start < linfo[i].insn_off) {
16006 				verbose(env, "missing bpf_line_info for func#%u\n", s);
16007 				err = -EINVAL;
16008 				goto err_free;
16009 			}
16010 		}
16011 
16012 		prev_offset = linfo[i].insn_off;
16013 		bpfptr_add(&ulinfo, rec_size);
16014 	}
16015 
16016 	if (s != env->subprog_cnt) {
16017 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
16018 			env->subprog_cnt - s, s);
16019 		err = -EINVAL;
16020 		goto err_free;
16021 	}
16022 
16023 	prog->aux->linfo = linfo;
16024 	prog->aux->nr_linfo = nr_linfo;
16025 
16026 	return 0;
16027 
16028 err_free:
16029 	kvfree(linfo);
16030 	return err;
16031 }
16032 
16033 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
16034 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
16035 
16036 static int check_core_relo(struct bpf_verifier_env *env,
16037 			   const union bpf_attr *attr,
16038 			   bpfptr_t uattr)
16039 {
16040 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
16041 	struct bpf_core_relo core_relo = {};
16042 	struct bpf_prog *prog = env->prog;
16043 	const struct btf *btf = prog->aux->btf;
16044 	struct bpf_core_ctx ctx = {
16045 		.log = &env->log,
16046 		.btf = btf,
16047 	};
16048 	bpfptr_t u_core_relo;
16049 	int err;
16050 
16051 	nr_core_relo = attr->core_relo_cnt;
16052 	if (!nr_core_relo)
16053 		return 0;
16054 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
16055 		return -EINVAL;
16056 
16057 	rec_size = attr->core_relo_rec_size;
16058 	if (rec_size < MIN_CORE_RELO_SIZE ||
16059 	    rec_size > MAX_CORE_RELO_SIZE ||
16060 	    rec_size % sizeof(u32))
16061 		return -EINVAL;
16062 
16063 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
16064 	expected_size = sizeof(struct bpf_core_relo);
16065 	ncopy = min_t(u32, expected_size, rec_size);
16066 
16067 	/* Unlike func_info and line_info, copy and apply each CO-RE
16068 	 * relocation record one at a time.
16069 	 */
16070 	for (i = 0; i < nr_core_relo; i++) {
16071 		/* future proofing when sizeof(bpf_core_relo) changes */
16072 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
16073 		if (err) {
16074 			if (err == -E2BIG) {
16075 				verbose(env, "nonzero tailing record in core_relo");
16076 				if (copy_to_bpfptr_offset(uattr,
16077 							  offsetof(union bpf_attr, core_relo_rec_size),
16078 							  &expected_size, sizeof(expected_size)))
16079 					err = -EFAULT;
16080 			}
16081 			break;
16082 		}
16083 
16084 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
16085 			err = -EFAULT;
16086 			break;
16087 		}
16088 
16089 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
16090 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
16091 				i, core_relo.insn_off, prog->len);
16092 			err = -EINVAL;
16093 			break;
16094 		}
16095 
16096 		err = bpf_core_apply(&ctx, &core_relo, i,
16097 				     &prog->insnsi[core_relo.insn_off / 8]);
16098 		if (err)
16099 			break;
16100 		bpfptr_add(&u_core_relo, rec_size);
16101 	}
16102 	return err;
16103 }
16104 
16105 static int check_btf_info_early(struct bpf_verifier_env *env,
16106 				const union bpf_attr *attr,
16107 				bpfptr_t uattr)
16108 {
16109 	struct btf *btf;
16110 	int err;
16111 
16112 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
16113 		if (check_abnormal_return(env))
16114 			return -EINVAL;
16115 		return 0;
16116 	}
16117 
16118 	btf = btf_get_by_fd(attr->prog_btf_fd);
16119 	if (IS_ERR(btf))
16120 		return PTR_ERR(btf);
16121 	if (btf_is_kernel(btf)) {
16122 		btf_put(btf);
16123 		return -EACCES;
16124 	}
16125 	env->prog->aux->btf = btf;
16126 
16127 	err = check_btf_func_early(env, attr, uattr);
16128 	if (err)
16129 		return err;
16130 	return 0;
16131 }
16132 
16133 static int check_btf_info(struct bpf_verifier_env *env,
16134 			  const union bpf_attr *attr,
16135 			  bpfptr_t uattr)
16136 {
16137 	int err;
16138 
16139 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
16140 		if (check_abnormal_return(env))
16141 			return -EINVAL;
16142 		return 0;
16143 	}
16144 
16145 	err = check_btf_func(env, attr, uattr);
16146 	if (err)
16147 		return err;
16148 
16149 	err = check_btf_line(env, attr, uattr);
16150 	if (err)
16151 		return err;
16152 
16153 	err = check_core_relo(env, attr, uattr);
16154 	if (err)
16155 		return err;
16156 
16157 	return 0;
16158 }
16159 
16160 /* check %cur's range satisfies %old's */
16161 static bool range_within(struct bpf_reg_state *old,
16162 			 struct bpf_reg_state *cur)
16163 {
16164 	return old->umin_value <= cur->umin_value &&
16165 	       old->umax_value >= cur->umax_value &&
16166 	       old->smin_value <= cur->smin_value &&
16167 	       old->smax_value >= cur->smax_value &&
16168 	       old->u32_min_value <= cur->u32_min_value &&
16169 	       old->u32_max_value >= cur->u32_max_value &&
16170 	       old->s32_min_value <= cur->s32_min_value &&
16171 	       old->s32_max_value >= cur->s32_max_value;
16172 }
16173 
16174 /* If in the old state two registers had the same id, then they need to have
16175  * the same id in the new state as well.  But that id could be different from
16176  * the old state, so we need to track the mapping from old to new ids.
16177  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
16178  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
16179  * regs with a different old id could still have new id 9, we don't care about
16180  * that.
16181  * So we look through our idmap to see if this old id has been seen before.  If
16182  * so, we require the new id to match; otherwise, we add the id pair to the map.
16183  */
16184 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16185 {
16186 	struct bpf_id_pair *map = idmap->map;
16187 	unsigned int i;
16188 
16189 	/* either both IDs should be set or both should be zero */
16190 	if (!!old_id != !!cur_id)
16191 		return false;
16192 
16193 	if (old_id == 0) /* cur_id == 0 as well */
16194 		return true;
16195 
16196 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
16197 		if (!map[i].old) {
16198 			/* Reached an empty slot; haven't seen this id before */
16199 			map[i].old = old_id;
16200 			map[i].cur = cur_id;
16201 			return true;
16202 		}
16203 		if (map[i].old == old_id)
16204 			return map[i].cur == cur_id;
16205 		if (map[i].cur == cur_id)
16206 			return false;
16207 	}
16208 	/* We ran out of idmap slots, which should be impossible */
16209 	WARN_ON_ONCE(1);
16210 	return false;
16211 }
16212 
16213 /* Similar to check_ids(), but allocate a unique temporary ID
16214  * for 'old_id' or 'cur_id' of zero.
16215  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
16216  */
16217 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16218 {
16219 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
16220 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
16221 
16222 	return check_ids(old_id, cur_id, idmap);
16223 }
16224 
16225 static void clean_func_state(struct bpf_verifier_env *env,
16226 			     struct bpf_func_state *st)
16227 {
16228 	enum bpf_reg_liveness live;
16229 	int i, j;
16230 
16231 	for (i = 0; i < BPF_REG_FP; i++) {
16232 		live = st->regs[i].live;
16233 		/* liveness must not touch this register anymore */
16234 		st->regs[i].live |= REG_LIVE_DONE;
16235 		if (!(live & REG_LIVE_READ))
16236 			/* since the register is unused, clear its state
16237 			 * to make further comparison simpler
16238 			 */
16239 			__mark_reg_not_init(env, &st->regs[i]);
16240 	}
16241 
16242 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
16243 		live = st->stack[i].spilled_ptr.live;
16244 		/* liveness must not touch this stack slot anymore */
16245 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
16246 		if (!(live & REG_LIVE_READ)) {
16247 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
16248 			for (j = 0; j < BPF_REG_SIZE; j++)
16249 				st->stack[i].slot_type[j] = STACK_INVALID;
16250 		}
16251 	}
16252 }
16253 
16254 static void clean_verifier_state(struct bpf_verifier_env *env,
16255 				 struct bpf_verifier_state *st)
16256 {
16257 	int i;
16258 
16259 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
16260 		/* all regs in this state in all frames were already marked */
16261 		return;
16262 
16263 	for (i = 0; i <= st->curframe; i++)
16264 		clean_func_state(env, st->frame[i]);
16265 }
16266 
16267 /* the parentage chains form a tree.
16268  * the verifier states are added to state lists at given insn and
16269  * pushed into state stack for future exploration.
16270  * when the verifier reaches bpf_exit insn some of the verifer states
16271  * stored in the state lists have their final liveness state already,
16272  * but a lot of states will get revised from liveness point of view when
16273  * the verifier explores other branches.
16274  * Example:
16275  * 1: r0 = 1
16276  * 2: if r1 == 100 goto pc+1
16277  * 3: r0 = 2
16278  * 4: exit
16279  * when the verifier reaches exit insn the register r0 in the state list of
16280  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
16281  * of insn 2 and goes exploring further. At the insn 4 it will walk the
16282  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
16283  *
16284  * Since the verifier pushes the branch states as it sees them while exploring
16285  * the program the condition of walking the branch instruction for the second
16286  * time means that all states below this branch were already explored and
16287  * their final liveness marks are already propagated.
16288  * Hence when the verifier completes the search of state list in is_state_visited()
16289  * we can call this clean_live_states() function to mark all liveness states
16290  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
16291  * will not be used.
16292  * This function also clears the registers and stack for states that !READ
16293  * to simplify state merging.
16294  *
16295  * Important note here that walking the same branch instruction in the callee
16296  * doesn't meant that the states are DONE. The verifier has to compare
16297  * the callsites
16298  */
16299 static void clean_live_states(struct bpf_verifier_env *env, int insn,
16300 			      struct bpf_verifier_state *cur)
16301 {
16302 	struct bpf_verifier_state_list *sl;
16303 
16304 	sl = *explored_state(env, insn);
16305 	while (sl) {
16306 		if (sl->state.branches)
16307 			goto next;
16308 		if (sl->state.insn_idx != insn ||
16309 		    !same_callsites(&sl->state, cur))
16310 			goto next;
16311 		clean_verifier_state(env, &sl->state);
16312 next:
16313 		sl = sl->next;
16314 	}
16315 }
16316 
16317 static bool regs_exact(const struct bpf_reg_state *rold,
16318 		       const struct bpf_reg_state *rcur,
16319 		       struct bpf_idmap *idmap)
16320 {
16321 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16322 	       check_ids(rold->id, rcur->id, idmap) &&
16323 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16324 }
16325 
16326 /* Returns true if (rold safe implies rcur safe) */
16327 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
16328 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
16329 {
16330 	if (exact)
16331 		return regs_exact(rold, rcur, idmap);
16332 
16333 	if (!(rold->live & REG_LIVE_READ))
16334 		/* explored state didn't use this */
16335 		return true;
16336 	if (rold->type == NOT_INIT)
16337 		/* explored state can't have used this */
16338 		return true;
16339 	if (rcur->type == NOT_INIT)
16340 		return false;
16341 
16342 	/* Enforce that register types have to match exactly, including their
16343 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16344 	 * rule.
16345 	 *
16346 	 * One can make a point that using a pointer register as unbounded
16347 	 * SCALAR would be technically acceptable, but this could lead to
16348 	 * pointer leaks because scalars are allowed to leak while pointers
16349 	 * are not. We could make this safe in special cases if root is
16350 	 * calling us, but it's probably not worth the hassle.
16351 	 *
16352 	 * Also, register types that are *not* MAYBE_NULL could technically be
16353 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16354 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16355 	 * to the same map).
16356 	 * However, if the old MAYBE_NULL register then got NULL checked,
16357 	 * doing so could have affected others with the same id, and we can't
16358 	 * check for that because we lost the id when we converted to
16359 	 * a non-MAYBE_NULL variant.
16360 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
16361 	 * non-MAYBE_NULL registers as well.
16362 	 */
16363 	if (rold->type != rcur->type)
16364 		return false;
16365 
16366 	switch (base_type(rold->type)) {
16367 	case SCALAR_VALUE:
16368 		if (env->explore_alu_limits) {
16369 			/* explore_alu_limits disables tnum_in() and range_within()
16370 			 * logic and requires everything to be strict
16371 			 */
16372 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16373 			       check_scalar_ids(rold->id, rcur->id, idmap);
16374 		}
16375 		if (!rold->precise)
16376 			return true;
16377 		/* Why check_ids() for scalar registers?
16378 		 *
16379 		 * Consider the following BPF code:
16380 		 *   1: r6 = ... unbound scalar, ID=a ...
16381 		 *   2: r7 = ... unbound scalar, ID=b ...
16382 		 *   3: if (r6 > r7) goto +1
16383 		 *   4: r6 = r7
16384 		 *   5: if (r6 > X) goto ...
16385 		 *   6: ... memory operation using r7 ...
16386 		 *
16387 		 * First verification path is [1-6]:
16388 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16389 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16390 		 *   r7 <= X, because r6 and r7 share same id.
16391 		 * Next verification path is [1-4, 6].
16392 		 *
16393 		 * Instruction (6) would be reached in two states:
16394 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16395 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16396 		 *
16397 		 * Use check_ids() to distinguish these states.
16398 		 * ---
16399 		 * Also verify that new value satisfies old value range knowledge.
16400 		 */
16401 		return range_within(rold, rcur) &&
16402 		       tnum_in(rold->var_off, rcur->var_off) &&
16403 		       check_scalar_ids(rold->id, rcur->id, idmap);
16404 	case PTR_TO_MAP_KEY:
16405 	case PTR_TO_MAP_VALUE:
16406 	case PTR_TO_MEM:
16407 	case PTR_TO_BUF:
16408 	case PTR_TO_TP_BUFFER:
16409 		/* If the new min/max/var_off satisfy the old ones and
16410 		 * everything else matches, we are OK.
16411 		 */
16412 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16413 		       range_within(rold, rcur) &&
16414 		       tnum_in(rold->var_off, rcur->var_off) &&
16415 		       check_ids(rold->id, rcur->id, idmap) &&
16416 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16417 	case PTR_TO_PACKET_META:
16418 	case PTR_TO_PACKET:
16419 		/* We must have at least as much range as the old ptr
16420 		 * did, so that any accesses which were safe before are
16421 		 * still safe.  This is true even if old range < old off,
16422 		 * since someone could have accessed through (ptr - k), or
16423 		 * even done ptr -= k in a register, to get a safe access.
16424 		 */
16425 		if (rold->range > rcur->range)
16426 			return false;
16427 		/* If the offsets don't match, we can't trust our alignment;
16428 		 * nor can we be sure that we won't fall out of range.
16429 		 */
16430 		if (rold->off != rcur->off)
16431 			return false;
16432 		/* id relations must be preserved */
16433 		if (!check_ids(rold->id, rcur->id, idmap))
16434 			return false;
16435 		/* new val must satisfy old val knowledge */
16436 		return range_within(rold, rcur) &&
16437 		       tnum_in(rold->var_off, rcur->var_off);
16438 	case PTR_TO_STACK:
16439 		/* two stack pointers are equal only if they're pointing to
16440 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16441 		 */
16442 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16443 	default:
16444 		return regs_exact(rold, rcur, idmap);
16445 	}
16446 }
16447 
16448 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16449 		      struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16450 {
16451 	int i, spi;
16452 
16453 	/* walk slots of the explored stack and ignore any additional
16454 	 * slots in the current stack, since explored(safe) state
16455 	 * didn't use them
16456 	 */
16457 	for (i = 0; i < old->allocated_stack; i++) {
16458 		struct bpf_reg_state *old_reg, *cur_reg;
16459 
16460 		spi = i / BPF_REG_SIZE;
16461 
16462 		if (exact &&
16463 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16464 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16465 			return false;
16466 
16467 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16468 			i += BPF_REG_SIZE - 1;
16469 			/* explored state didn't use this */
16470 			continue;
16471 		}
16472 
16473 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16474 			continue;
16475 
16476 		if (env->allow_uninit_stack &&
16477 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16478 			continue;
16479 
16480 		/* explored stack has more populated slots than current stack
16481 		 * and these slots were used
16482 		 */
16483 		if (i >= cur->allocated_stack)
16484 			return false;
16485 
16486 		/* if old state was safe with misc data in the stack
16487 		 * it will be safe with zero-initialized stack.
16488 		 * The opposite is not true
16489 		 */
16490 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16491 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16492 			continue;
16493 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16494 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16495 			/* Ex: old explored (safe) state has STACK_SPILL in
16496 			 * this stack slot, but current has STACK_MISC ->
16497 			 * this verifier states are not equivalent,
16498 			 * return false to continue verification of this path
16499 			 */
16500 			return false;
16501 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16502 			continue;
16503 		/* Both old and cur are having same slot_type */
16504 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16505 		case STACK_SPILL:
16506 			/* when explored and current stack slot are both storing
16507 			 * spilled registers, check that stored pointers types
16508 			 * are the same as well.
16509 			 * Ex: explored safe path could have stored
16510 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16511 			 * but current path has stored:
16512 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16513 			 * such verifier states are not equivalent.
16514 			 * return false to continue verification of this path
16515 			 */
16516 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16517 				     &cur->stack[spi].spilled_ptr, idmap, exact))
16518 				return false;
16519 			break;
16520 		case STACK_DYNPTR:
16521 			old_reg = &old->stack[spi].spilled_ptr;
16522 			cur_reg = &cur->stack[spi].spilled_ptr;
16523 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16524 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16525 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16526 				return false;
16527 			break;
16528 		case STACK_ITER:
16529 			old_reg = &old->stack[spi].spilled_ptr;
16530 			cur_reg = &cur->stack[spi].spilled_ptr;
16531 			/* iter.depth is not compared between states as it
16532 			 * doesn't matter for correctness and would otherwise
16533 			 * prevent convergence; we maintain it only to prevent
16534 			 * infinite loop check triggering, see
16535 			 * iter_active_depths_differ()
16536 			 */
16537 			if (old_reg->iter.btf != cur_reg->iter.btf ||
16538 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16539 			    old_reg->iter.state != cur_reg->iter.state ||
16540 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16541 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16542 				return false;
16543 			break;
16544 		case STACK_MISC:
16545 		case STACK_ZERO:
16546 		case STACK_INVALID:
16547 			continue;
16548 		/* Ensure that new unhandled slot types return false by default */
16549 		default:
16550 			return false;
16551 		}
16552 	}
16553 	return true;
16554 }
16555 
16556 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16557 		    struct bpf_idmap *idmap)
16558 {
16559 	int i;
16560 
16561 	if (old->acquired_refs != cur->acquired_refs)
16562 		return false;
16563 
16564 	for (i = 0; i < old->acquired_refs; i++) {
16565 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16566 			return false;
16567 	}
16568 
16569 	return true;
16570 }
16571 
16572 /* compare two verifier states
16573  *
16574  * all states stored in state_list are known to be valid, since
16575  * verifier reached 'bpf_exit' instruction through them
16576  *
16577  * this function is called when verifier exploring different branches of
16578  * execution popped from the state stack. If it sees an old state that has
16579  * more strict register state and more strict stack state then this execution
16580  * branch doesn't need to be explored further, since verifier already
16581  * concluded that more strict state leads to valid finish.
16582  *
16583  * Therefore two states are equivalent if register state is more conservative
16584  * and explored stack state is more conservative than the current one.
16585  * Example:
16586  *       explored                   current
16587  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16588  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16589  *
16590  * In other words if current stack state (one being explored) has more
16591  * valid slots than old one that already passed validation, it means
16592  * the verifier can stop exploring and conclude that current state is valid too
16593  *
16594  * Similarly with registers. If explored state has register type as invalid
16595  * whereas register type in current state is meaningful, it means that
16596  * the current state will reach 'bpf_exit' instruction safely
16597  */
16598 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16599 			      struct bpf_func_state *cur, bool exact)
16600 {
16601 	int i;
16602 
16603 	for (i = 0; i < MAX_BPF_REG; i++)
16604 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
16605 			     &env->idmap_scratch, exact))
16606 			return false;
16607 
16608 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16609 		return false;
16610 
16611 	if (!refsafe(old, cur, &env->idmap_scratch))
16612 		return false;
16613 
16614 	return true;
16615 }
16616 
16617 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16618 {
16619 	env->idmap_scratch.tmp_id_gen = env->id_gen;
16620 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16621 }
16622 
16623 static bool states_equal(struct bpf_verifier_env *env,
16624 			 struct bpf_verifier_state *old,
16625 			 struct bpf_verifier_state *cur,
16626 			 bool exact)
16627 {
16628 	int i;
16629 
16630 	if (old->curframe != cur->curframe)
16631 		return false;
16632 
16633 	reset_idmap_scratch(env);
16634 
16635 	/* Verification state from speculative execution simulation
16636 	 * must never prune a non-speculative execution one.
16637 	 */
16638 	if (old->speculative && !cur->speculative)
16639 		return false;
16640 
16641 	if (old->active_lock.ptr != cur->active_lock.ptr)
16642 		return false;
16643 
16644 	/* Old and cur active_lock's have to be either both present
16645 	 * or both absent.
16646 	 */
16647 	if (!!old->active_lock.id != !!cur->active_lock.id)
16648 		return false;
16649 
16650 	if (old->active_lock.id &&
16651 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16652 		return false;
16653 
16654 	if (old->active_rcu_lock != cur->active_rcu_lock)
16655 		return false;
16656 
16657 	/* for states to be equal callsites have to be the same
16658 	 * and all frame states need to be equivalent
16659 	 */
16660 	for (i = 0; i <= old->curframe; i++) {
16661 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
16662 			return false;
16663 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16664 			return false;
16665 	}
16666 	return true;
16667 }
16668 
16669 /* Return 0 if no propagation happened. Return negative error code if error
16670  * happened. Otherwise, return the propagated bit.
16671  */
16672 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16673 				  struct bpf_reg_state *reg,
16674 				  struct bpf_reg_state *parent_reg)
16675 {
16676 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16677 	u8 flag = reg->live & REG_LIVE_READ;
16678 	int err;
16679 
16680 	/* When comes here, read flags of PARENT_REG or REG could be any of
16681 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16682 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16683 	 */
16684 	if (parent_flag == REG_LIVE_READ64 ||
16685 	    /* Or if there is no read flag from REG. */
16686 	    !flag ||
16687 	    /* Or if the read flag from REG is the same as PARENT_REG. */
16688 	    parent_flag == flag)
16689 		return 0;
16690 
16691 	err = mark_reg_read(env, reg, parent_reg, flag);
16692 	if (err)
16693 		return err;
16694 
16695 	return flag;
16696 }
16697 
16698 /* A write screens off any subsequent reads; but write marks come from the
16699  * straight-line code between a state and its parent.  When we arrive at an
16700  * equivalent state (jump target or such) we didn't arrive by the straight-line
16701  * code, so read marks in the state must propagate to the parent regardless
16702  * of the state's write marks. That's what 'parent == state->parent' comparison
16703  * in mark_reg_read() is for.
16704  */
16705 static int propagate_liveness(struct bpf_verifier_env *env,
16706 			      const struct bpf_verifier_state *vstate,
16707 			      struct bpf_verifier_state *vparent)
16708 {
16709 	struct bpf_reg_state *state_reg, *parent_reg;
16710 	struct bpf_func_state *state, *parent;
16711 	int i, frame, err = 0;
16712 
16713 	if (vparent->curframe != vstate->curframe) {
16714 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
16715 		     vparent->curframe, vstate->curframe);
16716 		return -EFAULT;
16717 	}
16718 	/* Propagate read liveness of registers... */
16719 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16720 	for (frame = 0; frame <= vstate->curframe; frame++) {
16721 		parent = vparent->frame[frame];
16722 		state = vstate->frame[frame];
16723 		parent_reg = parent->regs;
16724 		state_reg = state->regs;
16725 		/* We don't need to worry about FP liveness, it's read-only */
16726 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16727 			err = propagate_liveness_reg(env, &state_reg[i],
16728 						     &parent_reg[i]);
16729 			if (err < 0)
16730 				return err;
16731 			if (err == REG_LIVE_READ64)
16732 				mark_insn_zext(env, &parent_reg[i]);
16733 		}
16734 
16735 		/* Propagate stack slots. */
16736 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16737 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16738 			parent_reg = &parent->stack[i].spilled_ptr;
16739 			state_reg = &state->stack[i].spilled_ptr;
16740 			err = propagate_liveness_reg(env, state_reg,
16741 						     parent_reg);
16742 			if (err < 0)
16743 				return err;
16744 		}
16745 	}
16746 	return 0;
16747 }
16748 
16749 /* find precise scalars in the previous equivalent state and
16750  * propagate them into the current state
16751  */
16752 static int propagate_precision(struct bpf_verifier_env *env,
16753 			       const struct bpf_verifier_state *old)
16754 {
16755 	struct bpf_reg_state *state_reg;
16756 	struct bpf_func_state *state;
16757 	int i, err = 0, fr;
16758 	bool first;
16759 
16760 	for (fr = old->curframe; fr >= 0; fr--) {
16761 		state = old->frame[fr];
16762 		state_reg = state->regs;
16763 		first = true;
16764 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16765 			if (state_reg->type != SCALAR_VALUE ||
16766 			    !state_reg->precise ||
16767 			    !(state_reg->live & REG_LIVE_READ))
16768 				continue;
16769 			if (env->log.level & BPF_LOG_LEVEL2) {
16770 				if (first)
16771 					verbose(env, "frame %d: propagating r%d", fr, i);
16772 				else
16773 					verbose(env, ",r%d", i);
16774 			}
16775 			bt_set_frame_reg(&env->bt, fr, i);
16776 			first = false;
16777 		}
16778 
16779 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16780 			if (!is_spilled_reg(&state->stack[i]))
16781 				continue;
16782 			state_reg = &state->stack[i].spilled_ptr;
16783 			if (state_reg->type != SCALAR_VALUE ||
16784 			    !state_reg->precise ||
16785 			    !(state_reg->live & REG_LIVE_READ))
16786 				continue;
16787 			if (env->log.level & BPF_LOG_LEVEL2) {
16788 				if (first)
16789 					verbose(env, "frame %d: propagating fp%d",
16790 						fr, (-i - 1) * BPF_REG_SIZE);
16791 				else
16792 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16793 			}
16794 			bt_set_frame_slot(&env->bt, fr, i);
16795 			first = false;
16796 		}
16797 		if (!first)
16798 			verbose(env, "\n");
16799 	}
16800 
16801 	err = mark_chain_precision_batch(env);
16802 	if (err < 0)
16803 		return err;
16804 
16805 	return 0;
16806 }
16807 
16808 static bool states_maybe_looping(struct bpf_verifier_state *old,
16809 				 struct bpf_verifier_state *cur)
16810 {
16811 	struct bpf_func_state *fold, *fcur;
16812 	int i, fr = cur->curframe;
16813 
16814 	if (old->curframe != fr)
16815 		return false;
16816 
16817 	fold = old->frame[fr];
16818 	fcur = cur->frame[fr];
16819 	for (i = 0; i < MAX_BPF_REG; i++)
16820 		if (memcmp(&fold->regs[i], &fcur->regs[i],
16821 			   offsetof(struct bpf_reg_state, parent)))
16822 			return false;
16823 	return true;
16824 }
16825 
16826 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16827 {
16828 	return env->insn_aux_data[insn_idx].is_iter_next;
16829 }
16830 
16831 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16832  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16833  * states to match, which otherwise would look like an infinite loop. So while
16834  * iter_next() calls are taken care of, we still need to be careful and
16835  * prevent erroneous and too eager declaration of "ininite loop", when
16836  * iterators are involved.
16837  *
16838  * Here's a situation in pseudo-BPF assembly form:
16839  *
16840  *   0: again:                          ; set up iter_next() call args
16841  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16842  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16843  *   3:   if r0 == 0 goto done
16844  *   4:   ... something useful here ...
16845  *   5:   goto again                    ; another iteration
16846  *   6: done:
16847  *   7:   r1 = &it
16848  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16849  *   9:   exit
16850  *
16851  * This is a typical loop. Let's assume that we have a prune point at 1:,
16852  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16853  * again`, assuming other heuristics don't get in a way).
16854  *
16855  * When we first time come to 1:, let's say we have some state X. We proceed
16856  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16857  * Now we come back to validate that forked ACTIVE state. We proceed through
16858  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16859  * are converging. But the problem is that we don't know that yet, as this
16860  * convergence has to happen at iter_next() call site only. So if nothing is
16861  * done, at 1: verifier will use bounded loop logic and declare infinite
16862  * looping (and would be *technically* correct, if not for iterator's
16863  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16864  * don't want that. So what we do in process_iter_next_call() when we go on
16865  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16866  * a different iteration. So when we suspect an infinite loop, we additionally
16867  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16868  * pretend we are not looping and wait for next iter_next() call.
16869  *
16870  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16871  * loop, because that would actually mean infinite loop, as DRAINED state is
16872  * "sticky", and so we'll keep returning into the same instruction with the
16873  * same state (at least in one of possible code paths).
16874  *
16875  * This approach allows to keep infinite loop heuristic even in the face of
16876  * active iterator. E.g., C snippet below is and will be detected as
16877  * inifintely looping:
16878  *
16879  *   struct bpf_iter_num it;
16880  *   int *p, x;
16881  *
16882  *   bpf_iter_num_new(&it, 0, 10);
16883  *   while ((p = bpf_iter_num_next(&t))) {
16884  *       x = p;
16885  *       while (x--) {} // <<-- infinite loop here
16886  *   }
16887  *
16888  */
16889 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16890 {
16891 	struct bpf_reg_state *slot, *cur_slot;
16892 	struct bpf_func_state *state;
16893 	int i, fr;
16894 
16895 	for (fr = old->curframe; fr >= 0; fr--) {
16896 		state = old->frame[fr];
16897 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16898 			if (state->stack[i].slot_type[0] != STACK_ITER)
16899 				continue;
16900 
16901 			slot = &state->stack[i].spilled_ptr;
16902 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16903 				continue;
16904 
16905 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16906 			if (cur_slot->iter.depth != slot->iter.depth)
16907 				return true;
16908 		}
16909 	}
16910 	return false;
16911 }
16912 
16913 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16914 {
16915 	struct bpf_verifier_state_list *new_sl;
16916 	struct bpf_verifier_state_list *sl, **pprev;
16917 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16918 	int i, j, n, err, states_cnt = 0;
16919 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16920 	bool add_new_state = force_new_state;
16921 	bool force_exact;
16922 
16923 	/* bpf progs typically have pruning point every 4 instructions
16924 	 * http://vger.kernel.org/bpfconf2019.html#session-1
16925 	 * Do not add new state for future pruning if the verifier hasn't seen
16926 	 * at least 2 jumps and at least 8 instructions.
16927 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16928 	 * In tests that amounts to up to 50% reduction into total verifier
16929 	 * memory consumption and 20% verifier time speedup.
16930 	 */
16931 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16932 	    env->insn_processed - env->prev_insn_processed >= 8)
16933 		add_new_state = true;
16934 
16935 	pprev = explored_state(env, insn_idx);
16936 	sl = *pprev;
16937 
16938 	clean_live_states(env, insn_idx, cur);
16939 
16940 	while (sl) {
16941 		states_cnt++;
16942 		if (sl->state.insn_idx != insn_idx)
16943 			goto next;
16944 
16945 		if (sl->state.branches) {
16946 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16947 
16948 			if (frame->in_async_callback_fn &&
16949 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16950 				/* Different async_entry_cnt means that the verifier is
16951 				 * processing another entry into async callback.
16952 				 * Seeing the same state is not an indication of infinite
16953 				 * loop or infinite recursion.
16954 				 * But finding the same state doesn't mean that it's safe
16955 				 * to stop processing the current state. The previous state
16956 				 * hasn't yet reached bpf_exit, since state.branches > 0.
16957 				 * Checking in_async_callback_fn alone is not enough either.
16958 				 * Since the verifier still needs to catch infinite loops
16959 				 * inside async callbacks.
16960 				 */
16961 				goto skip_inf_loop_check;
16962 			}
16963 			/* BPF open-coded iterators loop detection is special.
16964 			 * states_maybe_looping() logic is too simplistic in detecting
16965 			 * states that *might* be equivalent, because it doesn't know
16966 			 * about ID remapping, so don't even perform it.
16967 			 * See process_iter_next_call() and iter_active_depths_differ()
16968 			 * for overview of the logic. When current and one of parent
16969 			 * states are detected as equivalent, it's a good thing: we prove
16970 			 * convergence and can stop simulating further iterations.
16971 			 * It's safe to assume that iterator loop will finish, taking into
16972 			 * account iter_next() contract of eventually returning
16973 			 * sticky NULL result.
16974 			 *
16975 			 * Note, that states have to be compared exactly in this case because
16976 			 * read and precision marks might not be finalized inside the loop.
16977 			 * E.g. as in the program below:
16978 			 *
16979 			 *     1. r7 = -16
16980 			 *     2. r6 = bpf_get_prandom_u32()
16981 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
16982 			 *     4.   if (r6 != 42) {
16983 			 *     5.     r7 = -32
16984 			 *     6.     r6 = bpf_get_prandom_u32()
16985 			 *     7.     continue
16986 			 *     8.   }
16987 			 *     9.   r0 = r10
16988 			 *    10.   r0 += r7
16989 			 *    11.   r8 = *(u64 *)(r0 + 0)
16990 			 *    12.   r6 = bpf_get_prandom_u32()
16991 			 *    13. }
16992 			 *
16993 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
16994 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16995 			 * not have read or precision mark for r7 yet, thus inexact states
16996 			 * comparison would discard current state with r7=-32
16997 			 * => unsafe memory access at 11 would not be caught.
16998 			 */
16999 			if (is_iter_next_insn(env, insn_idx)) {
17000 				if (states_equal(env, &sl->state, cur, true)) {
17001 					struct bpf_func_state *cur_frame;
17002 					struct bpf_reg_state *iter_state, *iter_reg;
17003 					int spi;
17004 
17005 					cur_frame = cur->frame[cur->curframe];
17006 					/* btf_check_iter_kfuncs() enforces that
17007 					 * iter state pointer is always the first arg
17008 					 */
17009 					iter_reg = &cur_frame->regs[BPF_REG_1];
17010 					/* current state is valid due to states_equal(),
17011 					 * so we can assume valid iter and reg state,
17012 					 * no need for extra (re-)validations
17013 					 */
17014 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
17015 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
17016 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
17017 						update_loop_entry(cur, &sl->state);
17018 						goto hit;
17019 					}
17020 				}
17021 				goto skip_inf_loop_check;
17022 			}
17023 			if (calls_callback(env, insn_idx)) {
17024 				if (states_equal(env, &sl->state, cur, true))
17025 					goto hit;
17026 				goto skip_inf_loop_check;
17027 			}
17028 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
17029 			if (states_maybe_looping(&sl->state, cur) &&
17030 			    states_equal(env, &sl->state, cur, false) &&
17031 			    !iter_active_depths_differ(&sl->state, cur) &&
17032 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
17033 				verbose_linfo(env, insn_idx, "; ");
17034 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
17035 				verbose(env, "cur state:");
17036 				print_verifier_state(env, cur->frame[cur->curframe], true);
17037 				verbose(env, "old state:");
17038 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
17039 				return -EINVAL;
17040 			}
17041 			/* if the verifier is processing a loop, avoid adding new state
17042 			 * too often, since different loop iterations have distinct
17043 			 * states and may not help future pruning.
17044 			 * This threshold shouldn't be too low to make sure that
17045 			 * a loop with large bound will be rejected quickly.
17046 			 * The most abusive loop will be:
17047 			 * r1 += 1
17048 			 * if r1 < 1000000 goto pc-2
17049 			 * 1M insn_procssed limit / 100 == 10k peak states.
17050 			 * This threshold shouldn't be too high either, since states
17051 			 * at the end of the loop are likely to be useful in pruning.
17052 			 */
17053 skip_inf_loop_check:
17054 			if (!force_new_state &&
17055 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
17056 			    env->insn_processed - env->prev_insn_processed < 100)
17057 				add_new_state = false;
17058 			goto miss;
17059 		}
17060 		/* If sl->state is a part of a loop and this loop's entry is a part of
17061 		 * current verification path then states have to be compared exactly.
17062 		 * 'force_exact' is needed to catch the following case:
17063 		 *
17064 		 *                initial     Here state 'succ' was processed first,
17065 		 *                  |         it was eventually tracked to produce a
17066 		 *                  V         state identical to 'hdr'.
17067 		 *     .---------> hdr        All branches from 'succ' had been explored
17068 		 *     |            |         and thus 'succ' has its .branches == 0.
17069 		 *     |            V
17070 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
17071 		 *     |    |       |         to the same instruction + callsites.
17072 		 *     |    V       V         In such case it is necessary to check
17073 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
17074 		 *     |    |       |         If 'succ' and 'cur' are a part of the
17075 		 *     |    V       V         same loop exact flag has to be set.
17076 		 *     |   succ <- cur        To check if that is the case, verify
17077 		 *     |    |                 if loop entry of 'succ' is in current
17078 		 *     |    V                 DFS path.
17079 		 *     |   ...
17080 		 *     |    |
17081 		 *     '----'
17082 		 *
17083 		 * Additional details are in the comment before get_loop_entry().
17084 		 */
17085 		loop_entry = get_loop_entry(&sl->state);
17086 		force_exact = loop_entry && loop_entry->branches > 0;
17087 		if (states_equal(env, &sl->state, cur, force_exact)) {
17088 			if (force_exact)
17089 				update_loop_entry(cur, loop_entry);
17090 hit:
17091 			sl->hit_cnt++;
17092 			/* reached equivalent register/stack state,
17093 			 * prune the search.
17094 			 * Registers read by the continuation are read by us.
17095 			 * If we have any write marks in env->cur_state, they
17096 			 * will prevent corresponding reads in the continuation
17097 			 * from reaching our parent (an explored_state).  Our
17098 			 * own state will get the read marks recorded, but
17099 			 * they'll be immediately forgotten as we're pruning
17100 			 * this state and will pop a new one.
17101 			 */
17102 			err = propagate_liveness(env, &sl->state, cur);
17103 
17104 			/* if previous state reached the exit with precision and
17105 			 * current state is equivalent to it (except precsion marks)
17106 			 * the precision needs to be propagated back in
17107 			 * the current state.
17108 			 */
17109 			if (is_jmp_point(env, env->insn_idx))
17110 				err = err ? : push_jmp_history(env, cur, 0);
17111 			err = err ? : propagate_precision(env, &sl->state);
17112 			if (err)
17113 				return err;
17114 			return 1;
17115 		}
17116 miss:
17117 		/* when new state is not going to be added do not increase miss count.
17118 		 * Otherwise several loop iterations will remove the state
17119 		 * recorded earlier. The goal of these heuristics is to have
17120 		 * states from some iterations of the loop (some in the beginning
17121 		 * and some at the end) to help pruning.
17122 		 */
17123 		if (add_new_state)
17124 			sl->miss_cnt++;
17125 		/* heuristic to determine whether this state is beneficial
17126 		 * to keep checking from state equivalence point of view.
17127 		 * Higher numbers increase max_states_per_insn and verification time,
17128 		 * but do not meaningfully decrease insn_processed.
17129 		 * 'n' controls how many times state could miss before eviction.
17130 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
17131 		 * too early would hinder iterator convergence.
17132 		 */
17133 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
17134 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
17135 			/* the state is unlikely to be useful. Remove it to
17136 			 * speed up verification
17137 			 */
17138 			*pprev = sl->next;
17139 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
17140 			    !sl->state.used_as_loop_entry) {
17141 				u32 br = sl->state.branches;
17142 
17143 				WARN_ONCE(br,
17144 					  "BUG live_done but branches_to_explore %d\n",
17145 					  br);
17146 				free_verifier_state(&sl->state, false);
17147 				kfree(sl);
17148 				env->peak_states--;
17149 			} else {
17150 				/* cannot free this state, since parentage chain may
17151 				 * walk it later. Add it for free_list instead to
17152 				 * be freed at the end of verification
17153 				 */
17154 				sl->next = env->free_list;
17155 				env->free_list = sl;
17156 			}
17157 			sl = *pprev;
17158 			continue;
17159 		}
17160 next:
17161 		pprev = &sl->next;
17162 		sl = *pprev;
17163 	}
17164 
17165 	if (env->max_states_per_insn < states_cnt)
17166 		env->max_states_per_insn = states_cnt;
17167 
17168 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
17169 		return 0;
17170 
17171 	if (!add_new_state)
17172 		return 0;
17173 
17174 	/* There were no equivalent states, remember the current one.
17175 	 * Technically the current state is not proven to be safe yet,
17176 	 * but it will either reach outer most bpf_exit (which means it's safe)
17177 	 * or it will be rejected. When there are no loops the verifier won't be
17178 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
17179 	 * again on the way to bpf_exit.
17180 	 * When looping the sl->state.branches will be > 0 and this state
17181 	 * will not be considered for equivalence until branches == 0.
17182 	 */
17183 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
17184 	if (!new_sl)
17185 		return -ENOMEM;
17186 	env->total_states++;
17187 	env->peak_states++;
17188 	env->prev_jmps_processed = env->jmps_processed;
17189 	env->prev_insn_processed = env->insn_processed;
17190 
17191 	/* forget precise markings we inherited, see __mark_chain_precision */
17192 	if (env->bpf_capable)
17193 		mark_all_scalars_imprecise(env, cur);
17194 
17195 	/* add new state to the head of linked list */
17196 	new = &new_sl->state;
17197 	err = copy_verifier_state(new, cur);
17198 	if (err) {
17199 		free_verifier_state(new, false);
17200 		kfree(new_sl);
17201 		return err;
17202 	}
17203 	new->insn_idx = insn_idx;
17204 	WARN_ONCE(new->branches != 1,
17205 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
17206 
17207 	cur->parent = new;
17208 	cur->first_insn_idx = insn_idx;
17209 	cur->dfs_depth = new->dfs_depth + 1;
17210 	clear_jmp_history(cur);
17211 	new_sl->next = *explored_state(env, insn_idx);
17212 	*explored_state(env, insn_idx) = new_sl;
17213 	/* connect new state to parentage chain. Current frame needs all
17214 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
17215 	 * to the stack implicitly by JITs) so in callers' frames connect just
17216 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
17217 	 * the state of the call instruction (with WRITTEN set), and r0 comes
17218 	 * from callee with its full parentage chain, anyway.
17219 	 */
17220 	/* clear write marks in current state: the writes we did are not writes
17221 	 * our child did, so they don't screen off its reads from us.
17222 	 * (There are no read marks in current state, because reads always mark
17223 	 * their parent and current state never has children yet.  Only
17224 	 * explored_states can get read marks.)
17225 	 */
17226 	for (j = 0; j <= cur->curframe; j++) {
17227 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
17228 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
17229 		for (i = 0; i < BPF_REG_FP; i++)
17230 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
17231 	}
17232 
17233 	/* all stack frames are accessible from callee, clear them all */
17234 	for (j = 0; j <= cur->curframe; j++) {
17235 		struct bpf_func_state *frame = cur->frame[j];
17236 		struct bpf_func_state *newframe = new->frame[j];
17237 
17238 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
17239 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
17240 			frame->stack[i].spilled_ptr.parent =
17241 						&newframe->stack[i].spilled_ptr;
17242 		}
17243 	}
17244 	return 0;
17245 }
17246 
17247 /* Return true if it's OK to have the same insn return a different type. */
17248 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
17249 {
17250 	switch (base_type(type)) {
17251 	case PTR_TO_CTX:
17252 	case PTR_TO_SOCKET:
17253 	case PTR_TO_SOCK_COMMON:
17254 	case PTR_TO_TCP_SOCK:
17255 	case PTR_TO_XDP_SOCK:
17256 	case PTR_TO_BTF_ID:
17257 		return false;
17258 	default:
17259 		return true;
17260 	}
17261 }
17262 
17263 /* If an instruction was previously used with particular pointer types, then we
17264  * need to be careful to avoid cases such as the below, where it may be ok
17265  * for one branch accessing the pointer, but not ok for the other branch:
17266  *
17267  * R1 = sock_ptr
17268  * goto X;
17269  * ...
17270  * R1 = some_other_valid_ptr;
17271  * goto X;
17272  * ...
17273  * R2 = *(u32 *)(R1 + 0);
17274  */
17275 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17276 {
17277 	return src != prev && (!reg_type_mismatch_ok(src) ||
17278 			       !reg_type_mismatch_ok(prev));
17279 }
17280 
17281 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17282 			     bool allow_trust_missmatch)
17283 {
17284 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17285 
17286 	if (*prev_type == NOT_INIT) {
17287 		/* Saw a valid insn
17288 		 * dst_reg = *(u32 *)(src_reg + off)
17289 		 * save type to validate intersecting paths
17290 		 */
17291 		*prev_type = type;
17292 	} else if (reg_type_mismatch(type, *prev_type)) {
17293 		/* Abuser program is trying to use the same insn
17294 		 * dst_reg = *(u32*) (src_reg + off)
17295 		 * with different pointer types:
17296 		 * src_reg == ctx in one branch and
17297 		 * src_reg == stack|map in some other branch.
17298 		 * Reject it.
17299 		 */
17300 		if (allow_trust_missmatch &&
17301 		    base_type(type) == PTR_TO_BTF_ID &&
17302 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
17303 			/*
17304 			 * Have to support a use case when one path through
17305 			 * the program yields TRUSTED pointer while another
17306 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
17307 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
17308 			 */
17309 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
17310 		} else {
17311 			verbose(env, "same insn cannot be used with different pointers\n");
17312 			return -EINVAL;
17313 		}
17314 	}
17315 
17316 	return 0;
17317 }
17318 
17319 static int do_check(struct bpf_verifier_env *env)
17320 {
17321 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17322 	struct bpf_verifier_state *state = env->cur_state;
17323 	struct bpf_insn *insns = env->prog->insnsi;
17324 	struct bpf_reg_state *regs;
17325 	int insn_cnt = env->prog->len;
17326 	bool do_print_state = false;
17327 	int prev_insn_idx = -1;
17328 
17329 	for (;;) {
17330 		bool exception_exit = false;
17331 		struct bpf_insn *insn;
17332 		u8 class;
17333 		int err;
17334 
17335 		/* reset current history entry on each new instruction */
17336 		env->cur_hist_ent = NULL;
17337 
17338 		env->prev_insn_idx = prev_insn_idx;
17339 		if (env->insn_idx >= insn_cnt) {
17340 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
17341 				env->insn_idx, insn_cnt);
17342 			return -EFAULT;
17343 		}
17344 
17345 		insn = &insns[env->insn_idx];
17346 		class = BPF_CLASS(insn->code);
17347 
17348 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17349 			verbose(env,
17350 				"BPF program is too large. Processed %d insn\n",
17351 				env->insn_processed);
17352 			return -E2BIG;
17353 		}
17354 
17355 		state->last_insn_idx = env->prev_insn_idx;
17356 
17357 		if (is_prune_point(env, env->insn_idx)) {
17358 			err = is_state_visited(env, env->insn_idx);
17359 			if (err < 0)
17360 				return err;
17361 			if (err == 1) {
17362 				/* found equivalent state, can prune the search */
17363 				if (env->log.level & BPF_LOG_LEVEL) {
17364 					if (do_print_state)
17365 						verbose(env, "\nfrom %d to %d%s: safe\n",
17366 							env->prev_insn_idx, env->insn_idx,
17367 							env->cur_state->speculative ?
17368 							" (speculative execution)" : "");
17369 					else
17370 						verbose(env, "%d: safe\n", env->insn_idx);
17371 				}
17372 				goto process_bpf_exit;
17373 			}
17374 		}
17375 
17376 		if (is_jmp_point(env, env->insn_idx)) {
17377 			err = push_jmp_history(env, state, 0);
17378 			if (err)
17379 				return err;
17380 		}
17381 
17382 		if (signal_pending(current))
17383 			return -EAGAIN;
17384 
17385 		if (need_resched())
17386 			cond_resched();
17387 
17388 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17389 			verbose(env, "\nfrom %d to %d%s:",
17390 				env->prev_insn_idx, env->insn_idx,
17391 				env->cur_state->speculative ?
17392 				" (speculative execution)" : "");
17393 			print_verifier_state(env, state->frame[state->curframe], true);
17394 			do_print_state = false;
17395 		}
17396 
17397 		if (env->log.level & BPF_LOG_LEVEL) {
17398 			const struct bpf_insn_cbs cbs = {
17399 				.cb_call	= disasm_kfunc_name,
17400 				.cb_print	= verbose,
17401 				.private_data	= env,
17402 			};
17403 
17404 			if (verifier_state_scratched(env))
17405 				print_insn_state(env, state->frame[state->curframe]);
17406 
17407 			verbose_linfo(env, env->insn_idx, "; ");
17408 			env->prev_log_pos = env->log.end_pos;
17409 			verbose(env, "%d: ", env->insn_idx);
17410 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17411 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17412 			env->prev_log_pos = env->log.end_pos;
17413 		}
17414 
17415 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17416 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17417 							   env->prev_insn_idx);
17418 			if (err)
17419 				return err;
17420 		}
17421 
17422 		regs = cur_regs(env);
17423 		sanitize_mark_insn_seen(env);
17424 		prev_insn_idx = env->insn_idx;
17425 
17426 		if (class == BPF_ALU || class == BPF_ALU64) {
17427 			err = check_alu_op(env, insn);
17428 			if (err)
17429 				return err;
17430 
17431 		} else if (class == BPF_LDX) {
17432 			enum bpf_reg_type src_reg_type;
17433 
17434 			/* check for reserved fields is already done */
17435 
17436 			/* check src operand */
17437 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17438 			if (err)
17439 				return err;
17440 
17441 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17442 			if (err)
17443 				return err;
17444 
17445 			src_reg_type = regs[insn->src_reg].type;
17446 
17447 			/* check that memory (src_reg + off) is readable,
17448 			 * the state of dst_reg will be updated by this func
17449 			 */
17450 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17451 					       insn->off, BPF_SIZE(insn->code),
17452 					       BPF_READ, insn->dst_reg, false,
17453 					       BPF_MODE(insn->code) == BPF_MEMSX);
17454 			err = err ?: save_aux_ptr_type(env, src_reg_type, true);
17455 			err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], "ldx");
17456 			if (err)
17457 				return err;
17458 		} else if (class == BPF_STX) {
17459 			enum bpf_reg_type dst_reg_type;
17460 
17461 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17462 				err = check_atomic(env, env->insn_idx, insn);
17463 				if (err)
17464 					return err;
17465 				env->insn_idx++;
17466 				continue;
17467 			}
17468 
17469 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17470 				verbose(env, "BPF_STX uses reserved fields\n");
17471 				return -EINVAL;
17472 			}
17473 
17474 			/* check src1 operand */
17475 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17476 			if (err)
17477 				return err;
17478 			/* check src2 operand */
17479 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17480 			if (err)
17481 				return err;
17482 
17483 			dst_reg_type = regs[insn->dst_reg].type;
17484 
17485 			/* check that memory (dst_reg + off) is writeable */
17486 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17487 					       insn->off, BPF_SIZE(insn->code),
17488 					       BPF_WRITE, insn->src_reg, false, false);
17489 			if (err)
17490 				return err;
17491 
17492 			err = save_aux_ptr_type(env, dst_reg_type, false);
17493 			if (err)
17494 				return err;
17495 		} else if (class == BPF_ST) {
17496 			enum bpf_reg_type dst_reg_type;
17497 
17498 			if (BPF_MODE(insn->code) != BPF_MEM ||
17499 			    insn->src_reg != BPF_REG_0) {
17500 				verbose(env, "BPF_ST uses reserved fields\n");
17501 				return -EINVAL;
17502 			}
17503 			/* check src operand */
17504 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17505 			if (err)
17506 				return err;
17507 
17508 			dst_reg_type = regs[insn->dst_reg].type;
17509 
17510 			/* check that memory (dst_reg + off) is writeable */
17511 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17512 					       insn->off, BPF_SIZE(insn->code),
17513 					       BPF_WRITE, -1, false, false);
17514 			if (err)
17515 				return err;
17516 
17517 			err = save_aux_ptr_type(env, dst_reg_type, false);
17518 			if (err)
17519 				return err;
17520 		} else if (class == BPF_JMP || class == BPF_JMP32) {
17521 			u8 opcode = BPF_OP(insn->code);
17522 
17523 			env->jmps_processed++;
17524 			if (opcode == BPF_CALL) {
17525 				if (BPF_SRC(insn->code) != BPF_K ||
17526 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17527 				     && insn->off != 0) ||
17528 				    (insn->src_reg != BPF_REG_0 &&
17529 				     insn->src_reg != BPF_PSEUDO_CALL &&
17530 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17531 				    insn->dst_reg != BPF_REG_0 ||
17532 				    class == BPF_JMP32) {
17533 					verbose(env, "BPF_CALL uses reserved fields\n");
17534 					return -EINVAL;
17535 				}
17536 
17537 				if (env->cur_state->active_lock.ptr) {
17538 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17539 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
17540 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17541 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17542 						verbose(env, "function calls are not allowed while holding a lock\n");
17543 						return -EINVAL;
17544 					}
17545 				}
17546 				if (insn->src_reg == BPF_PSEUDO_CALL) {
17547 					err = check_func_call(env, insn, &env->insn_idx);
17548 				} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17549 					err = check_kfunc_call(env, insn, &env->insn_idx);
17550 					if (!err && is_bpf_throw_kfunc(insn)) {
17551 						exception_exit = true;
17552 						goto process_bpf_exit_full;
17553 					}
17554 				} else {
17555 					err = check_helper_call(env, insn, &env->insn_idx);
17556 				}
17557 				if (err)
17558 					return err;
17559 
17560 				mark_reg_scratched(env, BPF_REG_0);
17561 			} else if (opcode == BPF_JA) {
17562 				if (BPF_SRC(insn->code) != BPF_K ||
17563 				    insn->src_reg != BPF_REG_0 ||
17564 				    insn->dst_reg != BPF_REG_0 ||
17565 				    (class == BPF_JMP && insn->imm != 0) ||
17566 				    (class == BPF_JMP32 && insn->off != 0)) {
17567 					verbose(env, "BPF_JA uses reserved fields\n");
17568 					return -EINVAL;
17569 				}
17570 
17571 				if (class == BPF_JMP)
17572 					env->insn_idx += insn->off + 1;
17573 				else
17574 					env->insn_idx += insn->imm + 1;
17575 				continue;
17576 
17577 			} else if (opcode == BPF_EXIT) {
17578 				if (BPF_SRC(insn->code) != BPF_K ||
17579 				    insn->imm != 0 ||
17580 				    insn->src_reg != BPF_REG_0 ||
17581 				    insn->dst_reg != BPF_REG_0 ||
17582 				    class == BPF_JMP32) {
17583 					verbose(env, "BPF_EXIT uses reserved fields\n");
17584 					return -EINVAL;
17585 				}
17586 process_bpf_exit_full:
17587 				if (env->cur_state->active_lock.ptr &&
17588 				    !in_rbtree_lock_required_cb(env)) {
17589 					verbose(env, "bpf_spin_unlock is missing\n");
17590 					return -EINVAL;
17591 				}
17592 
17593 				if (env->cur_state->active_rcu_lock &&
17594 				    !in_rbtree_lock_required_cb(env)) {
17595 					verbose(env, "bpf_rcu_read_unlock is missing\n");
17596 					return -EINVAL;
17597 				}
17598 
17599 				/* We must do check_reference_leak here before
17600 				 * prepare_func_exit to handle the case when
17601 				 * state->curframe > 0, it may be a callback
17602 				 * function, for which reference_state must
17603 				 * match caller reference state when it exits.
17604 				 */
17605 				err = check_reference_leak(env, exception_exit);
17606 				if (err)
17607 					return err;
17608 
17609 				/* The side effect of the prepare_func_exit
17610 				 * which is being skipped is that it frees
17611 				 * bpf_func_state. Typically, process_bpf_exit
17612 				 * will only be hit with outermost exit.
17613 				 * copy_verifier_state in pop_stack will handle
17614 				 * freeing of any extra bpf_func_state left over
17615 				 * from not processing all nested function
17616 				 * exits. We also skip return code checks as
17617 				 * they are not needed for exceptional exits.
17618 				 */
17619 				if (exception_exit)
17620 					goto process_bpf_exit;
17621 
17622 				if (state->curframe) {
17623 					/* exit from nested function */
17624 					err = prepare_func_exit(env, &env->insn_idx);
17625 					if (err)
17626 						return err;
17627 					do_print_state = true;
17628 					continue;
17629 				}
17630 
17631 				err = check_return_code(env, BPF_REG_0, "R0");
17632 				if (err)
17633 					return err;
17634 process_bpf_exit:
17635 				mark_verifier_state_scratched(env);
17636 				update_branch_counts(env, env->cur_state);
17637 				err = pop_stack(env, &prev_insn_idx,
17638 						&env->insn_idx, pop_log);
17639 				if (err < 0) {
17640 					if (err != -ENOENT)
17641 						return err;
17642 					break;
17643 				} else {
17644 					do_print_state = true;
17645 					continue;
17646 				}
17647 			} else {
17648 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
17649 				if (err)
17650 					return err;
17651 			}
17652 		} else if (class == BPF_LD) {
17653 			u8 mode = BPF_MODE(insn->code);
17654 
17655 			if (mode == BPF_ABS || mode == BPF_IND) {
17656 				err = check_ld_abs(env, insn);
17657 				if (err)
17658 					return err;
17659 
17660 			} else if (mode == BPF_IMM) {
17661 				err = check_ld_imm(env, insn);
17662 				if (err)
17663 					return err;
17664 
17665 				env->insn_idx++;
17666 				sanitize_mark_insn_seen(env);
17667 			} else {
17668 				verbose(env, "invalid BPF_LD mode\n");
17669 				return -EINVAL;
17670 			}
17671 		} else {
17672 			verbose(env, "unknown insn class %d\n", class);
17673 			return -EINVAL;
17674 		}
17675 
17676 		env->insn_idx++;
17677 	}
17678 
17679 	return 0;
17680 }
17681 
17682 static int find_btf_percpu_datasec(struct btf *btf)
17683 {
17684 	const struct btf_type *t;
17685 	const char *tname;
17686 	int i, n;
17687 
17688 	/*
17689 	 * Both vmlinux and module each have their own ".data..percpu"
17690 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17691 	 * types to look at only module's own BTF types.
17692 	 */
17693 	n = btf_nr_types(btf);
17694 	if (btf_is_module(btf))
17695 		i = btf_nr_types(btf_vmlinux);
17696 	else
17697 		i = 1;
17698 
17699 	for(; i < n; i++) {
17700 		t = btf_type_by_id(btf, i);
17701 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17702 			continue;
17703 
17704 		tname = btf_name_by_offset(btf, t->name_off);
17705 		if (!strcmp(tname, ".data..percpu"))
17706 			return i;
17707 	}
17708 
17709 	return -ENOENT;
17710 }
17711 
17712 /* replace pseudo btf_id with kernel symbol address */
17713 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17714 			       struct bpf_insn *insn,
17715 			       struct bpf_insn_aux_data *aux)
17716 {
17717 	const struct btf_var_secinfo *vsi;
17718 	const struct btf_type *datasec;
17719 	struct btf_mod_pair *btf_mod;
17720 	const struct btf_type *t;
17721 	const char *sym_name;
17722 	bool percpu = false;
17723 	u32 type, id = insn->imm;
17724 	struct btf *btf;
17725 	s32 datasec_id;
17726 	u64 addr;
17727 	int i, btf_fd, err;
17728 
17729 	btf_fd = insn[1].imm;
17730 	if (btf_fd) {
17731 		btf = btf_get_by_fd(btf_fd);
17732 		if (IS_ERR(btf)) {
17733 			verbose(env, "invalid module BTF object FD specified.\n");
17734 			return -EINVAL;
17735 		}
17736 	} else {
17737 		if (!btf_vmlinux) {
17738 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17739 			return -EINVAL;
17740 		}
17741 		btf = btf_vmlinux;
17742 		btf_get(btf);
17743 	}
17744 
17745 	t = btf_type_by_id(btf, id);
17746 	if (!t) {
17747 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17748 		err = -ENOENT;
17749 		goto err_put;
17750 	}
17751 
17752 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17753 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17754 		err = -EINVAL;
17755 		goto err_put;
17756 	}
17757 
17758 	sym_name = btf_name_by_offset(btf, t->name_off);
17759 	addr = kallsyms_lookup_name(sym_name);
17760 	if (!addr) {
17761 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17762 			sym_name);
17763 		err = -ENOENT;
17764 		goto err_put;
17765 	}
17766 	insn[0].imm = (u32)addr;
17767 	insn[1].imm = addr >> 32;
17768 
17769 	if (btf_type_is_func(t)) {
17770 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17771 		aux->btf_var.mem_size = 0;
17772 		goto check_btf;
17773 	}
17774 
17775 	datasec_id = find_btf_percpu_datasec(btf);
17776 	if (datasec_id > 0) {
17777 		datasec = btf_type_by_id(btf, datasec_id);
17778 		for_each_vsi(i, datasec, vsi) {
17779 			if (vsi->type == id) {
17780 				percpu = true;
17781 				break;
17782 			}
17783 		}
17784 	}
17785 
17786 	type = t->type;
17787 	t = btf_type_skip_modifiers(btf, type, NULL);
17788 	if (percpu) {
17789 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17790 		aux->btf_var.btf = btf;
17791 		aux->btf_var.btf_id = type;
17792 	} else if (!btf_type_is_struct(t)) {
17793 		const struct btf_type *ret;
17794 		const char *tname;
17795 		u32 tsize;
17796 
17797 		/* resolve the type size of ksym. */
17798 		ret = btf_resolve_size(btf, t, &tsize);
17799 		if (IS_ERR(ret)) {
17800 			tname = btf_name_by_offset(btf, t->name_off);
17801 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17802 				tname, PTR_ERR(ret));
17803 			err = -EINVAL;
17804 			goto err_put;
17805 		}
17806 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17807 		aux->btf_var.mem_size = tsize;
17808 	} else {
17809 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
17810 		aux->btf_var.btf = btf;
17811 		aux->btf_var.btf_id = type;
17812 	}
17813 check_btf:
17814 	/* check whether we recorded this BTF (and maybe module) already */
17815 	for (i = 0; i < env->used_btf_cnt; i++) {
17816 		if (env->used_btfs[i].btf == btf) {
17817 			btf_put(btf);
17818 			return 0;
17819 		}
17820 	}
17821 
17822 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
17823 		err = -E2BIG;
17824 		goto err_put;
17825 	}
17826 
17827 	btf_mod = &env->used_btfs[env->used_btf_cnt];
17828 	btf_mod->btf = btf;
17829 	btf_mod->module = NULL;
17830 
17831 	/* if we reference variables from kernel module, bump its refcount */
17832 	if (btf_is_module(btf)) {
17833 		btf_mod->module = btf_try_get_module(btf);
17834 		if (!btf_mod->module) {
17835 			err = -ENXIO;
17836 			goto err_put;
17837 		}
17838 	}
17839 
17840 	env->used_btf_cnt++;
17841 
17842 	return 0;
17843 err_put:
17844 	btf_put(btf);
17845 	return err;
17846 }
17847 
17848 static bool is_tracing_prog_type(enum bpf_prog_type type)
17849 {
17850 	switch (type) {
17851 	case BPF_PROG_TYPE_KPROBE:
17852 	case BPF_PROG_TYPE_TRACEPOINT:
17853 	case BPF_PROG_TYPE_PERF_EVENT:
17854 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17855 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17856 		return true;
17857 	default:
17858 		return false;
17859 	}
17860 }
17861 
17862 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17863 					struct bpf_map *map,
17864 					struct bpf_prog *prog)
17865 
17866 {
17867 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17868 
17869 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17870 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
17871 		if (is_tracing_prog_type(prog_type)) {
17872 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17873 			return -EINVAL;
17874 		}
17875 	}
17876 
17877 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17878 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17879 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17880 			return -EINVAL;
17881 		}
17882 
17883 		if (is_tracing_prog_type(prog_type)) {
17884 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17885 			return -EINVAL;
17886 		}
17887 	}
17888 
17889 	if (btf_record_has_field(map->record, BPF_TIMER)) {
17890 		if (is_tracing_prog_type(prog_type)) {
17891 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
17892 			return -EINVAL;
17893 		}
17894 	}
17895 
17896 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17897 	    !bpf_offload_prog_map_match(prog, map)) {
17898 		verbose(env, "offload device mismatch between prog and map\n");
17899 		return -EINVAL;
17900 	}
17901 
17902 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17903 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17904 		return -EINVAL;
17905 	}
17906 
17907 	if (prog->aux->sleepable)
17908 		switch (map->map_type) {
17909 		case BPF_MAP_TYPE_HASH:
17910 		case BPF_MAP_TYPE_LRU_HASH:
17911 		case BPF_MAP_TYPE_ARRAY:
17912 		case BPF_MAP_TYPE_PERCPU_HASH:
17913 		case BPF_MAP_TYPE_PERCPU_ARRAY:
17914 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17915 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17916 		case BPF_MAP_TYPE_HASH_OF_MAPS:
17917 		case BPF_MAP_TYPE_RINGBUF:
17918 		case BPF_MAP_TYPE_USER_RINGBUF:
17919 		case BPF_MAP_TYPE_INODE_STORAGE:
17920 		case BPF_MAP_TYPE_SK_STORAGE:
17921 		case BPF_MAP_TYPE_TASK_STORAGE:
17922 		case BPF_MAP_TYPE_CGRP_STORAGE:
17923 			break;
17924 		default:
17925 			verbose(env,
17926 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17927 			return -EINVAL;
17928 		}
17929 
17930 	return 0;
17931 }
17932 
17933 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17934 {
17935 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17936 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17937 }
17938 
17939 /* find and rewrite pseudo imm in ld_imm64 instructions:
17940  *
17941  * 1. if it accesses map FD, replace it with actual map pointer.
17942  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17943  *
17944  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17945  */
17946 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17947 {
17948 	struct bpf_insn *insn = env->prog->insnsi;
17949 	int insn_cnt = env->prog->len;
17950 	int i, j, err;
17951 
17952 	err = bpf_prog_calc_tag(env->prog);
17953 	if (err)
17954 		return err;
17955 
17956 	for (i = 0; i < insn_cnt; i++, insn++) {
17957 		if (BPF_CLASS(insn->code) == BPF_LDX &&
17958 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17959 		    insn->imm != 0)) {
17960 			verbose(env, "BPF_LDX uses reserved fields\n");
17961 			return -EINVAL;
17962 		}
17963 
17964 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17965 			struct bpf_insn_aux_data *aux;
17966 			struct bpf_map *map;
17967 			struct fd f;
17968 			u64 addr;
17969 			u32 fd;
17970 
17971 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
17972 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17973 			    insn[1].off != 0) {
17974 				verbose(env, "invalid bpf_ld_imm64 insn\n");
17975 				return -EINVAL;
17976 			}
17977 
17978 			if (insn[0].src_reg == 0)
17979 				/* valid generic load 64-bit imm */
17980 				goto next_insn;
17981 
17982 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17983 				aux = &env->insn_aux_data[i];
17984 				err = check_pseudo_btf_id(env, insn, aux);
17985 				if (err)
17986 					return err;
17987 				goto next_insn;
17988 			}
17989 
17990 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17991 				aux = &env->insn_aux_data[i];
17992 				aux->ptr_type = PTR_TO_FUNC;
17993 				goto next_insn;
17994 			}
17995 
17996 			/* In final convert_pseudo_ld_imm64() step, this is
17997 			 * converted into regular 64-bit imm load insn.
17998 			 */
17999 			switch (insn[0].src_reg) {
18000 			case BPF_PSEUDO_MAP_VALUE:
18001 			case BPF_PSEUDO_MAP_IDX_VALUE:
18002 				break;
18003 			case BPF_PSEUDO_MAP_FD:
18004 			case BPF_PSEUDO_MAP_IDX:
18005 				if (insn[1].imm == 0)
18006 					break;
18007 				fallthrough;
18008 			default:
18009 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
18010 				return -EINVAL;
18011 			}
18012 
18013 			switch (insn[0].src_reg) {
18014 			case BPF_PSEUDO_MAP_IDX_VALUE:
18015 			case BPF_PSEUDO_MAP_IDX:
18016 				if (bpfptr_is_null(env->fd_array)) {
18017 					verbose(env, "fd_idx without fd_array is invalid\n");
18018 					return -EPROTO;
18019 				}
18020 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
18021 							    insn[0].imm * sizeof(fd),
18022 							    sizeof(fd)))
18023 					return -EFAULT;
18024 				break;
18025 			default:
18026 				fd = insn[0].imm;
18027 				break;
18028 			}
18029 
18030 			f = fdget(fd);
18031 			map = __bpf_map_get(f);
18032 			if (IS_ERR(map)) {
18033 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
18034 					insn[0].imm);
18035 				return PTR_ERR(map);
18036 			}
18037 
18038 			err = check_map_prog_compatibility(env, map, env->prog);
18039 			if (err) {
18040 				fdput(f);
18041 				return err;
18042 			}
18043 
18044 			aux = &env->insn_aux_data[i];
18045 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
18046 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
18047 				addr = (unsigned long)map;
18048 			} else {
18049 				u32 off = insn[1].imm;
18050 
18051 				if (off >= BPF_MAX_VAR_OFF) {
18052 					verbose(env, "direct value offset of %u is not allowed\n", off);
18053 					fdput(f);
18054 					return -EINVAL;
18055 				}
18056 
18057 				if (!map->ops->map_direct_value_addr) {
18058 					verbose(env, "no direct value access support for this map type\n");
18059 					fdput(f);
18060 					return -EINVAL;
18061 				}
18062 
18063 				err = map->ops->map_direct_value_addr(map, &addr, off);
18064 				if (err) {
18065 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
18066 						map->value_size, off);
18067 					fdput(f);
18068 					return err;
18069 				}
18070 
18071 				aux->map_off = off;
18072 				addr += off;
18073 			}
18074 
18075 			insn[0].imm = (u32)addr;
18076 			insn[1].imm = addr >> 32;
18077 
18078 			/* check whether we recorded this map already */
18079 			for (j = 0; j < env->used_map_cnt; j++) {
18080 				if (env->used_maps[j] == map) {
18081 					aux->map_index = j;
18082 					fdput(f);
18083 					goto next_insn;
18084 				}
18085 			}
18086 
18087 			if (env->used_map_cnt >= MAX_USED_MAPS) {
18088 				fdput(f);
18089 				return -E2BIG;
18090 			}
18091 
18092 			if (env->prog->aux->sleepable)
18093 				atomic64_inc(&map->sleepable_refcnt);
18094 			/* hold the map. If the program is rejected by verifier,
18095 			 * the map will be released by release_maps() or it
18096 			 * will be used by the valid program until it's unloaded
18097 			 * and all maps are released in bpf_free_used_maps()
18098 			 */
18099 			bpf_map_inc(map);
18100 
18101 			aux->map_index = env->used_map_cnt;
18102 			env->used_maps[env->used_map_cnt++] = map;
18103 
18104 			if (bpf_map_is_cgroup_storage(map) &&
18105 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
18106 				verbose(env, "only one cgroup storage of each type is allowed\n");
18107 				fdput(f);
18108 				return -EBUSY;
18109 			}
18110 
18111 			fdput(f);
18112 next_insn:
18113 			insn++;
18114 			i++;
18115 			continue;
18116 		}
18117 
18118 		/* Basic sanity check before we invest more work here. */
18119 		if (!bpf_opcode_in_insntable(insn->code)) {
18120 			verbose(env, "unknown opcode %02x\n", insn->code);
18121 			return -EINVAL;
18122 		}
18123 	}
18124 
18125 	/* now all pseudo BPF_LD_IMM64 instructions load valid
18126 	 * 'struct bpf_map *' into a register instead of user map_fd.
18127 	 * These pointers will be used later by verifier to validate map access.
18128 	 */
18129 	return 0;
18130 }
18131 
18132 /* drop refcnt of maps used by the rejected program */
18133 static void release_maps(struct bpf_verifier_env *env)
18134 {
18135 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
18136 			     env->used_map_cnt);
18137 }
18138 
18139 /* drop refcnt of maps used by the rejected program */
18140 static void release_btfs(struct bpf_verifier_env *env)
18141 {
18142 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
18143 			     env->used_btf_cnt);
18144 }
18145 
18146 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
18147 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
18148 {
18149 	struct bpf_insn *insn = env->prog->insnsi;
18150 	int insn_cnt = env->prog->len;
18151 	int i;
18152 
18153 	for (i = 0; i < insn_cnt; i++, insn++) {
18154 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
18155 			continue;
18156 		if (insn->src_reg == BPF_PSEUDO_FUNC)
18157 			continue;
18158 		insn->src_reg = 0;
18159 	}
18160 }
18161 
18162 /* single env->prog->insni[off] instruction was replaced with the range
18163  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
18164  * [0, off) and [off, end) to new locations, so the patched range stays zero
18165  */
18166 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
18167 				 struct bpf_insn_aux_data *new_data,
18168 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
18169 {
18170 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
18171 	struct bpf_insn *insn = new_prog->insnsi;
18172 	u32 old_seen = old_data[off].seen;
18173 	u32 prog_len;
18174 	int i;
18175 
18176 	/* aux info at OFF always needs adjustment, no matter fast path
18177 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
18178 	 * original insn at old prog.
18179 	 */
18180 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
18181 
18182 	if (cnt == 1)
18183 		return;
18184 	prog_len = new_prog->len;
18185 
18186 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
18187 	memcpy(new_data + off + cnt - 1, old_data + off,
18188 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
18189 	for (i = off; i < off + cnt - 1; i++) {
18190 		/* Expand insni[off]'s seen count to the patched range. */
18191 		new_data[i].seen = old_seen;
18192 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
18193 	}
18194 	env->insn_aux_data = new_data;
18195 	vfree(old_data);
18196 }
18197 
18198 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
18199 {
18200 	int i;
18201 
18202 	if (len == 1)
18203 		return;
18204 	/* NOTE: fake 'exit' subprog should be updated as well. */
18205 	for (i = 0; i <= env->subprog_cnt; i++) {
18206 		if (env->subprog_info[i].start <= off)
18207 			continue;
18208 		env->subprog_info[i].start += len - 1;
18209 	}
18210 }
18211 
18212 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
18213 {
18214 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
18215 	int i, sz = prog->aux->size_poke_tab;
18216 	struct bpf_jit_poke_descriptor *desc;
18217 
18218 	for (i = 0; i < sz; i++) {
18219 		desc = &tab[i];
18220 		if (desc->insn_idx <= off)
18221 			continue;
18222 		desc->insn_idx += len - 1;
18223 	}
18224 }
18225 
18226 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
18227 					    const struct bpf_insn *patch, u32 len)
18228 {
18229 	struct bpf_prog *new_prog;
18230 	struct bpf_insn_aux_data *new_data = NULL;
18231 
18232 	if (len > 1) {
18233 		new_data = vzalloc(array_size(env->prog->len + len - 1,
18234 					      sizeof(struct bpf_insn_aux_data)));
18235 		if (!new_data)
18236 			return NULL;
18237 	}
18238 
18239 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
18240 	if (IS_ERR(new_prog)) {
18241 		if (PTR_ERR(new_prog) == -ERANGE)
18242 			verbose(env,
18243 				"insn %d cannot be patched due to 16-bit range\n",
18244 				env->insn_aux_data[off].orig_idx);
18245 		vfree(new_data);
18246 		return NULL;
18247 	}
18248 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
18249 	adjust_subprog_starts(env, off, len);
18250 	adjust_poke_descs(new_prog, off, len);
18251 	return new_prog;
18252 }
18253 
18254 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
18255 					      u32 off, u32 cnt)
18256 {
18257 	int i, j;
18258 
18259 	/* find first prog starting at or after off (first to remove) */
18260 	for (i = 0; i < env->subprog_cnt; i++)
18261 		if (env->subprog_info[i].start >= off)
18262 			break;
18263 	/* find first prog starting at or after off + cnt (first to stay) */
18264 	for (j = i; j < env->subprog_cnt; j++)
18265 		if (env->subprog_info[j].start >= off + cnt)
18266 			break;
18267 	/* if j doesn't start exactly at off + cnt, we are just removing
18268 	 * the front of previous prog
18269 	 */
18270 	if (env->subprog_info[j].start != off + cnt)
18271 		j--;
18272 
18273 	if (j > i) {
18274 		struct bpf_prog_aux *aux = env->prog->aux;
18275 		int move;
18276 
18277 		/* move fake 'exit' subprog as well */
18278 		move = env->subprog_cnt + 1 - j;
18279 
18280 		memmove(env->subprog_info + i,
18281 			env->subprog_info + j,
18282 			sizeof(*env->subprog_info) * move);
18283 		env->subprog_cnt -= j - i;
18284 
18285 		/* remove func_info */
18286 		if (aux->func_info) {
18287 			move = aux->func_info_cnt - j;
18288 
18289 			memmove(aux->func_info + i,
18290 				aux->func_info + j,
18291 				sizeof(*aux->func_info) * move);
18292 			aux->func_info_cnt -= j - i;
18293 			/* func_info->insn_off is set after all code rewrites,
18294 			 * in adjust_btf_func() - no need to adjust
18295 			 */
18296 		}
18297 	} else {
18298 		/* convert i from "first prog to remove" to "first to adjust" */
18299 		if (env->subprog_info[i].start == off)
18300 			i++;
18301 	}
18302 
18303 	/* update fake 'exit' subprog as well */
18304 	for (; i <= env->subprog_cnt; i++)
18305 		env->subprog_info[i].start -= cnt;
18306 
18307 	return 0;
18308 }
18309 
18310 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
18311 				      u32 cnt)
18312 {
18313 	struct bpf_prog *prog = env->prog;
18314 	u32 i, l_off, l_cnt, nr_linfo;
18315 	struct bpf_line_info *linfo;
18316 
18317 	nr_linfo = prog->aux->nr_linfo;
18318 	if (!nr_linfo)
18319 		return 0;
18320 
18321 	linfo = prog->aux->linfo;
18322 
18323 	/* find first line info to remove, count lines to be removed */
18324 	for (i = 0; i < nr_linfo; i++)
18325 		if (linfo[i].insn_off >= off)
18326 			break;
18327 
18328 	l_off = i;
18329 	l_cnt = 0;
18330 	for (; i < nr_linfo; i++)
18331 		if (linfo[i].insn_off < off + cnt)
18332 			l_cnt++;
18333 		else
18334 			break;
18335 
18336 	/* First live insn doesn't match first live linfo, it needs to "inherit"
18337 	 * last removed linfo.  prog is already modified, so prog->len == off
18338 	 * means no live instructions after (tail of the program was removed).
18339 	 */
18340 	if (prog->len != off && l_cnt &&
18341 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
18342 		l_cnt--;
18343 		linfo[--i].insn_off = off + cnt;
18344 	}
18345 
18346 	/* remove the line info which refer to the removed instructions */
18347 	if (l_cnt) {
18348 		memmove(linfo + l_off, linfo + i,
18349 			sizeof(*linfo) * (nr_linfo - i));
18350 
18351 		prog->aux->nr_linfo -= l_cnt;
18352 		nr_linfo = prog->aux->nr_linfo;
18353 	}
18354 
18355 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
18356 	for (i = l_off; i < nr_linfo; i++)
18357 		linfo[i].insn_off -= cnt;
18358 
18359 	/* fix up all subprogs (incl. 'exit') which start >= off */
18360 	for (i = 0; i <= env->subprog_cnt; i++)
18361 		if (env->subprog_info[i].linfo_idx > l_off) {
18362 			/* program may have started in the removed region but
18363 			 * may not be fully removed
18364 			 */
18365 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18366 				env->subprog_info[i].linfo_idx -= l_cnt;
18367 			else
18368 				env->subprog_info[i].linfo_idx = l_off;
18369 		}
18370 
18371 	return 0;
18372 }
18373 
18374 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18375 {
18376 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18377 	unsigned int orig_prog_len = env->prog->len;
18378 	int err;
18379 
18380 	if (bpf_prog_is_offloaded(env->prog->aux))
18381 		bpf_prog_offload_remove_insns(env, off, cnt);
18382 
18383 	err = bpf_remove_insns(env->prog, off, cnt);
18384 	if (err)
18385 		return err;
18386 
18387 	err = adjust_subprog_starts_after_remove(env, off, cnt);
18388 	if (err)
18389 		return err;
18390 
18391 	err = bpf_adj_linfo_after_remove(env, off, cnt);
18392 	if (err)
18393 		return err;
18394 
18395 	memmove(aux_data + off,	aux_data + off + cnt,
18396 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18397 
18398 	return 0;
18399 }
18400 
18401 /* The verifier does more data flow analysis than llvm and will not
18402  * explore branches that are dead at run time. Malicious programs can
18403  * have dead code too. Therefore replace all dead at-run-time code
18404  * with 'ja -1'.
18405  *
18406  * Just nops are not optimal, e.g. if they would sit at the end of the
18407  * program and through another bug we would manage to jump there, then
18408  * we'd execute beyond program memory otherwise. Returning exception
18409  * code also wouldn't work since we can have subprogs where the dead
18410  * code could be located.
18411  */
18412 static void sanitize_dead_code(struct bpf_verifier_env *env)
18413 {
18414 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18415 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18416 	struct bpf_insn *insn = env->prog->insnsi;
18417 	const int insn_cnt = env->prog->len;
18418 	int i;
18419 
18420 	for (i = 0; i < insn_cnt; i++) {
18421 		if (aux_data[i].seen)
18422 			continue;
18423 		memcpy(insn + i, &trap, sizeof(trap));
18424 		aux_data[i].zext_dst = false;
18425 	}
18426 }
18427 
18428 static bool insn_is_cond_jump(u8 code)
18429 {
18430 	u8 op;
18431 
18432 	op = BPF_OP(code);
18433 	if (BPF_CLASS(code) == BPF_JMP32)
18434 		return op != BPF_JA;
18435 
18436 	if (BPF_CLASS(code) != BPF_JMP)
18437 		return false;
18438 
18439 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18440 }
18441 
18442 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18443 {
18444 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18445 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18446 	struct bpf_insn *insn = env->prog->insnsi;
18447 	const int insn_cnt = env->prog->len;
18448 	int i;
18449 
18450 	for (i = 0; i < insn_cnt; i++, insn++) {
18451 		if (!insn_is_cond_jump(insn->code))
18452 			continue;
18453 
18454 		if (!aux_data[i + 1].seen)
18455 			ja.off = insn->off;
18456 		else if (!aux_data[i + 1 + insn->off].seen)
18457 			ja.off = 0;
18458 		else
18459 			continue;
18460 
18461 		if (bpf_prog_is_offloaded(env->prog->aux))
18462 			bpf_prog_offload_replace_insn(env, i, &ja);
18463 
18464 		memcpy(insn, &ja, sizeof(ja));
18465 	}
18466 }
18467 
18468 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18469 {
18470 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18471 	int insn_cnt = env->prog->len;
18472 	int i, err;
18473 
18474 	for (i = 0; i < insn_cnt; i++) {
18475 		int j;
18476 
18477 		j = 0;
18478 		while (i + j < insn_cnt && !aux_data[i + j].seen)
18479 			j++;
18480 		if (!j)
18481 			continue;
18482 
18483 		err = verifier_remove_insns(env, i, j);
18484 		if (err)
18485 			return err;
18486 		insn_cnt = env->prog->len;
18487 	}
18488 
18489 	return 0;
18490 }
18491 
18492 static int opt_remove_nops(struct bpf_verifier_env *env)
18493 {
18494 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18495 	struct bpf_insn *insn = env->prog->insnsi;
18496 	int insn_cnt = env->prog->len;
18497 	int i, err;
18498 
18499 	for (i = 0; i < insn_cnt; i++) {
18500 		if (memcmp(&insn[i], &ja, sizeof(ja)))
18501 			continue;
18502 
18503 		err = verifier_remove_insns(env, i, 1);
18504 		if (err)
18505 			return err;
18506 		insn_cnt--;
18507 		i--;
18508 	}
18509 
18510 	return 0;
18511 }
18512 
18513 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18514 					 const union bpf_attr *attr)
18515 {
18516 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18517 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18518 	int i, patch_len, delta = 0, len = env->prog->len;
18519 	struct bpf_insn *insns = env->prog->insnsi;
18520 	struct bpf_prog *new_prog;
18521 	bool rnd_hi32;
18522 
18523 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18524 	zext_patch[1] = BPF_ZEXT_REG(0);
18525 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18526 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18527 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18528 	for (i = 0; i < len; i++) {
18529 		int adj_idx = i + delta;
18530 		struct bpf_insn insn;
18531 		int load_reg;
18532 
18533 		insn = insns[adj_idx];
18534 		load_reg = insn_def_regno(&insn);
18535 		if (!aux[adj_idx].zext_dst) {
18536 			u8 code, class;
18537 			u32 imm_rnd;
18538 
18539 			if (!rnd_hi32)
18540 				continue;
18541 
18542 			code = insn.code;
18543 			class = BPF_CLASS(code);
18544 			if (load_reg == -1)
18545 				continue;
18546 
18547 			/* NOTE: arg "reg" (the fourth one) is only used for
18548 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
18549 			 *       here.
18550 			 */
18551 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18552 				if (class == BPF_LD &&
18553 				    BPF_MODE(code) == BPF_IMM)
18554 					i++;
18555 				continue;
18556 			}
18557 
18558 			/* ctx load could be transformed into wider load. */
18559 			if (class == BPF_LDX &&
18560 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
18561 				continue;
18562 
18563 			imm_rnd = get_random_u32();
18564 			rnd_hi32_patch[0] = insn;
18565 			rnd_hi32_patch[1].imm = imm_rnd;
18566 			rnd_hi32_patch[3].dst_reg = load_reg;
18567 			patch = rnd_hi32_patch;
18568 			patch_len = 4;
18569 			goto apply_patch_buffer;
18570 		}
18571 
18572 		/* Add in an zero-extend instruction if a) the JIT has requested
18573 		 * it or b) it's a CMPXCHG.
18574 		 *
18575 		 * The latter is because: BPF_CMPXCHG always loads a value into
18576 		 * R0, therefore always zero-extends. However some archs'
18577 		 * equivalent instruction only does this load when the
18578 		 * comparison is successful. This detail of CMPXCHG is
18579 		 * orthogonal to the general zero-extension behaviour of the
18580 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
18581 		 */
18582 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18583 			continue;
18584 
18585 		/* Zero-extension is done by the caller. */
18586 		if (bpf_pseudo_kfunc_call(&insn))
18587 			continue;
18588 
18589 		if (WARN_ON(load_reg == -1)) {
18590 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18591 			return -EFAULT;
18592 		}
18593 
18594 		zext_patch[0] = insn;
18595 		zext_patch[1].dst_reg = load_reg;
18596 		zext_patch[1].src_reg = load_reg;
18597 		patch = zext_patch;
18598 		patch_len = 2;
18599 apply_patch_buffer:
18600 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18601 		if (!new_prog)
18602 			return -ENOMEM;
18603 		env->prog = new_prog;
18604 		insns = new_prog->insnsi;
18605 		aux = env->insn_aux_data;
18606 		delta += patch_len - 1;
18607 	}
18608 
18609 	return 0;
18610 }
18611 
18612 /* convert load instructions that access fields of a context type into a
18613  * sequence of instructions that access fields of the underlying structure:
18614  *     struct __sk_buff    -> struct sk_buff
18615  *     struct bpf_sock_ops -> struct sock
18616  */
18617 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18618 {
18619 	const struct bpf_verifier_ops *ops = env->ops;
18620 	int i, cnt, size, ctx_field_size, delta = 0;
18621 	const int insn_cnt = env->prog->len;
18622 	struct bpf_insn insn_buf[16], *insn;
18623 	u32 target_size, size_default, off;
18624 	struct bpf_prog *new_prog;
18625 	enum bpf_access_type type;
18626 	bool is_narrower_load;
18627 
18628 	if (ops->gen_prologue || env->seen_direct_write) {
18629 		if (!ops->gen_prologue) {
18630 			verbose(env, "bpf verifier is misconfigured\n");
18631 			return -EINVAL;
18632 		}
18633 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18634 					env->prog);
18635 		if (cnt >= ARRAY_SIZE(insn_buf)) {
18636 			verbose(env, "bpf verifier is misconfigured\n");
18637 			return -EINVAL;
18638 		} else if (cnt) {
18639 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18640 			if (!new_prog)
18641 				return -ENOMEM;
18642 
18643 			env->prog = new_prog;
18644 			delta += cnt - 1;
18645 		}
18646 	}
18647 
18648 	if (bpf_prog_is_offloaded(env->prog->aux))
18649 		return 0;
18650 
18651 	insn = env->prog->insnsi + delta;
18652 
18653 	for (i = 0; i < insn_cnt; i++, insn++) {
18654 		bpf_convert_ctx_access_t convert_ctx_access;
18655 		u8 mode;
18656 
18657 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18658 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18659 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18660 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18661 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18662 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18663 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18664 			type = BPF_READ;
18665 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18666 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18667 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18668 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18669 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18670 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18671 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18672 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18673 			type = BPF_WRITE;
18674 		} else {
18675 			continue;
18676 		}
18677 
18678 		if (type == BPF_WRITE &&
18679 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
18680 			struct bpf_insn patch[] = {
18681 				*insn,
18682 				BPF_ST_NOSPEC(),
18683 			};
18684 
18685 			cnt = ARRAY_SIZE(patch);
18686 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18687 			if (!new_prog)
18688 				return -ENOMEM;
18689 
18690 			delta    += cnt - 1;
18691 			env->prog = new_prog;
18692 			insn      = new_prog->insnsi + i + delta;
18693 			continue;
18694 		}
18695 
18696 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18697 		case PTR_TO_CTX:
18698 			if (!ops->convert_ctx_access)
18699 				continue;
18700 			convert_ctx_access = ops->convert_ctx_access;
18701 			break;
18702 		case PTR_TO_SOCKET:
18703 		case PTR_TO_SOCK_COMMON:
18704 			convert_ctx_access = bpf_sock_convert_ctx_access;
18705 			break;
18706 		case PTR_TO_TCP_SOCK:
18707 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18708 			break;
18709 		case PTR_TO_XDP_SOCK:
18710 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18711 			break;
18712 		case PTR_TO_BTF_ID:
18713 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18714 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18715 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18716 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18717 		 * any faults for loads into such types. BPF_WRITE is disallowed
18718 		 * for this case.
18719 		 */
18720 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18721 			if (type == BPF_READ) {
18722 				if (BPF_MODE(insn->code) == BPF_MEM)
18723 					insn->code = BPF_LDX | BPF_PROBE_MEM |
18724 						     BPF_SIZE((insn)->code);
18725 				else
18726 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18727 						     BPF_SIZE((insn)->code);
18728 				env->prog->aux->num_exentries++;
18729 			}
18730 			continue;
18731 		default:
18732 			continue;
18733 		}
18734 
18735 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18736 		size = BPF_LDST_BYTES(insn);
18737 		mode = BPF_MODE(insn->code);
18738 
18739 		/* If the read access is a narrower load of the field,
18740 		 * convert to a 4/8-byte load, to minimum program type specific
18741 		 * convert_ctx_access changes. If conversion is successful,
18742 		 * we will apply proper mask to the result.
18743 		 */
18744 		is_narrower_load = size < ctx_field_size;
18745 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18746 		off = insn->off;
18747 		if (is_narrower_load) {
18748 			u8 size_code;
18749 
18750 			if (type == BPF_WRITE) {
18751 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18752 				return -EINVAL;
18753 			}
18754 
18755 			size_code = BPF_H;
18756 			if (ctx_field_size == 4)
18757 				size_code = BPF_W;
18758 			else if (ctx_field_size == 8)
18759 				size_code = BPF_DW;
18760 
18761 			insn->off = off & ~(size_default - 1);
18762 			insn->code = BPF_LDX | BPF_MEM | size_code;
18763 		}
18764 
18765 		target_size = 0;
18766 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18767 					 &target_size);
18768 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18769 		    (ctx_field_size && !target_size)) {
18770 			verbose(env, "bpf verifier is misconfigured\n");
18771 			return -EINVAL;
18772 		}
18773 
18774 		if (is_narrower_load && size < target_size) {
18775 			u8 shift = bpf_ctx_narrow_access_offset(
18776 				off, size, size_default) * 8;
18777 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18778 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18779 				return -EINVAL;
18780 			}
18781 			if (ctx_field_size <= 4) {
18782 				if (shift)
18783 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18784 									insn->dst_reg,
18785 									shift);
18786 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18787 								(1 << size * 8) - 1);
18788 			} else {
18789 				if (shift)
18790 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18791 									insn->dst_reg,
18792 									shift);
18793 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18794 								(1ULL << size * 8) - 1);
18795 			}
18796 		}
18797 		if (mode == BPF_MEMSX)
18798 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18799 						       insn->dst_reg, insn->dst_reg,
18800 						       size * 8, 0);
18801 
18802 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18803 		if (!new_prog)
18804 			return -ENOMEM;
18805 
18806 		delta += cnt - 1;
18807 
18808 		/* keep walking new program and skip insns we just inserted */
18809 		env->prog = new_prog;
18810 		insn      = new_prog->insnsi + i + delta;
18811 	}
18812 
18813 	return 0;
18814 }
18815 
18816 static int jit_subprogs(struct bpf_verifier_env *env)
18817 {
18818 	struct bpf_prog *prog = env->prog, **func, *tmp;
18819 	int i, j, subprog_start, subprog_end = 0, len, subprog;
18820 	struct bpf_map *map_ptr;
18821 	struct bpf_insn *insn;
18822 	void *old_bpf_func;
18823 	int err, num_exentries;
18824 
18825 	if (env->subprog_cnt <= 1)
18826 		return 0;
18827 
18828 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18829 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18830 			continue;
18831 
18832 		/* Upon error here we cannot fall back to interpreter but
18833 		 * need a hard reject of the program. Thus -EFAULT is
18834 		 * propagated in any case.
18835 		 */
18836 		subprog = find_subprog(env, i + insn->imm + 1);
18837 		if (subprog < 0) {
18838 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18839 				  i + insn->imm + 1);
18840 			return -EFAULT;
18841 		}
18842 		/* temporarily remember subprog id inside insn instead of
18843 		 * aux_data, since next loop will split up all insns into funcs
18844 		 */
18845 		insn->off = subprog;
18846 		/* remember original imm in case JIT fails and fallback
18847 		 * to interpreter will be needed
18848 		 */
18849 		env->insn_aux_data[i].call_imm = insn->imm;
18850 		/* point imm to __bpf_call_base+1 from JITs point of view */
18851 		insn->imm = 1;
18852 		if (bpf_pseudo_func(insn))
18853 			/* jit (e.g. x86_64) may emit fewer instructions
18854 			 * if it learns a u32 imm is the same as a u64 imm.
18855 			 * Force a non zero here.
18856 			 */
18857 			insn[1].imm = 1;
18858 	}
18859 
18860 	err = bpf_prog_alloc_jited_linfo(prog);
18861 	if (err)
18862 		goto out_undo_insn;
18863 
18864 	err = -ENOMEM;
18865 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18866 	if (!func)
18867 		goto out_undo_insn;
18868 
18869 	for (i = 0; i < env->subprog_cnt; i++) {
18870 		subprog_start = subprog_end;
18871 		subprog_end = env->subprog_info[i + 1].start;
18872 
18873 		len = subprog_end - subprog_start;
18874 		/* bpf_prog_run() doesn't call subprogs directly,
18875 		 * hence main prog stats include the runtime of subprogs.
18876 		 * subprogs don't have IDs and not reachable via prog_get_next_id
18877 		 * func[i]->stats will never be accessed and stays NULL
18878 		 */
18879 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18880 		if (!func[i])
18881 			goto out_free;
18882 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18883 		       len * sizeof(struct bpf_insn));
18884 		func[i]->type = prog->type;
18885 		func[i]->len = len;
18886 		if (bpf_prog_calc_tag(func[i]))
18887 			goto out_free;
18888 		func[i]->is_func = 1;
18889 		func[i]->aux->func_idx = i;
18890 		/* Below members will be freed only at prog->aux */
18891 		func[i]->aux->btf = prog->aux->btf;
18892 		func[i]->aux->func_info = prog->aux->func_info;
18893 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18894 		func[i]->aux->poke_tab = prog->aux->poke_tab;
18895 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18896 
18897 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
18898 			struct bpf_jit_poke_descriptor *poke;
18899 
18900 			poke = &prog->aux->poke_tab[j];
18901 			if (poke->insn_idx < subprog_end &&
18902 			    poke->insn_idx >= subprog_start)
18903 				poke->aux = func[i]->aux;
18904 		}
18905 
18906 		func[i]->aux->name[0] = 'F';
18907 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18908 		func[i]->jit_requested = 1;
18909 		func[i]->blinding_requested = prog->blinding_requested;
18910 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18911 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18912 		func[i]->aux->linfo = prog->aux->linfo;
18913 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18914 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18915 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18916 		num_exentries = 0;
18917 		insn = func[i]->insnsi;
18918 		for (j = 0; j < func[i]->len; j++, insn++) {
18919 			if (BPF_CLASS(insn->code) == BPF_LDX &&
18920 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18921 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18922 				num_exentries++;
18923 		}
18924 		func[i]->aux->num_exentries = num_exentries;
18925 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18926 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
18927 		if (!i)
18928 			func[i]->aux->exception_boundary = env->seen_exception;
18929 		func[i] = bpf_int_jit_compile(func[i]);
18930 		if (!func[i]->jited) {
18931 			err = -ENOTSUPP;
18932 			goto out_free;
18933 		}
18934 		cond_resched();
18935 	}
18936 
18937 	/* at this point all bpf functions were successfully JITed
18938 	 * now populate all bpf_calls with correct addresses and
18939 	 * run last pass of JIT
18940 	 */
18941 	for (i = 0; i < env->subprog_cnt; i++) {
18942 		insn = func[i]->insnsi;
18943 		for (j = 0; j < func[i]->len; j++, insn++) {
18944 			if (bpf_pseudo_func(insn)) {
18945 				subprog = insn->off;
18946 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18947 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18948 				continue;
18949 			}
18950 			if (!bpf_pseudo_call(insn))
18951 				continue;
18952 			subprog = insn->off;
18953 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18954 		}
18955 
18956 		/* we use the aux data to keep a list of the start addresses
18957 		 * of the JITed images for each function in the program
18958 		 *
18959 		 * for some architectures, such as powerpc64, the imm field
18960 		 * might not be large enough to hold the offset of the start
18961 		 * address of the callee's JITed image from __bpf_call_base
18962 		 *
18963 		 * in such cases, we can lookup the start address of a callee
18964 		 * by using its subprog id, available from the off field of
18965 		 * the call instruction, as an index for this list
18966 		 */
18967 		func[i]->aux->func = func;
18968 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
18969 		func[i]->aux->real_func_cnt = env->subprog_cnt;
18970 	}
18971 	for (i = 0; i < env->subprog_cnt; i++) {
18972 		old_bpf_func = func[i]->bpf_func;
18973 		tmp = bpf_int_jit_compile(func[i]);
18974 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18975 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18976 			err = -ENOTSUPP;
18977 			goto out_free;
18978 		}
18979 		cond_resched();
18980 	}
18981 
18982 	/* finally lock prog and jit images for all functions and
18983 	 * populate kallsysm. Begin at the first subprogram, since
18984 	 * bpf_prog_load will add the kallsyms for the main program.
18985 	 */
18986 	for (i = 1; i < env->subprog_cnt; i++) {
18987 		bpf_prog_lock_ro(func[i]);
18988 		bpf_prog_kallsyms_add(func[i]);
18989 	}
18990 
18991 	/* Last step: make now unused interpreter insns from main
18992 	 * prog consistent for later dump requests, so they can
18993 	 * later look the same as if they were interpreted only.
18994 	 */
18995 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18996 		if (bpf_pseudo_func(insn)) {
18997 			insn[0].imm = env->insn_aux_data[i].call_imm;
18998 			insn[1].imm = insn->off;
18999 			insn->off = 0;
19000 			continue;
19001 		}
19002 		if (!bpf_pseudo_call(insn))
19003 			continue;
19004 		insn->off = env->insn_aux_data[i].call_imm;
19005 		subprog = find_subprog(env, i + insn->off + 1);
19006 		insn->imm = subprog;
19007 	}
19008 
19009 	prog->jited = 1;
19010 	prog->bpf_func = func[0]->bpf_func;
19011 	prog->jited_len = func[0]->jited_len;
19012 	prog->aux->extable = func[0]->aux->extable;
19013 	prog->aux->num_exentries = func[0]->aux->num_exentries;
19014 	prog->aux->func = func;
19015 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19016 	prog->aux->real_func_cnt = env->subprog_cnt;
19017 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
19018 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
19019 	bpf_prog_jit_attempt_done(prog);
19020 	return 0;
19021 out_free:
19022 	/* We failed JIT'ing, so at this point we need to unregister poke
19023 	 * descriptors from subprogs, so that kernel is not attempting to
19024 	 * patch it anymore as we're freeing the subprog JIT memory.
19025 	 */
19026 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19027 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19028 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
19029 	}
19030 	/* At this point we're guaranteed that poke descriptors are not
19031 	 * live anymore. We can just unlink its descriptor table as it's
19032 	 * released with the main prog.
19033 	 */
19034 	for (i = 0; i < env->subprog_cnt; i++) {
19035 		if (!func[i])
19036 			continue;
19037 		func[i]->aux->poke_tab = NULL;
19038 		bpf_jit_free(func[i]);
19039 	}
19040 	kfree(func);
19041 out_undo_insn:
19042 	/* cleanup main prog to be interpreted */
19043 	prog->jit_requested = 0;
19044 	prog->blinding_requested = 0;
19045 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19046 		if (!bpf_pseudo_call(insn))
19047 			continue;
19048 		insn->off = 0;
19049 		insn->imm = env->insn_aux_data[i].call_imm;
19050 	}
19051 	bpf_prog_jit_attempt_done(prog);
19052 	return err;
19053 }
19054 
19055 static int fixup_call_args(struct bpf_verifier_env *env)
19056 {
19057 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19058 	struct bpf_prog *prog = env->prog;
19059 	struct bpf_insn *insn = prog->insnsi;
19060 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
19061 	int i, depth;
19062 #endif
19063 	int err = 0;
19064 
19065 	if (env->prog->jit_requested &&
19066 	    !bpf_prog_is_offloaded(env->prog->aux)) {
19067 		err = jit_subprogs(env);
19068 		if (err == 0)
19069 			return 0;
19070 		if (err == -EFAULT)
19071 			return err;
19072 	}
19073 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19074 	if (has_kfunc_call) {
19075 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
19076 		return -EINVAL;
19077 	}
19078 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
19079 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
19080 		 * have to be rejected, since interpreter doesn't support them yet.
19081 		 */
19082 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
19083 		return -EINVAL;
19084 	}
19085 	for (i = 0; i < prog->len; i++, insn++) {
19086 		if (bpf_pseudo_func(insn)) {
19087 			/* When JIT fails the progs with callback calls
19088 			 * have to be rejected, since interpreter doesn't support them yet.
19089 			 */
19090 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
19091 			return -EINVAL;
19092 		}
19093 
19094 		if (!bpf_pseudo_call(insn))
19095 			continue;
19096 		depth = get_callee_stack_depth(env, insn, i);
19097 		if (depth < 0)
19098 			return depth;
19099 		bpf_patch_call_args(insn, depth);
19100 	}
19101 	err = 0;
19102 #endif
19103 	return err;
19104 }
19105 
19106 /* replace a generic kfunc with a specialized version if necessary */
19107 static void specialize_kfunc(struct bpf_verifier_env *env,
19108 			     u32 func_id, u16 offset, unsigned long *addr)
19109 {
19110 	struct bpf_prog *prog = env->prog;
19111 	bool seen_direct_write;
19112 	void *xdp_kfunc;
19113 	bool is_rdonly;
19114 
19115 	if (bpf_dev_bound_kfunc_id(func_id)) {
19116 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
19117 		if (xdp_kfunc) {
19118 			*addr = (unsigned long)xdp_kfunc;
19119 			return;
19120 		}
19121 		/* fallback to default kfunc when not supported by netdev */
19122 	}
19123 
19124 	if (offset)
19125 		return;
19126 
19127 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
19128 		seen_direct_write = env->seen_direct_write;
19129 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
19130 
19131 		if (is_rdonly)
19132 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
19133 
19134 		/* restore env->seen_direct_write to its original value, since
19135 		 * may_access_direct_pkt_data mutates it
19136 		 */
19137 		env->seen_direct_write = seen_direct_write;
19138 	}
19139 }
19140 
19141 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
19142 					    u16 struct_meta_reg,
19143 					    u16 node_offset_reg,
19144 					    struct bpf_insn *insn,
19145 					    struct bpf_insn *insn_buf,
19146 					    int *cnt)
19147 {
19148 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
19149 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
19150 
19151 	insn_buf[0] = addr[0];
19152 	insn_buf[1] = addr[1];
19153 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
19154 	insn_buf[3] = *insn;
19155 	*cnt = 4;
19156 }
19157 
19158 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
19159 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
19160 {
19161 	const struct bpf_kfunc_desc *desc;
19162 
19163 	if (!insn->imm) {
19164 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
19165 		return -EINVAL;
19166 	}
19167 
19168 	*cnt = 0;
19169 
19170 	/* insn->imm has the btf func_id. Replace it with an offset relative to
19171 	 * __bpf_call_base, unless the JIT needs to call functions that are
19172 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
19173 	 */
19174 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
19175 	if (!desc) {
19176 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
19177 			insn->imm);
19178 		return -EFAULT;
19179 	}
19180 
19181 	if (!bpf_jit_supports_far_kfunc_call())
19182 		insn->imm = BPF_CALL_IMM(desc->addr);
19183 	if (insn->off)
19184 		return 0;
19185 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
19186 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
19187 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19188 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19189 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
19190 
19191 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
19192 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19193 				insn_idx);
19194 			return -EFAULT;
19195 		}
19196 
19197 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
19198 		insn_buf[1] = addr[0];
19199 		insn_buf[2] = addr[1];
19200 		insn_buf[3] = *insn;
19201 		*cnt = 4;
19202 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
19203 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
19204 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
19205 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19206 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19207 
19208 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
19209 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19210 				insn_idx);
19211 			return -EFAULT;
19212 		}
19213 
19214 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
19215 		    !kptr_struct_meta) {
19216 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19217 				insn_idx);
19218 			return -EFAULT;
19219 		}
19220 
19221 		insn_buf[0] = addr[0];
19222 		insn_buf[1] = addr[1];
19223 		insn_buf[2] = *insn;
19224 		*cnt = 3;
19225 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
19226 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
19227 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19228 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19229 		int struct_meta_reg = BPF_REG_3;
19230 		int node_offset_reg = BPF_REG_4;
19231 
19232 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
19233 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19234 			struct_meta_reg = BPF_REG_4;
19235 			node_offset_reg = BPF_REG_5;
19236 		}
19237 
19238 		if (!kptr_struct_meta) {
19239 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19240 				insn_idx);
19241 			return -EFAULT;
19242 		}
19243 
19244 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
19245 						node_offset_reg, insn, insn_buf, cnt);
19246 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
19247 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
19248 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
19249 		*cnt = 1;
19250 	}
19251 	return 0;
19252 }
19253 
19254 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
19255 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
19256 {
19257 	struct bpf_subprog_info *info = env->subprog_info;
19258 	int cnt = env->subprog_cnt;
19259 	struct bpf_prog *prog;
19260 
19261 	/* We only reserve one slot for hidden subprogs in subprog_info. */
19262 	if (env->hidden_subprog_cnt) {
19263 		verbose(env, "verifier internal error: only one hidden subprog supported\n");
19264 		return -EFAULT;
19265 	}
19266 	/* We're not patching any existing instruction, just appending the new
19267 	 * ones for the hidden subprog. Hence all of the adjustment operations
19268 	 * in bpf_patch_insn_data are no-ops.
19269 	 */
19270 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
19271 	if (!prog)
19272 		return -ENOMEM;
19273 	env->prog = prog;
19274 	info[cnt + 1].start = info[cnt].start;
19275 	info[cnt].start = prog->len - len + 1;
19276 	env->subprog_cnt++;
19277 	env->hidden_subprog_cnt++;
19278 	return 0;
19279 }
19280 
19281 /* Do various post-verification rewrites in a single program pass.
19282  * These rewrites simplify JIT and interpreter implementations.
19283  */
19284 static int do_misc_fixups(struct bpf_verifier_env *env)
19285 {
19286 	struct bpf_prog *prog = env->prog;
19287 	enum bpf_attach_type eatype = prog->expected_attach_type;
19288 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
19289 	struct bpf_insn *insn = prog->insnsi;
19290 	const struct bpf_func_proto *fn;
19291 	const int insn_cnt = prog->len;
19292 	const struct bpf_map_ops *ops;
19293 	struct bpf_insn_aux_data *aux;
19294 	struct bpf_insn insn_buf[16];
19295 	struct bpf_prog *new_prog;
19296 	struct bpf_map *map_ptr;
19297 	int i, ret, cnt, delta = 0;
19298 
19299 	if (env->seen_exception && !env->exception_callback_subprog) {
19300 		struct bpf_insn patch[] = {
19301 			env->prog->insnsi[insn_cnt - 1],
19302 			BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
19303 			BPF_EXIT_INSN(),
19304 		};
19305 
19306 		ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
19307 		if (ret < 0)
19308 			return ret;
19309 		prog = env->prog;
19310 		insn = prog->insnsi;
19311 
19312 		env->exception_callback_subprog = env->subprog_cnt - 1;
19313 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
19314 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
19315 	}
19316 
19317 	for (i = 0; i < insn_cnt; i++, insn++) {
19318 		/* Make divide-by-zero exceptions impossible. */
19319 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
19320 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
19321 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
19322 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
19323 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
19324 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
19325 			struct bpf_insn *patchlet;
19326 			struct bpf_insn chk_and_div[] = {
19327 				/* [R,W]x div 0 -> 0 */
19328 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19329 					     BPF_JNE | BPF_K, insn->src_reg,
19330 					     0, 2, 0),
19331 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
19332 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19333 				*insn,
19334 			};
19335 			struct bpf_insn chk_and_mod[] = {
19336 				/* [R,W]x mod 0 -> [R,W]x */
19337 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19338 					     BPF_JEQ | BPF_K, insn->src_reg,
19339 					     0, 1 + (is64 ? 0 : 1), 0),
19340 				*insn,
19341 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19342 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
19343 			};
19344 
19345 			patchlet = isdiv ? chk_and_div : chk_and_mod;
19346 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
19347 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
19348 
19349 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
19350 			if (!new_prog)
19351 				return -ENOMEM;
19352 
19353 			delta    += cnt - 1;
19354 			env->prog = prog = new_prog;
19355 			insn      = new_prog->insnsi + i + delta;
19356 			continue;
19357 		}
19358 
19359 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
19360 		if (BPF_CLASS(insn->code) == BPF_LD &&
19361 		    (BPF_MODE(insn->code) == BPF_ABS ||
19362 		     BPF_MODE(insn->code) == BPF_IND)) {
19363 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
19364 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19365 				verbose(env, "bpf verifier is misconfigured\n");
19366 				return -EINVAL;
19367 			}
19368 
19369 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19370 			if (!new_prog)
19371 				return -ENOMEM;
19372 
19373 			delta    += cnt - 1;
19374 			env->prog = prog = new_prog;
19375 			insn      = new_prog->insnsi + i + delta;
19376 			continue;
19377 		}
19378 
19379 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
19380 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
19381 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
19382 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
19383 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
19384 			struct bpf_insn *patch = &insn_buf[0];
19385 			bool issrc, isneg, isimm;
19386 			u32 off_reg;
19387 
19388 			aux = &env->insn_aux_data[i + delta];
19389 			if (!aux->alu_state ||
19390 			    aux->alu_state == BPF_ALU_NON_POINTER)
19391 				continue;
19392 
19393 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
19394 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
19395 				BPF_ALU_SANITIZE_SRC;
19396 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
19397 
19398 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
19399 			if (isimm) {
19400 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19401 			} else {
19402 				if (isneg)
19403 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19404 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19405 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
19406 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
19407 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
19408 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
19409 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
19410 			}
19411 			if (!issrc)
19412 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
19413 			insn->src_reg = BPF_REG_AX;
19414 			if (isneg)
19415 				insn->code = insn->code == code_add ?
19416 					     code_sub : code_add;
19417 			*patch++ = *insn;
19418 			if (issrc && isneg && !isimm)
19419 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19420 			cnt = patch - insn_buf;
19421 
19422 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19423 			if (!new_prog)
19424 				return -ENOMEM;
19425 
19426 			delta    += cnt - 1;
19427 			env->prog = prog = new_prog;
19428 			insn      = new_prog->insnsi + i + delta;
19429 			continue;
19430 		}
19431 
19432 		if (insn->code != (BPF_JMP | BPF_CALL))
19433 			continue;
19434 		if (insn->src_reg == BPF_PSEUDO_CALL)
19435 			continue;
19436 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19437 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19438 			if (ret)
19439 				return ret;
19440 			if (cnt == 0)
19441 				continue;
19442 
19443 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19444 			if (!new_prog)
19445 				return -ENOMEM;
19446 
19447 			delta	 += cnt - 1;
19448 			env->prog = prog = new_prog;
19449 			insn	  = new_prog->insnsi + i + delta;
19450 			continue;
19451 		}
19452 
19453 		if (insn->imm == BPF_FUNC_get_route_realm)
19454 			prog->dst_needed = 1;
19455 		if (insn->imm == BPF_FUNC_get_prandom_u32)
19456 			bpf_user_rnd_init_once();
19457 		if (insn->imm == BPF_FUNC_override_return)
19458 			prog->kprobe_override = 1;
19459 		if (insn->imm == BPF_FUNC_tail_call) {
19460 			/* If we tail call into other programs, we
19461 			 * cannot make any assumptions since they can
19462 			 * be replaced dynamically during runtime in
19463 			 * the program array.
19464 			 */
19465 			prog->cb_access = 1;
19466 			if (!allow_tail_call_in_subprogs(env))
19467 				prog->aux->stack_depth = MAX_BPF_STACK;
19468 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19469 
19470 			/* mark bpf_tail_call as different opcode to avoid
19471 			 * conditional branch in the interpreter for every normal
19472 			 * call and to prevent accidental JITing by JIT compiler
19473 			 * that doesn't support bpf_tail_call yet
19474 			 */
19475 			insn->imm = 0;
19476 			insn->code = BPF_JMP | BPF_TAIL_CALL;
19477 
19478 			aux = &env->insn_aux_data[i + delta];
19479 			if (env->bpf_capable && !prog->blinding_requested &&
19480 			    prog->jit_requested &&
19481 			    !bpf_map_key_poisoned(aux) &&
19482 			    !bpf_map_ptr_poisoned(aux) &&
19483 			    !bpf_map_ptr_unpriv(aux)) {
19484 				struct bpf_jit_poke_descriptor desc = {
19485 					.reason = BPF_POKE_REASON_TAIL_CALL,
19486 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19487 					.tail_call.key = bpf_map_key_immediate(aux),
19488 					.insn_idx = i + delta,
19489 				};
19490 
19491 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
19492 				if (ret < 0) {
19493 					verbose(env, "adding tail call poke descriptor failed\n");
19494 					return ret;
19495 				}
19496 
19497 				insn->imm = ret + 1;
19498 				continue;
19499 			}
19500 
19501 			if (!bpf_map_ptr_unpriv(aux))
19502 				continue;
19503 
19504 			/* instead of changing every JIT dealing with tail_call
19505 			 * emit two extra insns:
19506 			 * if (index >= max_entries) goto out;
19507 			 * index &= array->index_mask;
19508 			 * to avoid out-of-bounds cpu speculation
19509 			 */
19510 			if (bpf_map_ptr_poisoned(aux)) {
19511 				verbose(env, "tail_call abusing map_ptr\n");
19512 				return -EINVAL;
19513 			}
19514 
19515 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19516 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19517 						  map_ptr->max_entries, 2);
19518 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19519 						    container_of(map_ptr,
19520 								 struct bpf_array,
19521 								 map)->index_mask);
19522 			insn_buf[2] = *insn;
19523 			cnt = 3;
19524 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19525 			if (!new_prog)
19526 				return -ENOMEM;
19527 
19528 			delta    += cnt - 1;
19529 			env->prog = prog = new_prog;
19530 			insn      = new_prog->insnsi + i + delta;
19531 			continue;
19532 		}
19533 
19534 		if (insn->imm == BPF_FUNC_timer_set_callback) {
19535 			/* The verifier will process callback_fn as many times as necessary
19536 			 * with different maps and the register states prepared by
19537 			 * set_timer_callback_state will be accurate.
19538 			 *
19539 			 * The following use case is valid:
19540 			 *   map1 is shared by prog1, prog2, prog3.
19541 			 *   prog1 calls bpf_timer_init for some map1 elements
19542 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
19543 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
19544 			 *   prog3 calls bpf_timer_start for some map1 elements.
19545 			 *     Those that were not both bpf_timer_init-ed and
19546 			 *     bpf_timer_set_callback-ed will return -EINVAL.
19547 			 */
19548 			struct bpf_insn ld_addrs[2] = {
19549 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19550 			};
19551 
19552 			insn_buf[0] = ld_addrs[0];
19553 			insn_buf[1] = ld_addrs[1];
19554 			insn_buf[2] = *insn;
19555 			cnt = 3;
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 		if (is_storage_get_function(insn->imm)) {
19568 			if (!env->prog->aux->sleepable ||
19569 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
19570 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19571 			else
19572 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
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_per_cpu_ptr() and bpf_this_cpu_ptr() */
19587 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
19588 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
19589 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
19590 			 */
19591 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
19592 			insn_buf[1] = *insn;
19593 			cnt = 2;
19594 
19595 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19596 			if (!new_prog)
19597 				return -ENOMEM;
19598 
19599 			delta += cnt - 1;
19600 			env->prog = prog = new_prog;
19601 			insn = new_prog->insnsi + i + delta;
19602 			goto patch_call_imm;
19603 		}
19604 
19605 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19606 		 * and other inlining handlers are currently limited to 64 bit
19607 		 * only.
19608 		 */
19609 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19610 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
19611 		     insn->imm == BPF_FUNC_map_update_elem ||
19612 		     insn->imm == BPF_FUNC_map_delete_elem ||
19613 		     insn->imm == BPF_FUNC_map_push_elem   ||
19614 		     insn->imm == BPF_FUNC_map_pop_elem    ||
19615 		     insn->imm == BPF_FUNC_map_peek_elem   ||
19616 		     insn->imm == BPF_FUNC_redirect_map    ||
19617 		     insn->imm == BPF_FUNC_for_each_map_elem ||
19618 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19619 			aux = &env->insn_aux_data[i + delta];
19620 			if (bpf_map_ptr_poisoned(aux))
19621 				goto patch_call_imm;
19622 
19623 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19624 			ops = map_ptr->ops;
19625 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
19626 			    ops->map_gen_lookup) {
19627 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19628 				if (cnt == -EOPNOTSUPP)
19629 					goto patch_map_ops_generic;
19630 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19631 					verbose(env, "bpf verifier is misconfigured\n");
19632 					return -EINVAL;
19633 				}
19634 
19635 				new_prog = bpf_patch_insn_data(env, i + delta,
19636 							       insn_buf, cnt);
19637 				if (!new_prog)
19638 					return -ENOMEM;
19639 
19640 				delta    += cnt - 1;
19641 				env->prog = prog = new_prog;
19642 				insn      = new_prog->insnsi + i + delta;
19643 				continue;
19644 			}
19645 
19646 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19647 				     (void *(*)(struct bpf_map *map, void *key))NULL));
19648 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19649 				     (long (*)(struct bpf_map *map, void *key))NULL));
19650 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19651 				     (long (*)(struct bpf_map *map, void *key, void *value,
19652 					      u64 flags))NULL));
19653 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19654 				     (long (*)(struct bpf_map *map, void *value,
19655 					      u64 flags))NULL));
19656 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19657 				     (long (*)(struct bpf_map *map, void *value))NULL));
19658 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19659 				     (long (*)(struct bpf_map *map, void *value))NULL));
19660 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
19661 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19662 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19663 				     (long (*)(struct bpf_map *map,
19664 					      bpf_callback_t callback_fn,
19665 					      void *callback_ctx,
19666 					      u64 flags))NULL));
19667 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19668 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19669 
19670 patch_map_ops_generic:
19671 			switch (insn->imm) {
19672 			case BPF_FUNC_map_lookup_elem:
19673 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19674 				continue;
19675 			case BPF_FUNC_map_update_elem:
19676 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19677 				continue;
19678 			case BPF_FUNC_map_delete_elem:
19679 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19680 				continue;
19681 			case BPF_FUNC_map_push_elem:
19682 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19683 				continue;
19684 			case BPF_FUNC_map_pop_elem:
19685 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19686 				continue;
19687 			case BPF_FUNC_map_peek_elem:
19688 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19689 				continue;
19690 			case BPF_FUNC_redirect_map:
19691 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
19692 				continue;
19693 			case BPF_FUNC_for_each_map_elem:
19694 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19695 				continue;
19696 			case BPF_FUNC_map_lookup_percpu_elem:
19697 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19698 				continue;
19699 			}
19700 
19701 			goto patch_call_imm;
19702 		}
19703 
19704 		/* Implement bpf_jiffies64 inline. */
19705 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19706 		    insn->imm == BPF_FUNC_jiffies64) {
19707 			struct bpf_insn ld_jiffies_addr[2] = {
19708 				BPF_LD_IMM64(BPF_REG_0,
19709 					     (unsigned long)&jiffies),
19710 			};
19711 
19712 			insn_buf[0] = ld_jiffies_addr[0];
19713 			insn_buf[1] = ld_jiffies_addr[1];
19714 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19715 						  BPF_REG_0, 0);
19716 			cnt = 3;
19717 
19718 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19719 						       cnt);
19720 			if (!new_prog)
19721 				return -ENOMEM;
19722 
19723 			delta    += cnt - 1;
19724 			env->prog = prog = new_prog;
19725 			insn      = new_prog->insnsi + i + delta;
19726 			continue;
19727 		}
19728 
19729 		/* Implement bpf_get_func_arg inline. */
19730 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19731 		    insn->imm == BPF_FUNC_get_func_arg) {
19732 			/* Load nr_args from ctx - 8 */
19733 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19734 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19735 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19736 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19737 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19738 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19739 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19740 			insn_buf[7] = BPF_JMP_A(1);
19741 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19742 			cnt = 9;
19743 
19744 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19745 			if (!new_prog)
19746 				return -ENOMEM;
19747 
19748 			delta    += cnt - 1;
19749 			env->prog = prog = new_prog;
19750 			insn      = new_prog->insnsi + i + delta;
19751 			continue;
19752 		}
19753 
19754 		/* Implement bpf_get_func_ret inline. */
19755 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19756 		    insn->imm == BPF_FUNC_get_func_ret) {
19757 			if (eatype == BPF_TRACE_FEXIT ||
19758 			    eatype == BPF_MODIFY_RETURN) {
19759 				/* Load nr_args from ctx - 8 */
19760 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19761 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19762 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19763 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19764 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19765 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19766 				cnt = 6;
19767 			} else {
19768 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19769 				cnt = 1;
19770 			}
19771 
19772 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19773 			if (!new_prog)
19774 				return -ENOMEM;
19775 
19776 			delta    += cnt - 1;
19777 			env->prog = prog = new_prog;
19778 			insn      = new_prog->insnsi + i + delta;
19779 			continue;
19780 		}
19781 
19782 		/* Implement get_func_arg_cnt inline. */
19783 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19784 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
19785 			/* Load nr_args from ctx - 8 */
19786 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19787 
19788 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19789 			if (!new_prog)
19790 				return -ENOMEM;
19791 
19792 			env->prog = prog = new_prog;
19793 			insn      = new_prog->insnsi + i + delta;
19794 			continue;
19795 		}
19796 
19797 		/* Implement bpf_get_func_ip inline. */
19798 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19799 		    insn->imm == BPF_FUNC_get_func_ip) {
19800 			/* Load IP address from ctx - 16 */
19801 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19802 
19803 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19804 			if (!new_prog)
19805 				return -ENOMEM;
19806 
19807 			env->prog = prog = new_prog;
19808 			insn      = new_prog->insnsi + i + delta;
19809 			continue;
19810 		}
19811 
19812 patch_call_imm:
19813 		fn = env->ops->get_func_proto(insn->imm, env->prog);
19814 		/* all functions that have prototype and verifier allowed
19815 		 * programs to call them, must be real in-kernel functions
19816 		 */
19817 		if (!fn->func) {
19818 			verbose(env,
19819 				"kernel subsystem misconfigured func %s#%d\n",
19820 				func_id_name(insn->imm), insn->imm);
19821 			return -EFAULT;
19822 		}
19823 		insn->imm = fn->func - __bpf_call_base;
19824 	}
19825 
19826 	/* Since poke tab is now finalized, publish aux to tracker. */
19827 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19828 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19829 		if (!map_ptr->ops->map_poke_track ||
19830 		    !map_ptr->ops->map_poke_untrack ||
19831 		    !map_ptr->ops->map_poke_run) {
19832 			verbose(env, "bpf verifier is misconfigured\n");
19833 			return -EINVAL;
19834 		}
19835 
19836 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19837 		if (ret < 0) {
19838 			verbose(env, "tracking tail call prog failed\n");
19839 			return ret;
19840 		}
19841 	}
19842 
19843 	sort_kfunc_descs_by_imm_off(env->prog);
19844 
19845 	return 0;
19846 }
19847 
19848 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19849 					int position,
19850 					s32 stack_base,
19851 					u32 callback_subprogno,
19852 					u32 *cnt)
19853 {
19854 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19855 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19856 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19857 	int reg_loop_max = BPF_REG_6;
19858 	int reg_loop_cnt = BPF_REG_7;
19859 	int reg_loop_ctx = BPF_REG_8;
19860 
19861 	struct bpf_prog *new_prog;
19862 	u32 callback_start;
19863 	u32 call_insn_offset;
19864 	s32 callback_offset;
19865 
19866 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
19867 	 * be careful to modify this code in sync.
19868 	 */
19869 	struct bpf_insn insn_buf[] = {
19870 		/* Return error and jump to the end of the patch if
19871 		 * expected number of iterations is too big.
19872 		 */
19873 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19874 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19875 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19876 		/* spill R6, R7, R8 to use these as loop vars */
19877 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19878 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19879 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19880 		/* initialize loop vars */
19881 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19882 		BPF_MOV32_IMM(reg_loop_cnt, 0),
19883 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19884 		/* loop header,
19885 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
19886 		 */
19887 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19888 		/* callback call,
19889 		 * correct callback offset would be set after patching
19890 		 */
19891 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19892 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19893 		BPF_CALL_REL(0),
19894 		/* increment loop counter */
19895 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19896 		/* jump to loop header if callback returned 0 */
19897 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19898 		/* return value of bpf_loop,
19899 		 * set R0 to the number of iterations
19900 		 */
19901 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19902 		/* restore original values of R6, R7, R8 */
19903 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19904 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19905 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19906 	};
19907 
19908 	*cnt = ARRAY_SIZE(insn_buf);
19909 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19910 	if (!new_prog)
19911 		return new_prog;
19912 
19913 	/* callback start is known only after patching */
19914 	callback_start = env->subprog_info[callback_subprogno].start;
19915 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19916 	call_insn_offset = position + 12;
19917 	callback_offset = callback_start - call_insn_offset - 1;
19918 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
19919 
19920 	return new_prog;
19921 }
19922 
19923 static bool is_bpf_loop_call(struct bpf_insn *insn)
19924 {
19925 	return insn->code == (BPF_JMP | BPF_CALL) &&
19926 		insn->src_reg == 0 &&
19927 		insn->imm == BPF_FUNC_loop;
19928 }
19929 
19930 /* For all sub-programs in the program (including main) check
19931  * insn_aux_data to see if there are bpf_loop calls that require
19932  * inlining. If such calls are found the calls are replaced with a
19933  * sequence of instructions produced by `inline_bpf_loop` function and
19934  * subprog stack_depth is increased by the size of 3 registers.
19935  * This stack space is used to spill values of the R6, R7, R8.  These
19936  * registers are used to store the loop bound, counter and context
19937  * variables.
19938  */
19939 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19940 {
19941 	struct bpf_subprog_info *subprogs = env->subprog_info;
19942 	int i, cur_subprog = 0, cnt, delta = 0;
19943 	struct bpf_insn *insn = env->prog->insnsi;
19944 	int insn_cnt = env->prog->len;
19945 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
19946 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19947 	u16 stack_depth_extra = 0;
19948 
19949 	for (i = 0; i < insn_cnt; i++, insn++) {
19950 		struct bpf_loop_inline_state *inline_state =
19951 			&env->insn_aux_data[i + delta].loop_inline_state;
19952 
19953 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19954 			struct bpf_prog *new_prog;
19955 
19956 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19957 			new_prog = inline_bpf_loop(env,
19958 						   i + delta,
19959 						   -(stack_depth + stack_depth_extra),
19960 						   inline_state->callback_subprogno,
19961 						   &cnt);
19962 			if (!new_prog)
19963 				return -ENOMEM;
19964 
19965 			delta     += cnt - 1;
19966 			env->prog  = new_prog;
19967 			insn       = new_prog->insnsi + i + delta;
19968 		}
19969 
19970 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19971 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
19972 			cur_subprog++;
19973 			stack_depth = subprogs[cur_subprog].stack_depth;
19974 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19975 			stack_depth_extra = 0;
19976 		}
19977 	}
19978 
19979 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19980 
19981 	return 0;
19982 }
19983 
19984 static void free_states(struct bpf_verifier_env *env)
19985 {
19986 	struct bpf_verifier_state_list *sl, *sln;
19987 	int i;
19988 
19989 	sl = env->free_list;
19990 	while (sl) {
19991 		sln = sl->next;
19992 		free_verifier_state(&sl->state, false);
19993 		kfree(sl);
19994 		sl = sln;
19995 	}
19996 	env->free_list = NULL;
19997 
19998 	if (!env->explored_states)
19999 		return;
20000 
20001 	for (i = 0; i < state_htab_size(env); i++) {
20002 		sl = env->explored_states[i];
20003 
20004 		while (sl) {
20005 			sln = sl->next;
20006 			free_verifier_state(&sl->state, false);
20007 			kfree(sl);
20008 			sl = sln;
20009 		}
20010 		env->explored_states[i] = NULL;
20011 	}
20012 }
20013 
20014 static int do_check_common(struct bpf_verifier_env *env, int subprog)
20015 {
20016 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20017 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
20018 	struct bpf_verifier_state *state;
20019 	struct bpf_reg_state *regs;
20020 	int ret, i;
20021 
20022 	env->prev_linfo = NULL;
20023 	env->pass_cnt++;
20024 
20025 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
20026 	if (!state)
20027 		return -ENOMEM;
20028 	state->curframe = 0;
20029 	state->speculative = false;
20030 	state->branches = 1;
20031 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
20032 	if (!state->frame[0]) {
20033 		kfree(state);
20034 		return -ENOMEM;
20035 	}
20036 	env->cur_state = state;
20037 	init_func_state(env, state->frame[0],
20038 			BPF_MAIN_FUNC /* callsite */,
20039 			0 /* frameno */,
20040 			subprog);
20041 	state->first_insn_idx = env->subprog_info[subprog].start;
20042 	state->last_insn_idx = -1;
20043 
20044 
20045 	regs = state->frame[state->curframe]->regs;
20046 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
20047 		const char *sub_name = subprog_name(env, subprog);
20048 		struct bpf_subprog_arg_info *arg;
20049 		struct bpf_reg_state *reg;
20050 
20051 		verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
20052 		ret = btf_prepare_func_args(env, subprog);
20053 		if (ret)
20054 			goto out;
20055 
20056 		if (subprog_is_exc_cb(env, subprog)) {
20057 			state->frame[0]->in_exception_callback_fn = true;
20058 			/* We have already ensured that the callback returns an integer, just
20059 			 * like all global subprogs. We need to determine it only has a single
20060 			 * scalar argument.
20061 			 */
20062 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
20063 				verbose(env, "exception cb only supports single integer argument\n");
20064 				ret = -EINVAL;
20065 				goto out;
20066 			}
20067 		}
20068 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
20069 			arg = &sub->args[i - BPF_REG_1];
20070 			reg = &regs[i];
20071 
20072 			if (arg->arg_type == ARG_PTR_TO_CTX) {
20073 				reg->type = PTR_TO_CTX;
20074 				mark_reg_known_zero(env, regs, i);
20075 			} else if (arg->arg_type == ARG_ANYTHING) {
20076 				reg->type = SCALAR_VALUE;
20077 				mark_reg_unknown(env, regs, i);
20078 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
20079 				/* assume unspecial LOCAL dynptr type */
20080 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
20081 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
20082 				reg->type = PTR_TO_MEM;
20083 				if (arg->arg_type & PTR_MAYBE_NULL)
20084 					reg->type |= PTR_MAYBE_NULL;
20085 				mark_reg_known_zero(env, regs, i);
20086 				reg->mem_size = arg->mem_size;
20087 				reg->id = ++env->id_gen;
20088 			} else {
20089 				WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
20090 					  i - BPF_REG_1, arg->arg_type);
20091 				ret = -EFAULT;
20092 				goto out;
20093 			}
20094 		}
20095 	} else {
20096 		/* if main BPF program has associated BTF info, validate that
20097 		 * it's matching expected signature, and otherwise mark BTF
20098 		 * info for main program as unreliable
20099 		 */
20100 		if (env->prog->aux->func_info_aux) {
20101 			ret = btf_prepare_func_args(env, 0);
20102 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
20103 				env->prog->aux->func_info_aux[0].unreliable = true;
20104 		}
20105 
20106 		/* 1st arg to a function */
20107 		regs[BPF_REG_1].type = PTR_TO_CTX;
20108 		mark_reg_known_zero(env, regs, BPF_REG_1);
20109 	}
20110 
20111 	ret = do_check(env);
20112 out:
20113 	/* check for NULL is necessary, since cur_state can be freed inside
20114 	 * do_check() under memory pressure.
20115 	 */
20116 	if (env->cur_state) {
20117 		free_verifier_state(env->cur_state, true);
20118 		env->cur_state = NULL;
20119 	}
20120 	while (!pop_stack(env, NULL, NULL, false));
20121 	if (!ret && pop_log)
20122 		bpf_vlog_reset(&env->log, 0);
20123 	free_states(env);
20124 	return ret;
20125 }
20126 
20127 /* Lazily verify all global functions based on their BTF, if they are called
20128  * from main BPF program or any of subprograms transitively.
20129  * BPF global subprogs called from dead code are not validated.
20130  * All callable global functions must pass verification.
20131  * Otherwise the whole program is rejected.
20132  * Consider:
20133  * int bar(int);
20134  * int foo(int f)
20135  * {
20136  *    return bar(f);
20137  * }
20138  * int bar(int b)
20139  * {
20140  *    ...
20141  * }
20142  * foo() will be verified first for R1=any_scalar_value. During verification it
20143  * will be assumed that bar() already verified successfully and call to bar()
20144  * from foo() will be checked for type match only. Later bar() will be verified
20145  * independently to check that it's safe for R1=any_scalar_value.
20146  */
20147 static int do_check_subprogs(struct bpf_verifier_env *env)
20148 {
20149 	struct bpf_prog_aux *aux = env->prog->aux;
20150 	struct bpf_func_info_aux *sub_aux;
20151 	int i, ret, new_cnt;
20152 
20153 	if (!aux->func_info)
20154 		return 0;
20155 
20156 	/* exception callback is presumed to be always called */
20157 	if (env->exception_callback_subprog)
20158 		subprog_aux(env, env->exception_callback_subprog)->called = true;
20159 
20160 again:
20161 	new_cnt = 0;
20162 	for (i = 1; i < env->subprog_cnt; i++) {
20163 		if (!subprog_is_global(env, i))
20164 			continue;
20165 
20166 		sub_aux = subprog_aux(env, i);
20167 		if (!sub_aux->called || sub_aux->verified)
20168 			continue;
20169 
20170 		env->insn_idx = env->subprog_info[i].start;
20171 		WARN_ON_ONCE(env->insn_idx == 0);
20172 		ret = do_check_common(env, i);
20173 		if (ret) {
20174 			return ret;
20175 		} else if (env->log.level & BPF_LOG_LEVEL) {
20176 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
20177 				i, subprog_name(env, i));
20178 		}
20179 
20180 		/* We verified new global subprog, it might have called some
20181 		 * more global subprogs that we haven't verified yet, so we
20182 		 * need to do another pass over subprogs to verify those.
20183 		 */
20184 		sub_aux->verified = true;
20185 		new_cnt++;
20186 	}
20187 
20188 	/* We can't loop forever as we verify at least one global subprog on
20189 	 * each pass.
20190 	 */
20191 	if (new_cnt)
20192 		goto again;
20193 
20194 	return 0;
20195 }
20196 
20197 static int do_check_main(struct bpf_verifier_env *env)
20198 {
20199 	int ret;
20200 
20201 	env->insn_idx = 0;
20202 	ret = do_check_common(env, 0);
20203 	if (!ret)
20204 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20205 	return ret;
20206 }
20207 
20208 
20209 static void print_verification_stats(struct bpf_verifier_env *env)
20210 {
20211 	int i;
20212 
20213 	if (env->log.level & BPF_LOG_STATS) {
20214 		verbose(env, "verification time %lld usec\n",
20215 			div_u64(env->verification_time, 1000));
20216 		verbose(env, "stack depth ");
20217 		for (i = 0; i < env->subprog_cnt; i++) {
20218 			u32 depth = env->subprog_info[i].stack_depth;
20219 
20220 			verbose(env, "%d", depth);
20221 			if (i + 1 < env->subprog_cnt)
20222 				verbose(env, "+");
20223 		}
20224 		verbose(env, "\n");
20225 	}
20226 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
20227 		"total_states %d peak_states %d mark_read %d\n",
20228 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
20229 		env->max_states_per_insn, env->total_states,
20230 		env->peak_states, env->longest_mark_read_walk);
20231 }
20232 
20233 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
20234 {
20235 	const struct btf_type *t, *func_proto;
20236 	const struct bpf_struct_ops *st_ops;
20237 	const struct btf_member *member;
20238 	struct bpf_prog *prog = env->prog;
20239 	u32 btf_id, member_idx;
20240 	const char *mname;
20241 
20242 	if (!prog->gpl_compatible) {
20243 		verbose(env, "struct ops programs must have a GPL compatible license\n");
20244 		return -EINVAL;
20245 	}
20246 
20247 	btf_id = prog->aux->attach_btf_id;
20248 	st_ops = bpf_struct_ops_find(btf_id);
20249 	if (!st_ops) {
20250 		verbose(env, "attach_btf_id %u is not a supported struct\n",
20251 			btf_id);
20252 		return -ENOTSUPP;
20253 	}
20254 
20255 	t = st_ops->type;
20256 	member_idx = prog->expected_attach_type;
20257 	if (member_idx >= btf_type_vlen(t)) {
20258 		verbose(env, "attach to invalid member idx %u of struct %s\n",
20259 			member_idx, st_ops->name);
20260 		return -EINVAL;
20261 	}
20262 
20263 	member = &btf_type_member(t)[member_idx];
20264 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
20265 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
20266 					       NULL);
20267 	if (!func_proto) {
20268 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
20269 			mname, member_idx, st_ops->name);
20270 		return -EINVAL;
20271 	}
20272 
20273 	if (st_ops->check_member) {
20274 		int err = st_ops->check_member(t, member, prog);
20275 
20276 		if (err) {
20277 			verbose(env, "attach to unsupported member %s of struct %s\n",
20278 				mname, st_ops->name);
20279 			return err;
20280 		}
20281 	}
20282 
20283 	prog->aux->attach_func_proto = func_proto;
20284 	prog->aux->attach_func_name = mname;
20285 	env->ops = st_ops->verifier_ops;
20286 
20287 	return 0;
20288 }
20289 #define SECURITY_PREFIX "security_"
20290 
20291 static int check_attach_modify_return(unsigned long addr, const char *func_name)
20292 {
20293 	if (within_error_injection_list(addr) ||
20294 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
20295 		return 0;
20296 
20297 	return -EINVAL;
20298 }
20299 
20300 /* list of non-sleepable functions that are otherwise on
20301  * ALLOW_ERROR_INJECTION list
20302  */
20303 BTF_SET_START(btf_non_sleepable_error_inject)
20304 /* Three functions below can be called from sleepable and non-sleepable context.
20305  * Assume non-sleepable from bpf safety point of view.
20306  */
20307 BTF_ID(func, __filemap_add_folio)
20308 BTF_ID(func, should_fail_alloc_page)
20309 BTF_ID(func, should_failslab)
20310 BTF_SET_END(btf_non_sleepable_error_inject)
20311 
20312 static int check_non_sleepable_error_inject(u32 btf_id)
20313 {
20314 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
20315 }
20316 
20317 int bpf_check_attach_target(struct bpf_verifier_log *log,
20318 			    const struct bpf_prog *prog,
20319 			    const struct bpf_prog *tgt_prog,
20320 			    u32 btf_id,
20321 			    struct bpf_attach_target_info *tgt_info)
20322 {
20323 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
20324 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
20325 	const char prefix[] = "btf_trace_";
20326 	int ret = 0, subprog = -1, i;
20327 	const struct btf_type *t;
20328 	bool conservative = true;
20329 	const char *tname;
20330 	struct btf *btf;
20331 	long addr = 0;
20332 	struct module *mod = NULL;
20333 
20334 	if (!btf_id) {
20335 		bpf_log(log, "Tracing programs must provide btf_id\n");
20336 		return -EINVAL;
20337 	}
20338 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
20339 	if (!btf) {
20340 		bpf_log(log,
20341 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
20342 		return -EINVAL;
20343 	}
20344 	t = btf_type_by_id(btf, btf_id);
20345 	if (!t) {
20346 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
20347 		return -EINVAL;
20348 	}
20349 	tname = btf_name_by_offset(btf, t->name_off);
20350 	if (!tname) {
20351 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
20352 		return -EINVAL;
20353 	}
20354 	if (tgt_prog) {
20355 		struct bpf_prog_aux *aux = tgt_prog->aux;
20356 
20357 		if (bpf_prog_is_dev_bound(prog->aux) &&
20358 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
20359 			bpf_log(log, "Target program bound device mismatch");
20360 			return -EINVAL;
20361 		}
20362 
20363 		for (i = 0; i < aux->func_info_cnt; i++)
20364 			if (aux->func_info[i].type_id == btf_id) {
20365 				subprog = i;
20366 				break;
20367 			}
20368 		if (subprog == -1) {
20369 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
20370 			return -EINVAL;
20371 		}
20372 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
20373 			bpf_log(log,
20374 				"%s programs cannot attach to exception callback\n",
20375 				prog_extension ? "Extension" : "FENTRY/FEXIT");
20376 			return -EINVAL;
20377 		}
20378 		conservative = aux->func_info_aux[subprog].unreliable;
20379 		if (prog_extension) {
20380 			if (conservative) {
20381 				bpf_log(log,
20382 					"Cannot replace static functions\n");
20383 				return -EINVAL;
20384 			}
20385 			if (!prog->jit_requested) {
20386 				bpf_log(log,
20387 					"Extension programs should be JITed\n");
20388 				return -EINVAL;
20389 			}
20390 		}
20391 		if (!tgt_prog->jited) {
20392 			bpf_log(log, "Can attach to only JITed progs\n");
20393 			return -EINVAL;
20394 		}
20395 		if (prog_tracing) {
20396 			if (aux->attach_tracing_prog) {
20397 				/*
20398 				 * Target program is an fentry/fexit which is already attached
20399 				 * to another tracing program. More levels of nesting
20400 				 * attachment are not allowed.
20401 				 */
20402 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
20403 				return -EINVAL;
20404 			}
20405 		} else if (tgt_prog->type == prog->type) {
20406 			/*
20407 			 * To avoid potential call chain cycles, prevent attaching of a
20408 			 * program extension to another extension. It's ok to attach
20409 			 * fentry/fexit to extension program.
20410 			 */
20411 			bpf_log(log, "Cannot recursively attach\n");
20412 			return -EINVAL;
20413 		}
20414 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
20415 		    prog_extension &&
20416 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
20417 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
20418 			/* Program extensions can extend all program types
20419 			 * except fentry/fexit. The reason is the following.
20420 			 * The fentry/fexit programs are used for performance
20421 			 * analysis, stats and can be attached to any program
20422 			 * type. When extension program is replacing XDP function
20423 			 * it is necessary to allow performance analysis of all
20424 			 * functions. Both original XDP program and its program
20425 			 * extension. Hence attaching fentry/fexit to
20426 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
20427 			 * fentry/fexit was allowed it would be possible to create
20428 			 * long call chain fentry->extension->fentry->extension
20429 			 * beyond reasonable stack size. Hence extending fentry
20430 			 * is not allowed.
20431 			 */
20432 			bpf_log(log, "Cannot extend fentry/fexit\n");
20433 			return -EINVAL;
20434 		}
20435 	} else {
20436 		if (prog_extension) {
20437 			bpf_log(log, "Cannot replace kernel functions\n");
20438 			return -EINVAL;
20439 		}
20440 	}
20441 
20442 	switch (prog->expected_attach_type) {
20443 	case BPF_TRACE_RAW_TP:
20444 		if (tgt_prog) {
20445 			bpf_log(log,
20446 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
20447 			return -EINVAL;
20448 		}
20449 		if (!btf_type_is_typedef(t)) {
20450 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
20451 				btf_id);
20452 			return -EINVAL;
20453 		}
20454 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
20455 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
20456 				btf_id, tname);
20457 			return -EINVAL;
20458 		}
20459 		tname += sizeof(prefix) - 1;
20460 		t = btf_type_by_id(btf, t->type);
20461 		if (!btf_type_is_ptr(t))
20462 			/* should never happen in valid vmlinux build */
20463 			return -EINVAL;
20464 		t = btf_type_by_id(btf, t->type);
20465 		if (!btf_type_is_func_proto(t))
20466 			/* should never happen in valid vmlinux build */
20467 			return -EINVAL;
20468 
20469 		break;
20470 	case BPF_TRACE_ITER:
20471 		if (!btf_type_is_func(t)) {
20472 			bpf_log(log, "attach_btf_id %u is not a function\n",
20473 				btf_id);
20474 			return -EINVAL;
20475 		}
20476 		t = btf_type_by_id(btf, t->type);
20477 		if (!btf_type_is_func_proto(t))
20478 			return -EINVAL;
20479 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20480 		if (ret)
20481 			return ret;
20482 		break;
20483 	default:
20484 		if (!prog_extension)
20485 			return -EINVAL;
20486 		fallthrough;
20487 	case BPF_MODIFY_RETURN:
20488 	case BPF_LSM_MAC:
20489 	case BPF_LSM_CGROUP:
20490 	case BPF_TRACE_FENTRY:
20491 	case BPF_TRACE_FEXIT:
20492 		if (!btf_type_is_func(t)) {
20493 			bpf_log(log, "attach_btf_id %u is not a function\n",
20494 				btf_id);
20495 			return -EINVAL;
20496 		}
20497 		if (prog_extension &&
20498 		    btf_check_type_match(log, prog, btf, t))
20499 			return -EINVAL;
20500 		t = btf_type_by_id(btf, t->type);
20501 		if (!btf_type_is_func_proto(t))
20502 			return -EINVAL;
20503 
20504 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
20505 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
20506 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
20507 			return -EINVAL;
20508 
20509 		if (tgt_prog && conservative)
20510 			t = NULL;
20511 
20512 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20513 		if (ret < 0)
20514 			return ret;
20515 
20516 		if (tgt_prog) {
20517 			if (subprog == 0)
20518 				addr = (long) tgt_prog->bpf_func;
20519 			else
20520 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20521 		} else {
20522 			if (btf_is_module(btf)) {
20523 				mod = btf_try_get_module(btf);
20524 				if (mod)
20525 					addr = find_kallsyms_symbol_value(mod, tname);
20526 				else
20527 					addr = 0;
20528 			} else {
20529 				addr = kallsyms_lookup_name(tname);
20530 			}
20531 			if (!addr) {
20532 				module_put(mod);
20533 				bpf_log(log,
20534 					"The address of function %s cannot be found\n",
20535 					tname);
20536 				return -ENOENT;
20537 			}
20538 		}
20539 
20540 		if (prog->aux->sleepable) {
20541 			ret = -EINVAL;
20542 			switch (prog->type) {
20543 			case BPF_PROG_TYPE_TRACING:
20544 
20545 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
20546 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20547 				 */
20548 				if (!check_non_sleepable_error_inject(btf_id) &&
20549 				    within_error_injection_list(addr))
20550 					ret = 0;
20551 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
20552 				 * in the fmodret id set with the KF_SLEEPABLE flag.
20553 				 */
20554 				else {
20555 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20556 										prog);
20557 
20558 					if (flags && (*flags & KF_SLEEPABLE))
20559 						ret = 0;
20560 				}
20561 				break;
20562 			case BPF_PROG_TYPE_LSM:
20563 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
20564 				 * Only some of them are sleepable.
20565 				 */
20566 				if (bpf_lsm_is_sleepable_hook(btf_id))
20567 					ret = 0;
20568 				break;
20569 			default:
20570 				break;
20571 			}
20572 			if (ret) {
20573 				module_put(mod);
20574 				bpf_log(log, "%s is not sleepable\n", tname);
20575 				return ret;
20576 			}
20577 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20578 			if (tgt_prog) {
20579 				module_put(mod);
20580 				bpf_log(log, "can't modify return codes of BPF programs\n");
20581 				return -EINVAL;
20582 			}
20583 			ret = -EINVAL;
20584 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20585 			    !check_attach_modify_return(addr, tname))
20586 				ret = 0;
20587 			if (ret) {
20588 				module_put(mod);
20589 				bpf_log(log, "%s() is not modifiable\n", tname);
20590 				return ret;
20591 			}
20592 		}
20593 
20594 		break;
20595 	}
20596 	tgt_info->tgt_addr = addr;
20597 	tgt_info->tgt_name = tname;
20598 	tgt_info->tgt_type = t;
20599 	tgt_info->tgt_mod = mod;
20600 	return 0;
20601 }
20602 
20603 BTF_SET_START(btf_id_deny)
20604 BTF_ID_UNUSED
20605 #ifdef CONFIG_SMP
20606 BTF_ID(func, migrate_disable)
20607 BTF_ID(func, migrate_enable)
20608 #endif
20609 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20610 BTF_ID(func, rcu_read_unlock_strict)
20611 #endif
20612 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20613 BTF_ID(func, preempt_count_add)
20614 BTF_ID(func, preempt_count_sub)
20615 #endif
20616 #ifdef CONFIG_PREEMPT_RCU
20617 BTF_ID(func, __rcu_read_lock)
20618 BTF_ID(func, __rcu_read_unlock)
20619 #endif
20620 BTF_SET_END(btf_id_deny)
20621 
20622 static bool can_be_sleepable(struct bpf_prog *prog)
20623 {
20624 	if (prog->type == BPF_PROG_TYPE_TRACING) {
20625 		switch (prog->expected_attach_type) {
20626 		case BPF_TRACE_FENTRY:
20627 		case BPF_TRACE_FEXIT:
20628 		case BPF_MODIFY_RETURN:
20629 		case BPF_TRACE_ITER:
20630 			return true;
20631 		default:
20632 			return false;
20633 		}
20634 	}
20635 	return prog->type == BPF_PROG_TYPE_LSM ||
20636 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20637 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20638 }
20639 
20640 static int check_attach_btf_id(struct bpf_verifier_env *env)
20641 {
20642 	struct bpf_prog *prog = env->prog;
20643 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20644 	struct bpf_attach_target_info tgt_info = {};
20645 	u32 btf_id = prog->aux->attach_btf_id;
20646 	struct bpf_trampoline *tr;
20647 	int ret;
20648 	u64 key;
20649 
20650 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20651 		if (prog->aux->sleepable)
20652 			/* attach_btf_id checked to be zero already */
20653 			return 0;
20654 		verbose(env, "Syscall programs can only be sleepable\n");
20655 		return -EINVAL;
20656 	}
20657 
20658 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20659 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20660 		return -EINVAL;
20661 	}
20662 
20663 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20664 		return check_struct_ops_btf_id(env);
20665 
20666 	if (prog->type != BPF_PROG_TYPE_TRACING &&
20667 	    prog->type != BPF_PROG_TYPE_LSM &&
20668 	    prog->type != BPF_PROG_TYPE_EXT)
20669 		return 0;
20670 
20671 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20672 	if (ret)
20673 		return ret;
20674 
20675 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20676 		/* to make freplace equivalent to their targets, they need to
20677 		 * inherit env->ops and expected_attach_type for the rest of the
20678 		 * verification
20679 		 */
20680 		env->ops = bpf_verifier_ops[tgt_prog->type];
20681 		prog->expected_attach_type = tgt_prog->expected_attach_type;
20682 	}
20683 
20684 	/* store info about the attachment target that will be used later */
20685 	prog->aux->attach_func_proto = tgt_info.tgt_type;
20686 	prog->aux->attach_func_name = tgt_info.tgt_name;
20687 	prog->aux->mod = tgt_info.tgt_mod;
20688 
20689 	if (tgt_prog) {
20690 		prog->aux->saved_dst_prog_type = tgt_prog->type;
20691 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20692 	}
20693 
20694 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20695 		prog->aux->attach_btf_trace = true;
20696 		return 0;
20697 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20698 		if (!bpf_iter_prog_supported(prog))
20699 			return -EINVAL;
20700 		return 0;
20701 	}
20702 
20703 	if (prog->type == BPF_PROG_TYPE_LSM) {
20704 		ret = bpf_lsm_verify_prog(&env->log, prog);
20705 		if (ret < 0)
20706 			return ret;
20707 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
20708 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
20709 		return -EINVAL;
20710 	}
20711 
20712 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20713 	tr = bpf_trampoline_get(key, &tgt_info);
20714 	if (!tr)
20715 		return -ENOMEM;
20716 
20717 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20718 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20719 
20720 	prog->aux->dst_trampoline = tr;
20721 	return 0;
20722 }
20723 
20724 struct btf *bpf_get_btf_vmlinux(void)
20725 {
20726 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20727 		mutex_lock(&bpf_verifier_lock);
20728 		if (!btf_vmlinux)
20729 			btf_vmlinux = btf_parse_vmlinux();
20730 		mutex_unlock(&bpf_verifier_lock);
20731 	}
20732 	return btf_vmlinux;
20733 }
20734 
20735 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20736 {
20737 	u64 start_time = ktime_get_ns();
20738 	struct bpf_verifier_env *env;
20739 	int i, len, ret = -EINVAL, err;
20740 	u32 log_true_size;
20741 	bool is_priv;
20742 
20743 	/* no program is valid */
20744 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20745 		return -EINVAL;
20746 
20747 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
20748 	 * allocate/free it every time bpf_check() is called
20749 	 */
20750 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20751 	if (!env)
20752 		return -ENOMEM;
20753 
20754 	env->bt.env = env;
20755 
20756 	len = (*prog)->len;
20757 	env->insn_aux_data =
20758 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20759 	ret = -ENOMEM;
20760 	if (!env->insn_aux_data)
20761 		goto err_free_env;
20762 	for (i = 0; i < len; i++)
20763 		env->insn_aux_data[i].orig_idx = i;
20764 	env->prog = *prog;
20765 	env->ops = bpf_verifier_ops[env->prog->type];
20766 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20767 	is_priv = bpf_capable();
20768 
20769 	bpf_get_btf_vmlinux();
20770 
20771 	/* grab the mutex to protect few globals used by verifier */
20772 	if (!is_priv)
20773 		mutex_lock(&bpf_verifier_lock);
20774 
20775 	/* user could have requested verbose verifier output
20776 	 * and supplied buffer to store the verification trace
20777 	 */
20778 	ret = bpf_vlog_init(&env->log, attr->log_level,
20779 			    (char __user *) (unsigned long) attr->log_buf,
20780 			    attr->log_size);
20781 	if (ret)
20782 		goto err_unlock;
20783 
20784 	mark_verifier_state_clean(env);
20785 
20786 	if (IS_ERR(btf_vmlinux)) {
20787 		/* Either gcc or pahole or kernel are broken. */
20788 		verbose(env, "in-kernel BTF is malformed\n");
20789 		ret = PTR_ERR(btf_vmlinux);
20790 		goto skip_full_check;
20791 	}
20792 
20793 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20794 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20795 		env->strict_alignment = true;
20796 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20797 		env->strict_alignment = false;
20798 
20799 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20800 	env->allow_uninit_stack = bpf_allow_uninit_stack();
20801 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
20802 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
20803 	env->bpf_capable = bpf_capable();
20804 
20805 	if (is_priv)
20806 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20807 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
20808 
20809 	env->explored_states = kvcalloc(state_htab_size(env),
20810 				       sizeof(struct bpf_verifier_state_list *),
20811 				       GFP_USER);
20812 	ret = -ENOMEM;
20813 	if (!env->explored_states)
20814 		goto skip_full_check;
20815 
20816 	ret = check_btf_info_early(env, attr, uattr);
20817 	if (ret < 0)
20818 		goto skip_full_check;
20819 
20820 	ret = add_subprog_and_kfunc(env);
20821 	if (ret < 0)
20822 		goto skip_full_check;
20823 
20824 	ret = check_subprogs(env);
20825 	if (ret < 0)
20826 		goto skip_full_check;
20827 
20828 	ret = check_btf_info(env, attr, uattr);
20829 	if (ret < 0)
20830 		goto skip_full_check;
20831 
20832 	ret = check_attach_btf_id(env);
20833 	if (ret)
20834 		goto skip_full_check;
20835 
20836 	ret = resolve_pseudo_ldimm64(env);
20837 	if (ret < 0)
20838 		goto skip_full_check;
20839 
20840 	if (bpf_prog_is_offloaded(env->prog->aux)) {
20841 		ret = bpf_prog_offload_verifier_prep(env->prog);
20842 		if (ret)
20843 			goto skip_full_check;
20844 	}
20845 
20846 	ret = check_cfg(env);
20847 	if (ret < 0)
20848 		goto skip_full_check;
20849 
20850 	ret = do_check_main(env);
20851 	ret = ret ?: do_check_subprogs(env);
20852 
20853 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20854 		ret = bpf_prog_offload_finalize(env);
20855 
20856 skip_full_check:
20857 	kvfree(env->explored_states);
20858 
20859 	if (ret == 0)
20860 		ret = check_max_stack_depth(env);
20861 
20862 	/* instruction rewrites happen after this point */
20863 	if (ret == 0)
20864 		ret = optimize_bpf_loop(env);
20865 
20866 	if (is_priv) {
20867 		if (ret == 0)
20868 			opt_hard_wire_dead_code_branches(env);
20869 		if (ret == 0)
20870 			ret = opt_remove_dead_code(env);
20871 		if (ret == 0)
20872 			ret = opt_remove_nops(env);
20873 	} else {
20874 		if (ret == 0)
20875 			sanitize_dead_code(env);
20876 	}
20877 
20878 	if (ret == 0)
20879 		/* program is valid, convert *(u32*)(ctx + off) accesses */
20880 		ret = convert_ctx_accesses(env);
20881 
20882 	if (ret == 0)
20883 		ret = do_misc_fixups(env);
20884 
20885 	/* do 32-bit optimization after insn patching has done so those patched
20886 	 * insns could be handled correctly.
20887 	 */
20888 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20889 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20890 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20891 								     : false;
20892 	}
20893 
20894 	if (ret == 0)
20895 		ret = fixup_call_args(env);
20896 
20897 	env->verification_time = ktime_get_ns() - start_time;
20898 	print_verification_stats(env);
20899 	env->prog->aux->verified_insns = env->insn_processed;
20900 
20901 	/* preserve original error even if log finalization is successful */
20902 	err = bpf_vlog_finalize(&env->log, &log_true_size);
20903 	if (err)
20904 		ret = err;
20905 
20906 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20907 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20908 				  &log_true_size, sizeof(log_true_size))) {
20909 		ret = -EFAULT;
20910 		goto err_release_maps;
20911 	}
20912 
20913 	if (ret)
20914 		goto err_release_maps;
20915 
20916 	if (env->used_map_cnt) {
20917 		/* if program passed verifier, update used_maps in bpf_prog_info */
20918 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20919 							  sizeof(env->used_maps[0]),
20920 							  GFP_KERNEL);
20921 
20922 		if (!env->prog->aux->used_maps) {
20923 			ret = -ENOMEM;
20924 			goto err_release_maps;
20925 		}
20926 
20927 		memcpy(env->prog->aux->used_maps, env->used_maps,
20928 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
20929 		env->prog->aux->used_map_cnt = env->used_map_cnt;
20930 	}
20931 	if (env->used_btf_cnt) {
20932 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
20933 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20934 							  sizeof(env->used_btfs[0]),
20935 							  GFP_KERNEL);
20936 		if (!env->prog->aux->used_btfs) {
20937 			ret = -ENOMEM;
20938 			goto err_release_maps;
20939 		}
20940 
20941 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
20942 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20943 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20944 	}
20945 	if (env->used_map_cnt || env->used_btf_cnt) {
20946 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
20947 		 * bpf_ld_imm64 instructions
20948 		 */
20949 		convert_pseudo_ld_imm64(env);
20950 	}
20951 
20952 	adjust_btf_func(env);
20953 
20954 err_release_maps:
20955 	if (!env->prog->aux->used_maps)
20956 		/* if we didn't copy map pointers into bpf_prog_info, release
20957 		 * them now. Otherwise free_used_maps() will release them.
20958 		 */
20959 		release_maps(env);
20960 	if (!env->prog->aux->used_btfs)
20961 		release_btfs(env);
20962 
20963 	/* extension progs temporarily inherit the attach_type of their targets
20964 	   for verification purposes, so set it back to zero before returning
20965 	 */
20966 	if (env->prog->type == BPF_PROG_TYPE_EXT)
20967 		env->prog->expected_attach_type = 0;
20968 
20969 	*prog = env->prog;
20970 err_unlock:
20971 	if (!is_priv)
20972 		mutex_unlock(&bpf_verifier_lock);
20973 	vfree(env->insn_aux_data);
20974 err_free_env:
20975 	kfree(env);
20976 	return ret;
20977 }
20978