xref: /linux/kernel/bpf/verifier.c (revision 79ac11393328fb1717d17c12e3c0eef0e9fa0647)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <linux/bpf_mem_alloc.h>
30 #include <net/xdp.h>
31 
32 #include "disasm.h"
33 
34 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
35 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
36 	[_id] = & _name ## _verifier_ops,
37 #define BPF_MAP_TYPE(_id, _ops)
38 #define BPF_LINK_TYPE(_id, _name)
39 #include <linux/bpf_types.h>
40 #undef BPF_PROG_TYPE
41 #undef BPF_MAP_TYPE
42 #undef BPF_LINK_TYPE
43 };
44 
45 struct bpf_mem_alloc bpf_global_percpu_ma;
46 static bool bpf_global_percpu_ma_set;
47 
48 /* bpf_check() is a static code analyzer that walks eBPF program
49  * instruction by instruction and updates register/stack state.
50  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
51  *
52  * The first pass is depth-first-search to check that the program is a DAG.
53  * It rejects the following programs:
54  * - larger than BPF_MAXINSNS insns
55  * - if loop is present (detected via back-edge)
56  * - unreachable insns exist (shouldn't be a forest. program = one function)
57  * - out of bounds or malformed jumps
58  * The second pass is all possible path descent from the 1st insn.
59  * Since it's analyzing all paths through the program, the length of the
60  * analysis is limited to 64k insn, which may be hit even if total number of
61  * insn is less then 4K, but there are too many branches that change stack/regs.
62  * Number of 'branches to be analyzed' is limited to 1k
63  *
64  * On entry to each instruction, each register has a type, and the instruction
65  * changes the types of the registers depending on instruction semantics.
66  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
67  * copied to R1.
68  *
69  * All registers are 64-bit.
70  * R0 - return register
71  * R1-R5 argument passing registers
72  * R6-R9 callee saved registers
73  * R10 - frame pointer read-only
74  *
75  * At the start of BPF program the register R1 contains a pointer to bpf_context
76  * and has type PTR_TO_CTX.
77  *
78  * Verifier tracks arithmetic operations on pointers in case:
79  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
80  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
81  * 1st insn copies R10 (which has FRAME_PTR) type into R1
82  * and 2nd arithmetic instruction is pattern matched to recognize
83  * that it wants to construct a pointer to some element within stack.
84  * So after 2nd insn, the register R1 has type PTR_TO_STACK
85  * (and -20 constant is saved for further stack bounds checking).
86  * Meaning that this reg is a pointer to stack plus known immediate constant.
87  *
88  * Most of the time the registers have SCALAR_VALUE type, which
89  * means the register has some value, but it's not a valid pointer.
90  * (like pointer plus pointer becomes SCALAR_VALUE type)
91  *
92  * When verifier sees load or store instructions the type of base register
93  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
94  * four pointer types recognized by check_mem_access() function.
95  *
96  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
97  * and the range of [ptr, ptr + map's value_size) is accessible.
98  *
99  * registers used to pass values to function calls are checked against
100  * function argument constraints.
101  *
102  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
103  * It means that the register type passed to this function must be
104  * PTR_TO_STACK and it will be used inside the function as
105  * 'pointer to map element key'
106  *
107  * For example the argument constraints for bpf_map_lookup_elem():
108  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
109  *   .arg1_type = ARG_CONST_MAP_PTR,
110  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
111  *
112  * ret_type says that this function returns 'pointer to map elem value or null'
113  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
114  * 2nd argument should be a pointer to stack, which will be used inside
115  * the helper function as a pointer to map element key.
116  *
117  * On the kernel side the helper function looks like:
118  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
119  * {
120  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
121  *    void *key = (void *) (unsigned long) r2;
122  *    void *value;
123  *
124  *    here kernel can access 'key' and 'map' pointers safely, knowing that
125  *    [key, key + map->key_size) bytes are valid and were initialized on
126  *    the stack of eBPF program.
127  * }
128  *
129  * Corresponding eBPF program may look like:
130  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
131  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
132  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
133  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
134  * here verifier looks at prototype of map_lookup_elem() and sees:
135  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
136  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
137  *
138  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
139  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
140  * and were initialized prior to this call.
141  * If it's ok, then verifier allows this BPF_CALL insn and looks at
142  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
143  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
144  * returns either pointer to map value or NULL.
145  *
146  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
147  * insn, the register holding that pointer in the true branch changes state to
148  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
149  * branch. See check_cond_jmp_op().
150  *
151  * After the call R0 is set to return type of the function and registers R1-R5
152  * are set to NOT_INIT to indicate that they are no longer readable.
153  *
154  * The following reference types represent a potential reference to a kernel
155  * resource which, after first being allocated, must be checked and freed by
156  * the BPF program:
157  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
158  *
159  * When the verifier sees a helper call return a reference type, it allocates a
160  * pointer id for the reference and stores it in the current function state.
161  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
162  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
163  * passes through a NULL-check conditional. For the branch wherein the state is
164  * changed to CONST_IMM, the verifier releases the reference.
165  *
166  * For each helper function that allocates a reference, such as
167  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
168  * bpf_sk_release(). When a reference type passes into the release function,
169  * the verifier also releases the reference. If any unchecked or unreleased
170  * reference remains at the end of the program, the verifier rejects it.
171  */
172 
173 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
174 struct bpf_verifier_stack_elem {
175 	/* verifer state is 'st'
176 	 * before processing instruction 'insn_idx'
177 	 * and after processing instruction 'prev_insn_idx'
178 	 */
179 	struct bpf_verifier_state st;
180 	int insn_idx;
181 	int prev_insn_idx;
182 	struct bpf_verifier_stack_elem *next;
183 	/* length of verifier log at the time this state was pushed on stack */
184 	u32 log_pos;
185 };
186 
187 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
188 #define BPF_COMPLEXITY_LIMIT_STATES	64
189 
190 #define BPF_MAP_KEY_POISON	(1ULL << 63)
191 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
192 
193 #define BPF_MAP_PTR_UNPRIV	1UL
194 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
195 					  POISON_POINTER_DELTA))
196 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
197 
198 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
199 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
200 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
201 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
202 static int ref_set_non_owning(struct bpf_verifier_env *env,
203 			      struct bpf_reg_state *reg);
204 static void specialize_kfunc(struct bpf_verifier_env *env,
205 			     u32 func_id, u16 offset, unsigned long *addr);
206 static bool is_trusted_reg(const struct bpf_reg_state *reg);
207 
208 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
209 {
210 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
211 }
212 
213 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
214 {
215 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
216 }
217 
218 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
219 			      const struct bpf_map *map, bool unpriv)
220 {
221 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
222 	unpriv |= bpf_map_ptr_unpriv(aux);
223 	aux->map_ptr_state = (unsigned long)map |
224 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
225 }
226 
227 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
228 {
229 	return aux->map_key_state & BPF_MAP_KEY_POISON;
230 }
231 
232 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
233 {
234 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
235 }
236 
237 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
238 {
239 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
240 }
241 
242 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
243 {
244 	bool poisoned = bpf_map_key_poisoned(aux);
245 
246 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
247 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
248 }
249 
250 static bool bpf_helper_call(const struct bpf_insn *insn)
251 {
252 	return insn->code == (BPF_JMP | BPF_CALL) &&
253 	       insn->src_reg == 0;
254 }
255 
256 static bool bpf_pseudo_call(const struct bpf_insn *insn)
257 {
258 	return insn->code == (BPF_JMP | BPF_CALL) &&
259 	       insn->src_reg == BPF_PSEUDO_CALL;
260 }
261 
262 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
263 {
264 	return insn->code == (BPF_JMP | BPF_CALL) &&
265 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
266 }
267 
268 struct bpf_call_arg_meta {
269 	struct bpf_map *map_ptr;
270 	bool raw_mode;
271 	bool pkt_access;
272 	u8 release_regno;
273 	int regno;
274 	int access_size;
275 	int mem_size;
276 	u64 msize_max_value;
277 	int ref_obj_id;
278 	int dynptr_id;
279 	int map_uid;
280 	int func_id;
281 	struct btf *btf;
282 	u32 btf_id;
283 	struct btf *ret_btf;
284 	u32 ret_btf_id;
285 	u32 subprogno;
286 	struct btf_field *kptr_field;
287 };
288 
289 struct bpf_kfunc_call_arg_meta {
290 	/* In parameters */
291 	struct btf *btf;
292 	u32 func_id;
293 	u32 kfunc_flags;
294 	const struct btf_type *func_proto;
295 	const char *func_name;
296 	/* Out parameters */
297 	u32 ref_obj_id;
298 	u8 release_regno;
299 	bool r0_rdonly;
300 	u32 ret_btf_id;
301 	u64 r0_size;
302 	u32 subprogno;
303 	struct {
304 		u64 value;
305 		bool found;
306 	} arg_constant;
307 
308 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
309 	 * generally to pass info about user-defined local kptr types to later
310 	 * verification logic
311 	 *   bpf_obj_drop/bpf_percpu_obj_drop
312 	 *     Record the local kptr type to be drop'd
313 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
314 	 *     Record the local kptr type to be refcount_incr'd and use
315 	 *     arg_owning_ref to determine whether refcount_acquire should be
316 	 *     fallible
317 	 */
318 	struct btf *arg_btf;
319 	u32 arg_btf_id;
320 	bool arg_owning_ref;
321 
322 	struct {
323 		struct btf_field *field;
324 	} arg_list_head;
325 	struct {
326 		struct btf_field *field;
327 	} arg_rbtree_root;
328 	struct {
329 		enum bpf_dynptr_type type;
330 		u32 id;
331 		u32 ref_obj_id;
332 	} initialized_dynptr;
333 	struct {
334 		u8 spi;
335 		u8 frameno;
336 	} iter;
337 	u64 mem_size;
338 };
339 
340 struct btf *btf_vmlinux;
341 
342 static const char *btf_type_name(const struct btf *btf, u32 id)
343 {
344 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
345 }
346 
347 static DEFINE_MUTEX(bpf_verifier_lock);
348 static DEFINE_MUTEX(bpf_percpu_ma_lock);
349 
350 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
351 {
352 	struct bpf_verifier_env *env = private_data;
353 	va_list args;
354 
355 	if (!bpf_verifier_log_needed(&env->log))
356 		return;
357 
358 	va_start(args, fmt);
359 	bpf_verifier_vlog(&env->log, fmt, args);
360 	va_end(args);
361 }
362 
363 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
364 				   struct bpf_reg_state *reg,
365 				   struct tnum *range, const char *ctx,
366 				   const char *reg_name)
367 {
368 	char tn_buf[48];
369 
370 	verbose(env, "At %s the register %s ", ctx, reg_name);
371 	if (!tnum_is_unknown(reg->var_off)) {
372 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
373 		verbose(env, "has value %s", tn_buf);
374 	} else {
375 		verbose(env, "has unknown scalar value");
376 	}
377 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
378 	verbose(env, " should have been in %s\n", tn_buf);
379 }
380 
381 static bool type_may_be_null(u32 type)
382 {
383 	return type & PTR_MAYBE_NULL;
384 }
385 
386 static bool reg_not_null(const struct bpf_reg_state *reg)
387 {
388 	enum bpf_reg_type type;
389 
390 	type = reg->type;
391 	if (type_may_be_null(type))
392 		return false;
393 
394 	type = base_type(type);
395 	return type == PTR_TO_SOCKET ||
396 		type == PTR_TO_TCP_SOCK ||
397 		type == PTR_TO_MAP_VALUE ||
398 		type == PTR_TO_MAP_KEY ||
399 		type == PTR_TO_SOCK_COMMON ||
400 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
401 		type == PTR_TO_MEM;
402 }
403 
404 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
405 {
406 	struct btf_record *rec = NULL;
407 	struct btf_struct_meta *meta;
408 
409 	if (reg->type == PTR_TO_MAP_VALUE) {
410 		rec = reg->map_ptr->record;
411 	} else if (type_is_ptr_alloc_obj(reg->type)) {
412 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
413 		if (meta)
414 			rec = meta->record;
415 	}
416 	return rec;
417 }
418 
419 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
420 {
421 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
422 
423 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
424 }
425 
426 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
427 {
428 	struct bpf_func_info *info;
429 
430 	if (!env->prog->aux->func_info)
431 		return "";
432 
433 	info = &env->prog->aux->func_info[subprog];
434 	return btf_type_name(env->prog->aux->btf, info->type_id);
435 }
436 
437 static struct bpf_func_info_aux *subprog_aux(const struct bpf_verifier_env *env, int subprog)
438 {
439 	return &env->prog->aux->func_info_aux[subprog];
440 }
441 
442 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
443 {
444 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
445 }
446 
447 static bool type_is_rdonly_mem(u32 type)
448 {
449 	return type & MEM_RDONLY;
450 }
451 
452 static bool is_acquire_function(enum bpf_func_id func_id,
453 				const struct bpf_map *map)
454 {
455 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
456 
457 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
458 	    func_id == BPF_FUNC_sk_lookup_udp ||
459 	    func_id == BPF_FUNC_skc_lookup_tcp ||
460 	    func_id == BPF_FUNC_ringbuf_reserve ||
461 	    func_id == BPF_FUNC_kptr_xchg)
462 		return true;
463 
464 	if (func_id == BPF_FUNC_map_lookup_elem &&
465 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
466 	     map_type == BPF_MAP_TYPE_SOCKHASH))
467 		return true;
468 
469 	return false;
470 }
471 
472 static bool is_ptr_cast_function(enum bpf_func_id func_id)
473 {
474 	return func_id == BPF_FUNC_tcp_sock ||
475 		func_id == BPF_FUNC_sk_fullsock ||
476 		func_id == BPF_FUNC_skc_to_tcp_sock ||
477 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
478 		func_id == BPF_FUNC_skc_to_udp6_sock ||
479 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
480 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
481 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
482 }
483 
484 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
485 {
486 	return func_id == BPF_FUNC_dynptr_data;
487 }
488 
489 static bool is_sync_callback_calling_kfunc(u32 btf_id);
490 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
491 
492 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
493 {
494 	return func_id == BPF_FUNC_for_each_map_elem ||
495 	       func_id == BPF_FUNC_find_vma ||
496 	       func_id == BPF_FUNC_loop ||
497 	       func_id == BPF_FUNC_user_ringbuf_drain;
498 }
499 
500 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
501 {
502 	return func_id == BPF_FUNC_timer_set_callback;
503 }
504 
505 static bool is_callback_calling_function(enum bpf_func_id func_id)
506 {
507 	return is_sync_callback_calling_function(func_id) ||
508 	       is_async_callback_calling_function(func_id);
509 }
510 
511 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
512 {
513 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
514 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
515 }
516 
517 static bool is_storage_get_function(enum bpf_func_id func_id)
518 {
519 	return func_id == BPF_FUNC_sk_storage_get ||
520 	       func_id == BPF_FUNC_inode_storage_get ||
521 	       func_id == BPF_FUNC_task_storage_get ||
522 	       func_id == BPF_FUNC_cgrp_storage_get;
523 }
524 
525 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
526 					const struct bpf_map *map)
527 {
528 	int ref_obj_uses = 0;
529 
530 	if (is_ptr_cast_function(func_id))
531 		ref_obj_uses++;
532 	if (is_acquire_function(func_id, map))
533 		ref_obj_uses++;
534 	if (is_dynptr_ref_function(func_id))
535 		ref_obj_uses++;
536 
537 	return ref_obj_uses > 1;
538 }
539 
540 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
541 {
542 	return BPF_CLASS(insn->code) == BPF_STX &&
543 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
544 	       insn->imm == BPF_CMPXCHG;
545 }
546 
547 static int __get_spi(s32 off)
548 {
549 	return (-off - 1) / BPF_REG_SIZE;
550 }
551 
552 static struct bpf_func_state *func(struct bpf_verifier_env *env,
553 				   const struct bpf_reg_state *reg)
554 {
555 	struct bpf_verifier_state *cur = env->cur_state;
556 
557 	return cur->frame[reg->frameno];
558 }
559 
560 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
561 {
562        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
563 
564        /* We need to check that slots between [spi - nr_slots + 1, spi] are
565 	* within [0, allocated_stack).
566 	*
567 	* Please note that the spi grows downwards. For example, a dynptr
568 	* takes the size of two stack slots; the first slot will be at
569 	* spi and the second slot will be at spi - 1.
570 	*/
571        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
572 }
573 
574 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
575 			          const char *obj_kind, int nr_slots)
576 {
577 	int off, spi;
578 
579 	if (!tnum_is_const(reg->var_off)) {
580 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
581 		return -EINVAL;
582 	}
583 
584 	off = reg->off + reg->var_off.value;
585 	if (off % BPF_REG_SIZE) {
586 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
587 		return -EINVAL;
588 	}
589 
590 	spi = __get_spi(off);
591 	if (spi + 1 < nr_slots) {
592 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
593 		return -EINVAL;
594 	}
595 
596 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
597 		return -ERANGE;
598 	return spi;
599 }
600 
601 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
602 {
603 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
604 }
605 
606 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
607 {
608 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
609 }
610 
611 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
612 {
613 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
614 	case DYNPTR_TYPE_LOCAL:
615 		return BPF_DYNPTR_TYPE_LOCAL;
616 	case DYNPTR_TYPE_RINGBUF:
617 		return BPF_DYNPTR_TYPE_RINGBUF;
618 	case DYNPTR_TYPE_SKB:
619 		return BPF_DYNPTR_TYPE_SKB;
620 	case DYNPTR_TYPE_XDP:
621 		return BPF_DYNPTR_TYPE_XDP;
622 	default:
623 		return BPF_DYNPTR_TYPE_INVALID;
624 	}
625 }
626 
627 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
628 {
629 	switch (type) {
630 	case BPF_DYNPTR_TYPE_LOCAL:
631 		return DYNPTR_TYPE_LOCAL;
632 	case BPF_DYNPTR_TYPE_RINGBUF:
633 		return DYNPTR_TYPE_RINGBUF;
634 	case BPF_DYNPTR_TYPE_SKB:
635 		return DYNPTR_TYPE_SKB;
636 	case BPF_DYNPTR_TYPE_XDP:
637 		return DYNPTR_TYPE_XDP;
638 	default:
639 		return 0;
640 	}
641 }
642 
643 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
644 {
645 	return type == BPF_DYNPTR_TYPE_RINGBUF;
646 }
647 
648 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
649 			      enum bpf_dynptr_type type,
650 			      bool first_slot, int dynptr_id);
651 
652 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
653 				struct bpf_reg_state *reg);
654 
655 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
656 				   struct bpf_reg_state *sreg1,
657 				   struct bpf_reg_state *sreg2,
658 				   enum bpf_dynptr_type type)
659 {
660 	int id = ++env->id_gen;
661 
662 	__mark_dynptr_reg(sreg1, type, true, id);
663 	__mark_dynptr_reg(sreg2, type, false, id);
664 }
665 
666 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
667 			       struct bpf_reg_state *reg,
668 			       enum bpf_dynptr_type type)
669 {
670 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
671 }
672 
673 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
674 				        struct bpf_func_state *state, int spi);
675 
676 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
677 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
678 {
679 	struct bpf_func_state *state = func(env, reg);
680 	enum bpf_dynptr_type type;
681 	int spi, i, err;
682 
683 	spi = dynptr_get_spi(env, reg);
684 	if (spi < 0)
685 		return spi;
686 
687 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
688 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
689 	 * to ensure that for the following example:
690 	 *	[d1][d1][d2][d2]
691 	 * spi    3   2   1   0
692 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
693 	 * case they do belong to same dynptr, second call won't see slot_type
694 	 * as STACK_DYNPTR and will simply skip destruction.
695 	 */
696 	err = destroy_if_dynptr_stack_slot(env, state, spi);
697 	if (err)
698 		return err;
699 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
700 	if (err)
701 		return err;
702 
703 	for (i = 0; i < BPF_REG_SIZE; i++) {
704 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
705 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
706 	}
707 
708 	type = arg_to_dynptr_type(arg_type);
709 	if (type == BPF_DYNPTR_TYPE_INVALID)
710 		return -EINVAL;
711 
712 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
713 			       &state->stack[spi - 1].spilled_ptr, type);
714 
715 	if (dynptr_type_refcounted(type)) {
716 		/* The id is used to track proper releasing */
717 		int id;
718 
719 		if (clone_ref_obj_id)
720 			id = clone_ref_obj_id;
721 		else
722 			id = acquire_reference_state(env, insn_idx);
723 
724 		if (id < 0)
725 			return id;
726 
727 		state->stack[spi].spilled_ptr.ref_obj_id = id;
728 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
729 	}
730 
731 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
732 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
733 
734 	return 0;
735 }
736 
737 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
738 {
739 	int i;
740 
741 	for (i = 0; i < BPF_REG_SIZE; i++) {
742 		state->stack[spi].slot_type[i] = STACK_INVALID;
743 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
744 	}
745 
746 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
747 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
748 
749 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
750 	 *
751 	 * While we don't allow reading STACK_INVALID, it is still possible to
752 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
753 	 * helpers or insns can do partial read of that part without failing,
754 	 * but check_stack_range_initialized, check_stack_read_var_off, and
755 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
756 	 * the slot conservatively. Hence we need to prevent those liveness
757 	 * marking walks.
758 	 *
759 	 * This was not a problem before because STACK_INVALID is only set by
760 	 * default (where the default reg state has its reg->parent as NULL), or
761 	 * in clean_live_states after REG_LIVE_DONE (at which point
762 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
763 	 * verifier state exploration (like we did above). Hence, for our case
764 	 * parentage chain will still be live (i.e. reg->parent may be
765 	 * non-NULL), while earlier reg->parent was NULL, so we need
766 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
767 	 * done later on reads or by mark_dynptr_read as well to unnecessary
768 	 * mark registers in verifier state.
769 	 */
770 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
771 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
772 }
773 
774 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
775 {
776 	struct bpf_func_state *state = func(env, reg);
777 	int spi, ref_obj_id, i;
778 
779 	spi = dynptr_get_spi(env, reg);
780 	if (spi < 0)
781 		return spi;
782 
783 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
784 		invalidate_dynptr(env, state, spi);
785 		return 0;
786 	}
787 
788 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
789 
790 	/* If the dynptr has a ref_obj_id, then we need to invalidate
791 	 * two things:
792 	 *
793 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
794 	 * 2) Any slices derived from this dynptr.
795 	 */
796 
797 	/* Invalidate any slices associated with this dynptr */
798 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
799 
800 	/* Invalidate any dynptr clones */
801 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
802 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
803 			continue;
804 
805 		/* it should always be the case that if the ref obj id
806 		 * matches then the stack slot also belongs to a
807 		 * dynptr
808 		 */
809 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
810 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
811 			return -EFAULT;
812 		}
813 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
814 			invalidate_dynptr(env, state, i);
815 	}
816 
817 	return 0;
818 }
819 
820 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
821 			       struct bpf_reg_state *reg);
822 
823 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
824 {
825 	if (!env->allow_ptr_leaks)
826 		__mark_reg_not_init(env, reg);
827 	else
828 		__mark_reg_unknown(env, reg);
829 }
830 
831 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
832 				        struct bpf_func_state *state, int spi)
833 {
834 	struct bpf_func_state *fstate;
835 	struct bpf_reg_state *dreg;
836 	int i, dynptr_id;
837 
838 	/* We always ensure that STACK_DYNPTR is never set partially,
839 	 * hence just checking for slot_type[0] is enough. This is
840 	 * different for STACK_SPILL, where it may be only set for
841 	 * 1 byte, so code has to use is_spilled_reg.
842 	 */
843 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
844 		return 0;
845 
846 	/* Reposition spi to first slot */
847 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
848 		spi = spi + 1;
849 
850 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
851 		verbose(env, "cannot overwrite referenced dynptr\n");
852 		return -EINVAL;
853 	}
854 
855 	mark_stack_slot_scratched(env, spi);
856 	mark_stack_slot_scratched(env, spi - 1);
857 
858 	/* Writing partially to one dynptr stack slot destroys both. */
859 	for (i = 0; i < BPF_REG_SIZE; i++) {
860 		state->stack[spi].slot_type[i] = STACK_INVALID;
861 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
862 	}
863 
864 	dynptr_id = state->stack[spi].spilled_ptr.id;
865 	/* Invalidate any slices associated with this dynptr */
866 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
867 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
868 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
869 			continue;
870 		if (dreg->dynptr_id == dynptr_id)
871 			mark_reg_invalid(env, dreg);
872 	}));
873 
874 	/* Do not release reference state, we are destroying dynptr on stack,
875 	 * not using some helper to release it. Just reset register.
876 	 */
877 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
878 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
879 
880 	/* Same reason as unmark_stack_slots_dynptr above */
881 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
882 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
883 
884 	return 0;
885 }
886 
887 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
888 {
889 	int spi;
890 
891 	if (reg->type == CONST_PTR_TO_DYNPTR)
892 		return false;
893 
894 	spi = dynptr_get_spi(env, reg);
895 
896 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
897 	 * error because this just means the stack state hasn't been updated yet.
898 	 * We will do check_mem_access to check and update stack bounds later.
899 	 */
900 	if (spi < 0 && spi != -ERANGE)
901 		return false;
902 
903 	/* We don't need to check if the stack slots are marked by previous
904 	 * dynptr initializations because we allow overwriting existing unreferenced
905 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
906 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
907 	 * touching are completely destructed before we reinitialize them for a new
908 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
909 	 * instead of delaying it until the end where the user will get "Unreleased
910 	 * reference" error.
911 	 */
912 	return true;
913 }
914 
915 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
916 {
917 	struct bpf_func_state *state = func(env, reg);
918 	int i, spi;
919 
920 	/* This already represents first slot of initialized bpf_dynptr.
921 	 *
922 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
923 	 * check_func_arg_reg_off's logic, so we don't need to check its
924 	 * offset and alignment.
925 	 */
926 	if (reg->type == CONST_PTR_TO_DYNPTR)
927 		return true;
928 
929 	spi = dynptr_get_spi(env, reg);
930 	if (spi < 0)
931 		return false;
932 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
933 		return false;
934 
935 	for (i = 0; i < BPF_REG_SIZE; i++) {
936 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
937 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
938 			return false;
939 	}
940 
941 	return true;
942 }
943 
944 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
945 				    enum bpf_arg_type arg_type)
946 {
947 	struct bpf_func_state *state = func(env, reg);
948 	enum bpf_dynptr_type dynptr_type;
949 	int spi;
950 
951 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
952 	if (arg_type == ARG_PTR_TO_DYNPTR)
953 		return true;
954 
955 	dynptr_type = arg_to_dynptr_type(arg_type);
956 	if (reg->type == CONST_PTR_TO_DYNPTR) {
957 		return reg->dynptr.type == dynptr_type;
958 	} else {
959 		spi = dynptr_get_spi(env, reg);
960 		if (spi < 0)
961 			return false;
962 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
963 	}
964 }
965 
966 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
967 
968 static bool in_rcu_cs(struct bpf_verifier_env *env);
969 
970 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
971 
972 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
973 				 struct bpf_kfunc_call_arg_meta *meta,
974 				 struct bpf_reg_state *reg, int insn_idx,
975 				 struct btf *btf, u32 btf_id, int nr_slots)
976 {
977 	struct bpf_func_state *state = func(env, reg);
978 	int spi, i, j, id;
979 
980 	spi = iter_get_spi(env, reg, nr_slots);
981 	if (spi < 0)
982 		return spi;
983 
984 	id = acquire_reference_state(env, insn_idx);
985 	if (id < 0)
986 		return id;
987 
988 	for (i = 0; i < nr_slots; i++) {
989 		struct bpf_stack_state *slot = &state->stack[spi - i];
990 		struct bpf_reg_state *st = &slot->spilled_ptr;
991 
992 		__mark_reg_known_zero(st);
993 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
994 		if (is_kfunc_rcu_protected(meta)) {
995 			if (in_rcu_cs(env))
996 				st->type |= MEM_RCU;
997 			else
998 				st->type |= PTR_UNTRUSTED;
999 		}
1000 		st->live |= REG_LIVE_WRITTEN;
1001 		st->ref_obj_id = i == 0 ? id : 0;
1002 		st->iter.btf = btf;
1003 		st->iter.btf_id = btf_id;
1004 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1005 		st->iter.depth = 0;
1006 
1007 		for (j = 0; j < BPF_REG_SIZE; j++)
1008 			slot->slot_type[j] = STACK_ITER;
1009 
1010 		mark_stack_slot_scratched(env, spi - i);
1011 	}
1012 
1013 	return 0;
1014 }
1015 
1016 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1017 				   struct bpf_reg_state *reg, int nr_slots)
1018 {
1019 	struct bpf_func_state *state = func(env, reg);
1020 	int spi, i, j;
1021 
1022 	spi = iter_get_spi(env, reg, nr_slots);
1023 	if (spi < 0)
1024 		return spi;
1025 
1026 	for (i = 0; i < nr_slots; i++) {
1027 		struct bpf_stack_state *slot = &state->stack[spi - i];
1028 		struct bpf_reg_state *st = &slot->spilled_ptr;
1029 
1030 		if (i == 0)
1031 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1032 
1033 		__mark_reg_not_init(env, st);
1034 
1035 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1036 		st->live |= REG_LIVE_WRITTEN;
1037 
1038 		for (j = 0; j < BPF_REG_SIZE; j++)
1039 			slot->slot_type[j] = STACK_INVALID;
1040 
1041 		mark_stack_slot_scratched(env, spi - i);
1042 	}
1043 
1044 	return 0;
1045 }
1046 
1047 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1048 				     struct bpf_reg_state *reg, int nr_slots)
1049 {
1050 	struct bpf_func_state *state = func(env, reg);
1051 	int spi, i, j;
1052 
1053 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1054 	 * will do check_mem_access to check and update stack bounds later, so
1055 	 * return true for that case.
1056 	 */
1057 	spi = iter_get_spi(env, reg, nr_slots);
1058 	if (spi == -ERANGE)
1059 		return true;
1060 	if (spi < 0)
1061 		return false;
1062 
1063 	for (i = 0; i < nr_slots; i++) {
1064 		struct bpf_stack_state *slot = &state->stack[spi - i];
1065 
1066 		for (j = 0; j < BPF_REG_SIZE; j++)
1067 			if (slot->slot_type[j] == STACK_ITER)
1068 				return false;
1069 	}
1070 
1071 	return true;
1072 }
1073 
1074 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1075 				   struct btf *btf, u32 btf_id, int nr_slots)
1076 {
1077 	struct bpf_func_state *state = func(env, reg);
1078 	int spi, i, j;
1079 
1080 	spi = iter_get_spi(env, reg, nr_slots);
1081 	if (spi < 0)
1082 		return -EINVAL;
1083 
1084 	for (i = 0; i < nr_slots; i++) {
1085 		struct bpf_stack_state *slot = &state->stack[spi - i];
1086 		struct bpf_reg_state *st = &slot->spilled_ptr;
1087 
1088 		if (st->type & PTR_UNTRUSTED)
1089 			return -EPROTO;
1090 		/* only main (first) slot has ref_obj_id set */
1091 		if (i == 0 && !st->ref_obj_id)
1092 			return -EINVAL;
1093 		if (i != 0 && st->ref_obj_id)
1094 			return -EINVAL;
1095 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1096 			return -EINVAL;
1097 
1098 		for (j = 0; j < BPF_REG_SIZE; j++)
1099 			if (slot->slot_type[j] != STACK_ITER)
1100 				return -EINVAL;
1101 	}
1102 
1103 	return 0;
1104 }
1105 
1106 /* Check if given stack slot is "special":
1107  *   - spilled register state (STACK_SPILL);
1108  *   - dynptr state (STACK_DYNPTR);
1109  *   - iter state (STACK_ITER).
1110  */
1111 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1112 {
1113 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1114 
1115 	switch (type) {
1116 	case STACK_SPILL:
1117 	case STACK_DYNPTR:
1118 	case STACK_ITER:
1119 		return true;
1120 	case STACK_INVALID:
1121 	case STACK_MISC:
1122 	case STACK_ZERO:
1123 		return false;
1124 	default:
1125 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1126 		return true;
1127 	}
1128 }
1129 
1130 /* The reg state of a pointer or a bounded scalar was saved when
1131  * it was spilled to the stack.
1132  */
1133 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1134 {
1135 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1136 }
1137 
1138 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1139 {
1140 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1141 	       stack->spilled_ptr.type == SCALAR_VALUE;
1142 }
1143 
1144 static void scrub_spilled_slot(u8 *stype)
1145 {
1146 	if (*stype != STACK_INVALID)
1147 		*stype = STACK_MISC;
1148 }
1149 
1150 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1151  * small to hold src. This is different from krealloc since we don't want to preserve
1152  * the contents of dst.
1153  *
1154  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1155  * not be allocated.
1156  */
1157 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1158 {
1159 	size_t alloc_bytes;
1160 	void *orig = dst;
1161 	size_t bytes;
1162 
1163 	if (ZERO_OR_NULL_PTR(src))
1164 		goto out;
1165 
1166 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1167 		return NULL;
1168 
1169 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1170 	dst = krealloc(orig, alloc_bytes, flags);
1171 	if (!dst) {
1172 		kfree(orig);
1173 		return NULL;
1174 	}
1175 
1176 	memcpy(dst, src, bytes);
1177 out:
1178 	return dst ? dst : ZERO_SIZE_PTR;
1179 }
1180 
1181 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1182  * small to hold new_n items. new items are zeroed out if the array grows.
1183  *
1184  * Contrary to krealloc_array, does not free arr if new_n is zero.
1185  */
1186 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1187 {
1188 	size_t alloc_size;
1189 	void *new_arr;
1190 
1191 	if (!new_n || old_n == new_n)
1192 		goto out;
1193 
1194 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1195 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1196 	if (!new_arr) {
1197 		kfree(arr);
1198 		return NULL;
1199 	}
1200 	arr = new_arr;
1201 
1202 	if (new_n > old_n)
1203 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1204 
1205 out:
1206 	return arr ? arr : ZERO_SIZE_PTR;
1207 }
1208 
1209 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1210 {
1211 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1212 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1213 	if (!dst->refs)
1214 		return -ENOMEM;
1215 
1216 	dst->acquired_refs = src->acquired_refs;
1217 	return 0;
1218 }
1219 
1220 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1221 {
1222 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1223 
1224 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1225 				GFP_KERNEL);
1226 	if (!dst->stack)
1227 		return -ENOMEM;
1228 
1229 	dst->allocated_stack = src->allocated_stack;
1230 	return 0;
1231 }
1232 
1233 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1234 {
1235 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1236 				    sizeof(struct bpf_reference_state));
1237 	if (!state->refs)
1238 		return -ENOMEM;
1239 
1240 	state->acquired_refs = n;
1241 	return 0;
1242 }
1243 
1244 static int grow_stack_state(struct bpf_func_state *state, int size)
1245 {
1246 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1247 
1248 	if (old_n >= n)
1249 		return 0;
1250 
1251 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1252 	if (!state->stack)
1253 		return -ENOMEM;
1254 
1255 	state->allocated_stack = size;
1256 	return 0;
1257 }
1258 
1259 /* Acquire a pointer id from the env and update the state->refs to include
1260  * this new pointer reference.
1261  * On success, returns a valid pointer id to associate with the register
1262  * On failure, returns a negative errno.
1263  */
1264 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1265 {
1266 	struct bpf_func_state *state = cur_func(env);
1267 	int new_ofs = state->acquired_refs;
1268 	int id, err;
1269 
1270 	err = resize_reference_state(state, state->acquired_refs + 1);
1271 	if (err)
1272 		return err;
1273 	id = ++env->id_gen;
1274 	state->refs[new_ofs].id = id;
1275 	state->refs[new_ofs].insn_idx = insn_idx;
1276 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1277 
1278 	return id;
1279 }
1280 
1281 /* release function corresponding to acquire_reference_state(). Idempotent. */
1282 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1283 {
1284 	int i, last_idx;
1285 
1286 	last_idx = state->acquired_refs - 1;
1287 	for (i = 0; i < state->acquired_refs; i++) {
1288 		if (state->refs[i].id == ptr_id) {
1289 			/* Cannot release caller references in callbacks */
1290 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1291 				return -EINVAL;
1292 			if (last_idx && i != last_idx)
1293 				memcpy(&state->refs[i], &state->refs[last_idx],
1294 				       sizeof(*state->refs));
1295 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1296 			state->acquired_refs--;
1297 			return 0;
1298 		}
1299 	}
1300 	return -EINVAL;
1301 }
1302 
1303 static void free_func_state(struct bpf_func_state *state)
1304 {
1305 	if (!state)
1306 		return;
1307 	kfree(state->refs);
1308 	kfree(state->stack);
1309 	kfree(state);
1310 }
1311 
1312 static void clear_jmp_history(struct bpf_verifier_state *state)
1313 {
1314 	kfree(state->jmp_history);
1315 	state->jmp_history = NULL;
1316 	state->jmp_history_cnt = 0;
1317 }
1318 
1319 static void free_verifier_state(struct bpf_verifier_state *state,
1320 				bool free_self)
1321 {
1322 	int i;
1323 
1324 	for (i = 0; i <= state->curframe; i++) {
1325 		free_func_state(state->frame[i]);
1326 		state->frame[i] = NULL;
1327 	}
1328 	clear_jmp_history(state);
1329 	if (free_self)
1330 		kfree(state);
1331 }
1332 
1333 /* copy verifier state from src to dst growing dst stack space
1334  * when necessary to accommodate larger src stack
1335  */
1336 static int copy_func_state(struct bpf_func_state *dst,
1337 			   const struct bpf_func_state *src)
1338 {
1339 	int err;
1340 
1341 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1342 	err = copy_reference_state(dst, src);
1343 	if (err)
1344 		return err;
1345 	return copy_stack_state(dst, src);
1346 }
1347 
1348 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1349 			       const struct bpf_verifier_state *src)
1350 {
1351 	struct bpf_func_state *dst;
1352 	int i, err;
1353 
1354 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1355 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1356 					    GFP_USER);
1357 	if (!dst_state->jmp_history)
1358 		return -ENOMEM;
1359 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1360 
1361 	/* if dst has more stack frames then src frame, free them, this is also
1362 	 * necessary in case of exceptional exits using bpf_throw.
1363 	 */
1364 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1365 		free_func_state(dst_state->frame[i]);
1366 		dst_state->frame[i] = NULL;
1367 	}
1368 	dst_state->speculative = src->speculative;
1369 	dst_state->active_rcu_lock = src->active_rcu_lock;
1370 	dst_state->curframe = src->curframe;
1371 	dst_state->active_lock.ptr = src->active_lock.ptr;
1372 	dst_state->active_lock.id = src->active_lock.id;
1373 	dst_state->branches = src->branches;
1374 	dst_state->parent = src->parent;
1375 	dst_state->first_insn_idx = src->first_insn_idx;
1376 	dst_state->last_insn_idx = src->last_insn_idx;
1377 	dst_state->dfs_depth = src->dfs_depth;
1378 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1379 	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1380 	for (i = 0; i <= src->curframe; i++) {
1381 		dst = dst_state->frame[i];
1382 		if (!dst) {
1383 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1384 			if (!dst)
1385 				return -ENOMEM;
1386 			dst_state->frame[i] = dst;
1387 		}
1388 		err = copy_func_state(dst, src->frame[i]);
1389 		if (err)
1390 			return err;
1391 	}
1392 	return 0;
1393 }
1394 
1395 static u32 state_htab_size(struct bpf_verifier_env *env)
1396 {
1397 	return env->prog->len;
1398 }
1399 
1400 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1401 {
1402 	struct bpf_verifier_state *cur = env->cur_state;
1403 	struct bpf_func_state *state = cur->frame[cur->curframe];
1404 
1405 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1406 }
1407 
1408 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1409 {
1410 	int fr;
1411 
1412 	if (a->curframe != b->curframe)
1413 		return false;
1414 
1415 	for (fr = a->curframe; fr >= 0; fr--)
1416 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1417 			return false;
1418 
1419 	return true;
1420 }
1421 
1422 /* Open coded iterators allow back-edges in the state graph in order to
1423  * check unbounded loops that iterators.
1424  *
1425  * In is_state_visited() it is necessary to know if explored states are
1426  * part of some loops in order to decide whether non-exact states
1427  * comparison could be used:
1428  * - non-exact states comparison establishes sub-state relation and uses
1429  *   read and precision marks to do so, these marks are propagated from
1430  *   children states and thus are not guaranteed to be final in a loop;
1431  * - exact states comparison just checks if current and explored states
1432  *   are identical (and thus form a back-edge).
1433  *
1434  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1435  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1436  * algorithm for loop structure detection and gives an overview of
1437  * relevant terminology. It also has helpful illustrations.
1438  *
1439  * [1] https://api.semanticscholar.org/CorpusID:15784067
1440  *
1441  * We use a similar algorithm but because loop nested structure is
1442  * irrelevant for verifier ours is significantly simpler and resembles
1443  * strongly connected components algorithm from Sedgewick's textbook.
1444  *
1445  * Define topmost loop entry as a first node of the loop traversed in a
1446  * depth first search starting from initial state. The goal of the loop
1447  * tracking algorithm is to associate topmost loop entries with states
1448  * derived from these entries.
1449  *
1450  * For each step in the DFS states traversal algorithm needs to identify
1451  * the following situations:
1452  *
1453  *          initial                     initial                   initial
1454  *            |                           |                         |
1455  *            V                           V                         V
1456  *           ...                         ...           .---------> hdr
1457  *            |                           |            |            |
1458  *            V                           V            |            V
1459  *           cur                     .-> succ          |    .------...
1460  *            |                      |    |            |    |       |
1461  *            V                      |    V            |    V       V
1462  *           succ                    '-- cur           |   ...     ...
1463  *                                                     |    |       |
1464  *                                                     |    V       V
1465  *                                                     |   succ <- cur
1466  *                                                     |    |
1467  *                                                     |    V
1468  *                                                     |   ...
1469  *                                                     |    |
1470  *                                                     '----'
1471  *
1472  *  (A) successor state of cur   (B) successor state of cur or it's entry
1473  *      not yet traversed            are in current DFS path, thus cur and succ
1474  *                                   are members of the same outermost loop
1475  *
1476  *                      initial                  initial
1477  *                        |                        |
1478  *                        V                        V
1479  *                       ...                      ...
1480  *                        |                        |
1481  *                        V                        V
1482  *                .------...               .------...
1483  *                |       |                |       |
1484  *                V       V                V       V
1485  *           .-> hdr     ...              ...     ...
1486  *           |    |       |                |       |
1487  *           |    V       V                V       V
1488  *           |   succ <- cur              succ <- cur
1489  *           |    |                        |
1490  *           |    V                        V
1491  *           |   ...                      ...
1492  *           |    |                        |
1493  *           '----'                       exit
1494  *
1495  * (C) successor state of cur is a part of some loop but this loop
1496  *     does not include cur or successor state is not in a loop at all.
1497  *
1498  * Algorithm could be described as the following python code:
1499  *
1500  *     traversed = set()   # Set of traversed nodes
1501  *     entries = {}        # Mapping from node to loop entry
1502  *     depths = {}         # Depth level assigned to graph node
1503  *     path = set()        # Current DFS path
1504  *
1505  *     # Find outermost loop entry known for n
1506  *     def get_loop_entry(n):
1507  *         h = entries.get(n, None)
1508  *         while h in entries and entries[h] != h:
1509  *             h = entries[h]
1510  *         return h
1511  *
1512  *     # Update n's loop entry if h's outermost entry comes
1513  *     # before n's outermost entry in current DFS path.
1514  *     def update_loop_entry(n, h):
1515  *         n1 = get_loop_entry(n) or n
1516  *         h1 = get_loop_entry(h) or h
1517  *         if h1 in path and depths[h1] <= depths[n1]:
1518  *             entries[n] = h1
1519  *
1520  *     def dfs(n, depth):
1521  *         traversed.add(n)
1522  *         path.add(n)
1523  *         depths[n] = depth
1524  *         for succ in G.successors(n):
1525  *             if succ not in traversed:
1526  *                 # Case A: explore succ and update cur's loop entry
1527  *                 #         only if succ's entry is in current DFS path.
1528  *                 dfs(succ, depth + 1)
1529  *                 h = get_loop_entry(succ)
1530  *                 update_loop_entry(n, h)
1531  *             else:
1532  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1533  *                 update_loop_entry(n, succ)
1534  *         path.remove(n)
1535  *
1536  * To adapt this algorithm for use with verifier:
1537  * - use st->branch == 0 as a signal that DFS of succ had been finished
1538  *   and cur's loop entry has to be updated (case A), handle this in
1539  *   update_branch_counts();
1540  * - use st->branch > 0 as a signal that st is in the current DFS path;
1541  * - handle cases B and C in is_state_visited();
1542  * - update topmost loop entry for intermediate states in get_loop_entry().
1543  */
1544 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1545 {
1546 	struct bpf_verifier_state *topmost = st->loop_entry, *old;
1547 
1548 	while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1549 		topmost = topmost->loop_entry;
1550 	/* Update loop entries for intermediate states to avoid this
1551 	 * traversal in future get_loop_entry() calls.
1552 	 */
1553 	while (st && st->loop_entry != topmost) {
1554 		old = st->loop_entry;
1555 		st->loop_entry = topmost;
1556 		st = old;
1557 	}
1558 	return topmost;
1559 }
1560 
1561 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1562 {
1563 	struct bpf_verifier_state *cur1, *hdr1;
1564 
1565 	cur1 = get_loop_entry(cur) ?: cur;
1566 	hdr1 = get_loop_entry(hdr) ?: hdr;
1567 	/* The head1->branches check decides between cases B and C in
1568 	 * comment for get_loop_entry(). If hdr1->branches == 0 then
1569 	 * head's topmost loop entry is not in current DFS path,
1570 	 * hence 'cur' and 'hdr' are not in the same loop and there is
1571 	 * no need to update cur->loop_entry.
1572 	 */
1573 	if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1574 		cur->loop_entry = hdr;
1575 		hdr->used_as_loop_entry = true;
1576 	}
1577 }
1578 
1579 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1580 {
1581 	while (st) {
1582 		u32 br = --st->branches;
1583 
1584 		/* br == 0 signals that DFS exploration for 'st' is finished,
1585 		 * thus it is necessary to update parent's loop entry if it
1586 		 * turned out that st is a part of some loop.
1587 		 * This is a part of 'case A' in get_loop_entry() comment.
1588 		 */
1589 		if (br == 0 && st->parent && st->loop_entry)
1590 			update_loop_entry(st->parent, st->loop_entry);
1591 
1592 		/* WARN_ON(br > 1) technically makes sense here,
1593 		 * but see comment in push_stack(), hence:
1594 		 */
1595 		WARN_ONCE((int)br < 0,
1596 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1597 			  br);
1598 		if (br)
1599 			break;
1600 		st = st->parent;
1601 	}
1602 }
1603 
1604 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1605 		     int *insn_idx, bool pop_log)
1606 {
1607 	struct bpf_verifier_state *cur = env->cur_state;
1608 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1609 	int err;
1610 
1611 	if (env->head == NULL)
1612 		return -ENOENT;
1613 
1614 	if (cur) {
1615 		err = copy_verifier_state(cur, &head->st);
1616 		if (err)
1617 			return err;
1618 	}
1619 	if (pop_log)
1620 		bpf_vlog_reset(&env->log, head->log_pos);
1621 	if (insn_idx)
1622 		*insn_idx = head->insn_idx;
1623 	if (prev_insn_idx)
1624 		*prev_insn_idx = head->prev_insn_idx;
1625 	elem = head->next;
1626 	free_verifier_state(&head->st, false);
1627 	kfree(head);
1628 	env->head = elem;
1629 	env->stack_size--;
1630 	return 0;
1631 }
1632 
1633 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1634 					     int insn_idx, int prev_insn_idx,
1635 					     bool speculative)
1636 {
1637 	struct bpf_verifier_state *cur = env->cur_state;
1638 	struct bpf_verifier_stack_elem *elem;
1639 	int err;
1640 
1641 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1642 	if (!elem)
1643 		goto err;
1644 
1645 	elem->insn_idx = insn_idx;
1646 	elem->prev_insn_idx = prev_insn_idx;
1647 	elem->next = env->head;
1648 	elem->log_pos = env->log.end_pos;
1649 	env->head = elem;
1650 	env->stack_size++;
1651 	err = copy_verifier_state(&elem->st, cur);
1652 	if (err)
1653 		goto err;
1654 	elem->st.speculative |= speculative;
1655 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1656 		verbose(env, "The sequence of %d jumps is too complex.\n",
1657 			env->stack_size);
1658 		goto err;
1659 	}
1660 	if (elem->st.parent) {
1661 		++elem->st.parent->branches;
1662 		/* WARN_ON(branches > 2) technically makes sense here,
1663 		 * but
1664 		 * 1. speculative states will bump 'branches' for non-branch
1665 		 * instructions
1666 		 * 2. is_state_visited() heuristics may decide not to create
1667 		 * a new state for a sequence of branches and all such current
1668 		 * and cloned states will be pointing to a single parent state
1669 		 * which might have large 'branches' count.
1670 		 */
1671 	}
1672 	return &elem->st;
1673 err:
1674 	free_verifier_state(env->cur_state, true);
1675 	env->cur_state = NULL;
1676 	/* pop all elements and return */
1677 	while (!pop_stack(env, NULL, NULL, false));
1678 	return NULL;
1679 }
1680 
1681 #define CALLER_SAVED_REGS 6
1682 static const int caller_saved[CALLER_SAVED_REGS] = {
1683 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1684 };
1685 
1686 /* This helper doesn't clear reg->id */
1687 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1688 {
1689 	reg->var_off = tnum_const(imm);
1690 	reg->smin_value = (s64)imm;
1691 	reg->smax_value = (s64)imm;
1692 	reg->umin_value = imm;
1693 	reg->umax_value = imm;
1694 
1695 	reg->s32_min_value = (s32)imm;
1696 	reg->s32_max_value = (s32)imm;
1697 	reg->u32_min_value = (u32)imm;
1698 	reg->u32_max_value = (u32)imm;
1699 }
1700 
1701 /* Mark the unknown part of a register (variable offset or scalar value) as
1702  * known to have the value @imm.
1703  */
1704 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1705 {
1706 	/* Clear off and union(map_ptr, range) */
1707 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1708 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1709 	reg->id = 0;
1710 	reg->ref_obj_id = 0;
1711 	___mark_reg_known(reg, imm);
1712 }
1713 
1714 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1715 {
1716 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1717 	reg->s32_min_value = (s32)imm;
1718 	reg->s32_max_value = (s32)imm;
1719 	reg->u32_min_value = (u32)imm;
1720 	reg->u32_max_value = (u32)imm;
1721 }
1722 
1723 /* Mark the 'variable offset' part of a register as zero.  This should be
1724  * used only on registers holding a pointer type.
1725  */
1726 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1727 {
1728 	__mark_reg_known(reg, 0);
1729 }
1730 
1731 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1732 {
1733 	__mark_reg_known(reg, 0);
1734 	reg->type = SCALAR_VALUE;
1735 }
1736 
1737 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1738 				struct bpf_reg_state *regs, u32 regno)
1739 {
1740 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1741 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1742 		/* Something bad happened, let's kill all regs */
1743 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1744 			__mark_reg_not_init(env, regs + regno);
1745 		return;
1746 	}
1747 	__mark_reg_known_zero(regs + regno);
1748 }
1749 
1750 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1751 			      bool first_slot, int dynptr_id)
1752 {
1753 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1754 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1755 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1756 	 */
1757 	__mark_reg_known_zero(reg);
1758 	reg->type = CONST_PTR_TO_DYNPTR;
1759 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1760 	reg->id = dynptr_id;
1761 	reg->dynptr.type = type;
1762 	reg->dynptr.first_slot = first_slot;
1763 }
1764 
1765 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1766 {
1767 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1768 		const struct bpf_map *map = reg->map_ptr;
1769 
1770 		if (map->inner_map_meta) {
1771 			reg->type = CONST_PTR_TO_MAP;
1772 			reg->map_ptr = map->inner_map_meta;
1773 			/* transfer reg's id which is unique for every map_lookup_elem
1774 			 * as UID of the inner map.
1775 			 */
1776 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1777 				reg->map_uid = reg->id;
1778 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1779 			reg->type = PTR_TO_XDP_SOCK;
1780 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1781 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1782 			reg->type = PTR_TO_SOCKET;
1783 		} else {
1784 			reg->type = PTR_TO_MAP_VALUE;
1785 		}
1786 		return;
1787 	}
1788 
1789 	reg->type &= ~PTR_MAYBE_NULL;
1790 }
1791 
1792 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1793 				struct btf_field_graph_root *ds_head)
1794 {
1795 	__mark_reg_known_zero(&regs[regno]);
1796 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1797 	regs[regno].btf = ds_head->btf;
1798 	regs[regno].btf_id = ds_head->value_btf_id;
1799 	regs[regno].off = ds_head->node_offset;
1800 }
1801 
1802 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1803 {
1804 	return type_is_pkt_pointer(reg->type);
1805 }
1806 
1807 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1808 {
1809 	return reg_is_pkt_pointer(reg) ||
1810 	       reg->type == PTR_TO_PACKET_END;
1811 }
1812 
1813 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1814 {
1815 	return base_type(reg->type) == PTR_TO_MEM &&
1816 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1817 }
1818 
1819 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1820 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1821 				    enum bpf_reg_type which)
1822 {
1823 	/* The register can already have a range from prior markings.
1824 	 * This is fine as long as it hasn't been advanced from its
1825 	 * origin.
1826 	 */
1827 	return reg->type == which &&
1828 	       reg->id == 0 &&
1829 	       reg->off == 0 &&
1830 	       tnum_equals_const(reg->var_off, 0);
1831 }
1832 
1833 /* Reset the min/max bounds of a register */
1834 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1835 {
1836 	reg->smin_value = S64_MIN;
1837 	reg->smax_value = S64_MAX;
1838 	reg->umin_value = 0;
1839 	reg->umax_value = U64_MAX;
1840 
1841 	reg->s32_min_value = S32_MIN;
1842 	reg->s32_max_value = S32_MAX;
1843 	reg->u32_min_value = 0;
1844 	reg->u32_max_value = U32_MAX;
1845 }
1846 
1847 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1848 {
1849 	reg->smin_value = S64_MIN;
1850 	reg->smax_value = S64_MAX;
1851 	reg->umin_value = 0;
1852 	reg->umax_value = U64_MAX;
1853 }
1854 
1855 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1856 {
1857 	reg->s32_min_value = S32_MIN;
1858 	reg->s32_max_value = S32_MAX;
1859 	reg->u32_min_value = 0;
1860 	reg->u32_max_value = U32_MAX;
1861 }
1862 
1863 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1864 {
1865 	struct tnum var32_off = tnum_subreg(reg->var_off);
1866 
1867 	/* min signed is max(sign bit) | min(other bits) */
1868 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1869 			var32_off.value | (var32_off.mask & S32_MIN));
1870 	/* max signed is min(sign bit) | max(other bits) */
1871 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1872 			var32_off.value | (var32_off.mask & S32_MAX));
1873 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1874 	reg->u32_max_value = min(reg->u32_max_value,
1875 				 (u32)(var32_off.value | var32_off.mask));
1876 }
1877 
1878 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1879 {
1880 	/* min signed is max(sign bit) | min(other bits) */
1881 	reg->smin_value = max_t(s64, reg->smin_value,
1882 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1883 	/* max signed is min(sign bit) | max(other bits) */
1884 	reg->smax_value = min_t(s64, reg->smax_value,
1885 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1886 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1887 	reg->umax_value = min(reg->umax_value,
1888 			      reg->var_off.value | reg->var_off.mask);
1889 }
1890 
1891 static void __update_reg_bounds(struct bpf_reg_state *reg)
1892 {
1893 	__update_reg32_bounds(reg);
1894 	__update_reg64_bounds(reg);
1895 }
1896 
1897 /* Uses signed min/max values to inform unsigned, and vice-versa */
1898 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1899 {
1900 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
1901 	 * bits to improve our u32/s32 boundaries.
1902 	 *
1903 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
1904 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
1905 	 * [10, 20] range. But this property holds for any 64-bit range as
1906 	 * long as upper 32 bits in that entire range of values stay the same.
1907 	 *
1908 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
1909 	 * in decimal) has the same upper 32 bits throughout all the values in
1910 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
1911 	 * range.
1912 	 *
1913 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
1914 	 * following the rules outlined below about u64/s64 correspondence
1915 	 * (which equally applies to u32 vs s32 correspondence). In general it
1916 	 * depends on actual hexadecimal values of 32-bit range. They can form
1917 	 * only valid u32, or only valid s32 ranges in some cases.
1918 	 *
1919 	 * So we use all these insights to derive bounds for subregisters here.
1920 	 */
1921 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
1922 		/* u64 to u32 casting preserves validity of low 32 bits as
1923 		 * a range, if upper 32 bits are the same
1924 		 */
1925 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
1926 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
1927 
1928 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
1929 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
1930 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
1931 		}
1932 	}
1933 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
1934 		/* low 32 bits should form a proper u32 range */
1935 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
1936 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
1937 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
1938 		}
1939 		/* low 32 bits should form a proper s32 range */
1940 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
1941 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
1942 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
1943 		}
1944 	}
1945 	/* Special case where upper bits form a small sequence of two
1946 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
1947 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
1948 	 * going from negative numbers to positive numbers. E.g., let's say we
1949 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
1950 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
1951 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
1952 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
1953 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
1954 	 * upper 32 bits. As a random example, s64 range
1955 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
1956 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
1957 	 */
1958 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
1959 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
1960 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
1961 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
1962 	}
1963 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
1964 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
1965 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
1966 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
1967 	}
1968 	/* if u32 range forms a valid s32 range (due to matching sign bit),
1969 	 * try to learn from that
1970 	 */
1971 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
1972 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
1973 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
1974 	}
1975 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
1976 	 * are the same, so combine.  This works even in the negative case, e.g.
1977 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1978 	 */
1979 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
1980 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
1981 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
1982 	}
1983 }
1984 
1985 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1986 {
1987 	/* If u64 range forms a valid s64 range (due to matching sign bit),
1988 	 * try to learn from that. Let's do a bit of ASCII art to see when
1989 	 * this is happening. Let's take u64 range first:
1990 	 *
1991 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
1992 	 * |-------------------------------|--------------------------------|
1993 	 *
1994 	 * Valid u64 range is formed when umin and umax are anywhere in the
1995 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
1996 	 * straightforward. Let's see how s64 range maps onto the same range
1997 	 * of values, annotated below the line for comparison:
1998 	 *
1999 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2000 	 * |-------------------------------|--------------------------------|
2001 	 * 0                        S64_MAX S64_MIN                        -1
2002 	 *
2003 	 * So s64 values basically start in the middle and they are logically
2004 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2005 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2006 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2007 	 * more visually as mapped to sign-agnostic range of hex values.
2008 	 *
2009 	 *  u64 start                                               u64 end
2010 	 *  _______________________________________________________________
2011 	 * /                                                               \
2012 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2013 	 * |-------------------------------|--------------------------------|
2014 	 * 0                        S64_MAX S64_MIN                        -1
2015 	 *                                / \
2016 	 * >------------------------------   ------------------------------->
2017 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2018 	 *
2019 	 * What this means is that, in general, we can't always derive
2020 	 * something new about u64 from any random s64 range, and vice versa.
2021 	 *
2022 	 * But we can do that in two particular cases. One is when entire
2023 	 * u64/s64 range is *entirely* contained within left half of the above
2024 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2025 	 *
2026 	 * |-------------------------------|--------------------------------|
2027 	 *     ^                   ^            ^                 ^
2028 	 *     A                   B            C                 D
2029 	 *
2030 	 * [A, B] and [C, D] are contained entirely in their respective halves
2031 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2032 	 * will be non-negative both as u64 and s64 (and in fact it will be
2033 	 * identical ranges no matter the signedness). [C, D] treated as s64
2034 	 * will be a range of negative values, while in u64 it will be
2035 	 * non-negative range of values larger than 0x8000000000000000.
2036 	 *
2037 	 * Now, any other range here can't be represented in both u64 and s64
2038 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2039 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2040 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2041 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2042 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2043 	 * ranges as u64. Currently reg_state can't represent two segments per
2044 	 * numeric domain, so in such situations we can only derive maximal
2045 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2046 	 *
2047 	 * So we use these facts to derive umin/umax from smin/smax and vice
2048 	 * versa only if they stay within the same "half". This is equivalent
2049 	 * to checking sign bit: lower half will have sign bit as zero, upper
2050 	 * half have sign bit 1. Below in code we simplify this by just
2051 	 * casting umin/umax as smin/smax and checking if they form valid
2052 	 * range, and vice versa. Those are equivalent checks.
2053 	 */
2054 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2055 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2056 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2057 	}
2058 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2059 	 * are the same, so combine.  This works even in the negative case, e.g.
2060 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2061 	 */
2062 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2063 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2064 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2065 	}
2066 }
2067 
2068 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2069 {
2070 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2071 	 * values on both sides of 64-bit range in hope to have tigher range.
2072 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2073 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2074 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2075 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2076 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2077 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2078 	 * We just need to make sure that derived bounds we are intersecting
2079 	 * with are well-formed ranges in respecitve s64 or u64 domain, just
2080 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2081 	 */
2082 	__u64 new_umin, new_umax;
2083 	__s64 new_smin, new_smax;
2084 
2085 	/* u32 -> u64 tightening, it's always well-formed */
2086 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2087 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2088 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2089 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2090 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2091 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2092 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2093 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2094 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2095 
2096 	/* if s32 can be treated as valid u32 range, we can use it as well */
2097 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2098 		/* s32 -> u64 tightening */
2099 		new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2100 		new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2101 		reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2102 		reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2103 		/* s32 -> s64 tightening */
2104 		new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2105 		new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2106 		reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2107 		reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2108 	}
2109 }
2110 
2111 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2112 {
2113 	__reg32_deduce_bounds(reg);
2114 	__reg64_deduce_bounds(reg);
2115 	__reg_deduce_mixed_bounds(reg);
2116 }
2117 
2118 /* Attempts to improve var_off based on unsigned min/max information */
2119 static void __reg_bound_offset(struct bpf_reg_state *reg)
2120 {
2121 	struct tnum var64_off = tnum_intersect(reg->var_off,
2122 					       tnum_range(reg->umin_value,
2123 							  reg->umax_value));
2124 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2125 					       tnum_range(reg->u32_min_value,
2126 							  reg->u32_max_value));
2127 
2128 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2129 }
2130 
2131 static void reg_bounds_sync(struct bpf_reg_state *reg)
2132 {
2133 	/* We might have learned new bounds from the var_off. */
2134 	__update_reg_bounds(reg);
2135 	/* We might have learned something about the sign bit. */
2136 	__reg_deduce_bounds(reg);
2137 	__reg_deduce_bounds(reg);
2138 	/* We might have learned some bits from the bounds. */
2139 	__reg_bound_offset(reg);
2140 	/* Intersecting with the old var_off might have improved our bounds
2141 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2142 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2143 	 */
2144 	__update_reg_bounds(reg);
2145 }
2146 
2147 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2148 				   struct bpf_reg_state *reg, const char *ctx)
2149 {
2150 	const char *msg;
2151 
2152 	if (reg->umin_value > reg->umax_value ||
2153 	    reg->smin_value > reg->smax_value ||
2154 	    reg->u32_min_value > reg->u32_max_value ||
2155 	    reg->s32_min_value > reg->s32_max_value) {
2156 		    msg = "range bounds violation";
2157 		    goto out;
2158 	}
2159 
2160 	if (tnum_is_const(reg->var_off)) {
2161 		u64 uval = reg->var_off.value;
2162 		s64 sval = (s64)uval;
2163 
2164 		if (reg->umin_value != uval || reg->umax_value != uval ||
2165 		    reg->smin_value != sval || reg->smax_value != sval) {
2166 			msg = "const tnum out of sync with range bounds";
2167 			goto out;
2168 		}
2169 	}
2170 
2171 	if (tnum_subreg_is_const(reg->var_off)) {
2172 		u32 uval32 = tnum_subreg(reg->var_off).value;
2173 		s32 sval32 = (s32)uval32;
2174 
2175 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2176 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2177 			msg = "const subreg tnum out of sync with range bounds";
2178 			goto out;
2179 		}
2180 	}
2181 
2182 	return 0;
2183 out:
2184 	verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2185 		"s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n",
2186 		ctx, msg, reg->umin_value, reg->umax_value,
2187 		reg->smin_value, reg->smax_value,
2188 		reg->u32_min_value, reg->u32_max_value,
2189 		reg->s32_min_value, reg->s32_max_value,
2190 		reg->var_off.value, reg->var_off.mask);
2191 	if (env->test_reg_invariants)
2192 		return -EFAULT;
2193 	__mark_reg_unbounded(reg);
2194 	return 0;
2195 }
2196 
2197 static bool __reg32_bound_s64(s32 a)
2198 {
2199 	return a >= 0 && a <= S32_MAX;
2200 }
2201 
2202 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2203 {
2204 	reg->umin_value = reg->u32_min_value;
2205 	reg->umax_value = reg->u32_max_value;
2206 
2207 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2208 	 * be positive otherwise set to worse case bounds and refine later
2209 	 * from tnum.
2210 	 */
2211 	if (__reg32_bound_s64(reg->s32_min_value) &&
2212 	    __reg32_bound_s64(reg->s32_max_value)) {
2213 		reg->smin_value = reg->s32_min_value;
2214 		reg->smax_value = reg->s32_max_value;
2215 	} else {
2216 		reg->smin_value = 0;
2217 		reg->smax_value = U32_MAX;
2218 	}
2219 }
2220 
2221 /* Mark a register as having a completely unknown (scalar) value. */
2222 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2223 			       struct bpf_reg_state *reg)
2224 {
2225 	/*
2226 	 * Clear type, off, and union(map_ptr, range) and
2227 	 * padding between 'type' and union
2228 	 */
2229 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2230 	reg->type = SCALAR_VALUE;
2231 	reg->id = 0;
2232 	reg->ref_obj_id = 0;
2233 	reg->var_off = tnum_unknown;
2234 	reg->frameno = 0;
2235 	reg->precise = !env->bpf_capable;
2236 	__mark_reg_unbounded(reg);
2237 }
2238 
2239 static void mark_reg_unknown(struct bpf_verifier_env *env,
2240 			     struct bpf_reg_state *regs, u32 regno)
2241 {
2242 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2243 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2244 		/* Something bad happened, let's kill all regs except FP */
2245 		for (regno = 0; regno < BPF_REG_FP; regno++)
2246 			__mark_reg_not_init(env, regs + regno);
2247 		return;
2248 	}
2249 	__mark_reg_unknown(env, regs + regno);
2250 }
2251 
2252 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2253 				struct bpf_reg_state *reg)
2254 {
2255 	__mark_reg_unknown(env, reg);
2256 	reg->type = NOT_INIT;
2257 }
2258 
2259 static void mark_reg_not_init(struct bpf_verifier_env *env,
2260 			      struct bpf_reg_state *regs, u32 regno)
2261 {
2262 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2263 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2264 		/* Something bad happened, let's kill all regs except FP */
2265 		for (regno = 0; regno < BPF_REG_FP; regno++)
2266 			__mark_reg_not_init(env, regs + regno);
2267 		return;
2268 	}
2269 	__mark_reg_not_init(env, regs + regno);
2270 }
2271 
2272 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2273 			    struct bpf_reg_state *regs, u32 regno,
2274 			    enum bpf_reg_type reg_type,
2275 			    struct btf *btf, u32 btf_id,
2276 			    enum bpf_type_flag flag)
2277 {
2278 	if (reg_type == SCALAR_VALUE) {
2279 		mark_reg_unknown(env, regs, regno);
2280 		return;
2281 	}
2282 	mark_reg_known_zero(env, regs, regno);
2283 	regs[regno].type = PTR_TO_BTF_ID | flag;
2284 	regs[regno].btf = btf;
2285 	regs[regno].btf_id = btf_id;
2286 }
2287 
2288 #define DEF_NOT_SUBREG	(0)
2289 static void init_reg_state(struct bpf_verifier_env *env,
2290 			   struct bpf_func_state *state)
2291 {
2292 	struct bpf_reg_state *regs = state->regs;
2293 	int i;
2294 
2295 	for (i = 0; i < MAX_BPF_REG; i++) {
2296 		mark_reg_not_init(env, regs, i);
2297 		regs[i].live = REG_LIVE_NONE;
2298 		regs[i].parent = NULL;
2299 		regs[i].subreg_def = DEF_NOT_SUBREG;
2300 	}
2301 
2302 	/* frame pointer */
2303 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2304 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2305 	regs[BPF_REG_FP].frameno = state->frameno;
2306 }
2307 
2308 #define BPF_MAIN_FUNC (-1)
2309 static void init_func_state(struct bpf_verifier_env *env,
2310 			    struct bpf_func_state *state,
2311 			    int callsite, int frameno, int subprogno)
2312 {
2313 	state->callsite = callsite;
2314 	state->frameno = frameno;
2315 	state->subprogno = subprogno;
2316 	state->callback_ret_range = tnum_range(0, 0);
2317 	init_reg_state(env, state);
2318 	mark_verifier_state_scratched(env);
2319 }
2320 
2321 /* Similar to push_stack(), but for async callbacks */
2322 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2323 						int insn_idx, int prev_insn_idx,
2324 						int subprog)
2325 {
2326 	struct bpf_verifier_stack_elem *elem;
2327 	struct bpf_func_state *frame;
2328 
2329 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2330 	if (!elem)
2331 		goto err;
2332 
2333 	elem->insn_idx = insn_idx;
2334 	elem->prev_insn_idx = prev_insn_idx;
2335 	elem->next = env->head;
2336 	elem->log_pos = env->log.end_pos;
2337 	env->head = elem;
2338 	env->stack_size++;
2339 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2340 		verbose(env,
2341 			"The sequence of %d jumps is too complex for async cb.\n",
2342 			env->stack_size);
2343 		goto err;
2344 	}
2345 	/* Unlike push_stack() do not copy_verifier_state().
2346 	 * The caller state doesn't matter.
2347 	 * This is async callback. It starts in a fresh stack.
2348 	 * Initialize it similar to do_check_common().
2349 	 */
2350 	elem->st.branches = 1;
2351 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2352 	if (!frame)
2353 		goto err;
2354 	init_func_state(env, frame,
2355 			BPF_MAIN_FUNC /* callsite */,
2356 			0 /* frameno within this callchain */,
2357 			subprog /* subprog number within this prog */);
2358 	elem->st.frame[0] = frame;
2359 	return &elem->st;
2360 err:
2361 	free_verifier_state(env->cur_state, true);
2362 	env->cur_state = NULL;
2363 	/* pop all elements and return */
2364 	while (!pop_stack(env, NULL, NULL, false));
2365 	return NULL;
2366 }
2367 
2368 
2369 enum reg_arg_type {
2370 	SRC_OP,		/* register is used as source operand */
2371 	DST_OP,		/* register is used as destination operand */
2372 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2373 };
2374 
2375 static int cmp_subprogs(const void *a, const void *b)
2376 {
2377 	return ((struct bpf_subprog_info *)a)->start -
2378 	       ((struct bpf_subprog_info *)b)->start;
2379 }
2380 
2381 static int find_subprog(struct bpf_verifier_env *env, int off)
2382 {
2383 	struct bpf_subprog_info *p;
2384 
2385 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2386 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2387 	if (!p)
2388 		return -ENOENT;
2389 	return p - env->subprog_info;
2390 
2391 }
2392 
2393 static int add_subprog(struct bpf_verifier_env *env, int off)
2394 {
2395 	int insn_cnt = env->prog->len;
2396 	int ret;
2397 
2398 	if (off >= insn_cnt || off < 0) {
2399 		verbose(env, "call to invalid destination\n");
2400 		return -EINVAL;
2401 	}
2402 	ret = find_subprog(env, off);
2403 	if (ret >= 0)
2404 		return ret;
2405 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2406 		verbose(env, "too many subprograms\n");
2407 		return -E2BIG;
2408 	}
2409 	/* determine subprog starts. The end is one before the next starts */
2410 	env->subprog_info[env->subprog_cnt++].start = off;
2411 	sort(env->subprog_info, env->subprog_cnt,
2412 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2413 	return env->subprog_cnt - 1;
2414 }
2415 
2416 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2417 {
2418 	struct bpf_prog_aux *aux = env->prog->aux;
2419 	struct btf *btf = aux->btf;
2420 	const struct btf_type *t;
2421 	u32 main_btf_id, id;
2422 	const char *name;
2423 	int ret, i;
2424 
2425 	/* Non-zero func_info_cnt implies valid btf */
2426 	if (!aux->func_info_cnt)
2427 		return 0;
2428 	main_btf_id = aux->func_info[0].type_id;
2429 
2430 	t = btf_type_by_id(btf, main_btf_id);
2431 	if (!t) {
2432 		verbose(env, "invalid btf id for main subprog in func_info\n");
2433 		return -EINVAL;
2434 	}
2435 
2436 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2437 	if (IS_ERR(name)) {
2438 		ret = PTR_ERR(name);
2439 		/* If there is no tag present, there is no exception callback */
2440 		if (ret == -ENOENT)
2441 			ret = 0;
2442 		else if (ret == -EEXIST)
2443 			verbose(env, "multiple exception callback tags for main subprog\n");
2444 		return ret;
2445 	}
2446 
2447 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2448 	if (ret < 0) {
2449 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2450 		return ret;
2451 	}
2452 	id = ret;
2453 	t = btf_type_by_id(btf, id);
2454 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2455 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2456 		return -EINVAL;
2457 	}
2458 	ret = 0;
2459 	for (i = 0; i < aux->func_info_cnt; i++) {
2460 		if (aux->func_info[i].type_id != id)
2461 			continue;
2462 		ret = aux->func_info[i].insn_off;
2463 		/* Further func_info and subprog checks will also happen
2464 		 * later, so assume this is the right insn_off for now.
2465 		 */
2466 		if (!ret) {
2467 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2468 			ret = -EINVAL;
2469 		}
2470 	}
2471 	if (!ret) {
2472 		verbose(env, "exception callback type id not found in func_info\n");
2473 		ret = -EINVAL;
2474 	}
2475 	return ret;
2476 }
2477 
2478 #define MAX_KFUNC_DESCS 256
2479 #define MAX_KFUNC_BTFS	256
2480 
2481 struct bpf_kfunc_desc {
2482 	struct btf_func_model func_model;
2483 	u32 func_id;
2484 	s32 imm;
2485 	u16 offset;
2486 	unsigned long addr;
2487 };
2488 
2489 struct bpf_kfunc_btf {
2490 	struct btf *btf;
2491 	struct module *module;
2492 	u16 offset;
2493 };
2494 
2495 struct bpf_kfunc_desc_tab {
2496 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2497 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2498 	 * available, therefore at the end of verification do_misc_fixups()
2499 	 * sorts this by imm and offset.
2500 	 */
2501 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2502 	u32 nr_descs;
2503 };
2504 
2505 struct bpf_kfunc_btf_tab {
2506 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2507 	u32 nr_descs;
2508 };
2509 
2510 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2511 {
2512 	const struct bpf_kfunc_desc *d0 = a;
2513 	const struct bpf_kfunc_desc *d1 = b;
2514 
2515 	/* func_id is not greater than BTF_MAX_TYPE */
2516 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2517 }
2518 
2519 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2520 {
2521 	const struct bpf_kfunc_btf *d0 = a;
2522 	const struct bpf_kfunc_btf *d1 = b;
2523 
2524 	return d0->offset - d1->offset;
2525 }
2526 
2527 static const struct bpf_kfunc_desc *
2528 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2529 {
2530 	struct bpf_kfunc_desc desc = {
2531 		.func_id = func_id,
2532 		.offset = offset,
2533 	};
2534 	struct bpf_kfunc_desc_tab *tab;
2535 
2536 	tab = prog->aux->kfunc_tab;
2537 	return bsearch(&desc, tab->descs, tab->nr_descs,
2538 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2539 }
2540 
2541 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2542 		       u16 btf_fd_idx, u8 **func_addr)
2543 {
2544 	const struct bpf_kfunc_desc *desc;
2545 
2546 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2547 	if (!desc)
2548 		return -EFAULT;
2549 
2550 	*func_addr = (u8 *)desc->addr;
2551 	return 0;
2552 }
2553 
2554 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2555 					 s16 offset)
2556 {
2557 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2558 	struct bpf_kfunc_btf_tab *tab;
2559 	struct bpf_kfunc_btf *b;
2560 	struct module *mod;
2561 	struct btf *btf;
2562 	int btf_fd;
2563 
2564 	tab = env->prog->aux->kfunc_btf_tab;
2565 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2566 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2567 	if (!b) {
2568 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2569 			verbose(env, "too many different module BTFs\n");
2570 			return ERR_PTR(-E2BIG);
2571 		}
2572 
2573 		if (bpfptr_is_null(env->fd_array)) {
2574 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2575 			return ERR_PTR(-EPROTO);
2576 		}
2577 
2578 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2579 					    offset * sizeof(btf_fd),
2580 					    sizeof(btf_fd)))
2581 			return ERR_PTR(-EFAULT);
2582 
2583 		btf = btf_get_by_fd(btf_fd);
2584 		if (IS_ERR(btf)) {
2585 			verbose(env, "invalid module BTF fd specified\n");
2586 			return btf;
2587 		}
2588 
2589 		if (!btf_is_module(btf)) {
2590 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2591 			btf_put(btf);
2592 			return ERR_PTR(-EINVAL);
2593 		}
2594 
2595 		mod = btf_try_get_module(btf);
2596 		if (!mod) {
2597 			btf_put(btf);
2598 			return ERR_PTR(-ENXIO);
2599 		}
2600 
2601 		b = &tab->descs[tab->nr_descs++];
2602 		b->btf = btf;
2603 		b->module = mod;
2604 		b->offset = offset;
2605 
2606 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2607 		     kfunc_btf_cmp_by_off, NULL);
2608 	}
2609 	return b->btf;
2610 }
2611 
2612 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2613 {
2614 	if (!tab)
2615 		return;
2616 
2617 	while (tab->nr_descs--) {
2618 		module_put(tab->descs[tab->nr_descs].module);
2619 		btf_put(tab->descs[tab->nr_descs].btf);
2620 	}
2621 	kfree(tab);
2622 }
2623 
2624 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2625 {
2626 	if (offset) {
2627 		if (offset < 0) {
2628 			/* In the future, this can be allowed to increase limit
2629 			 * of fd index into fd_array, interpreted as u16.
2630 			 */
2631 			verbose(env, "negative offset disallowed for kernel module function call\n");
2632 			return ERR_PTR(-EINVAL);
2633 		}
2634 
2635 		return __find_kfunc_desc_btf(env, offset);
2636 	}
2637 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2638 }
2639 
2640 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2641 {
2642 	const struct btf_type *func, *func_proto;
2643 	struct bpf_kfunc_btf_tab *btf_tab;
2644 	struct bpf_kfunc_desc_tab *tab;
2645 	struct bpf_prog_aux *prog_aux;
2646 	struct bpf_kfunc_desc *desc;
2647 	const char *func_name;
2648 	struct btf *desc_btf;
2649 	unsigned long call_imm;
2650 	unsigned long addr;
2651 	int err;
2652 
2653 	prog_aux = env->prog->aux;
2654 	tab = prog_aux->kfunc_tab;
2655 	btf_tab = prog_aux->kfunc_btf_tab;
2656 	if (!tab) {
2657 		if (!btf_vmlinux) {
2658 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2659 			return -ENOTSUPP;
2660 		}
2661 
2662 		if (!env->prog->jit_requested) {
2663 			verbose(env, "JIT is required for calling kernel function\n");
2664 			return -ENOTSUPP;
2665 		}
2666 
2667 		if (!bpf_jit_supports_kfunc_call()) {
2668 			verbose(env, "JIT does not support calling kernel function\n");
2669 			return -ENOTSUPP;
2670 		}
2671 
2672 		if (!env->prog->gpl_compatible) {
2673 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2674 			return -EINVAL;
2675 		}
2676 
2677 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2678 		if (!tab)
2679 			return -ENOMEM;
2680 		prog_aux->kfunc_tab = tab;
2681 	}
2682 
2683 	/* func_id == 0 is always invalid, but instead of returning an error, be
2684 	 * conservative and wait until the code elimination pass before returning
2685 	 * error, so that invalid calls that get pruned out can be in BPF programs
2686 	 * loaded from userspace.  It is also required that offset be untouched
2687 	 * for such calls.
2688 	 */
2689 	if (!func_id && !offset)
2690 		return 0;
2691 
2692 	if (!btf_tab && offset) {
2693 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2694 		if (!btf_tab)
2695 			return -ENOMEM;
2696 		prog_aux->kfunc_btf_tab = btf_tab;
2697 	}
2698 
2699 	desc_btf = find_kfunc_desc_btf(env, offset);
2700 	if (IS_ERR(desc_btf)) {
2701 		verbose(env, "failed to find BTF for kernel function\n");
2702 		return PTR_ERR(desc_btf);
2703 	}
2704 
2705 	if (find_kfunc_desc(env->prog, func_id, offset))
2706 		return 0;
2707 
2708 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2709 		verbose(env, "too many different kernel function calls\n");
2710 		return -E2BIG;
2711 	}
2712 
2713 	func = btf_type_by_id(desc_btf, func_id);
2714 	if (!func || !btf_type_is_func(func)) {
2715 		verbose(env, "kernel btf_id %u is not a function\n",
2716 			func_id);
2717 		return -EINVAL;
2718 	}
2719 	func_proto = btf_type_by_id(desc_btf, func->type);
2720 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2721 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2722 			func_id);
2723 		return -EINVAL;
2724 	}
2725 
2726 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2727 	addr = kallsyms_lookup_name(func_name);
2728 	if (!addr) {
2729 		verbose(env, "cannot find address for kernel function %s\n",
2730 			func_name);
2731 		return -EINVAL;
2732 	}
2733 	specialize_kfunc(env, func_id, offset, &addr);
2734 
2735 	if (bpf_jit_supports_far_kfunc_call()) {
2736 		call_imm = func_id;
2737 	} else {
2738 		call_imm = BPF_CALL_IMM(addr);
2739 		/* Check whether the relative offset overflows desc->imm */
2740 		if ((unsigned long)(s32)call_imm != call_imm) {
2741 			verbose(env, "address of kernel function %s is out of range\n",
2742 				func_name);
2743 			return -EINVAL;
2744 		}
2745 	}
2746 
2747 	if (bpf_dev_bound_kfunc_id(func_id)) {
2748 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2749 		if (err)
2750 			return err;
2751 	}
2752 
2753 	desc = &tab->descs[tab->nr_descs++];
2754 	desc->func_id = func_id;
2755 	desc->imm = call_imm;
2756 	desc->offset = offset;
2757 	desc->addr = addr;
2758 	err = btf_distill_func_proto(&env->log, desc_btf,
2759 				     func_proto, func_name,
2760 				     &desc->func_model);
2761 	if (!err)
2762 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2763 		     kfunc_desc_cmp_by_id_off, NULL);
2764 	return err;
2765 }
2766 
2767 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2768 {
2769 	const struct bpf_kfunc_desc *d0 = a;
2770 	const struct bpf_kfunc_desc *d1 = b;
2771 
2772 	if (d0->imm != d1->imm)
2773 		return d0->imm < d1->imm ? -1 : 1;
2774 	if (d0->offset != d1->offset)
2775 		return d0->offset < d1->offset ? -1 : 1;
2776 	return 0;
2777 }
2778 
2779 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2780 {
2781 	struct bpf_kfunc_desc_tab *tab;
2782 
2783 	tab = prog->aux->kfunc_tab;
2784 	if (!tab)
2785 		return;
2786 
2787 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2788 	     kfunc_desc_cmp_by_imm_off, NULL);
2789 }
2790 
2791 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2792 {
2793 	return !!prog->aux->kfunc_tab;
2794 }
2795 
2796 const struct btf_func_model *
2797 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2798 			 const struct bpf_insn *insn)
2799 {
2800 	const struct bpf_kfunc_desc desc = {
2801 		.imm = insn->imm,
2802 		.offset = insn->off,
2803 	};
2804 	const struct bpf_kfunc_desc *res;
2805 	struct bpf_kfunc_desc_tab *tab;
2806 
2807 	tab = prog->aux->kfunc_tab;
2808 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2809 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2810 
2811 	return res ? &res->func_model : NULL;
2812 }
2813 
2814 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2815 {
2816 	struct bpf_subprog_info *subprog = env->subprog_info;
2817 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
2818 	struct bpf_insn *insn = env->prog->insnsi;
2819 
2820 	/* Add entry function. */
2821 	ret = add_subprog(env, 0);
2822 	if (ret)
2823 		return ret;
2824 
2825 	for (i = 0; i < insn_cnt; i++, insn++) {
2826 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2827 		    !bpf_pseudo_kfunc_call(insn))
2828 			continue;
2829 
2830 		if (!env->bpf_capable) {
2831 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2832 			return -EPERM;
2833 		}
2834 
2835 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2836 			ret = add_subprog(env, i + insn->imm + 1);
2837 		else
2838 			ret = add_kfunc_call(env, insn->imm, insn->off);
2839 
2840 		if (ret < 0)
2841 			return ret;
2842 	}
2843 
2844 	ret = bpf_find_exception_callback_insn_off(env);
2845 	if (ret < 0)
2846 		return ret;
2847 	ex_cb_insn = ret;
2848 
2849 	/* If ex_cb_insn > 0, this means that the main program has a subprog
2850 	 * marked using BTF decl tag to serve as the exception callback.
2851 	 */
2852 	if (ex_cb_insn) {
2853 		ret = add_subprog(env, ex_cb_insn);
2854 		if (ret < 0)
2855 			return ret;
2856 		for (i = 1; i < env->subprog_cnt; i++) {
2857 			if (env->subprog_info[i].start != ex_cb_insn)
2858 				continue;
2859 			env->exception_callback_subprog = i;
2860 			break;
2861 		}
2862 	}
2863 
2864 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2865 	 * logic. 'subprog_cnt' should not be increased.
2866 	 */
2867 	subprog[env->subprog_cnt].start = insn_cnt;
2868 
2869 	if (env->log.level & BPF_LOG_LEVEL2)
2870 		for (i = 0; i < env->subprog_cnt; i++)
2871 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2872 
2873 	return 0;
2874 }
2875 
2876 static int check_subprogs(struct bpf_verifier_env *env)
2877 {
2878 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2879 	struct bpf_subprog_info *subprog = env->subprog_info;
2880 	struct bpf_insn *insn = env->prog->insnsi;
2881 	int insn_cnt = env->prog->len;
2882 
2883 	/* now check that all jumps are within the same subprog */
2884 	subprog_start = subprog[cur_subprog].start;
2885 	subprog_end = subprog[cur_subprog + 1].start;
2886 	for (i = 0; i < insn_cnt; i++) {
2887 		u8 code = insn[i].code;
2888 
2889 		if (code == (BPF_JMP | BPF_CALL) &&
2890 		    insn[i].src_reg == 0 &&
2891 		    insn[i].imm == BPF_FUNC_tail_call)
2892 			subprog[cur_subprog].has_tail_call = true;
2893 		if (BPF_CLASS(code) == BPF_LD &&
2894 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2895 			subprog[cur_subprog].has_ld_abs = true;
2896 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2897 			goto next;
2898 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2899 			goto next;
2900 		if (code == (BPF_JMP32 | BPF_JA))
2901 			off = i + insn[i].imm + 1;
2902 		else
2903 			off = i + insn[i].off + 1;
2904 		if (off < subprog_start || off >= subprog_end) {
2905 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2906 			return -EINVAL;
2907 		}
2908 next:
2909 		if (i == subprog_end - 1) {
2910 			/* to avoid fall-through from one subprog into another
2911 			 * the last insn of the subprog should be either exit
2912 			 * or unconditional jump back or bpf_throw call
2913 			 */
2914 			if (code != (BPF_JMP | BPF_EXIT) &&
2915 			    code != (BPF_JMP32 | BPF_JA) &&
2916 			    code != (BPF_JMP | BPF_JA)) {
2917 				verbose(env, "last insn is not an exit or jmp\n");
2918 				return -EINVAL;
2919 			}
2920 			subprog_start = subprog_end;
2921 			cur_subprog++;
2922 			if (cur_subprog < env->subprog_cnt)
2923 				subprog_end = subprog[cur_subprog + 1].start;
2924 		}
2925 	}
2926 	return 0;
2927 }
2928 
2929 /* Parentage chain of this register (or stack slot) should take care of all
2930  * issues like callee-saved registers, stack slot allocation time, etc.
2931  */
2932 static int mark_reg_read(struct bpf_verifier_env *env,
2933 			 const struct bpf_reg_state *state,
2934 			 struct bpf_reg_state *parent, u8 flag)
2935 {
2936 	bool writes = parent == state->parent; /* Observe write marks */
2937 	int cnt = 0;
2938 
2939 	while (parent) {
2940 		/* if read wasn't screened by an earlier write ... */
2941 		if (writes && state->live & REG_LIVE_WRITTEN)
2942 			break;
2943 		if (parent->live & REG_LIVE_DONE) {
2944 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2945 				reg_type_str(env, parent->type),
2946 				parent->var_off.value, parent->off);
2947 			return -EFAULT;
2948 		}
2949 		/* The first condition is more likely to be true than the
2950 		 * second, checked it first.
2951 		 */
2952 		if ((parent->live & REG_LIVE_READ) == flag ||
2953 		    parent->live & REG_LIVE_READ64)
2954 			/* The parentage chain never changes and
2955 			 * this parent was already marked as LIVE_READ.
2956 			 * There is no need to keep walking the chain again and
2957 			 * keep re-marking all parents as LIVE_READ.
2958 			 * This case happens when the same register is read
2959 			 * multiple times without writes into it in-between.
2960 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2961 			 * then no need to set the weak REG_LIVE_READ32.
2962 			 */
2963 			break;
2964 		/* ... then we depend on parent's value */
2965 		parent->live |= flag;
2966 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2967 		if (flag == REG_LIVE_READ64)
2968 			parent->live &= ~REG_LIVE_READ32;
2969 		state = parent;
2970 		parent = state->parent;
2971 		writes = true;
2972 		cnt++;
2973 	}
2974 
2975 	if (env->longest_mark_read_walk < cnt)
2976 		env->longest_mark_read_walk = cnt;
2977 	return 0;
2978 }
2979 
2980 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2981 {
2982 	struct bpf_func_state *state = func(env, reg);
2983 	int spi, ret;
2984 
2985 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
2986 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2987 	 * check_kfunc_call.
2988 	 */
2989 	if (reg->type == CONST_PTR_TO_DYNPTR)
2990 		return 0;
2991 	spi = dynptr_get_spi(env, reg);
2992 	if (spi < 0)
2993 		return spi;
2994 	/* Caller ensures dynptr is valid and initialized, which means spi is in
2995 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2996 	 * read.
2997 	 */
2998 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2999 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3000 	if (ret)
3001 		return ret;
3002 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3003 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3004 }
3005 
3006 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3007 			  int spi, int nr_slots)
3008 {
3009 	struct bpf_func_state *state = func(env, reg);
3010 	int err, i;
3011 
3012 	for (i = 0; i < nr_slots; i++) {
3013 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3014 
3015 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3016 		if (err)
3017 			return err;
3018 
3019 		mark_stack_slot_scratched(env, spi - i);
3020 	}
3021 
3022 	return 0;
3023 }
3024 
3025 /* This function is supposed to be used by the following 32-bit optimization
3026  * code only. It returns TRUE if the source or destination register operates
3027  * on 64-bit, otherwise return FALSE.
3028  */
3029 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3030 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3031 {
3032 	u8 code, class, op;
3033 
3034 	code = insn->code;
3035 	class = BPF_CLASS(code);
3036 	op = BPF_OP(code);
3037 	if (class == BPF_JMP) {
3038 		/* BPF_EXIT for "main" will reach here. Return TRUE
3039 		 * conservatively.
3040 		 */
3041 		if (op == BPF_EXIT)
3042 			return true;
3043 		if (op == BPF_CALL) {
3044 			/* BPF to BPF call will reach here because of marking
3045 			 * caller saved clobber with DST_OP_NO_MARK for which we
3046 			 * don't care the register def because they are anyway
3047 			 * marked as NOT_INIT already.
3048 			 */
3049 			if (insn->src_reg == BPF_PSEUDO_CALL)
3050 				return false;
3051 			/* Helper call will reach here because of arg type
3052 			 * check, conservatively return TRUE.
3053 			 */
3054 			if (t == SRC_OP)
3055 				return true;
3056 
3057 			return false;
3058 		}
3059 	}
3060 
3061 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3062 		return false;
3063 
3064 	if (class == BPF_ALU64 || class == BPF_JMP ||
3065 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3066 		return true;
3067 
3068 	if (class == BPF_ALU || class == BPF_JMP32)
3069 		return false;
3070 
3071 	if (class == BPF_LDX) {
3072 		if (t != SRC_OP)
3073 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3074 		/* LDX source must be ptr. */
3075 		return true;
3076 	}
3077 
3078 	if (class == BPF_STX) {
3079 		/* BPF_STX (including atomic variants) has multiple source
3080 		 * operands, one of which is a ptr. Check whether the caller is
3081 		 * asking about it.
3082 		 */
3083 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3084 			return true;
3085 		return BPF_SIZE(code) == BPF_DW;
3086 	}
3087 
3088 	if (class == BPF_LD) {
3089 		u8 mode = BPF_MODE(code);
3090 
3091 		/* LD_IMM64 */
3092 		if (mode == BPF_IMM)
3093 			return true;
3094 
3095 		/* Both LD_IND and LD_ABS return 32-bit data. */
3096 		if (t != SRC_OP)
3097 			return  false;
3098 
3099 		/* Implicit ctx ptr. */
3100 		if (regno == BPF_REG_6)
3101 			return true;
3102 
3103 		/* Explicit source could be any width. */
3104 		return true;
3105 	}
3106 
3107 	if (class == BPF_ST)
3108 		/* The only source register for BPF_ST is a ptr. */
3109 		return true;
3110 
3111 	/* Conservatively return true at default. */
3112 	return true;
3113 }
3114 
3115 /* Return the regno defined by the insn, or -1. */
3116 static int insn_def_regno(const struct bpf_insn *insn)
3117 {
3118 	switch (BPF_CLASS(insn->code)) {
3119 	case BPF_JMP:
3120 	case BPF_JMP32:
3121 	case BPF_ST:
3122 		return -1;
3123 	case BPF_STX:
3124 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3125 		    (insn->imm & BPF_FETCH)) {
3126 			if (insn->imm == BPF_CMPXCHG)
3127 				return BPF_REG_0;
3128 			else
3129 				return insn->src_reg;
3130 		} else {
3131 			return -1;
3132 		}
3133 	default:
3134 		return insn->dst_reg;
3135 	}
3136 }
3137 
3138 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3139 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3140 {
3141 	int dst_reg = insn_def_regno(insn);
3142 
3143 	if (dst_reg == -1)
3144 		return false;
3145 
3146 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3147 }
3148 
3149 static void mark_insn_zext(struct bpf_verifier_env *env,
3150 			   struct bpf_reg_state *reg)
3151 {
3152 	s32 def_idx = reg->subreg_def;
3153 
3154 	if (def_idx == DEF_NOT_SUBREG)
3155 		return;
3156 
3157 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3158 	/* The dst will be zero extended, so won't be sub-register anymore. */
3159 	reg->subreg_def = DEF_NOT_SUBREG;
3160 }
3161 
3162 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3163 			   enum reg_arg_type t)
3164 {
3165 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3166 	struct bpf_reg_state *reg;
3167 	bool rw64;
3168 
3169 	if (regno >= MAX_BPF_REG) {
3170 		verbose(env, "R%d is invalid\n", regno);
3171 		return -EINVAL;
3172 	}
3173 
3174 	mark_reg_scratched(env, regno);
3175 
3176 	reg = &regs[regno];
3177 	rw64 = is_reg64(env, insn, regno, reg, t);
3178 	if (t == SRC_OP) {
3179 		/* check whether register used as source operand can be read */
3180 		if (reg->type == NOT_INIT) {
3181 			verbose(env, "R%d !read_ok\n", regno);
3182 			return -EACCES;
3183 		}
3184 		/* We don't need to worry about FP liveness because it's read-only */
3185 		if (regno == BPF_REG_FP)
3186 			return 0;
3187 
3188 		if (rw64)
3189 			mark_insn_zext(env, reg);
3190 
3191 		return mark_reg_read(env, reg, reg->parent,
3192 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3193 	} else {
3194 		/* check whether register used as dest operand can be written to */
3195 		if (regno == BPF_REG_FP) {
3196 			verbose(env, "frame pointer is read only\n");
3197 			return -EACCES;
3198 		}
3199 		reg->live |= REG_LIVE_WRITTEN;
3200 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3201 		if (t == DST_OP)
3202 			mark_reg_unknown(env, regs, regno);
3203 	}
3204 	return 0;
3205 }
3206 
3207 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3208 			 enum reg_arg_type t)
3209 {
3210 	struct bpf_verifier_state *vstate = env->cur_state;
3211 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3212 
3213 	return __check_reg_arg(env, state->regs, regno, t);
3214 }
3215 
3216 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3217 {
3218 	env->insn_aux_data[idx].jmp_point = true;
3219 }
3220 
3221 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3222 {
3223 	return env->insn_aux_data[insn_idx].jmp_point;
3224 }
3225 
3226 /* for any branch, call, exit record the history of jmps in the given state */
3227 static int push_jmp_history(struct bpf_verifier_env *env,
3228 			    struct bpf_verifier_state *cur)
3229 {
3230 	u32 cnt = cur->jmp_history_cnt;
3231 	struct bpf_idx_pair *p;
3232 	size_t alloc_size;
3233 
3234 	if (!is_jmp_point(env, env->insn_idx))
3235 		return 0;
3236 
3237 	cnt++;
3238 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3239 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3240 	if (!p)
3241 		return -ENOMEM;
3242 	p[cnt - 1].idx = env->insn_idx;
3243 	p[cnt - 1].prev_idx = env->prev_insn_idx;
3244 	cur->jmp_history = p;
3245 	cur->jmp_history_cnt = cnt;
3246 	return 0;
3247 }
3248 
3249 /* Backtrack one insn at a time. If idx is not at the top of recorded
3250  * history then previous instruction came from straight line execution.
3251  * Return -ENOENT if we exhausted all instructions within given state.
3252  *
3253  * It's legal to have a bit of a looping with the same starting and ending
3254  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3255  * instruction index is the same as state's first_idx doesn't mean we are
3256  * done. If there is still some jump history left, we should keep going. We
3257  * need to take into account that we might have a jump history between given
3258  * state's parent and itself, due to checkpointing. In this case, we'll have
3259  * history entry recording a jump from last instruction of parent state and
3260  * first instruction of given state.
3261  */
3262 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3263 			     u32 *history)
3264 {
3265 	u32 cnt = *history;
3266 
3267 	if (i == st->first_insn_idx) {
3268 		if (cnt == 0)
3269 			return -ENOENT;
3270 		if (cnt == 1 && st->jmp_history[0].idx == i)
3271 			return -ENOENT;
3272 	}
3273 
3274 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3275 		i = st->jmp_history[cnt - 1].prev_idx;
3276 		(*history)--;
3277 	} else {
3278 		i--;
3279 	}
3280 	return i;
3281 }
3282 
3283 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3284 {
3285 	const struct btf_type *func;
3286 	struct btf *desc_btf;
3287 
3288 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3289 		return NULL;
3290 
3291 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3292 	if (IS_ERR(desc_btf))
3293 		return "<error>";
3294 
3295 	func = btf_type_by_id(desc_btf, insn->imm);
3296 	return btf_name_by_offset(desc_btf, func->name_off);
3297 }
3298 
3299 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3300 {
3301 	bt->frame = frame;
3302 }
3303 
3304 static inline void bt_reset(struct backtrack_state *bt)
3305 {
3306 	struct bpf_verifier_env *env = bt->env;
3307 
3308 	memset(bt, 0, sizeof(*bt));
3309 	bt->env = env;
3310 }
3311 
3312 static inline u32 bt_empty(struct backtrack_state *bt)
3313 {
3314 	u64 mask = 0;
3315 	int i;
3316 
3317 	for (i = 0; i <= bt->frame; i++)
3318 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3319 
3320 	return mask == 0;
3321 }
3322 
3323 static inline int bt_subprog_enter(struct backtrack_state *bt)
3324 {
3325 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3326 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3327 		WARN_ONCE(1, "verifier backtracking bug");
3328 		return -EFAULT;
3329 	}
3330 	bt->frame++;
3331 	return 0;
3332 }
3333 
3334 static inline int bt_subprog_exit(struct backtrack_state *bt)
3335 {
3336 	if (bt->frame == 0) {
3337 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3338 		WARN_ONCE(1, "verifier backtracking bug");
3339 		return -EFAULT;
3340 	}
3341 	bt->frame--;
3342 	return 0;
3343 }
3344 
3345 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3346 {
3347 	bt->reg_masks[frame] |= 1 << reg;
3348 }
3349 
3350 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3351 {
3352 	bt->reg_masks[frame] &= ~(1 << reg);
3353 }
3354 
3355 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3356 {
3357 	bt_set_frame_reg(bt, bt->frame, reg);
3358 }
3359 
3360 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3361 {
3362 	bt_clear_frame_reg(bt, bt->frame, reg);
3363 }
3364 
3365 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3366 {
3367 	bt->stack_masks[frame] |= 1ull << slot;
3368 }
3369 
3370 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3371 {
3372 	bt->stack_masks[frame] &= ~(1ull << slot);
3373 }
3374 
3375 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3376 {
3377 	bt_set_frame_slot(bt, bt->frame, slot);
3378 }
3379 
3380 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3381 {
3382 	bt_clear_frame_slot(bt, bt->frame, slot);
3383 }
3384 
3385 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3386 {
3387 	return bt->reg_masks[frame];
3388 }
3389 
3390 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3391 {
3392 	return bt->reg_masks[bt->frame];
3393 }
3394 
3395 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3396 {
3397 	return bt->stack_masks[frame];
3398 }
3399 
3400 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3401 {
3402 	return bt->stack_masks[bt->frame];
3403 }
3404 
3405 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3406 {
3407 	return bt->reg_masks[bt->frame] & (1 << reg);
3408 }
3409 
3410 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3411 {
3412 	return bt->stack_masks[bt->frame] & (1ull << slot);
3413 }
3414 
3415 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3416 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3417 {
3418 	DECLARE_BITMAP(mask, 64);
3419 	bool first = true;
3420 	int i, n;
3421 
3422 	buf[0] = '\0';
3423 
3424 	bitmap_from_u64(mask, reg_mask);
3425 	for_each_set_bit(i, mask, 32) {
3426 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3427 		first = false;
3428 		buf += n;
3429 		buf_sz -= n;
3430 		if (buf_sz < 0)
3431 			break;
3432 	}
3433 }
3434 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3435 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3436 {
3437 	DECLARE_BITMAP(mask, 64);
3438 	bool first = true;
3439 	int i, n;
3440 
3441 	buf[0] = '\0';
3442 
3443 	bitmap_from_u64(mask, stack_mask);
3444 	for_each_set_bit(i, mask, 64) {
3445 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3446 		first = false;
3447 		buf += n;
3448 		buf_sz -= n;
3449 		if (buf_sz < 0)
3450 			break;
3451 	}
3452 }
3453 
3454 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3455 
3456 /* For given verifier state backtrack_insn() is called from the last insn to
3457  * the first insn. Its purpose is to compute a bitmask of registers and
3458  * stack slots that needs precision in the parent verifier state.
3459  *
3460  * @idx is an index of the instruction we are currently processing;
3461  * @subseq_idx is an index of the subsequent instruction that:
3462  *   - *would be* executed next, if jump history is viewed in forward order;
3463  *   - *was* processed previously during backtracking.
3464  */
3465 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3466 			  struct backtrack_state *bt)
3467 {
3468 	const struct bpf_insn_cbs cbs = {
3469 		.cb_call	= disasm_kfunc_name,
3470 		.cb_print	= verbose,
3471 		.private_data	= env,
3472 	};
3473 	struct bpf_insn *insn = env->prog->insnsi + idx;
3474 	u8 class = BPF_CLASS(insn->code);
3475 	u8 opcode = BPF_OP(insn->code);
3476 	u8 mode = BPF_MODE(insn->code);
3477 	u32 dreg = insn->dst_reg;
3478 	u32 sreg = insn->src_reg;
3479 	u32 spi, i;
3480 
3481 	if (insn->code == 0)
3482 		return 0;
3483 	if (env->log.level & BPF_LOG_LEVEL2) {
3484 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3485 		verbose(env, "mark_precise: frame%d: regs=%s ",
3486 			bt->frame, env->tmp_str_buf);
3487 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3488 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3489 		verbose(env, "%d: ", idx);
3490 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3491 	}
3492 
3493 	if (class == BPF_ALU || class == BPF_ALU64) {
3494 		if (!bt_is_reg_set(bt, dreg))
3495 			return 0;
3496 		if (opcode == BPF_END || opcode == BPF_NEG) {
3497 			/* sreg is reserved and unused
3498 			 * dreg still need precision before this insn
3499 			 */
3500 			return 0;
3501 		} else if (opcode == BPF_MOV) {
3502 			if (BPF_SRC(insn->code) == BPF_X) {
3503 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3504 				 * dreg needs precision after this insn
3505 				 * sreg needs precision before this insn
3506 				 */
3507 				bt_clear_reg(bt, dreg);
3508 				bt_set_reg(bt, sreg);
3509 			} else {
3510 				/* dreg = K
3511 				 * dreg needs precision after this insn.
3512 				 * Corresponding register is already marked
3513 				 * as precise=true in this verifier state.
3514 				 * No further markings in parent are necessary
3515 				 */
3516 				bt_clear_reg(bt, dreg);
3517 			}
3518 		} else {
3519 			if (BPF_SRC(insn->code) == BPF_X) {
3520 				/* dreg += sreg
3521 				 * both dreg and sreg need precision
3522 				 * before this insn
3523 				 */
3524 				bt_set_reg(bt, sreg);
3525 			} /* else dreg += K
3526 			   * dreg still needs precision before this insn
3527 			   */
3528 		}
3529 	} else if (class == BPF_LDX) {
3530 		if (!bt_is_reg_set(bt, dreg))
3531 			return 0;
3532 		bt_clear_reg(bt, dreg);
3533 
3534 		/* scalars can only be spilled into stack w/o losing precision.
3535 		 * Load from any other memory can be zero extended.
3536 		 * The desire to keep that precision is already indicated
3537 		 * by 'precise' mark in corresponding register of this state.
3538 		 * No further tracking necessary.
3539 		 */
3540 		if (insn->src_reg != BPF_REG_FP)
3541 			return 0;
3542 
3543 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3544 		 * that [fp - off] slot contains scalar that needs to be
3545 		 * tracked with precision
3546 		 */
3547 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3548 		if (spi >= 64) {
3549 			verbose(env, "BUG spi %d\n", spi);
3550 			WARN_ONCE(1, "verifier backtracking bug");
3551 			return -EFAULT;
3552 		}
3553 		bt_set_slot(bt, spi);
3554 	} else if (class == BPF_STX || class == BPF_ST) {
3555 		if (bt_is_reg_set(bt, dreg))
3556 			/* stx & st shouldn't be using _scalar_ dst_reg
3557 			 * to access memory. It means backtracking
3558 			 * encountered a case of pointer subtraction.
3559 			 */
3560 			return -ENOTSUPP;
3561 		/* scalars can only be spilled into stack */
3562 		if (insn->dst_reg != BPF_REG_FP)
3563 			return 0;
3564 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3565 		if (spi >= 64) {
3566 			verbose(env, "BUG spi %d\n", spi);
3567 			WARN_ONCE(1, "verifier backtracking bug");
3568 			return -EFAULT;
3569 		}
3570 		if (!bt_is_slot_set(bt, spi))
3571 			return 0;
3572 		bt_clear_slot(bt, spi);
3573 		if (class == BPF_STX)
3574 			bt_set_reg(bt, sreg);
3575 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3576 		if (bpf_pseudo_call(insn)) {
3577 			int subprog_insn_idx, subprog;
3578 
3579 			subprog_insn_idx = idx + insn->imm + 1;
3580 			subprog = find_subprog(env, subprog_insn_idx);
3581 			if (subprog < 0)
3582 				return -EFAULT;
3583 
3584 			if (subprog_is_global(env, subprog)) {
3585 				/* check that jump history doesn't have any
3586 				 * extra instructions from subprog; the next
3587 				 * instruction after call to global subprog
3588 				 * should be literally next instruction in
3589 				 * caller program
3590 				 */
3591 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3592 				/* r1-r5 are invalidated after subprog call,
3593 				 * so for global func call it shouldn't be set
3594 				 * anymore
3595 				 */
3596 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3597 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3598 					WARN_ONCE(1, "verifier backtracking bug");
3599 					return -EFAULT;
3600 				}
3601 				/* global subprog always sets R0 */
3602 				bt_clear_reg(bt, BPF_REG_0);
3603 				return 0;
3604 			} else {
3605 				/* static subprog call instruction, which
3606 				 * means that we are exiting current subprog,
3607 				 * so only r1-r5 could be still requested as
3608 				 * precise, r0 and r6-r10 or any stack slot in
3609 				 * the current frame should be zero by now
3610 				 */
3611 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3612 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3613 					WARN_ONCE(1, "verifier backtracking bug");
3614 					return -EFAULT;
3615 				}
3616 				/* we don't track register spills perfectly,
3617 				 * so fallback to force-precise instead of failing */
3618 				if (bt_stack_mask(bt) != 0)
3619 					return -ENOTSUPP;
3620 				/* propagate r1-r5 to the caller */
3621 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3622 					if (bt_is_reg_set(bt, i)) {
3623 						bt_clear_reg(bt, i);
3624 						bt_set_frame_reg(bt, bt->frame - 1, i);
3625 					}
3626 				}
3627 				if (bt_subprog_exit(bt))
3628 					return -EFAULT;
3629 				return 0;
3630 			}
3631 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3632 			/* exit from callback subprog to callback-calling helper or
3633 			 * kfunc call. Use idx/subseq_idx check to discern it from
3634 			 * straight line code backtracking.
3635 			 * Unlike the subprog call handling above, we shouldn't
3636 			 * propagate precision of r1-r5 (if any requested), as they are
3637 			 * not actually arguments passed directly to callback subprogs
3638 			 */
3639 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3640 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3641 				WARN_ONCE(1, "verifier backtracking bug");
3642 				return -EFAULT;
3643 			}
3644 			if (bt_stack_mask(bt) != 0)
3645 				return -ENOTSUPP;
3646 			/* clear r1-r5 in callback subprog's mask */
3647 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3648 				bt_clear_reg(bt, i);
3649 			if (bt_subprog_exit(bt))
3650 				return -EFAULT;
3651 			return 0;
3652 		} else if (opcode == BPF_CALL) {
3653 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3654 			 * catch this error later. Make backtracking conservative
3655 			 * with ENOTSUPP.
3656 			 */
3657 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3658 				return -ENOTSUPP;
3659 			/* regular helper call sets R0 */
3660 			bt_clear_reg(bt, BPF_REG_0);
3661 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3662 				/* if backtracing was looking for registers R1-R5
3663 				 * they should have been found already.
3664 				 */
3665 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3666 				WARN_ONCE(1, "verifier backtracking bug");
3667 				return -EFAULT;
3668 			}
3669 		} else if (opcode == BPF_EXIT) {
3670 			bool r0_precise;
3671 
3672 			/* Backtracking to a nested function call, 'idx' is a part of
3673 			 * the inner frame 'subseq_idx' is a part of the outer frame.
3674 			 * In case of a regular function call, instructions giving
3675 			 * precision to registers R1-R5 should have been found already.
3676 			 * In case of a callback, it is ok to have R1-R5 marked for
3677 			 * backtracking, as these registers are set by the function
3678 			 * invoking callback.
3679 			 */
3680 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3681 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3682 					bt_clear_reg(bt, i);
3683 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3684 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3685 				WARN_ONCE(1, "verifier backtracking bug");
3686 				return -EFAULT;
3687 			}
3688 
3689 			/* BPF_EXIT in subprog or callback always returns
3690 			 * right after the call instruction, so by checking
3691 			 * whether the instruction at subseq_idx-1 is subprog
3692 			 * call or not we can distinguish actual exit from
3693 			 * *subprog* from exit from *callback*. In the former
3694 			 * case, we need to propagate r0 precision, if
3695 			 * necessary. In the former we never do that.
3696 			 */
3697 			r0_precise = subseq_idx - 1 >= 0 &&
3698 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3699 				     bt_is_reg_set(bt, BPF_REG_0);
3700 
3701 			bt_clear_reg(bt, BPF_REG_0);
3702 			if (bt_subprog_enter(bt))
3703 				return -EFAULT;
3704 
3705 			if (r0_precise)
3706 				bt_set_reg(bt, BPF_REG_0);
3707 			/* r6-r9 and stack slots will stay set in caller frame
3708 			 * bitmasks until we return back from callee(s)
3709 			 */
3710 			return 0;
3711 		} else if (BPF_SRC(insn->code) == BPF_X) {
3712 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3713 				return 0;
3714 			/* dreg <cond> sreg
3715 			 * Both dreg and sreg need precision before
3716 			 * this insn. If only sreg was marked precise
3717 			 * before it would be equally necessary to
3718 			 * propagate it to dreg.
3719 			 */
3720 			bt_set_reg(bt, dreg);
3721 			bt_set_reg(bt, sreg);
3722 			 /* else dreg <cond> K
3723 			  * Only dreg still needs precision before
3724 			  * this insn, so for the K-based conditional
3725 			  * there is nothing new to be marked.
3726 			  */
3727 		}
3728 	} else if (class == BPF_LD) {
3729 		if (!bt_is_reg_set(bt, dreg))
3730 			return 0;
3731 		bt_clear_reg(bt, dreg);
3732 		/* It's ld_imm64 or ld_abs or ld_ind.
3733 		 * For ld_imm64 no further tracking of precision
3734 		 * into parent is necessary
3735 		 */
3736 		if (mode == BPF_IND || mode == BPF_ABS)
3737 			/* to be analyzed */
3738 			return -ENOTSUPP;
3739 	}
3740 	return 0;
3741 }
3742 
3743 /* the scalar precision tracking algorithm:
3744  * . at the start all registers have precise=false.
3745  * . scalar ranges are tracked as normal through alu and jmp insns.
3746  * . once precise value of the scalar register is used in:
3747  *   .  ptr + scalar alu
3748  *   . if (scalar cond K|scalar)
3749  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3750  *   backtrack through the verifier states and mark all registers and
3751  *   stack slots with spilled constants that these scalar regisers
3752  *   should be precise.
3753  * . during state pruning two registers (or spilled stack slots)
3754  *   are equivalent if both are not precise.
3755  *
3756  * Note the verifier cannot simply walk register parentage chain,
3757  * since many different registers and stack slots could have been
3758  * used to compute single precise scalar.
3759  *
3760  * The approach of starting with precise=true for all registers and then
3761  * backtrack to mark a register as not precise when the verifier detects
3762  * that program doesn't care about specific value (e.g., when helper
3763  * takes register as ARG_ANYTHING parameter) is not safe.
3764  *
3765  * It's ok to walk single parentage chain of the verifier states.
3766  * It's possible that this backtracking will go all the way till 1st insn.
3767  * All other branches will be explored for needing precision later.
3768  *
3769  * The backtracking needs to deal with cases like:
3770  *   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)
3771  * r9 -= r8
3772  * r5 = r9
3773  * if r5 > 0x79f goto pc+7
3774  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3775  * r5 += 1
3776  * ...
3777  * call bpf_perf_event_output#25
3778  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3779  *
3780  * and this case:
3781  * r6 = 1
3782  * call foo // uses callee's r6 inside to compute r0
3783  * r0 += r6
3784  * if r0 == 0 goto
3785  *
3786  * to track above reg_mask/stack_mask needs to be independent for each frame.
3787  *
3788  * Also if parent's curframe > frame where backtracking started,
3789  * the verifier need to mark registers in both frames, otherwise callees
3790  * may incorrectly prune callers. This is similar to
3791  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3792  *
3793  * For now backtracking falls back into conservative marking.
3794  */
3795 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3796 				     struct bpf_verifier_state *st)
3797 {
3798 	struct bpf_func_state *func;
3799 	struct bpf_reg_state *reg;
3800 	int i, j;
3801 
3802 	if (env->log.level & BPF_LOG_LEVEL2) {
3803 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3804 			st->curframe);
3805 	}
3806 
3807 	/* big hammer: mark all scalars precise in this path.
3808 	 * pop_stack may still get !precise scalars.
3809 	 * We also skip current state and go straight to first parent state,
3810 	 * because precision markings in current non-checkpointed state are
3811 	 * not needed. See why in the comment in __mark_chain_precision below.
3812 	 */
3813 	for (st = st->parent; st; st = st->parent) {
3814 		for (i = 0; i <= st->curframe; i++) {
3815 			func = st->frame[i];
3816 			for (j = 0; j < BPF_REG_FP; j++) {
3817 				reg = &func->regs[j];
3818 				if (reg->type != SCALAR_VALUE || reg->precise)
3819 					continue;
3820 				reg->precise = true;
3821 				if (env->log.level & BPF_LOG_LEVEL2) {
3822 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3823 						i, j);
3824 				}
3825 			}
3826 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3827 				if (!is_spilled_reg(&func->stack[j]))
3828 					continue;
3829 				reg = &func->stack[j].spilled_ptr;
3830 				if (reg->type != SCALAR_VALUE || reg->precise)
3831 					continue;
3832 				reg->precise = true;
3833 				if (env->log.level & BPF_LOG_LEVEL2) {
3834 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3835 						i, -(j + 1) * 8);
3836 				}
3837 			}
3838 		}
3839 	}
3840 }
3841 
3842 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3843 {
3844 	struct bpf_func_state *func;
3845 	struct bpf_reg_state *reg;
3846 	int i, j;
3847 
3848 	for (i = 0; i <= st->curframe; i++) {
3849 		func = st->frame[i];
3850 		for (j = 0; j < BPF_REG_FP; j++) {
3851 			reg = &func->regs[j];
3852 			if (reg->type != SCALAR_VALUE)
3853 				continue;
3854 			reg->precise = false;
3855 		}
3856 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3857 			if (!is_spilled_reg(&func->stack[j]))
3858 				continue;
3859 			reg = &func->stack[j].spilled_ptr;
3860 			if (reg->type != SCALAR_VALUE)
3861 				continue;
3862 			reg->precise = false;
3863 		}
3864 	}
3865 }
3866 
3867 static bool idset_contains(struct bpf_idset *s, u32 id)
3868 {
3869 	u32 i;
3870 
3871 	for (i = 0; i < s->count; ++i)
3872 		if (s->ids[i] == id)
3873 			return true;
3874 
3875 	return false;
3876 }
3877 
3878 static int idset_push(struct bpf_idset *s, u32 id)
3879 {
3880 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3881 		return -EFAULT;
3882 	s->ids[s->count++] = id;
3883 	return 0;
3884 }
3885 
3886 static void idset_reset(struct bpf_idset *s)
3887 {
3888 	s->count = 0;
3889 }
3890 
3891 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3892  * Mark all registers with these IDs as precise.
3893  */
3894 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3895 {
3896 	struct bpf_idset *precise_ids = &env->idset_scratch;
3897 	struct backtrack_state *bt = &env->bt;
3898 	struct bpf_func_state *func;
3899 	struct bpf_reg_state *reg;
3900 	DECLARE_BITMAP(mask, 64);
3901 	int i, fr;
3902 
3903 	idset_reset(precise_ids);
3904 
3905 	for (fr = bt->frame; fr >= 0; fr--) {
3906 		func = st->frame[fr];
3907 
3908 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3909 		for_each_set_bit(i, mask, 32) {
3910 			reg = &func->regs[i];
3911 			if (!reg->id || reg->type != SCALAR_VALUE)
3912 				continue;
3913 			if (idset_push(precise_ids, reg->id))
3914 				return -EFAULT;
3915 		}
3916 
3917 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3918 		for_each_set_bit(i, mask, 64) {
3919 			if (i >= func->allocated_stack / BPF_REG_SIZE)
3920 				break;
3921 			if (!is_spilled_scalar_reg(&func->stack[i]))
3922 				continue;
3923 			reg = &func->stack[i].spilled_ptr;
3924 			if (!reg->id)
3925 				continue;
3926 			if (idset_push(precise_ids, reg->id))
3927 				return -EFAULT;
3928 		}
3929 	}
3930 
3931 	for (fr = 0; fr <= st->curframe; ++fr) {
3932 		func = st->frame[fr];
3933 
3934 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
3935 			reg = &func->regs[i];
3936 			if (!reg->id)
3937 				continue;
3938 			if (!idset_contains(precise_ids, reg->id))
3939 				continue;
3940 			bt_set_frame_reg(bt, fr, i);
3941 		}
3942 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
3943 			if (!is_spilled_scalar_reg(&func->stack[i]))
3944 				continue;
3945 			reg = &func->stack[i].spilled_ptr;
3946 			if (!reg->id)
3947 				continue;
3948 			if (!idset_contains(precise_ids, reg->id))
3949 				continue;
3950 			bt_set_frame_slot(bt, fr, i);
3951 		}
3952 	}
3953 
3954 	return 0;
3955 }
3956 
3957 /*
3958  * __mark_chain_precision() backtracks BPF program instruction sequence and
3959  * chain of verifier states making sure that register *regno* (if regno >= 0)
3960  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3961  * SCALARS, as well as any other registers and slots that contribute to
3962  * a tracked state of given registers/stack slots, depending on specific BPF
3963  * assembly instructions (see backtrack_insns() for exact instruction handling
3964  * logic). This backtracking relies on recorded jmp_history and is able to
3965  * traverse entire chain of parent states. This process ends only when all the
3966  * necessary registers/slots and their transitive dependencies are marked as
3967  * precise.
3968  *
3969  * One important and subtle aspect is that precise marks *do not matter* in
3970  * the currently verified state (current state). It is important to understand
3971  * why this is the case.
3972  *
3973  * First, note that current state is the state that is not yet "checkpointed",
3974  * i.e., it is not yet put into env->explored_states, and it has no children
3975  * states as well. It's ephemeral, and can end up either a) being discarded if
3976  * compatible explored state is found at some point or BPF_EXIT instruction is
3977  * reached or b) checkpointed and put into env->explored_states, branching out
3978  * into one or more children states.
3979  *
3980  * In the former case, precise markings in current state are completely
3981  * ignored by state comparison code (see regsafe() for details). Only
3982  * checkpointed ("old") state precise markings are important, and if old
3983  * state's register/slot is precise, regsafe() assumes current state's
3984  * register/slot as precise and checks value ranges exactly and precisely. If
3985  * states turn out to be compatible, current state's necessary precise
3986  * markings and any required parent states' precise markings are enforced
3987  * after the fact with propagate_precision() logic, after the fact. But it's
3988  * important to realize that in this case, even after marking current state
3989  * registers/slots as precise, we immediately discard current state. So what
3990  * actually matters is any of the precise markings propagated into current
3991  * state's parent states, which are always checkpointed (due to b) case above).
3992  * As such, for scenario a) it doesn't matter if current state has precise
3993  * markings set or not.
3994  *
3995  * Now, for the scenario b), checkpointing and forking into child(ren)
3996  * state(s). Note that before current state gets to checkpointing step, any
3997  * processed instruction always assumes precise SCALAR register/slot
3998  * knowledge: if precise value or range is useful to prune jump branch, BPF
3999  * verifier takes this opportunity enthusiastically. Similarly, when
4000  * register's value is used to calculate offset or memory address, exact
4001  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4002  * what we mentioned above about state comparison ignoring precise markings
4003  * during state comparison, BPF verifier ignores and also assumes precise
4004  * markings *at will* during instruction verification process. But as verifier
4005  * assumes precision, it also propagates any precision dependencies across
4006  * parent states, which are not yet finalized, so can be further restricted
4007  * based on new knowledge gained from restrictions enforced by their children
4008  * states. This is so that once those parent states are finalized, i.e., when
4009  * they have no more active children state, state comparison logic in
4010  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4011  * required for correctness.
4012  *
4013  * To build a bit more intuition, note also that once a state is checkpointed,
4014  * the path we took to get to that state is not important. This is crucial
4015  * property for state pruning. When state is checkpointed and finalized at
4016  * some instruction index, it can be correctly and safely used to "short
4017  * circuit" any *compatible* state that reaches exactly the same instruction
4018  * index. I.e., if we jumped to that instruction from a completely different
4019  * code path than original finalized state was derived from, it doesn't
4020  * matter, current state can be discarded because from that instruction
4021  * forward having a compatible state will ensure we will safely reach the
4022  * exit. States describe preconditions for further exploration, but completely
4023  * forget the history of how we got here.
4024  *
4025  * This also means that even if we needed precise SCALAR range to get to
4026  * finalized state, but from that point forward *that same* SCALAR register is
4027  * never used in a precise context (i.e., it's precise value is not needed for
4028  * correctness), it's correct and safe to mark such register as "imprecise"
4029  * (i.e., precise marking set to false). This is what we rely on when we do
4030  * not set precise marking in current state. If no child state requires
4031  * precision for any given SCALAR register, it's safe to dictate that it can
4032  * be imprecise. If any child state does require this register to be precise,
4033  * we'll mark it precise later retroactively during precise markings
4034  * propagation from child state to parent states.
4035  *
4036  * Skipping precise marking setting in current state is a mild version of
4037  * relying on the above observation. But we can utilize this property even
4038  * more aggressively by proactively forgetting any precise marking in the
4039  * current state (which we inherited from the parent state), right before we
4040  * checkpoint it and branch off into new child state. This is done by
4041  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4042  * finalized states which help in short circuiting more future states.
4043  */
4044 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4045 {
4046 	struct backtrack_state *bt = &env->bt;
4047 	struct bpf_verifier_state *st = env->cur_state;
4048 	int first_idx = st->first_insn_idx;
4049 	int last_idx = env->insn_idx;
4050 	int subseq_idx = -1;
4051 	struct bpf_func_state *func;
4052 	struct bpf_reg_state *reg;
4053 	bool skip_first = true;
4054 	int i, fr, err;
4055 
4056 	if (!env->bpf_capable)
4057 		return 0;
4058 
4059 	/* set frame number from which we are starting to backtrack */
4060 	bt_init(bt, env->cur_state->curframe);
4061 
4062 	/* Do sanity checks against current state of register and/or stack
4063 	 * slot, but don't set precise flag in current state, as precision
4064 	 * tracking in the current state is unnecessary.
4065 	 */
4066 	func = st->frame[bt->frame];
4067 	if (regno >= 0) {
4068 		reg = &func->regs[regno];
4069 		if (reg->type != SCALAR_VALUE) {
4070 			WARN_ONCE(1, "backtracing misuse");
4071 			return -EFAULT;
4072 		}
4073 		bt_set_reg(bt, regno);
4074 	}
4075 
4076 	if (bt_empty(bt))
4077 		return 0;
4078 
4079 	for (;;) {
4080 		DECLARE_BITMAP(mask, 64);
4081 		u32 history = st->jmp_history_cnt;
4082 
4083 		if (env->log.level & BPF_LOG_LEVEL2) {
4084 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4085 				bt->frame, last_idx, first_idx, subseq_idx);
4086 		}
4087 
4088 		/* If some register with scalar ID is marked as precise,
4089 		 * make sure that all registers sharing this ID are also precise.
4090 		 * This is needed to estimate effect of find_equal_scalars().
4091 		 * Do this at the last instruction of each state,
4092 		 * bpf_reg_state::id fields are valid for these instructions.
4093 		 *
4094 		 * Allows to track precision in situation like below:
4095 		 *
4096 		 *     r2 = unknown value
4097 		 *     ...
4098 		 *   --- state #0 ---
4099 		 *     ...
4100 		 *     r1 = r2                 // r1 and r2 now share the same ID
4101 		 *     ...
4102 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4103 		 *     ...
4104 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4105 		 *     ...
4106 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4107 		 *     r3 = r10
4108 		 *     r3 += r1                // need to mark both r1 and r2
4109 		 */
4110 		if (mark_precise_scalar_ids(env, st))
4111 			return -EFAULT;
4112 
4113 		if (last_idx < 0) {
4114 			/* we are at the entry into subprog, which
4115 			 * is expected for global funcs, but only if
4116 			 * requested precise registers are R1-R5
4117 			 * (which are global func's input arguments)
4118 			 */
4119 			if (st->curframe == 0 &&
4120 			    st->frame[0]->subprogno > 0 &&
4121 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4122 			    bt_stack_mask(bt) == 0 &&
4123 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4124 				bitmap_from_u64(mask, bt_reg_mask(bt));
4125 				for_each_set_bit(i, mask, 32) {
4126 					reg = &st->frame[0]->regs[i];
4127 					bt_clear_reg(bt, i);
4128 					if (reg->type == SCALAR_VALUE)
4129 						reg->precise = true;
4130 				}
4131 				return 0;
4132 			}
4133 
4134 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4135 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4136 			WARN_ONCE(1, "verifier backtracking bug");
4137 			return -EFAULT;
4138 		}
4139 
4140 		for (i = last_idx;;) {
4141 			if (skip_first) {
4142 				err = 0;
4143 				skip_first = false;
4144 			} else {
4145 				err = backtrack_insn(env, i, subseq_idx, bt);
4146 			}
4147 			if (err == -ENOTSUPP) {
4148 				mark_all_scalars_precise(env, env->cur_state);
4149 				bt_reset(bt);
4150 				return 0;
4151 			} else if (err) {
4152 				return err;
4153 			}
4154 			if (bt_empty(bt))
4155 				/* Found assignment(s) into tracked register in this state.
4156 				 * Since this state is already marked, just return.
4157 				 * Nothing to be tracked further in the parent state.
4158 				 */
4159 				return 0;
4160 			subseq_idx = i;
4161 			i = get_prev_insn_idx(st, i, &history);
4162 			if (i == -ENOENT)
4163 				break;
4164 			if (i >= env->prog->len) {
4165 				/* This can happen if backtracking reached insn 0
4166 				 * and there are still reg_mask or stack_mask
4167 				 * to backtrack.
4168 				 * It means the backtracking missed the spot where
4169 				 * particular register was initialized with a constant.
4170 				 */
4171 				verbose(env, "BUG backtracking idx %d\n", i);
4172 				WARN_ONCE(1, "verifier backtracking bug");
4173 				return -EFAULT;
4174 			}
4175 		}
4176 		st = st->parent;
4177 		if (!st)
4178 			break;
4179 
4180 		for (fr = bt->frame; fr >= 0; fr--) {
4181 			func = st->frame[fr];
4182 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4183 			for_each_set_bit(i, mask, 32) {
4184 				reg = &func->regs[i];
4185 				if (reg->type != SCALAR_VALUE) {
4186 					bt_clear_frame_reg(bt, fr, i);
4187 					continue;
4188 				}
4189 				if (reg->precise)
4190 					bt_clear_frame_reg(bt, fr, i);
4191 				else
4192 					reg->precise = true;
4193 			}
4194 
4195 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4196 			for_each_set_bit(i, mask, 64) {
4197 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4198 					/* the sequence of instructions:
4199 					 * 2: (bf) r3 = r10
4200 					 * 3: (7b) *(u64 *)(r3 -8) = r0
4201 					 * 4: (79) r4 = *(u64 *)(r10 -8)
4202 					 * doesn't contain jmps. It's backtracked
4203 					 * as a single block.
4204 					 * During backtracking insn 3 is not recognized as
4205 					 * stack access, so at the end of backtracking
4206 					 * stack slot fp-8 is still marked in stack_mask.
4207 					 * However the parent state may not have accessed
4208 					 * fp-8 and it's "unallocated" stack space.
4209 					 * In such case fallback to conservative.
4210 					 */
4211 					mark_all_scalars_precise(env, env->cur_state);
4212 					bt_reset(bt);
4213 					return 0;
4214 				}
4215 
4216 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4217 					bt_clear_frame_slot(bt, fr, i);
4218 					continue;
4219 				}
4220 				reg = &func->stack[i].spilled_ptr;
4221 				if (reg->precise)
4222 					bt_clear_frame_slot(bt, fr, i);
4223 				else
4224 					reg->precise = true;
4225 			}
4226 			if (env->log.level & BPF_LOG_LEVEL2) {
4227 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4228 					     bt_frame_reg_mask(bt, fr));
4229 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4230 					fr, env->tmp_str_buf);
4231 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4232 					       bt_frame_stack_mask(bt, fr));
4233 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4234 				print_verifier_state(env, func, true);
4235 			}
4236 		}
4237 
4238 		if (bt_empty(bt))
4239 			return 0;
4240 
4241 		subseq_idx = first_idx;
4242 		last_idx = st->last_insn_idx;
4243 		first_idx = st->first_insn_idx;
4244 	}
4245 
4246 	/* if we still have requested precise regs or slots, we missed
4247 	 * something (e.g., stack access through non-r10 register), so
4248 	 * fallback to marking all precise
4249 	 */
4250 	if (!bt_empty(bt)) {
4251 		mark_all_scalars_precise(env, env->cur_state);
4252 		bt_reset(bt);
4253 	}
4254 
4255 	return 0;
4256 }
4257 
4258 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4259 {
4260 	return __mark_chain_precision(env, regno);
4261 }
4262 
4263 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4264  * desired reg and stack masks across all relevant frames
4265  */
4266 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4267 {
4268 	return __mark_chain_precision(env, -1);
4269 }
4270 
4271 static bool is_spillable_regtype(enum bpf_reg_type type)
4272 {
4273 	switch (base_type(type)) {
4274 	case PTR_TO_MAP_VALUE:
4275 	case PTR_TO_STACK:
4276 	case PTR_TO_CTX:
4277 	case PTR_TO_PACKET:
4278 	case PTR_TO_PACKET_META:
4279 	case PTR_TO_PACKET_END:
4280 	case PTR_TO_FLOW_KEYS:
4281 	case CONST_PTR_TO_MAP:
4282 	case PTR_TO_SOCKET:
4283 	case PTR_TO_SOCK_COMMON:
4284 	case PTR_TO_TCP_SOCK:
4285 	case PTR_TO_XDP_SOCK:
4286 	case PTR_TO_BTF_ID:
4287 	case PTR_TO_BUF:
4288 	case PTR_TO_MEM:
4289 	case PTR_TO_FUNC:
4290 	case PTR_TO_MAP_KEY:
4291 		return true;
4292 	default:
4293 		return false;
4294 	}
4295 }
4296 
4297 /* Does this register contain a constant zero? */
4298 static bool register_is_null(struct bpf_reg_state *reg)
4299 {
4300 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4301 }
4302 
4303 /* check if register is a constant scalar value */
4304 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4305 {
4306 	return reg->type == SCALAR_VALUE &&
4307 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4308 }
4309 
4310 /* assuming is_reg_const() is true, return constant value of a register */
4311 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4312 {
4313 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4314 }
4315 
4316 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4317 {
4318 	return tnum_is_unknown(reg->var_off) &&
4319 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4320 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4321 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4322 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4323 }
4324 
4325 static bool register_is_bounded(struct bpf_reg_state *reg)
4326 {
4327 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4328 }
4329 
4330 static bool __is_pointer_value(bool allow_ptr_leaks,
4331 			       const struct bpf_reg_state *reg)
4332 {
4333 	if (allow_ptr_leaks)
4334 		return false;
4335 
4336 	return reg->type != SCALAR_VALUE;
4337 }
4338 
4339 /* Copy src state preserving dst->parent and dst->live fields */
4340 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4341 {
4342 	struct bpf_reg_state *parent = dst->parent;
4343 	enum bpf_reg_liveness live = dst->live;
4344 
4345 	*dst = *src;
4346 	dst->parent = parent;
4347 	dst->live = live;
4348 }
4349 
4350 static void save_register_state(struct bpf_func_state *state,
4351 				int spi, struct bpf_reg_state *reg,
4352 				int size)
4353 {
4354 	int i;
4355 
4356 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4357 	if (size == BPF_REG_SIZE)
4358 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4359 
4360 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4361 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4362 
4363 	/* size < 8 bytes spill */
4364 	for (; i; i--)
4365 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4366 }
4367 
4368 static bool is_bpf_st_mem(struct bpf_insn *insn)
4369 {
4370 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4371 }
4372 
4373 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4374  * stack boundary and alignment are checked in check_mem_access()
4375  */
4376 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4377 				       /* stack frame we're writing to */
4378 				       struct bpf_func_state *state,
4379 				       int off, int size, int value_regno,
4380 				       int insn_idx)
4381 {
4382 	struct bpf_func_state *cur; /* state of the current function */
4383 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4384 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4385 	struct bpf_reg_state *reg = NULL;
4386 	u32 dst_reg = insn->dst_reg;
4387 
4388 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
4389 	if (err)
4390 		return err;
4391 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4392 	 * so it's aligned access and [off, off + size) are within stack limits
4393 	 */
4394 	if (!env->allow_ptr_leaks &&
4395 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
4396 	    size != BPF_REG_SIZE) {
4397 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4398 		return -EACCES;
4399 	}
4400 
4401 	cur = env->cur_state->frame[env->cur_state->curframe];
4402 	if (value_regno >= 0)
4403 		reg = &cur->regs[value_regno];
4404 	if (!env->bypass_spec_v4) {
4405 		bool sanitize = reg && is_spillable_regtype(reg->type);
4406 
4407 		for (i = 0; i < size; i++) {
4408 			u8 type = state->stack[spi].slot_type[i];
4409 
4410 			if (type != STACK_MISC && type != STACK_ZERO) {
4411 				sanitize = true;
4412 				break;
4413 			}
4414 		}
4415 
4416 		if (sanitize)
4417 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4418 	}
4419 
4420 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4421 	if (err)
4422 		return err;
4423 
4424 	mark_stack_slot_scratched(env, spi);
4425 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4426 	    !register_is_null(reg) && env->bpf_capable) {
4427 		if (dst_reg != BPF_REG_FP) {
4428 			/* The backtracking logic can only recognize explicit
4429 			 * stack slot address like [fp - 8]. Other spill of
4430 			 * scalar via different register has to be conservative.
4431 			 * Backtrack from here and mark all registers as precise
4432 			 * that contributed into 'reg' being a constant.
4433 			 */
4434 			err = mark_chain_precision(env, value_regno);
4435 			if (err)
4436 				return err;
4437 		}
4438 		save_register_state(state, spi, reg, size);
4439 		/* Break the relation on a narrowing spill. */
4440 		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4441 			state->stack[spi].spilled_ptr.id = 0;
4442 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4443 		   insn->imm != 0 && env->bpf_capable) {
4444 		struct bpf_reg_state fake_reg = {};
4445 
4446 		__mark_reg_known(&fake_reg, insn->imm);
4447 		fake_reg.type = SCALAR_VALUE;
4448 		save_register_state(state, spi, &fake_reg, size);
4449 	} else if (reg && is_spillable_regtype(reg->type)) {
4450 		/* register containing pointer is being spilled into stack */
4451 		if (size != BPF_REG_SIZE) {
4452 			verbose_linfo(env, insn_idx, "; ");
4453 			verbose(env, "invalid size of register spill\n");
4454 			return -EACCES;
4455 		}
4456 		if (state != cur && reg->type == PTR_TO_STACK) {
4457 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4458 			return -EINVAL;
4459 		}
4460 		save_register_state(state, spi, reg, size);
4461 	} else {
4462 		u8 type = STACK_MISC;
4463 
4464 		/* regular write of data into stack destroys any spilled ptr */
4465 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4466 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4467 		if (is_stack_slot_special(&state->stack[spi]))
4468 			for (i = 0; i < BPF_REG_SIZE; i++)
4469 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4470 
4471 		/* only mark the slot as written if all 8 bytes were written
4472 		 * otherwise read propagation may incorrectly stop too soon
4473 		 * when stack slots are partially written.
4474 		 * This heuristic means that read propagation will be
4475 		 * conservative, since it will add reg_live_read marks
4476 		 * to stack slots all the way to first state when programs
4477 		 * writes+reads less than 8 bytes
4478 		 */
4479 		if (size == BPF_REG_SIZE)
4480 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4481 
4482 		/* when we zero initialize stack slots mark them as such */
4483 		if ((reg && register_is_null(reg)) ||
4484 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4485 			/* backtracking doesn't work for STACK_ZERO yet. */
4486 			err = mark_chain_precision(env, value_regno);
4487 			if (err)
4488 				return err;
4489 			type = STACK_ZERO;
4490 		}
4491 
4492 		/* Mark slots affected by this stack write. */
4493 		for (i = 0; i < size; i++)
4494 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4495 				type;
4496 	}
4497 	return 0;
4498 }
4499 
4500 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4501  * known to contain a variable offset.
4502  * This function checks whether the write is permitted and conservatively
4503  * tracks the effects of the write, considering that each stack slot in the
4504  * dynamic range is potentially written to.
4505  *
4506  * 'off' includes 'regno->off'.
4507  * 'value_regno' can be -1, meaning that an unknown value is being written to
4508  * the stack.
4509  *
4510  * Spilled pointers in range are not marked as written because we don't know
4511  * what's going to be actually written. This means that read propagation for
4512  * future reads cannot be terminated by this write.
4513  *
4514  * For privileged programs, uninitialized stack slots are considered
4515  * initialized by this write (even though we don't know exactly what offsets
4516  * are going to be written to). The idea is that we don't want the verifier to
4517  * reject future reads that access slots written to through variable offsets.
4518  */
4519 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4520 				     /* func where register points to */
4521 				     struct bpf_func_state *state,
4522 				     int ptr_regno, int off, int size,
4523 				     int value_regno, int insn_idx)
4524 {
4525 	struct bpf_func_state *cur; /* state of the current function */
4526 	int min_off, max_off;
4527 	int i, err;
4528 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4529 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4530 	bool writing_zero = false;
4531 	/* set if the fact that we're writing a zero is used to let any
4532 	 * stack slots remain STACK_ZERO
4533 	 */
4534 	bool zero_used = false;
4535 
4536 	cur = env->cur_state->frame[env->cur_state->curframe];
4537 	ptr_reg = &cur->regs[ptr_regno];
4538 	min_off = ptr_reg->smin_value + off;
4539 	max_off = ptr_reg->smax_value + off + size;
4540 	if (value_regno >= 0)
4541 		value_reg = &cur->regs[value_regno];
4542 	if ((value_reg && register_is_null(value_reg)) ||
4543 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4544 		writing_zero = true;
4545 
4546 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4547 	if (err)
4548 		return err;
4549 
4550 	for (i = min_off; i < max_off; i++) {
4551 		int spi;
4552 
4553 		spi = __get_spi(i);
4554 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4555 		if (err)
4556 			return err;
4557 	}
4558 
4559 	/* Variable offset writes destroy any spilled pointers in range. */
4560 	for (i = min_off; i < max_off; i++) {
4561 		u8 new_type, *stype;
4562 		int slot, spi;
4563 
4564 		slot = -i - 1;
4565 		spi = slot / BPF_REG_SIZE;
4566 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4567 		mark_stack_slot_scratched(env, spi);
4568 
4569 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4570 			/* Reject the write if range we may write to has not
4571 			 * been initialized beforehand. If we didn't reject
4572 			 * here, the ptr status would be erased below (even
4573 			 * though not all slots are actually overwritten),
4574 			 * possibly opening the door to leaks.
4575 			 *
4576 			 * We do however catch STACK_INVALID case below, and
4577 			 * only allow reading possibly uninitialized memory
4578 			 * later for CAP_PERFMON, as the write may not happen to
4579 			 * that slot.
4580 			 */
4581 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4582 				insn_idx, i);
4583 			return -EINVAL;
4584 		}
4585 
4586 		/* Erase all spilled pointers. */
4587 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4588 
4589 		/* Update the slot type. */
4590 		new_type = STACK_MISC;
4591 		if (writing_zero && *stype == STACK_ZERO) {
4592 			new_type = STACK_ZERO;
4593 			zero_used = true;
4594 		}
4595 		/* If the slot is STACK_INVALID, we check whether it's OK to
4596 		 * pretend that it will be initialized by this write. The slot
4597 		 * might not actually be written to, and so if we mark it as
4598 		 * initialized future reads might leak uninitialized memory.
4599 		 * For privileged programs, we will accept such reads to slots
4600 		 * that may or may not be written because, if we're reject
4601 		 * them, the error would be too confusing.
4602 		 */
4603 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4604 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4605 					insn_idx, i);
4606 			return -EINVAL;
4607 		}
4608 		*stype = new_type;
4609 	}
4610 	if (zero_used) {
4611 		/* backtracking doesn't work for STACK_ZERO yet. */
4612 		err = mark_chain_precision(env, value_regno);
4613 		if (err)
4614 			return err;
4615 	}
4616 	return 0;
4617 }
4618 
4619 /* When register 'dst_regno' is assigned some values from stack[min_off,
4620  * max_off), we set the register's type according to the types of the
4621  * respective stack slots. If all the stack values are known to be zeros, then
4622  * so is the destination reg. Otherwise, the register is considered to be
4623  * SCALAR. This function does not deal with register filling; the caller must
4624  * ensure that all spilled registers in the stack range have been marked as
4625  * read.
4626  */
4627 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4628 				/* func where src register points to */
4629 				struct bpf_func_state *ptr_state,
4630 				int min_off, int max_off, int dst_regno)
4631 {
4632 	struct bpf_verifier_state *vstate = env->cur_state;
4633 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4634 	int i, slot, spi;
4635 	u8 *stype;
4636 	int zeros = 0;
4637 
4638 	for (i = min_off; i < max_off; i++) {
4639 		slot = -i - 1;
4640 		spi = slot / BPF_REG_SIZE;
4641 		mark_stack_slot_scratched(env, spi);
4642 		stype = ptr_state->stack[spi].slot_type;
4643 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4644 			break;
4645 		zeros++;
4646 	}
4647 	if (zeros == max_off - min_off) {
4648 		/* any access_size read into register is zero extended,
4649 		 * so the whole register == const_zero
4650 		 */
4651 		__mark_reg_const_zero(&state->regs[dst_regno]);
4652 		/* backtracking doesn't support STACK_ZERO yet,
4653 		 * so mark it precise here, so that later
4654 		 * backtracking can stop here.
4655 		 * Backtracking may not need this if this register
4656 		 * doesn't participate in pointer adjustment.
4657 		 * Forward propagation of precise flag is not
4658 		 * necessary either. This mark is only to stop
4659 		 * backtracking. Any register that contributed
4660 		 * to const 0 was marked precise before spill.
4661 		 */
4662 		state->regs[dst_regno].precise = true;
4663 	} else {
4664 		/* have read misc data from the stack */
4665 		mark_reg_unknown(env, state->regs, dst_regno);
4666 	}
4667 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4668 }
4669 
4670 /* Read the stack at 'off' and put the results into the register indicated by
4671  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4672  * spilled reg.
4673  *
4674  * 'dst_regno' can be -1, meaning that the read value is not going to a
4675  * register.
4676  *
4677  * The access is assumed to be within the current stack bounds.
4678  */
4679 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4680 				      /* func where src register points to */
4681 				      struct bpf_func_state *reg_state,
4682 				      int off, int size, int dst_regno)
4683 {
4684 	struct bpf_verifier_state *vstate = env->cur_state;
4685 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4686 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4687 	struct bpf_reg_state *reg;
4688 	u8 *stype, type;
4689 
4690 	stype = reg_state->stack[spi].slot_type;
4691 	reg = &reg_state->stack[spi].spilled_ptr;
4692 
4693 	mark_stack_slot_scratched(env, spi);
4694 
4695 	if (is_spilled_reg(&reg_state->stack[spi])) {
4696 		u8 spill_size = 1;
4697 
4698 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4699 			spill_size++;
4700 
4701 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4702 			if (reg->type != SCALAR_VALUE) {
4703 				verbose_linfo(env, env->insn_idx, "; ");
4704 				verbose(env, "invalid size of register fill\n");
4705 				return -EACCES;
4706 			}
4707 
4708 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4709 			if (dst_regno < 0)
4710 				return 0;
4711 
4712 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4713 				/* The earlier check_reg_arg() has decided the
4714 				 * subreg_def for this insn.  Save it first.
4715 				 */
4716 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4717 
4718 				copy_register_state(&state->regs[dst_regno], reg);
4719 				state->regs[dst_regno].subreg_def = subreg_def;
4720 			} else {
4721 				for (i = 0; i < size; i++) {
4722 					type = stype[(slot - i) % BPF_REG_SIZE];
4723 					if (type == STACK_SPILL)
4724 						continue;
4725 					if (type == STACK_MISC)
4726 						continue;
4727 					if (type == STACK_INVALID && env->allow_uninit_stack)
4728 						continue;
4729 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4730 						off, i, size);
4731 					return -EACCES;
4732 				}
4733 				mark_reg_unknown(env, state->regs, dst_regno);
4734 			}
4735 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4736 			return 0;
4737 		}
4738 
4739 		if (dst_regno >= 0) {
4740 			/* restore register state from stack */
4741 			copy_register_state(&state->regs[dst_regno], reg);
4742 			/* mark reg as written since spilled pointer state likely
4743 			 * has its liveness marks cleared by is_state_visited()
4744 			 * which resets stack/reg liveness for state transitions
4745 			 */
4746 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4747 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4748 			/* If dst_regno==-1, the caller is asking us whether
4749 			 * it is acceptable to use this value as a SCALAR_VALUE
4750 			 * (e.g. for XADD).
4751 			 * We must not allow unprivileged callers to do that
4752 			 * with spilled pointers.
4753 			 */
4754 			verbose(env, "leaking pointer from stack off %d\n",
4755 				off);
4756 			return -EACCES;
4757 		}
4758 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4759 	} else {
4760 		for (i = 0; i < size; i++) {
4761 			type = stype[(slot - i) % BPF_REG_SIZE];
4762 			if (type == STACK_MISC)
4763 				continue;
4764 			if (type == STACK_ZERO)
4765 				continue;
4766 			if (type == STACK_INVALID && env->allow_uninit_stack)
4767 				continue;
4768 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4769 				off, i, size);
4770 			return -EACCES;
4771 		}
4772 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4773 		if (dst_regno >= 0)
4774 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4775 	}
4776 	return 0;
4777 }
4778 
4779 enum bpf_access_src {
4780 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4781 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4782 };
4783 
4784 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4785 					 int regno, int off, int access_size,
4786 					 bool zero_size_allowed,
4787 					 enum bpf_access_src type,
4788 					 struct bpf_call_arg_meta *meta);
4789 
4790 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4791 {
4792 	return cur_regs(env) + regno;
4793 }
4794 
4795 /* Read the stack at 'ptr_regno + off' and put the result into the register
4796  * 'dst_regno'.
4797  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4798  * but not its variable offset.
4799  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4800  *
4801  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4802  * filling registers (i.e. reads of spilled register cannot be detected when
4803  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4804  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4805  * offset; for a fixed offset check_stack_read_fixed_off should be used
4806  * instead.
4807  */
4808 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4809 				    int ptr_regno, int off, int size, int dst_regno)
4810 {
4811 	/* The state of the source register. */
4812 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4813 	struct bpf_func_state *ptr_state = func(env, reg);
4814 	int err;
4815 	int min_off, max_off;
4816 
4817 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4818 	 */
4819 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4820 					    false, ACCESS_DIRECT, NULL);
4821 	if (err)
4822 		return err;
4823 
4824 	min_off = reg->smin_value + off;
4825 	max_off = reg->smax_value + off;
4826 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4827 	return 0;
4828 }
4829 
4830 /* check_stack_read dispatches to check_stack_read_fixed_off or
4831  * check_stack_read_var_off.
4832  *
4833  * The caller must ensure that the offset falls within the allocated stack
4834  * bounds.
4835  *
4836  * 'dst_regno' is a register which will receive the value from the stack. It
4837  * can be -1, meaning that the read value is not going to a register.
4838  */
4839 static int check_stack_read(struct bpf_verifier_env *env,
4840 			    int ptr_regno, int off, int size,
4841 			    int dst_regno)
4842 {
4843 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4844 	struct bpf_func_state *state = func(env, reg);
4845 	int err;
4846 	/* Some accesses are only permitted with a static offset. */
4847 	bool var_off = !tnum_is_const(reg->var_off);
4848 
4849 	/* The offset is required to be static when reads don't go to a
4850 	 * register, in order to not leak pointers (see
4851 	 * check_stack_read_fixed_off).
4852 	 */
4853 	if (dst_regno < 0 && var_off) {
4854 		char tn_buf[48];
4855 
4856 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4857 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4858 			tn_buf, off, size);
4859 		return -EACCES;
4860 	}
4861 	/* Variable offset is prohibited for unprivileged mode for simplicity
4862 	 * since it requires corresponding support in Spectre masking for stack
4863 	 * ALU. See also retrieve_ptr_limit(). The check in
4864 	 * check_stack_access_for_ptr_arithmetic() called by
4865 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4866 	 * with variable offsets, therefore no check is required here. Further,
4867 	 * just checking it here would be insufficient as speculative stack
4868 	 * writes could still lead to unsafe speculative behaviour.
4869 	 */
4870 	if (!var_off) {
4871 		off += reg->var_off.value;
4872 		err = check_stack_read_fixed_off(env, state, off, size,
4873 						 dst_regno);
4874 	} else {
4875 		/* Variable offset stack reads need more conservative handling
4876 		 * than fixed offset ones. Note that dst_regno >= 0 on this
4877 		 * branch.
4878 		 */
4879 		err = check_stack_read_var_off(env, ptr_regno, off, size,
4880 					       dst_regno);
4881 	}
4882 	return err;
4883 }
4884 
4885 
4886 /* check_stack_write dispatches to check_stack_write_fixed_off or
4887  * check_stack_write_var_off.
4888  *
4889  * 'ptr_regno' is the register used as a pointer into the stack.
4890  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4891  * 'value_regno' is the register whose value we're writing to the stack. It can
4892  * be -1, meaning that we're not writing from a register.
4893  *
4894  * The caller must ensure that the offset falls within the maximum stack size.
4895  */
4896 static int check_stack_write(struct bpf_verifier_env *env,
4897 			     int ptr_regno, int off, int size,
4898 			     int value_regno, int insn_idx)
4899 {
4900 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4901 	struct bpf_func_state *state = func(env, reg);
4902 	int err;
4903 
4904 	if (tnum_is_const(reg->var_off)) {
4905 		off += reg->var_off.value;
4906 		err = check_stack_write_fixed_off(env, state, off, size,
4907 						  value_regno, insn_idx);
4908 	} else {
4909 		/* Variable offset stack reads need more conservative handling
4910 		 * than fixed offset ones.
4911 		 */
4912 		err = check_stack_write_var_off(env, state,
4913 						ptr_regno, off, size,
4914 						value_regno, insn_idx);
4915 	}
4916 	return err;
4917 }
4918 
4919 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4920 				 int off, int size, enum bpf_access_type type)
4921 {
4922 	struct bpf_reg_state *regs = cur_regs(env);
4923 	struct bpf_map *map = regs[regno].map_ptr;
4924 	u32 cap = bpf_map_flags_to_cap(map);
4925 
4926 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4927 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4928 			map->value_size, off, size);
4929 		return -EACCES;
4930 	}
4931 
4932 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4933 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4934 			map->value_size, off, size);
4935 		return -EACCES;
4936 	}
4937 
4938 	return 0;
4939 }
4940 
4941 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4942 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4943 			      int off, int size, u32 mem_size,
4944 			      bool zero_size_allowed)
4945 {
4946 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4947 	struct bpf_reg_state *reg;
4948 
4949 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4950 		return 0;
4951 
4952 	reg = &cur_regs(env)[regno];
4953 	switch (reg->type) {
4954 	case PTR_TO_MAP_KEY:
4955 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4956 			mem_size, off, size);
4957 		break;
4958 	case PTR_TO_MAP_VALUE:
4959 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4960 			mem_size, off, size);
4961 		break;
4962 	case PTR_TO_PACKET:
4963 	case PTR_TO_PACKET_META:
4964 	case PTR_TO_PACKET_END:
4965 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4966 			off, size, regno, reg->id, off, mem_size);
4967 		break;
4968 	case PTR_TO_MEM:
4969 	default:
4970 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4971 			mem_size, off, size);
4972 	}
4973 
4974 	return -EACCES;
4975 }
4976 
4977 /* check read/write into a memory region with possible variable offset */
4978 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4979 				   int off, int size, u32 mem_size,
4980 				   bool zero_size_allowed)
4981 {
4982 	struct bpf_verifier_state *vstate = env->cur_state;
4983 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4984 	struct bpf_reg_state *reg = &state->regs[regno];
4985 	int err;
4986 
4987 	/* We may have adjusted the register pointing to memory region, so we
4988 	 * need to try adding each of min_value and max_value to off
4989 	 * to make sure our theoretical access will be safe.
4990 	 *
4991 	 * The minimum value is only important with signed
4992 	 * comparisons where we can't assume the floor of a
4993 	 * value is 0.  If we are using signed variables for our
4994 	 * index'es we need to make sure that whatever we use
4995 	 * will have a set floor within our range.
4996 	 */
4997 	if (reg->smin_value < 0 &&
4998 	    (reg->smin_value == S64_MIN ||
4999 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5000 	      reg->smin_value + off < 0)) {
5001 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5002 			regno);
5003 		return -EACCES;
5004 	}
5005 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5006 				 mem_size, zero_size_allowed);
5007 	if (err) {
5008 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5009 			regno);
5010 		return err;
5011 	}
5012 
5013 	/* If we haven't set a max value then we need to bail since we can't be
5014 	 * sure we won't do bad things.
5015 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5016 	 */
5017 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5018 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5019 			regno);
5020 		return -EACCES;
5021 	}
5022 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5023 				 mem_size, zero_size_allowed);
5024 	if (err) {
5025 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5026 			regno);
5027 		return err;
5028 	}
5029 
5030 	return 0;
5031 }
5032 
5033 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5034 			       const struct bpf_reg_state *reg, int regno,
5035 			       bool fixed_off_ok)
5036 {
5037 	/* Access to this pointer-typed register or passing it to a helper
5038 	 * is only allowed in its original, unmodified form.
5039 	 */
5040 
5041 	if (reg->off < 0) {
5042 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5043 			reg_type_str(env, reg->type), regno, reg->off);
5044 		return -EACCES;
5045 	}
5046 
5047 	if (!fixed_off_ok && reg->off) {
5048 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5049 			reg_type_str(env, reg->type), regno, reg->off);
5050 		return -EACCES;
5051 	}
5052 
5053 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5054 		char tn_buf[48];
5055 
5056 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5057 		verbose(env, "variable %s access var_off=%s disallowed\n",
5058 			reg_type_str(env, reg->type), tn_buf);
5059 		return -EACCES;
5060 	}
5061 
5062 	return 0;
5063 }
5064 
5065 int check_ptr_off_reg(struct bpf_verifier_env *env,
5066 		      const struct bpf_reg_state *reg, int regno)
5067 {
5068 	return __check_ptr_off_reg(env, reg, regno, false);
5069 }
5070 
5071 static int map_kptr_match_type(struct bpf_verifier_env *env,
5072 			       struct btf_field *kptr_field,
5073 			       struct bpf_reg_state *reg, u32 regno)
5074 {
5075 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5076 	int perm_flags;
5077 	const char *reg_name = "";
5078 
5079 	if (btf_is_kernel(reg->btf)) {
5080 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5081 
5082 		/* Only unreferenced case accepts untrusted pointers */
5083 		if (kptr_field->type == BPF_KPTR_UNREF)
5084 			perm_flags |= PTR_UNTRUSTED;
5085 	} else {
5086 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5087 		if (kptr_field->type == BPF_KPTR_PERCPU)
5088 			perm_flags |= MEM_PERCPU;
5089 	}
5090 
5091 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5092 		goto bad_type;
5093 
5094 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5095 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5096 
5097 	/* For ref_ptr case, release function check should ensure we get one
5098 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5099 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5100 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5101 	 * reg->off and reg->ref_obj_id are not needed here.
5102 	 */
5103 	if (__check_ptr_off_reg(env, reg, regno, true))
5104 		return -EACCES;
5105 
5106 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5107 	 * we also need to take into account the reg->off.
5108 	 *
5109 	 * We want to support cases like:
5110 	 *
5111 	 * struct foo {
5112 	 *         struct bar br;
5113 	 *         struct baz bz;
5114 	 * };
5115 	 *
5116 	 * struct foo *v;
5117 	 * v = func();	      // PTR_TO_BTF_ID
5118 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5119 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5120 	 *                    // first member type of struct after comparison fails
5121 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5122 	 *                    // to match type
5123 	 *
5124 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5125 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5126 	 * the struct to match type against first member of struct, i.e. reject
5127 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5128 	 * strict mode to true for type match.
5129 	 */
5130 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5131 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5132 				  kptr_field->type != BPF_KPTR_UNREF))
5133 		goto bad_type;
5134 	return 0;
5135 bad_type:
5136 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5137 		reg_type_str(env, reg->type), reg_name);
5138 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5139 	if (kptr_field->type == BPF_KPTR_UNREF)
5140 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5141 			targ_name);
5142 	else
5143 		verbose(env, "\n");
5144 	return -EINVAL;
5145 }
5146 
5147 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5148  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5149  */
5150 static bool in_rcu_cs(struct bpf_verifier_env *env)
5151 {
5152 	return env->cur_state->active_rcu_lock ||
5153 	       env->cur_state->active_lock.ptr ||
5154 	       !env->prog->aux->sleepable;
5155 }
5156 
5157 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5158 BTF_SET_START(rcu_protected_types)
5159 BTF_ID(struct, prog_test_ref_kfunc)
5160 #ifdef CONFIG_CGROUPS
5161 BTF_ID(struct, cgroup)
5162 #endif
5163 BTF_ID(struct, bpf_cpumask)
5164 BTF_ID(struct, task_struct)
5165 BTF_SET_END(rcu_protected_types)
5166 
5167 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5168 {
5169 	if (!btf_is_kernel(btf))
5170 		return true;
5171 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5172 }
5173 
5174 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5175 {
5176 	struct btf_struct_meta *meta;
5177 
5178 	if (btf_is_kernel(kptr_field->kptr.btf))
5179 		return NULL;
5180 
5181 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5182 				    kptr_field->kptr.btf_id);
5183 
5184 	return meta ? meta->record : NULL;
5185 }
5186 
5187 static bool rcu_safe_kptr(const struct btf_field *field)
5188 {
5189 	const struct btf_field_kptr *kptr = &field->kptr;
5190 
5191 	return field->type == BPF_KPTR_PERCPU ||
5192 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5193 }
5194 
5195 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5196 {
5197 	struct btf_record *rec;
5198 	u32 ret;
5199 
5200 	ret = PTR_MAYBE_NULL;
5201 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5202 		ret |= MEM_RCU;
5203 		if (kptr_field->type == BPF_KPTR_PERCPU)
5204 			ret |= MEM_PERCPU;
5205 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5206 			ret |= MEM_ALLOC;
5207 
5208 		rec = kptr_pointee_btf_record(kptr_field);
5209 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5210 			ret |= NON_OWN_REF;
5211 	} else {
5212 		ret |= PTR_UNTRUSTED;
5213 	}
5214 
5215 	return ret;
5216 }
5217 
5218 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5219 				 int value_regno, int insn_idx,
5220 				 struct btf_field *kptr_field)
5221 {
5222 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5223 	int class = BPF_CLASS(insn->code);
5224 	struct bpf_reg_state *val_reg;
5225 
5226 	/* Things we already checked for in check_map_access and caller:
5227 	 *  - Reject cases where variable offset may touch kptr
5228 	 *  - size of access (must be BPF_DW)
5229 	 *  - tnum_is_const(reg->var_off)
5230 	 *  - kptr_field->offset == off + reg->var_off.value
5231 	 */
5232 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5233 	if (BPF_MODE(insn->code) != BPF_MEM) {
5234 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5235 		return -EACCES;
5236 	}
5237 
5238 	/* We only allow loading referenced kptr, since it will be marked as
5239 	 * untrusted, similar to unreferenced kptr.
5240 	 */
5241 	if (class != BPF_LDX &&
5242 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5243 		verbose(env, "store to referenced kptr disallowed\n");
5244 		return -EACCES;
5245 	}
5246 
5247 	if (class == BPF_LDX) {
5248 		val_reg = reg_state(env, value_regno);
5249 		/* We can simply mark the value_regno receiving the pointer
5250 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5251 		 */
5252 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5253 				kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5254 		/* For mark_ptr_or_null_reg */
5255 		val_reg->id = ++env->id_gen;
5256 	} else if (class == BPF_STX) {
5257 		val_reg = reg_state(env, value_regno);
5258 		if (!register_is_null(val_reg) &&
5259 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5260 			return -EACCES;
5261 	} else if (class == BPF_ST) {
5262 		if (insn->imm) {
5263 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5264 				kptr_field->offset);
5265 			return -EACCES;
5266 		}
5267 	} else {
5268 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5269 		return -EACCES;
5270 	}
5271 	return 0;
5272 }
5273 
5274 /* check read/write into a map element with possible variable offset */
5275 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5276 			    int off, int size, bool zero_size_allowed,
5277 			    enum bpf_access_src src)
5278 {
5279 	struct bpf_verifier_state *vstate = env->cur_state;
5280 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5281 	struct bpf_reg_state *reg = &state->regs[regno];
5282 	struct bpf_map *map = reg->map_ptr;
5283 	struct btf_record *rec;
5284 	int err, i;
5285 
5286 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5287 				      zero_size_allowed);
5288 	if (err)
5289 		return err;
5290 
5291 	if (IS_ERR_OR_NULL(map->record))
5292 		return 0;
5293 	rec = map->record;
5294 	for (i = 0; i < rec->cnt; i++) {
5295 		struct btf_field *field = &rec->fields[i];
5296 		u32 p = field->offset;
5297 
5298 		/* If any part of a field  can be touched by load/store, reject
5299 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5300 		 * it is sufficient to check x1 < y2 && y1 < x2.
5301 		 */
5302 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5303 		    p < reg->umax_value + off + size) {
5304 			switch (field->type) {
5305 			case BPF_KPTR_UNREF:
5306 			case BPF_KPTR_REF:
5307 			case BPF_KPTR_PERCPU:
5308 				if (src != ACCESS_DIRECT) {
5309 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5310 					return -EACCES;
5311 				}
5312 				if (!tnum_is_const(reg->var_off)) {
5313 					verbose(env, "kptr access cannot have variable offset\n");
5314 					return -EACCES;
5315 				}
5316 				if (p != off + reg->var_off.value) {
5317 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5318 						p, off + reg->var_off.value);
5319 					return -EACCES;
5320 				}
5321 				if (size != bpf_size_to_bytes(BPF_DW)) {
5322 					verbose(env, "kptr access size must be BPF_DW\n");
5323 					return -EACCES;
5324 				}
5325 				break;
5326 			default:
5327 				verbose(env, "%s cannot be accessed directly by load/store\n",
5328 					btf_field_type_name(field->type));
5329 				return -EACCES;
5330 			}
5331 		}
5332 	}
5333 	return 0;
5334 }
5335 
5336 #define MAX_PACKET_OFF 0xffff
5337 
5338 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5339 				       const struct bpf_call_arg_meta *meta,
5340 				       enum bpf_access_type t)
5341 {
5342 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5343 
5344 	switch (prog_type) {
5345 	/* Program types only with direct read access go here! */
5346 	case BPF_PROG_TYPE_LWT_IN:
5347 	case BPF_PROG_TYPE_LWT_OUT:
5348 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5349 	case BPF_PROG_TYPE_SK_REUSEPORT:
5350 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5351 	case BPF_PROG_TYPE_CGROUP_SKB:
5352 		if (t == BPF_WRITE)
5353 			return false;
5354 		fallthrough;
5355 
5356 	/* Program types with direct read + write access go here! */
5357 	case BPF_PROG_TYPE_SCHED_CLS:
5358 	case BPF_PROG_TYPE_SCHED_ACT:
5359 	case BPF_PROG_TYPE_XDP:
5360 	case BPF_PROG_TYPE_LWT_XMIT:
5361 	case BPF_PROG_TYPE_SK_SKB:
5362 	case BPF_PROG_TYPE_SK_MSG:
5363 		if (meta)
5364 			return meta->pkt_access;
5365 
5366 		env->seen_direct_write = true;
5367 		return true;
5368 
5369 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5370 		if (t == BPF_WRITE)
5371 			env->seen_direct_write = true;
5372 
5373 		return true;
5374 
5375 	default:
5376 		return false;
5377 	}
5378 }
5379 
5380 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5381 			       int size, bool zero_size_allowed)
5382 {
5383 	struct bpf_reg_state *regs = cur_regs(env);
5384 	struct bpf_reg_state *reg = &regs[regno];
5385 	int err;
5386 
5387 	/* We may have added a variable offset to the packet pointer; but any
5388 	 * reg->range we have comes after that.  We are only checking the fixed
5389 	 * offset.
5390 	 */
5391 
5392 	/* We don't allow negative numbers, because we aren't tracking enough
5393 	 * detail to prove they're safe.
5394 	 */
5395 	if (reg->smin_value < 0) {
5396 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5397 			regno);
5398 		return -EACCES;
5399 	}
5400 
5401 	err = reg->range < 0 ? -EINVAL :
5402 	      __check_mem_access(env, regno, off, size, reg->range,
5403 				 zero_size_allowed);
5404 	if (err) {
5405 		verbose(env, "R%d offset is outside of the packet\n", regno);
5406 		return err;
5407 	}
5408 
5409 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5410 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5411 	 * otherwise find_good_pkt_pointers would have refused to set range info
5412 	 * that __check_mem_access would have rejected this pkt access.
5413 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5414 	 */
5415 	env->prog->aux->max_pkt_offset =
5416 		max_t(u32, env->prog->aux->max_pkt_offset,
5417 		      off + reg->umax_value + size - 1);
5418 
5419 	return err;
5420 }
5421 
5422 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5423 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5424 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5425 			    struct btf **btf, u32 *btf_id)
5426 {
5427 	struct bpf_insn_access_aux info = {
5428 		.reg_type = *reg_type,
5429 		.log = &env->log,
5430 	};
5431 
5432 	if (env->ops->is_valid_access &&
5433 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5434 		/* A non zero info.ctx_field_size indicates that this field is a
5435 		 * candidate for later verifier transformation to load the whole
5436 		 * field and then apply a mask when accessed with a narrower
5437 		 * access than actual ctx access size. A zero info.ctx_field_size
5438 		 * will only allow for whole field access and rejects any other
5439 		 * type of narrower access.
5440 		 */
5441 		*reg_type = info.reg_type;
5442 
5443 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5444 			*btf = info.btf;
5445 			*btf_id = info.btf_id;
5446 		} else {
5447 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5448 		}
5449 		/* remember the offset of last byte accessed in ctx */
5450 		if (env->prog->aux->max_ctx_offset < off + size)
5451 			env->prog->aux->max_ctx_offset = off + size;
5452 		return 0;
5453 	}
5454 
5455 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5456 	return -EACCES;
5457 }
5458 
5459 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5460 				  int size)
5461 {
5462 	if (size < 0 || off < 0 ||
5463 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5464 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5465 			off, size);
5466 		return -EACCES;
5467 	}
5468 	return 0;
5469 }
5470 
5471 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5472 			     u32 regno, int off, int size,
5473 			     enum bpf_access_type t)
5474 {
5475 	struct bpf_reg_state *regs = cur_regs(env);
5476 	struct bpf_reg_state *reg = &regs[regno];
5477 	struct bpf_insn_access_aux info = {};
5478 	bool valid;
5479 
5480 	if (reg->smin_value < 0) {
5481 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5482 			regno);
5483 		return -EACCES;
5484 	}
5485 
5486 	switch (reg->type) {
5487 	case PTR_TO_SOCK_COMMON:
5488 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5489 		break;
5490 	case PTR_TO_SOCKET:
5491 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5492 		break;
5493 	case PTR_TO_TCP_SOCK:
5494 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5495 		break;
5496 	case PTR_TO_XDP_SOCK:
5497 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5498 		break;
5499 	default:
5500 		valid = false;
5501 	}
5502 
5503 
5504 	if (valid) {
5505 		env->insn_aux_data[insn_idx].ctx_field_size =
5506 			info.ctx_field_size;
5507 		return 0;
5508 	}
5509 
5510 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5511 		regno, reg_type_str(env, reg->type), off, size);
5512 
5513 	return -EACCES;
5514 }
5515 
5516 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5517 {
5518 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5519 }
5520 
5521 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5522 {
5523 	const struct bpf_reg_state *reg = reg_state(env, regno);
5524 
5525 	return reg->type == PTR_TO_CTX;
5526 }
5527 
5528 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5529 {
5530 	const struct bpf_reg_state *reg = reg_state(env, regno);
5531 
5532 	return type_is_sk_pointer(reg->type);
5533 }
5534 
5535 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5536 {
5537 	const struct bpf_reg_state *reg = reg_state(env, regno);
5538 
5539 	return type_is_pkt_pointer(reg->type);
5540 }
5541 
5542 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5543 {
5544 	const struct bpf_reg_state *reg = reg_state(env, regno);
5545 
5546 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5547 	return reg->type == PTR_TO_FLOW_KEYS;
5548 }
5549 
5550 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5551 #ifdef CONFIG_NET
5552 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5553 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5554 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5555 #endif
5556 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5557 };
5558 
5559 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5560 {
5561 	/* A referenced register is always trusted. */
5562 	if (reg->ref_obj_id)
5563 		return true;
5564 
5565 	/* Types listed in the reg2btf_ids are always trusted */
5566 	if (reg2btf_ids[base_type(reg->type)])
5567 		return true;
5568 
5569 	/* If a register is not referenced, it is trusted if it has the
5570 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5571 	 * other type modifiers may be safe, but we elect to take an opt-in
5572 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5573 	 * not.
5574 	 *
5575 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5576 	 * for whether a register is trusted.
5577 	 */
5578 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5579 	       !bpf_type_has_unsafe_modifiers(reg->type);
5580 }
5581 
5582 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5583 {
5584 	return reg->type & MEM_RCU;
5585 }
5586 
5587 static void clear_trusted_flags(enum bpf_type_flag *flag)
5588 {
5589 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5590 }
5591 
5592 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5593 				   const struct bpf_reg_state *reg,
5594 				   int off, int size, bool strict)
5595 {
5596 	struct tnum reg_off;
5597 	int ip_align;
5598 
5599 	/* Byte size accesses are always allowed. */
5600 	if (!strict || size == 1)
5601 		return 0;
5602 
5603 	/* For platforms that do not have a Kconfig enabling
5604 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5605 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5606 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5607 	 * to this code only in strict mode where we want to emulate
5608 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5609 	 * unconditional IP align value of '2'.
5610 	 */
5611 	ip_align = 2;
5612 
5613 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5614 	if (!tnum_is_aligned(reg_off, size)) {
5615 		char tn_buf[48];
5616 
5617 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5618 		verbose(env,
5619 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5620 			ip_align, tn_buf, reg->off, off, size);
5621 		return -EACCES;
5622 	}
5623 
5624 	return 0;
5625 }
5626 
5627 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5628 				       const struct bpf_reg_state *reg,
5629 				       const char *pointer_desc,
5630 				       int off, int size, bool strict)
5631 {
5632 	struct tnum reg_off;
5633 
5634 	/* Byte size accesses are always allowed. */
5635 	if (!strict || size == 1)
5636 		return 0;
5637 
5638 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5639 	if (!tnum_is_aligned(reg_off, size)) {
5640 		char tn_buf[48];
5641 
5642 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5643 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5644 			pointer_desc, tn_buf, reg->off, off, size);
5645 		return -EACCES;
5646 	}
5647 
5648 	return 0;
5649 }
5650 
5651 static int check_ptr_alignment(struct bpf_verifier_env *env,
5652 			       const struct bpf_reg_state *reg, int off,
5653 			       int size, bool strict_alignment_once)
5654 {
5655 	bool strict = env->strict_alignment || strict_alignment_once;
5656 	const char *pointer_desc = "";
5657 
5658 	switch (reg->type) {
5659 	case PTR_TO_PACKET:
5660 	case PTR_TO_PACKET_META:
5661 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5662 		 * right in front, treat it the very same way.
5663 		 */
5664 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5665 	case PTR_TO_FLOW_KEYS:
5666 		pointer_desc = "flow keys ";
5667 		break;
5668 	case PTR_TO_MAP_KEY:
5669 		pointer_desc = "key ";
5670 		break;
5671 	case PTR_TO_MAP_VALUE:
5672 		pointer_desc = "value ";
5673 		break;
5674 	case PTR_TO_CTX:
5675 		pointer_desc = "context ";
5676 		break;
5677 	case PTR_TO_STACK:
5678 		pointer_desc = "stack ";
5679 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5680 		 * and check_stack_read_fixed_off() relies on stack accesses being
5681 		 * aligned.
5682 		 */
5683 		strict = true;
5684 		break;
5685 	case PTR_TO_SOCKET:
5686 		pointer_desc = "sock ";
5687 		break;
5688 	case PTR_TO_SOCK_COMMON:
5689 		pointer_desc = "sock_common ";
5690 		break;
5691 	case PTR_TO_TCP_SOCK:
5692 		pointer_desc = "tcp_sock ";
5693 		break;
5694 	case PTR_TO_XDP_SOCK:
5695 		pointer_desc = "xdp_sock ";
5696 		break;
5697 	default:
5698 		break;
5699 	}
5700 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5701 					   strict);
5702 }
5703 
5704 static int update_stack_depth(struct bpf_verifier_env *env,
5705 			      const struct bpf_func_state *func,
5706 			      int off)
5707 {
5708 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
5709 
5710 	if (stack >= -off)
5711 		return 0;
5712 
5713 	/* update known max for given subprogram */
5714 	env->subprog_info[func->subprogno].stack_depth = -off;
5715 	return 0;
5716 }
5717 
5718 /* starting from main bpf function walk all instructions of the function
5719  * and recursively walk all callees that given function can call.
5720  * Ignore jump and exit insns.
5721  * Since recursion is prevented by check_cfg() this algorithm
5722  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5723  */
5724 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5725 {
5726 	struct bpf_subprog_info *subprog = env->subprog_info;
5727 	struct bpf_insn *insn = env->prog->insnsi;
5728 	int depth = 0, frame = 0, i, subprog_end;
5729 	bool tail_call_reachable = false;
5730 	int ret_insn[MAX_CALL_FRAMES];
5731 	int ret_prog[MAX_CALL_FRAMES];
5732 	int j;
5733 
5734 	i = subprog[idx].start;
5735 process_func:
5736 	/* protect against potential stack overflow that might happen when
5737 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5738 	 * depth for such case down to 256 so that the worst case scenario
5739 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5740 	 * 8k).
5741 	 *
5742 	 * To get the idea what might happen, see an example:
5743 	 * func1 -> sub rsp, 128
5744 	 *  subfunc1 -> sub rsp, 256
5745 	 *  tailcall1 -> add rsp, 256
5746 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5747 	 *   subfunc2 -> sub rsp, 64
5748 	 *   subfunc22 -> sub rsp, 128
5749 	 *   tailcall2 -> add rsp, 128
5750 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5751 	 *
5752 	 * tailcall will unwind the current stack frame but it will not get rid
5753 	 * of caller's stack as shown on the example above.
5754 	 */
5755 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5756 		verbose(env,
5757 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5758 			depth);
5759 		return -EACCES;
5760 	}
5761 	/* round up to 32-bytes, since this is granularity
5762 	 * of interpreter stack size
5763 	 */
5764 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5765 	if (depth > MAX_BPF_STACK) {
5766 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5767 			frame + 1, depth);
5768 		return -EACCES;
5769 	}
5770 continue_func:
5771 	subprog_end = subprog[idx + 1].start;
5772 	for (; i < subprog_end; i++) {
5773 		int next_insn, sidx;
5774 
5775 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
5776 			bool err = false;
5777 
5778 			if (!is_bpf_throw_kfunc(insn + i))
5779 				continue;
5780 			if (subprog[idx].is_cb)
5781 				err = true;
5782 			for (int c = 0; c < frame && !err; c++) {
5783 				if (subprog[ret_prog[c]].is_cb) {
5784 					err = true;
5785 					break;
5786 				}
5787 			}
5788 			if (!err)
5789 				continue;
5790 			verbose(env,
5791 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5792 				i, idx);
5793 			return -EINVAL;
5794 		}
5795 
5796 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5797 			continue;
5798 		/* remember insn and function to return to */
5799 		ret_insn[frame] = i + 1;
5800 		ret_prog[frame] = idx;
5801 
5802 		/* find the callee */
5803 		next_insn = i + insn[i].imm + 1;
5804 		sidx = find_subprog(env, next_insn);
5805 		if (sidx < 0) {
5806 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5807 				  next_insn);
5808 			return -EFAULT;
5809 		}
5810 		if (subprog[sidx].is_async_cb) {
5811 			if (subprog[sidx].has_tail_call) {
5812 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5813 				return -EFAULT;
5814 			}
5815 			/* async callbacks don't increase bpf prog stack size unless called directly */
5816 			if (!bpf_pseudo_call(insn + i))
5817 				continue;
5818 			if (subprog[sidx].is_exception_cb) {
5819 				verbose(env, "insn %d cannot call exception cb directly\n", i);
5820 				return -EINVAL;
5821 			}
5822 		}
5823 		i = next_insn;
5824 		idx = sidx;
5825 
5826 		if (subprog[idx].has_tail_call)
5827 			tail_call_reachable = true;
5828 
5829 		frame++;
5830 		if (frame >= MAX_CALL_FRAMES) {
5831 			verbose(env, "the call stack of %d frames is too deep !\n",
5832 				frame);
5833 			return -E2BIG;
5834 		}
5835 		goto process_func;
5836 	}
5837 	/* if tail call got detected across bpf2bpf calls then mark each of the
5838 	 * currently present subprog frames as tail call reachable subprogs;
5839 	 * this info will be utilized by JIT so that we will be preserving the
5840 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5841 	 */
5842 	if (tail_call_reachable)
5843 		for (j = 0; j < frame; j++) {
5844 			if (subprog[ret_prog[j]].is_exception_cb) {
5845 				verbose(env, "cannot tail call within exception cb\n");
5846 				return -EINVAL;
5847 			}
5848 			subprog[ret_prog[j]].tail_call_reachable = true;
5849 		}
5850 	if (subprog[0].tail_call_reachable)
5851 		env->prog->aux->tail_call_reachable = true;
5852 
5853 	/* end of for() loop means the last insn of the 'subprog'
5854 	 * was reached. Doesn't matter whether it was JA or EXIT
5855 	 */
5856 	if (frame == 0)
5857 		return 0;
5858 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5859 	frame--;
5860 	i = ret_insn[frame];
5861 	idx = ret_prog[frame];
5862 	goto continue_func;
5863 }
5864 
5865 static int check_max_stack_depth(struct bpf_verifier_env *env)
5866 {
5867 	struct bpf_subprog_info *si = env->subprog_info;
5868 	int ret;
5869 
5870 	for (int i = 0; i < env->subprog_cnt; i++) {
5871 		if (!i || si[i].is_async_cb) {
5872 			ret = check_max_stack_depth_subprog(env, i);
5873 			if (ret < 0)
5874 				return ret;
5875 		}
5876 		continue;
5877 	}
5878 	return 0;
5879 }
5880 
5881 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5882 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5883 				  const struct bpf_insn *insn, int idx)
5884 {
5885 	int start = idx + insn->imm + 1, subprog;
5886 
5887 	subprog = find_subprog(env, start);
5888 	if (subprog < 0) {
5889 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5890 			  start);
5891 		return -EFAULT;
5892 	}
5893 	return env->subprog_info[subprog].stack_depth;
5894 }
5895 #endif
5896 
5897 static int __check_buffer_access(struct bpf_verifier_env *env,
5898 				 const char *buf_info,
5899 				 const struct bpf_reg_state *reg,
5900 				 int regno, int off, int size)
5901 {
5902 	if (off < 0) {
5903 		verbose(env,
5904 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5905 			regno, buf_info, off, size);
5906 		return -EACCES;
5907 	}
5908 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5909 		char tn_buf[48];
5910 
5911 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5912 		verbose(env,
5913 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5914 			regno, off, tn_buf);
5915 		return -EACCES;
5916 	}
5917 
5918 	return 0;
5919 }
5920 
5921 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5922 				  const struct bpf_reg_state *reg,
5923 				  int regno, int off, int size)
5924 {
5925 	int err;
5926 
5927 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5928 	if (err)
5929 		return err;
5930 
5931 	if (off + size > env->prog->aux->max_tp_access)
5932 		env->prog->aux->max_tp_access = off + size;
5933 
5934 	return 0;
5935 }
5936 
5937 static int check_buffer_access(struct bpf_verifier_env *env,
5938 			       const struct bpf_reg_state *reg,
5939 			       int regno, int off, int size,
5940 			       bool zero_size_allowed,
5941 			       u32 *max_access)
5942 {
5943 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5944 	int err;
5945 
5946 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5947 	if (err)
5948 		return err;
5949 
5950 	if (off + size > *max_access)
5951 		*max_access = off + size;
5952 
5953 	return 0;
5954 }
5955 
5956 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5957 static void zext_32_to_64(struct bpf_reg_state *reg)
5958 {
5959 	reg->var_off = tnum_subreg(reg->var_off);
5960 	__reg_assign_32_into_64(reg);
5961 }
5962 
5963 /* truncate register to smaller size (in bytes)
5964  * must be called with size < BPF_REG_SIZE
5965  */
5966 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5967 {
5968 	u64 mask;
5969 
5970 	/* clear high bits in bit representation */
5971 	reg->var_off = tnum_cast(reg->var_off, size);
5972 
5973 	/* fix arithmetic bounds */
5974 	mask = ((u64)1 << (size * 8)) - 1;
5975 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5976 		reg->umin_value &= mask;
5977 		reg->umax_value &= mask;
5978 	} else {
5979 		reg->umin_value = 0;
5980 		reg->umax_value = mask;
5981 	}
5982 	reg->smin_value = reg->umin_value;
5983 	reg->smax_value = reg->umax_value;
5984 
5985 	/* If size is smaller than 32bit register the 32bit register
5986 	 * values are also truncated so we push 64-bit bounds into
5987 	 * 32-bit bounds. Above were truncated < 32-bits already.
5988 	 */
5989 	if (size < 4) {
5990 		__mark_reg32_unbounded(reg);
5991 		reg_bounds_sync(reg);
5992 	}
5993 }
5994 
5995 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
5996 {
5997 	if (size == 1) {
5998 		reg->smin_value = reg->s32_min_value = S8_MIN;
5999 		reg->smax_value = reg->s32_max_value = S8_MAX;
6000 	} else if (size == 2) {
6001 		reg->smin_value = reg->s32_min_value = S16_MIN;
6002 		reg->smax_value = reg->s32_max_value = S16_MAX;
6003 	} else {
6004 		/* size == 4 */
6005 		reg->smin_value = reg->s32_min_value = S32_MIN;
6006 		reg->smax_value = reg->s32_max_value = S32_MAX;
6007 	}
6008 	reg->umin_value = reg->u32_min_value = 0;
6009 	reg->umax_value = U64_MAX;
6010 	reg->u32_max_value = U32_MAX;
6011 	reg->var_off = tnum_unknown;
6012 }
6013 
6014 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6015 {
6016 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6017 	u64 top_smax_value, top_smin_value;
6018 	u64 num_bits = size * 8;
6019 
6020 	if (tnum_is_const(reg->var_off)) {
6021 		u64_cval = reg->var_off.value;
6022 		if (size == 1)
6023 			reg->var_off = tnum_const((s8)u64_cval);
6024 		else if (size == 2)
6025 			reg->var_off = tnum_const((s16)u64_cval);
6026 		else
6027 			/* size == 4 */
6028 			reg->var_off = tnum_const((s32)u64_cval);
6029 
6030 		u64_cval = reg->var_off.value;
6031 		reg->smax_value = reg->smin_value = u64_cval;
6032 		reg->umax_value = reg->umin_value = u64_cval;
6033 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6034 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6035 		return;
6036 	}
6037 
6038 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6039 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6040 
6041 	if (top_smax_value != top_smin_value)
6042 		goto out;
6043 
6044 	/* find the s64_min and s64_min after sign extension */
6045 	if (size == 1) {
6046 		init_s64_max = (s8)reg->smax_value;
6047 		init_s64_min = (s8)reg->smin_value;
6048 	} else if (size == 2) {
6049 		init_s64_max = (s16)reg->smax_value;
6050 		init_s64_min = (s16)reg->smin_value;
6051 	} else {
6052 		init_s64_max = (s32)reg->smax_value;
6053 		init_s64_min = (s32)reg->smin_value;
6054 	}
6055 
6056 	s64_max = max(init_s64_max, init_s64_min);
6057 	s64_min = min(init_s64_max, init_s64_min);
6058 
6059 	/* both of s64_max/s64_min positive or negative */
6060 	if ((s64_max >= 0) == (s64_min >= 0)) {
6061 		reg->smin_value = reg->s32_min_value = s64_min;
6062 		reg->smax_value = reg->s32_max_value = s64_max;
6063 		reg->umin_value = reg->u32_min_value = s64_min;
6064 		reg->umax_value = reg->u32_max_value = s64_max;
6065 		reg->var_off = tnum_range(s64_min, s64_max);
6066 		return;
6067 	}
6068 
6069 out:
6070 	set_sext64_default_val(reg, size);
6071 }
6072 
6073 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6074 {
6075 	if (size == 1) {
6076 		reg->s32_min_value = S8_MIN;
6077 		reg->s32_max_value = S8_MAX;
6078 	} else {
6079 		/* size == 2 */
6080 		reg->s32_min_value = S16_MIN;
6081 		reg->s32_max_value = S16_MAX;
6082 	}
6083 	reg->u32_min_value = 0;
6084 	reg->u32_max_value = U32_MAX;
6085 }
6086 
6087 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6088 {
6089 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6090 	u32 top_smax_value, top_smin_value;
6091 	u32 num_bits = size * 8;
6092 
6093 	if (tnum_is_const(reg->var_off)) {
6094 		u32_val = reg->var_off.value;
6095 		if (size == 1)
6096 			reg->var_off = tnum_const((s8)u32_val);
6097 		else
6098 			reg->var_off = tnum_const((s16)u32_val);
6099 
6100 		u32_val = reg->var_off.value;
6101 		reg->s32_min_value = reg->s32_max_value = u32_val;
6102 		reg->u32_min_value = reg->u32_max_value = u32_val;
6103 		return;
6104 	}
6105 
6106 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6107 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6108 
6109 	if (top_smax_value != top_smin_value)
6110 		goto out;
6111 
6112 	/* find the s32_min and s32_min after sign extension */
6113 	if (size == 1) {
6114 		init_s32_max = (s8)reg->s32_max_value;
6115 		init_s32_min = (s8)reg->s32_min_value;
6116 	} else {
6117 		/* size == 2 */
6118 		init_s32_max = (s16)reg->s32_max_value;
6119 		init_s32_min = (s16)reg->s32_min_value;
6120 	}
6121 	s32_max = max(init_s32_max, init_s32_min);
6122 	s32_min = min(init_s32_max, init_s32_min);
6123 
6124 	if ((s32_min >= 0) == (s32_max >= 0)) {
6125 		reg->s32_min_value = s32_min;
6126 		reg->s32_max_value = s32_max;
6127 		reg->u32_min_value = (u32)s32_min;
6128 		reg->u32_max_value = (u32)s32_max;
6129 		return;
6130 	}
6131 
6132 out:
6133 	set_sext32_default_val(reg, size);
6134 }
6135 
6136 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6137 {
6138 	/* A map is considered read-only if the following condition are true:
6139 	 *
6140 	 * 1) BPF program side cannot change any of the map content. The
6141 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6142 	 *    and was set at map creation time.
6143 	 * 2) The map value(s) have been initialized from user space by a
6144 	 *    loader and then "frozen", such that no new map update/delete
6145 	 *    operations from syscall side are possible for the rest of
6146 	 *    the map's lifetime from that point onwards.
6147 	 * 3) Any parallel/pending map update/delete operations from syscall
6148 	 *    side have been completed. Only after that point, it's safe to
6149 	 *    assume that map value(s) are immutable.
6150 	 */
6151 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6152 	       READ_ONCE(map->frozen) &&
6153 	       !bpf_map_write_active(map);
6154 }
6155 
6156 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6157 			       bool is_ldsx)
6158 {
6159 	void *ptr;
6160 	u64 addr;
6161 	int err;
6162 
6163 	err = map->ops->map_direct_value_addr(map, &addr, off);
6164 	if (err)
6165 		return err;
6166 	ptr = (void *)(long)addr + off;
6167 
6168 	switch (size) {
6169 	case sizeof(u8):
6170 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6171 		break;
6172 	case sizeof(u16):
6173 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6174 		break;
6175 	case sizeof(u32):
6176 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6177 		break;
6178 	case sizeof(u64):
6179 		*val = *(u64 *)ptr;
6180 		break;
6181 	default:
6182 		return -EINVAL;
6183 	}
6184 	return 0;
6185 }
6186 
6187 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6188 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6189 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6190 
6191 /*
6192  * Allow list few fields as RCU trusted or full trusted.
6193  * This logic doesn't allow mix tagging and will be removed once GCC supports
6194  * btf_type_tag.
6195  */
6196 
6197 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6198 BTF_TYPE_SAFE_RCU(struct task_struct) {
6199 	const cpumask_t *cpus_ptr;
6200 	struct css_set __rcu *cgroups;
6201 	struct task_struct __rcu *real_parent;
6202 	struct task_struct *group_leader;
6203 };
6204 
6205 BTF_TYPE_SAFE_RCU(struct cgroup) {
6206 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6207 	struct kernfs_node *kn;
6208 };
6209 
6210 BTF_TYPE_SAFE_RCU(struct css_set) {
6211 	struct cgroup *dfl_cgrp;
6212 };
6213 
6214 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6215 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6216 	struct file __rcu *exe_file;
6217 };
6218 
6219 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6220  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6221  */
6222 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6223 	struct sock *sk;
6224 };
6225 
6226 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6227 	struct sock *sk;
6228 };
6229 
6230 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6231 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6232 	struct seq_file *seq;
6233 };
6234 
6235 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6236 	struct bpf_iter_meta *meta;
6237 	struct task_struct *task;
6238 };
6239 
6240 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6241 	struct file *file;
6242 };
6243 
6244 BTF_TYPE_SAFE_TRUSTED(struct file) {
6245 	struct inode *f_inode;
6246 };
6247 
6248 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6249 	/* no negative dentry-s in places where bpf can see it */
6250 	struct inode *d_inode;
6251 };
6252 
6253 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6254 	struct sock *sk;
6255 };
6256 
6257 static bool type_is_rcu(struct bpf_verifier_env *env,
6258 			struct bpf_reg_state *reg,
6259 			const char *field_name, u32 btf_id)
6260 {
6261 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6262 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6263 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6264 
6265 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6266 }
6267 
6268 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6269 				struct bpf_reg_state *reg,
6270 				const char *field_name, u32 btf_id)
6271 {
6272 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6273 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6274 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6275 
6276 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6277 }
6278 
6279 static bool type_is_trusted(struct bpf_verifier_env *env,
6280 			    struct bpf_reg_state *reg,
6281 			    const char *field_name, u32 btf_id)
6282 {
6283 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6284 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6285 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6286 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6287 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6288 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6289 
6290 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6291 }
6292 
6293 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6294 				   struct bpf_reg_state *regs,
6295 				   int regno, int off, int size,
6296 				   enum bpf_access_type atype,
6297 				   int value_regno)
6298 {
6299 	struct bpf_reg_state *reg = regs + regno;
6300 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6301 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6302 	const char *field_name = NULL;
6303 	enum bpf_type_flag flag = 0;
6304 	u32 btf_id = 0;
6305 	int ret;
6306 
6307 	if (!env->allow_ptr_leaks) {
6308 		verbose(env,
6309 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6310 			tname);
6311 		return -EPERM;
6312 	}
6313 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6314 		verbose(env,
6315 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6316 			tname);
6317 		return -EINVAL;
6318 	}
6319 	if (off < 0) {
6320 		verbose(env,
6321 			"R%d is ptr_%s invalid negative access: off=%d\n",
6322 			regno, tname, off);
6323 		return -EACCES;
6324 	}
6325 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6326 		char tn_buf[48];
6327 
6328 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6329 		verbose(env,
6330 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6331 			regno, tname, off, tn_buf);
6332 		return -EACCES;
6333 	}
6334 
6335 	if (reg->type & MEM_USER) {
6336 		verbose(env,
6337 			"R%d is ptr_%s access user memory: off=%d\n",
6338 			regno, tname, off);
6339 		return -EACCES;
6340 	}
6341 
6342 	if (reg->type & MEM_PERCPU) {
6343 		verbose(env,
6344 			"R%d is ptr_%s access percpu memory: off=%d\n",
6345 			regno, tname, off);
6346 		return -EACCES;
6347 	}
6348 
6349 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6350 		if (!btf_is_kernel(reg->btf)) {
6351 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6352 			return -EFAULT;
6353 		}
6354 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6355 	} else {
6356 		/* Writes are permitted with default btf_struct_access for
6357 		 * program allocated objects (which always have ref_obj_id > 0),
6358 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6359 		 */
6360 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6361 			verbose(env, "only read is supported\n");
6362 			return -EACCES;
6363 		}
6364 
6365 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6366 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
6367 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6368 			return -EFAULT;
6369 		}
6370 
6371 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6372 	}
6373 
6374 	if (ret < 0)
6375 		return ret;
6376 
6377 	if (ret != PTR_TO_BTF_ID) {
6378 		/* just mark; */
6379 
6380 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6381 		/* If this is an untrusted pointer, all pointers formed by walking it
6382 		 * also inherit the untrusted flag.
6383 		 */
6384 		flag = PTR_UNTRUSTED;
6385 
6386 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6387 		/* By default any pointer obtained from walking a trusted pointer is no
6388 		 * longer trusted, unless the field being accessed has explicitly been
6389 		 * marked as inheriting its parent's state of trust (either full or RCU).
6390 		 * For example:
6391 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6392 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6393 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6394 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6395 		 *
6396 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6397 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6398 		 */
6399 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6400 			flag |= PTR_TRUSTED;
6401 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6402 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6403 				/* ignore __rcu tag and mark it MEM_RCU */
6404 				flag |= MEM_RCU;
6405 			} else if (flag & MEM_RCU ||
6406 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6407 				/* __rcu tagged pointers can be NULL */
6408 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6409 
6410 				/* We always trust them */
6411 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6412 				    flag & PTR_UNTRUSTED)
6413 					flag &= ~PTR_UNTRUSTED;
6414 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6415 				/* keep as-is */
6416 			} else {
6417 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6418 				clear_trusted_flags(&flag);
6419 			}
6420 		} else {
6421 			/*
6422 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6423 			 * aggressively mark as untrusted otherwise such
6424 			 * pointers will be plain PTR_TO_BTF_ID without flags
6425 			 * and will be allowed to be passed into helpers for
6426 			 * compat reasons.
6427 			 */
6428 			flag = PTR_UNTRUSTED;
6429 		}
6430 	} else {
6431 		/* Old compat. Deprecated */
6432 		clear_trusted_flags(&flag);
6433 	}
6434 
6435 	if (atype == BPF_READ && value_regno >= 0)
6436 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6437 
6438 	return 0;
6439 }
6440 
6441 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6442 				   struct bpf_reg_state *regs,
6443 				   int regno, int off, int size,
6444 				   enum bpf_access_type atype,
6445 				   int value_regno)
6446 {
6447 	struct bpf_reg_state *reg = regs + regno;
6448 	struct bpf_map *map = reg->map_ptr;
6449 	struct bpf_reg_state map_reg;
6450 	enum bpf_type_flag flag = 0;
6451 	const struct btf_type *t;
6452 	const char *tname;
6453 	u32 btf_id;
6454 	int ret;
6455 
6456 	if (!btf_vmlinux) {
6457 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6458 		return -ENOTSUPP;
6459 	}
6460 
6461 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6462 		verbose(env, "map_ptr access not supported for map type %d\n",
6463 			map->map_type);
6464 		return -ENOTSUPP;
6465 	}
6466 
6467 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6468 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6469 
6470 	if (!env->allow_ptr_leaks) {
6471 		verbose(env,
6472 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6473 			tname);
6474 		return -EPERM;
6475 	}
6476 
6477 	if (off < 0) {
6478 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6479 			regno, tname, off);
6480 		return -EACCES;
6481 	}
6482 
6483 	if (atype != BPF_READ) {
6484 		verbose(env, "only read from %s is supported\n", tname);
6485 		return -EACCES;
6486 	}
6487 
6488 	/* Simulate access to a PTR_TO_BTF_ID */
6489 	memset(&map_reg, 0, sizeof(map_reg));
6490 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6491 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6492 	if (ret < 0)
6493 		return ret;
6494 
6495 	if (value_regno >= 0)
6496 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6497 
6498 	return 0;
6499 }
6500 
6501 /* Check that the stack access at the given offset is within bounds. The
6502  * maximum valid offset is -1.
6503  *
6504  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6505  * -state->allocated_stack for reads.
6506  */
6507 static int check_stack_slot_within_bounds(int off,
6508 					  struct bpf_func_state *state,
6509 					  enum bpf_access_type t)
6510 {
6511 	int min_valid_off;
6512 
6513 	if (t == BPF_WRITE)
6514 		min_valid_off = -MAX_BPF_STACK;
6515 	else
6516 		min_valid_off = -state->allocated_stack;
6517 
6518 	if (off < min_valid_off || off > -1)
6519 		return -EACCES;
6520 	return 0;
6521 }
6522 
6523 /* Check that the stack access at 'regno + off' falls within the maximum stack
6524  * bounds.
6525  *
6526  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6527  */
6528 static int check_stack_access_within_bounds(
6529 		struct bpf_verifier_env *env,
6530 		int regno, int off, int access_size,
6531 		enum bpf_access_src src, enum bpf_access_type type)
6532 {
6533 	struct bpf_reg_state *regs = cur_regs(env);
6534 	struct bpf_reg_state *reg = regs + regno;
6535 	struct bpf_func_state *state = func(env, reg);
6536 	int min_off, max_off;
6537 	int err;
6538 	char *err_extra;
6539 
6540 	if (src == ACCESS_HELPER)
6541 		/* We don't know if helpers are reading or writing (or both). */
6542 		err_extra = " indirect access to";
6543 	else if (type == BPF_READ)
6544 		err_extra = " read from";
6545 	else
6546 		err_extra = " write to";
6547 
6548 	if (tnum_is_const(reg->var_off)) {
6549 		min_off = reg->var_off.value + off;
6550 		if (access_size > 0)
6551 			max_off = min_off + access_size - 1;
6552 		else
6553 			max_off = min_off;
6554 	} else {
6555 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6556 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6557 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6558 				err_extra, regno);
6559 			return -EACCES;
6560 		}
6561 		min_off = reg->smin_value + off;
6562 		if (access_size > 0)
6563 			max_off = reg->smax_value + off + access_size - 1;
6564 		else
6565 			max_off = min_off;
6566 	}
6567 
6568 	err = check_stack_slot_within_bounds(min_off, state, type);
6569 	if (!err)
6570 		err = check_stack_slot_within_bounds(max_off, state, type);
6571 
6572 	if (err) {
6573 		if (tnum_is_const(reg->var_off)) {
6574 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6575 				err_extra, regno, off, access_size);
6576 		} else {
6577 			char tn_buf[48];
6578 
6579 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6580 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6581 				err_extra, regno, tn_buf, access_size);
6582 		}
6583 	}
6584 	return err;
6585 }
6586 
6587 /* check whether memory at (regno + off) is accessible for t = (read | write)
6588  * if t==write, value_regno is a register which value is stored into memory
6589  * if t==read, value_regno is a register which will receive the value from memory
6590  * if t==write && value_regno==-1, some unknown value is stored into memory
6591  * if t==read && value_regno==-1, don't care what we read from memory
6592  */
6593 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6594 			    int off, int bpf_size, enum bpf_access_type t,
6595 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6596 {
6597 	struct bpf_reg_state *regs = cur_regs(env);
6598 	struct bpf_reg_state *reg = regs + regno;
6599 	struct bpf_func_state *state;
6600 	int size, err = 0;
6601 
6602 	size = bpf_size_to_bytes(bpf_size);
6603 	if (size < 0)
6604 		return size;
6605 
6606 	/* alignment checks will add in reg->off themselves */
6607 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6608 	if (err)
6609 		return err;
6610 
6611 	/* for access checks, reg->off is just part of off */
6612 	off += reg->off;
6613 
6614 	if (reg->type == PTR_TO_MAP_KEY) {
6615 		if (t == BPF_WRITE) {
6616 			verbose(env, "write to change key R%d not allowed\n", regno);
6617 			return -EACCES;
6618 		}
6619 
6620 		err = check_mem_region_access(env, regno, off, size,
6621 					      reg->map_ptr->key_size, false);
6622 		if (err)
6623 			return err;
6624 		if (value_regno >= 0)
6625 			mark_reg_unknown(env, regs, value_regno);
6626 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6627 		struct btf_field *kptr_field = NULL;
6628 
6629 		if (t == BPF_WRITE && value_regno >= 0 &&
6630 		    is_pointer_value(env, value_regno)) {
6631 			verbose(env, "R%d leaks addr into map\n", value_regno);
6632 			return -EACCES;
6633 		}
6634 		err = check_map_access_type(env, regno, off, size, t);
6635 		if (err)
6636 			return err;
6637 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6638 		if (err)
6639 			return err;
6640 		if (tnum_is_const(reg->var_off))
6641 			kptr_field = btf_record_find(reg->map_ptr->record,
6642 						     off + reg->var_off.value, BPF_KPTR);
6643 		if (kptr_field) {
6644 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6645 		} else if (t == BPF_READ && value_regno >= 0) {
6646 			struct bpf_map *map = reg->map_ptr;
6647 
6648 			/* if map is read-only, track its contents as scalars */
6649 			if (tnum_is_const(reg->var_off) &&
6650 			    bpf_map_is_rdonly(map) &&
6651 			    map->ops->map_direct_value_addr) {
6652 				int map_off = off + reg->var_off.value;
6653 				u64 val = 0;
6654 
6655 				err = bpf_map_direct_read(map, map_off, size,
6656 							  &val, is_ldsx);
6657 				if (err)
6658 					return err;
6659 
6660 				regs[value_regno].type = SCALAR_VALUE;
6661 				__mark_reg_known(&regs[value_regno], val);
6662 			} else {
6663 				mark_reg_unknown(env, regs, value_regno);
6664 			}
6665 		}
6666 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6667 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6668 
6669 		if (type_may_be_null(reg->type)) {
6670 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6671 				reg_type_str(env, reg->type));
6672 			return -EACCES;
6673 		}
6674 
6675 		if (t == BPF_WRITE && rdonly_mem) {
6676 			verbose(env, "R%d cannot write into %s\n",
6677 				regno, reg_type_str(env, reg->type));
6678 			return -EACCES;
6679 		}
6680 
6681 		if (t == BPF_WRITE && value_regno >= 0 &&
6682 		    is_pointer_value(env, value_regno)) {
6683 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6684 			return -EACCES;
6685 		}
6686 
6687 		err = check_mem_region_access(env, regno, off, size,
6688 					      reg->mem_size, false);
6689 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6690 			mark_reg_unknown(env, regs, value_regno);
6691 	} else if (reg->type == PTR_TO_CTX) {
6692 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6693 		struct btf *btf = NULL;
6694 		u32 btf_id = 0;
6695 
6696 		if (t == BPF_WRITE && value_regno >= 0 &&
6697 		    is_pointer_value(env, value_regno)) {
6698 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6699 			return -EACCES;
6700 		}
6701 
6702 		err = check_ptr_off_reg(env, reg, regno);
6703 		if (err < 0)
6704 			return err;
6705 
6706 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6707 				       &btf_id);
6708 		if (err)
6709 			verbose_linfo(env, insn_idx, "; ");
6710 		if (!err && t == BPF_READ && value_regno >= 0) {
6711 			/* ctx access returns either a scalar, or a
6712 			 * PTR_TO_PACKET[_META,_END]. In the latter
6713 			 * case, we know the offset is zero.
6714 			 */
6715 			if (reg_type == SCALAR_VALUE) {
6716 				mark_reg_unknown(env, regs, value_regno);
6717 			} else {
6718 				mark_reg_known_zero(env, regs,
6719 						    value_regno);
6720 				if (type_may_be_null(reg_type))
6721 					regs[value_regno].id = ++env->id_gen;
6722 				/* A load of ctx field could have different
6723 				 * actual load size with the one encoded in the
6724 				 * insn. When the dst is PTR, it is for sure not
6725 				 * a sub-register.
6726 				 */
6727 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6728 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6729 					regs[value_regno].btf = btf;
6730 					regs[value_regno].btf_id = btf_id;
6731 				}
6732 			}
6733 			regs[value_regno].type = reg_type;
6734 		}
6735 
6736 	} else if (reg->type == PTR_TO_STACK) {
6737 		/* Basic bounds checks. */
6738 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6739 		if (err)
6740 			return err;
6741 
6742 		state = func(env, reg);
6743 		err = update_stack_depth(env, state, off);
6744 		if (err)
6745 			return err;
6746 
6747 		if (t == BPF_READ)
6748 			err = check_stack_read(env, regno, off, size,
6749 					       value_regno);
6750 		else
6751 			err = check_stack_write(env, regno, off, size,
6752 						value_regno, insn_idx);
6753 	} else if (reg_is_pkt_pointer(reg)) {
6754 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6755 			verbose(env, "cannot write into packet\n");
6756 			return -EACCES;
6757 		}
6758 		if (t == BPF_WRITE && value_regno >= 0 &&
6759 		    is_pointer_value(env, value_regno)) {
6760 			verbose(env, "R%d leaks addr into packet\n",
6761 				value_regno);
6762 			return -EACCES;
6763 		}
6764 		err = check_packet_access(env, regno, off, size, false);
6765 		if (!err && t == BPF_READ && value_regno >= 0)
6766 			mark_reg_unknown(env, regs, value_regno);
6767 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6768 		if (t == BPF_WRITE && value_regno >= 0 &&
6769 		    is_pointer_value(env, value_regno)) {
6770 			verbose(env, "R%d leaks addr into flow keys\n",
6771 				value_regno);
6772 			return -EACCES;
6773 		}
6774 
6775 		err = check_flow_keys_access(env, off, size);
6776 		if (!err && t == BPF_READ && value_regno >= 0)
6777 			mark_reg_unknown(env, regs, value_regno);
6778 	} else if (type_is_sk_pointer(reg->type)) {
6779 		if (t == BPF_WRITE) {
6780 			verbose(env, "R%d cannot write into %s\n",
6781 				regno, reg_type_str(env, reg->type));
6782 			return -EACCES;
6783 		}
6784 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6785 		if (!err && value_regno >= 0)
6786 			mark_reg_unknown(env, regs, value_regno);
6787 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6788 		err = check_tp_buffer_access(env, reg, regno, off, size);
6789 		if (!err && t == BPF_READ && value_regno >= 0)
6790 			mark_reg_unknown(env, regs, value_regno);
6791 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6792 		   !type_may_be_null(reg->type)) {
6793 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6794 					      value_regno);
6795 	} else if (reg->type == CONST_PTR_TO_MAP) {
6796 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6797 					      value_regno);
6798 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6799 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6800 		u32 *max_access;
6801 
6802 		if (rdonly_mem) {
6803 			if (t == BPF_WRITE) {
6804 				verbose(env, "R%d cannot write into %s\n",
6805 					regno, reg_type_str(env, reg->type));
6806 				return -EACCES;
6807 			}
6808 			max_access = &env->prog->aux->max_rdonly_access;
6809 		} else {
6810 			max_access = &env->prog->aux->max_rdwr_access;
6811 		}
6812 
6813 		err = check_buffer_access(env, reg, regno, off, size, false,
6814 					  max_access);
6815 
6816 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6817 			mark_reg_unknown(env, regs, value_regno);
6818 	} else {
6819 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6820 			reg_type_str(env, reg->type));
6821 		return -EACCES;
6822 	}
6823 
6824 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6825 	    regs[value_regno].type == SCALAR_VALUE) {
6826 		if (!is_ldsx)
6827 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6828 			coerce_reg_to_size(&regs[value_regno], size);
6829 		else
6830 			coerce_reg_to_size_sx(&regs[value_regno], size);
6831 	}
6832 	return err;
6833 }
6834 
6835 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6836 {
6837 	int load_reg;
6838 	int err;
6839 
6840 	switch (insn->imm) {
6841 	case BPF_ADD:
6842 	case BPF_ADD | BPF_FETCH:
6843 	case BPF_AND:
6844 	case BPF_AND | BPF_FETCH:
6845 	case BPF_OR:
6846 	case BPF_OR | BPF_FETCH:
6847 	case BPF_XOR:
6848 	case BPF_XOR | BPF_FETCH:
6849 	case BPF_XCHG:
6850 	case BPF_CMPXCHG:
6851 		break;
6852 	default:
6853 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6854 		return -EINVAL;
6855 	}
6856 
6857 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6858 		verbose(env, "invalid atomic operand size\n");
6859 		return -EINVAL;
6860 	}
6861 
6862 	/* check src1 operand */
6863 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6864 	if (err)
6865 		return err;
6866 
6867 	/* check src2 operand */
6868 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6869 	if (err)
6870 		return err;
6871 
6872 	if (insn->imm == BPF_CMPXCHG) {
6873 		/* Check comparison of R0 with memory location */
6874 		const u32 aux_reg = BPF_REG_0;
6875 
6876 		err = check_reg_arg(env, aux_reg, SRC_OP);
6877 		if (err)
6878 			return err;
6879 
6880 		if (is_pointer_value(env, aux_reg)) {
6881 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6882 			return -EACCES;
6883 		}
6884 	}
6885 
6886 	if (is_pointer_value(env, insn->src_reg)) {
6887 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6888 		return -EACCES;
6889 	}
6890 
6891 	if (is_ctx_reg(env, insn->dst_reg) ||
6892 	    is_pkt_reg(env, insn->dst_reg) ||
6893 	    is_flow_key_reg(env, insn->dst_reg) ||
6894 	    is_sk_reg(env, insn->dst_reg)) {
6895 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6896 			insn->dst_reg,
6897 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6898 		return -EACCES;
6899 	}
6900 
6901 	if (insn->imm & BPF_FETCH) {
6902 		if (insn->imm == BPF_CMPXCHG)
6903 			load_reg = BPF_REG_0;
6904 		else
6905 			load_reg = insn->src_reg;
6906 
6907 		/* check and record load of old value */
6908 		err = check_reg_arg(env, load_reg, DST_OP);
6909 		if (err)
6910 			return err;
6911 	} else {
6912 		/* This instruction accesses a memory location but doesn't
6913 		 * actually load it into a register.
6914 		 */
6915 		load_reg = -1;
6916 	}
6917 
6918 	/* Check whether we can read the memory, with second call for fetch
6919 	 * case to simulate the register fill.
6920 	 */
6921 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6922 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6923 	if (!err && load_reg >= 0)
6924 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6925 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
6926 				       true, false);
6927 	if (err)
6928 		return err;
6929 
6930 	/* Check whether we can write into the same memory. */
6931 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6932 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6933 	if (err)
6934 		return err;
6935 
6936 	return 0;
6937 }
6938 
6939 /* When register 'regno' is used to read the stack (either directly or through
6940  * a helper function) make sure that it's within stack boundary and, depending
6941  * on the access type, that all elements of the stack are initialized.
6942  *
6943  * 'off' includes 'regno->off', but not its dynamic part (if any).
6944  *
6945  * All registers that have been spilled on the stack in the slots within the
6946  * read offsets are marked as read.
6947  */
6948 static int check_stack_range_initialized(
6949 		struct bpf_verifier_env *env, int regno, int off,
6950 		int access_size, bool zero_size_allowed,
6951 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6952 {
6953 	struct bpf_reg_state *reg = reg_state(env, regno);
6954 	struct bpf_func_state *state = func(env, reg);
6955 	int err, min_off, max_off, i, j, slot, spi;
6956 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6957 	enum bpf_access_type bounds_check_type;
6958 	/* Some accesses can write anything into the stack, others are
6959 	 * read-only.
6960 	 */
6961 	bool clobber = false;
6962 
6963 	if (access_size == 0 && !zero_size_allowed) {
6964 		verbose(env, "invalid zero-sized read\n");
6965 		return -EACCES;
6966 	}
6967 
6968 	if (type == ACCESS_HELPER) {
6969 		/* The bounds checks for writes are more permissive than for
6970 		 * reads. However, if raw_mode is not set, we'll do extra
6971 		 * checks below.
6972 		 */
6973 		bounds_check_type = BPF_WRITE;
6974 		clobber = true;
6975 	} else {
6976 		bounds_check_type = BPF_READ;
6977 	}
6978 	err = check_stack_access_within_bounds(env, regno, off, access_size,
6979 					       type, bounds_check_type);
6980 	if (err)
6981 		return err;
6982 
6983 
6984 	if (tnum_is_const(reg->var_off)) {
6985 		min_off = max_off = reg->var_off.value + off;
6986 	} else {
6987 		/* Variable offset is prohibited for unprivileged mode for
6988 		 * simplicity since it requires corresponding support in
6989 		 * Spectre masking for stack ALU.
6990 		 * See also retrieve_ptr_limit().
6991 		 */
6992 		if (!env->bypass_spec_v1) {
6993 			char tn_buf[48];
6994 
6995 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6996 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6997 				regno, err_extra, tn_buf);
6998 			return -EACCES;
6999 		}
7000 		/* Only initialized buffer on stack is allowed to be accessed
7001 		 * with variable offset. With uninitialized buffer it's hard to
7002 		 * guarantee that whole memory is marked as initialized on
7003 		 * helper return since specific bounds are unknown what may
7004 		 * cause uninitialized stack leaking.
7005 		 */
7006 		if (meta && meta->raw_mode)
7007 			meta = NULL;
7008 
7009 		min_off = reg->smin_value + off;
7010 		max_off = reg->smax_value + off;
7011 	}
7012 
7013 	if (meta && meta->raw_mode) {
7014 		/* Ensure we won't be overwriting dynptrs when simulating byte
7015 		 * by byte access in check_helper_call using meta.access_size.
7016 		 * This would be a problem if we have a helper in the future
7017 		 * which takes:
7018 		 *
7019 		 *	helper(uninit_mem, len, dynptr)
7020 		 *
7021 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7022 		 * may end up writing to dynptr itself when touching memory from
7023 		 * arg 1. This can be relaxed on a case by case basis for known
7024 		 * safe cases, but reject due to the possibilitiy of aliasing by
7025 		 * default.
7026 		 */
7027 		for (i = min_off; i < max_off + access_size; i++) {
7028 			int stack_off = -i - 1;
7029 
7030 			spi = __get_spi(i);
7031 			/* raw_mode may write past allocated_stack */
7032 			if (state->allocated_stack <= stack_off)
7033 				continue;
7034 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7035 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7036 				return -EACCES;
7037 			}
7038 		}
7039 		meta->access_size = access_size;
7040 		meta->regno = regno;
7041 		return 0;
7042 	}
7043 
7044 	for (i = min_off; i < max_off + access_size; i++) {
7045 		u8 *stype;
7046 
7047 		slot = -i - 1;
7048 		spi = slot / BPF_REG_SIZE;
7049 		if (state->allocated_stack <= slot)
7050 			goto err;
7051 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7052 		if (*stype == STACK_MISC)
7053 			goto mark;
7054 		if ((*stype == STACK_ZERO) ||
7055 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7056 			if (clobber) {
7057 				/* helper can write anything into the stack */
7058 				*stype = STACK_MISC;
7059 			}
7060 			goto mark;
7061 		}
7062 
7063 		if (is_spilled_reg(&state->stack[spi]) &&
7064 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7065 		     env->allow_ptr_leaks)) {
7066 			if (clobber) {
7067 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7068 				for (j = 0; j < BPF_REG_SIZE; j++)
7069 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7070 			}
7071 			goto mark;
7072 		}
7073 
7074 err:
7075 		if (tnum_is_const(reg->var_off)) {
7076 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7077 				err_extra, regno, min_off, i - min_off, access_size);
7078 		} else {
7079 			char tn_buf[48];
7080 
7081 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7082 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7083 				err_extra, regno, tn_buf, i - min_off, access_size);
7084 		}
7085 		return -EACCES;
7086 mark:
7087 		/* reading any byte out of 8-byte 'spill_slot' will cause
7088 		 * the whole slot to be marked as 'read'
7089 		 */
7090 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7091 			      state->stack[spi].spilled_ptr.parent,
7092 			      REG_LIVE_READ64);
7093 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7094 		 * be sure that whether stack slot is written to or not. Hence,
7095 		 * we must still conservatively propagate reads upwards even if
7096 		 * helper may write to the entire memory range.
7097 		 */
7098 	}
7099 	return update_stack_depth(env, state, min_off);
7100 }
7101 
7102 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7103 				   int access_size, bool zero_size_allowed,
7104 				   struct bpf_call_arg_meta *meta)
7105 {
7106 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7107 	u32 *max_access;
7108 
7109 	switch (base_type(reg->type)) {
7110 	case PTR_TO_PACKET:
7111 	case PTR_TO_PACKET_META:
7112 		return check_packet_access(env, regno, reg->off, access_size,
7113 					   zero_size_allowed);
7114 	case PTR_TO_MAP_KEY:
7115 		if (meta && meta->raw_mode) {
7116 			verbose(env, "R%d cannot write into %s\n", regno,
7117 				reg_type_str(env, reg->type));
7118 			return -EACCES;
7119 		}
7120 		return check_mem_region_access(env, regno, reg->off, access_size,
7121 					       reg->map_ptr->key_size, false);
7122 	case PTR_TO_MAP_VALUE:
7123 		if (check_map_access_type(env, regno, reg->off, access_size,
7124 					  meta && meta->raw_mode ? BPF_WRITE :
7125 					  BPF_READ))
7126 			return -EACCES;
7127 		return check_map_access(env, regno, reg->off, access_size,
7128 					zero_size_allowed, ACCESS_HELPER);
7129 	case PTR_TO_MEM:
7130 		if (type_is_rdonly_mem(reg->type)) {
7131 			if (meta && meta->raw_mode) {
7132 				verbose(env, "R%d cannot write into %s\n", regno,
7133 					reg_type_str(env, reg->type));
7134 				return -EACCES;
7135 			}
7136 		}
7137 		return check_mem_region_access(env, regno, reg->off,
7138 					       access_size, reg->mem_size,
7139 					       zero_size_allowed);
7140 	case PTR_TO_BUF:
7141 		if (type_is_rdonly_mem(reg->type)) {
7142 			if (meta && meta->raw_mode) {
7143 				verbose(env, "R%d cannot write into %s\n", regno,
7144 					reg_type_str(env, reg->type));
7145 				return -EACCES;
7146 			}
7147 
7148 			max_access = &env->prog->aux->max_rdonly_access;
7149 		} else {
7150 			max_access = &env->prog->aux->max_rdwr_access;
7151 		}
7152 		return check_buffer_access(env, reg, regno, reg->off,
7153 					   access_size, zero_size_allowed,
7154 					   max_access);
7155 	case PTR_TO_STACK:
7156 		return check_stack_range_initialized(
7157 				env,
7158 				regno, reg->off, access_size,
7159 				zero_size_allowed, ACCESS_HELPER, meta);
7160 	case PTR_TO_BTF_ID:
7161 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7162 					       access_size, BPF_READ, -1);
7163 	case PTR_TO_CTX:
7164 		/* in case the function doesn't know how to access the context,
7165 		 * (because we are in a program of type SYSCALL for example), we
7166 		 * can not statically check its size.
7167 		 * Dynamically check it now.
7168 		 */
7169 		if (!env->ops->convert_ctx_access) {
7170 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7171 			int offset = access_size - 1;
7172 
7173 			/* Allow zero-byte read from PTR_TO_CTX */
7174 			if (access_size == 0)
7175 				return zero_size_allowed ? 0 : -EACCES;
7176 
7177 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7178 						atype, -1, false, false);
7179 		}
7180 
7181 		fallthrough;
7182 	default: /* scalar_value or invalid ptr */
7183 		/* Allow zero-byte read from NULL, regardless of pointer type */
7184 		if (zero_size_allowed && access_size == 0 &&
7185 		    register_is_null(reg))
7186 			return 0;
7187 
7188 		verbose(env, "R%d type=%s ", regno,
7189 			reg_type_str(env, reg->type));
7190 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7191 		return -EACCES;
7192 	}
7193 }
7194 
7195 static int check_mem_size_reg(struct bpf_verifier_env *env,
7196 			      struct bpf_reg_state *reg, u32 regno,
7197 			      bool zero_size_allowed,
7198 			      struct bpf_call_arg_meta *meta)
7199 {
7200 	int err;
7201 
7202 	/* This is used to refine r0 return value bounds for helpers
7203 	 * that enforce this value as an upper bound on return values.
7204 	 * See do_refine_retval_range() for helpers that can refine
7205 	 * the return value. C type of helper is u32 so we pull register
7206 	 * bound from umax_value however, if negative verifier errors
7207 	 * out. Only upper bounds can be learned because retval is an
7208 	 * int type and negative retvals are allowed.
7209 	 */
7210 	meta->msize_max_value = reg->umax_value;
7211 
7212 	/* The register is SCALAR_VALUE; the access check
7213 	 * happens using its boundaries.
7214 	 */
7215 	if (!tnum_is_const(reg->var_off))
7216 		/* For unprivileged variable accesses, disable raw
7217 		 * mode so that the program is required to
7218 		 * initialize all the memory that the helper could
7219 		 * just partially fill up.
7220 		 */
7221 		meta = NULL;
7222 
7223 	if (reg->smin_value < 0) {
7224 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7225 			regno);
7226 		return -EACCES;
7227 	}
7228 
7229 	if (reg->umin_value == 0) {
7230 		err = check_helper_mem_access(env, regno - 1, 0,
7231 					      zero_size_allowed,
7232 					      meta);
7233 		if (err)
7234 			return err;
7235 	}
7236 
7237 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7238 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7239 			regno);
7240 		return -EACCES;
7241 	}
7242 	err = check_helper_mem_access(env, regno - 1,
7243 				      reg->umax_value,
7244 				      zero_size_allowed, meta);
7245 	if (!err)
7246 		err = mark_chain_precision(env, regno);
7247 	return err;
7248 }
7249 
7250 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7251 		   u32 regno, u32 mem_size)
7252 {
7253 	bool may_be_null = type_may_be_null(reg->type);
7254 	struct bpf_reg_state saved_reg;
7255 	struct bpf_call_arg_meta meta;
7256 	int err;
7257 
7258 	if (register_is_null(reg))
7259 		return 0;
7260 
7261 	memset(&meta, 0, sizeof(meta));
7262 	/* Assuming that the register contains a value check if the memory
7263 	 * access is safe. Temporarily save and restore the register's state as
7264 	 * the conversion shouldn't be visible to a caller.
7265 	 */
7266 	if (may_be_null) {
7267 		saved_reg = *reg;
7268 		mark_ptr_not_null_reg(reg);
7269 	}
7270 
7271 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7272 	/* Check access for BPF_WRITE */
7273 	meta.raw_mode = true;
7274 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7275 
7276 	if (may_be_null)
7277 		*reg = saved_reg;
7278 
7279 	return err;
7280 }
7281 
7282 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7283 				    u32 regno)
7284 {
7285 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7286 	bool may_be_null = type_may_be_null(mem_reg->type);
7287 	struct bpf_reg_state saved_reg;
7288 	struct bpf_call_arg_meta meta;
7289 	int err;
7290 
7291 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7292 
7293 	memset(&meta, 0, sizeof(meta));
7294 
7295 	if (may_be_null) {
7296 		saved_reg = *mem_reg;
7297 		mark_ptr_not_null_reg(mem_reg);
7298 	}
7299 
7300 	err = check_mem_size_reg(env, reg, regno, true, &meta);
7301 	/* Check access for BPF_WRITE */
7302 	meta.raw_mode = true;
7303 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7304 
7305 	if (may_be_null)
7306 		*mem_reg = saved_reg;
7307 	return err;
7308 }
7309 
7310 /* Implementation details:
7311  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7312  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7313  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7314  * Two separate bpf_obj_new will also have different reg->id.
7315  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7316  * clears reg->id after value_or_null->value transition, since the verifier only
7317  * cares about the range of access to valid map value pointer and doesn't care
7318  * about actual address of the map element.
7319  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7320  * reg->id > 0 after value_or_null->value transition. By doing so
7321  * two bpf_map_lookups will be considered two different pointers that
7322  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7323  * returned from bpf_obj_new.
7324  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7325  * dead-locks.
7326  * Since only one bpf_spin_lock is allowed the checks are simpler than
7327  * reg_is_refcounted() logic. The verifier needs to remember only
7328  * one spin_lock instead of array of acquired_refs.
7329  * cur_state->active_lock remembers which map value element or allocated
7330  * object got locked and clears it after bpf_spin_unlock.
7331  */
7332 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7333 			     bool is_lock)
7334 {
7335 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7336 	struct bpf_verifier_state *cur = env->cur_state;
7337 	bool is_const = tnum_is_const(reg->var_off);
7338 	u64 val = reg->var_off.value;
7339 	struct bpf_map *map = NULL;
7340 	struct btf *btf = NULL;
7341 	struct btf_record *rec;
7342 
7343 	if (!is_const) {
7344 		verbose(env,
7345 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7346 			regno);
7347 		return -EINVAL;
7348 	}
7349 	if (reg->type == PTR_TO_MAP_VALUE) {
7350 		map = reg->map_ptr;
7351 		if (!map->btf) {
7352 			verbose(env,
7353 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7354 				map->name);
7355 			return -EINVAL;
7356 		}
7357 	} else {
7358 		btf = reg->btf;
7359 	}
7360 
7361 	rec = reg_btf_record(reg);
7362 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7363 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7364 			map ? map->name : "kptr");
7365 		return -EINVAL;
7366 	}
7367 	if (rec->spin_lock_off != val + reg->off) {
7368 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7369 			val + reg->off, rec->spin_lock_off);
7370 		return -EINVAL;
7371 	}
7372 	if (is_lock) {
7373 		if (cur->active_lock.ptr) {
7374 			verbose(env,
7375 				"Locking two bpf_spin_locks are not allowed\n");
7376 			return -EINVAL;
7377 		}
7378 		if (map)
7379 			cur->active_lock.ptr = map;
7380 		else
7381 			cur->active_lock.ptr = btf;
7382 		cur->active_lock.id = reg->id;
7383 	} else {
7384 		void *ptr;
7385 
7386 		if (map)
7387 			ptr = map;
7388 		else
7389 			ptr = btf;
7390 
7391 		if (!cur->active_lock.ptr) {
7392 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7393 			return -EINVAL;
7394 		}
7395 		if (cur->active_lock.ptr != ptr ||
7396 		    cur->active_lock.id != reg->id) {
7397 			verbose(env, "bpf_spin_unlock of different lock\n");
7398 			return -EINVAL;
7399 		}
7400 
7401 		invalidate_non_owning_refs(env);
7402 
7403 		cur->active_lock.ptr = NULL;
7404 		cur->active_lock.id = 0;
7405 	}
7406 	return 0;
7407 }
7408 
7409 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7410 			      struct bpf_call_arg_meta *meta)
7411 {
7412 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7413 	bool is_const = tnum_is_const(reg->var_off);
7414 	struct bpf_map *map = reg->map_ptr;
7415 	u64 val = reg->var_off.value;
7416 
7417 	if (!is_const) {
7418 		verbose(env,
7419 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7420 			regno);
7421 		return -EINVAL;
7422 	}
7423 	if (!map->btf) {
7424 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7425 			map->name);
7426 		return -EINVAL;
7427 	}
7428 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7429 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7430 		return -EINVAL;
7431 	}
7432 	if (map->record->timer_off != val + reg->off) {
7433 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7434 			val + reg->off, map->record->timer_off);
7435 		return -EINVAL;
7436 	}
7437 	if (meta->map_ptr) {
7438 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7439 		return -EFAULT;
7440 	}
7441 	meta->map_uid = reg->map_uid;
7442 	meta->map_ptr = map;
7443 	return 0;
7444 }
7445 
7446 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7447 			     struct bpf_call_arg_meta *meta)
7448 {
7449 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7450 	struct bpf_map *map_ptr = reg->map_ptr;
7451 	struct btf_field *kptr_field;
7452 	u32 kptr_off;
7453 
7454 	if (!tnum_is_const(reg->var_off)) {
7455 		verbose(env,
7456 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7457 			regno);
7458 		return -EINVAL;
7459 	}
7460 	if (!map_ptr->btf) {
7461 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7462 			map_ptr->name);
7463 		return -EINVAL;
7464 	}
7465 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7466 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7467 		return -EINVAL;
7468 	}
7469 
7470 	meta->map_ptr = map_ptr;
7471 	kptr_off = reg->off + reg->var_off.value;
7472 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7473 	if (!kptr_field) {
7474 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7475 		return -EACCES;
7476 	}
7477 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7478 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7479 		return -EACCES;
7480 	}
7481 	meta->kptr_field = kptr_field;
7482 	return 0;
7483 }
7484 
7485 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7486  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7487  *
7488  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7489  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7490  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7491  *
7492  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7493  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7494  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7495  * mutate the view of the dynptr and also possibly destroy it. In the latter
7496  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7497  * memory that dynptr points to.
7498  *
7499  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7500  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7501  * readonly dynptr view yet, hence only the first case is tracked and checked.
7502  *
7503  * This is consistent with how C applies the const modifier to a struct object,
7504  * where the pointer itself inside bpf_dynptr becomes const but not what it
7505  * points to.
7506  *
7507  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7508  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7509  */
7510 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7511 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7512 {
7513 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7514 	int err;
7515 
7516 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7517 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7518 	 */
7519 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7520 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7521 		return -EFAULT;
7522 	}
7523 
7524 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7525 	 *		 constructing a mutable bpf_dynptr object.
7526 	 *
7527 	 *		 Currently, this is only possible with PTR_TO_STACK
7528 	 *		 pointing to a region of at least 16 bytes which doesn't
7529 	 *		 contain an existing bpf_dynptr.
7530 	 *
7531 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7532 	 *		 mutated or destroyed. However, the memory it points to
7533 	 *		 may be mutated.
7534 	 *
7535 	 *  None       - Points to a initialized dynptr that can be mutated and
7536 	 *		 destroyed, including mutation of the memory it points
7537 	 *		 to.
7538 	 */
7539 	if (arg_type & MEM_UNINIT) {
7540 		int i;
7541 
7542 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7543 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7544 			return -EINVAL;
7545 		}
7546 
7547 		/* we write BPF_DW bits (8 bytes) at a time */
7548 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7549 			err = check_mem_access(env, insn_idx, regno,
7550 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7551 			if (err)
7552 				return err;
7553 		}
7554 
7555 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7556 	} else /* MEM_RDONLY and None case from above */ {
7557 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7558 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7559 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7560 			return -EINVAL;
7561 		}
7562 
7563 		if (!is_dynptr_reg_valid_init(env, reg)) {
7564 			verbose(env,
7565 				"Expected an initialized dynptr as arg #%d\n",
7566 				regno);
7567 			return -EINVAL;
7568 		}
7569 
7570 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7571 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7572 			verbose(env,
7573 				"Expected a dynptr of type %s as arg #%d\n",
7574 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7575 			return -EINVAL;
7576 		}
7577 
7578 		err = mark_dynptr_read(env, reg);
7579 	}
7580 	return err;
7581 }
7582 
7583 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7584 {
7585 	struct bpf_func_state *state = func(env, reg);
7586 
7587 	return state->stack[spi].spilled_ptr.ref_obj_id;
7588 }
7589 
7590 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7591 {
7592 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7593 }
7594 
7595 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7596 {
7597 	return meta->kfunc_flags & KF_ITER_NEW;
7598 }
7599 
7600 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7601 {
7602 	return meta->kfunc_flags & KF_ITER_NEXT;
7603 }
7604 
7605 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7606 {
7607 	return meta->kfunc_flags & KF_ITER_DESTROY;
7608 }
7609 
7610 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7611 {
7612 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7613 	 * kfunc is iter state pointer
7614 	 */
7615 	return arg == 0 && is_iter_kfunc(meta);
7616 }
7617 
7618 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7619 			    struct bpf_kfunc_call_arg_meta *meta)
7620 {
7621 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7622 	const struct btf_type *t;
7623 	const struct btf_param *arg;
7624 	int spi, err, i, nr_slots;
7625 	u32 btf_id;
7626 
7627 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7628 	arg = &btf_params(meta->func_proto)[0];
7629 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7630 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7631 	nr_slots = t->size / BPF_REG_SIZE;
7632 
7633 	if (is_iter_new_kfunc(meta)) {
7634 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7635 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7636 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7637 				iter_type_str(meta->btf, btf_id), regno);
7638 			return -EINVAL;
7639 		}
7640 
7641 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7642 			err = check_mem_access(env, insn_idx, regno,
7643 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7644 			if (err)
7645 				return err;
7646 		}
7647 
7648 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
7649 		if (err)
7650 			return err;
7651 	} else {
7652 		/* iter_next() or iter_destroy() expect initialized iter state*/
7653 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
7654 		switch (err) {
7655 		case 0:
7656 			break;
7657 		case -EINVAL:
7658 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7659 				iter_type_str(meta->btf, btf_id), regno);
7660 			return err;
7661 		case -EPROTO:
7662 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
7663 			return err;
7664 		default:
7665 			return err;
7666 		}
7667 
7668 		spi = iter_get_spi(env, reg, nr_slots);
7669 		if (spi < 0)
7670 			return spi;
7671 
7672 		err = mark_iter_read(env, reg, spi, nr_slots);
7673 		if (err)
7674 			return err;
7675 
7676 		/* remember meta->iter info for process_iter_next_call() */
7677 		meta->iter.spi = spi;
7678 		meta->iter.frameno = reg->frameno;
7679 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7680 
7681 		if (is_iter_destroy_kfunc(meta)) {
7682 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7683 			if (err)
7684 				return err;
7685 		}
7686 	}
7687 
7688 	return 0;
7689 }
7690 
7691 /* Look for a previous loop entry at insn_idx: nearest parent state
7692  * stopped at insn_idx with callsites matching those in cur->frame.
7693  */
7694 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7695 						  struct bpf_verifier_state *cur,
7696 						  int insn_idx)
7697 {
7698 	struct bpf_verifier_state_list *sl;
7699 	struct bpf_verifier_state *st;
7700 
7701 	/* Explored states are pushed in stack order, most recent states come first */
7702 	sl = *explored_state(env, insn_idx);
7703 	for (; sl; sl = sl->next) {
7704 		/* If st->branches != 0 state is a part of current DFS verification path,
7705 		 * hence cur & st for a loop.
7706 		 */
7707 		st = &sl->state;
7708 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7709 		    st->dfs_depth < cur->dfs_depth)
7710 			return st;
7711 	}
7712 
7713 	return NULL;
7714 }
7715 
7716 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7717 static bool regs_exact(const struct bpf_reg_state *rold,
7718 		       const struct bpf_reg_state *rcur,
7719 		       struct bpf_idmap *idmap);
7720 
7721 static void maybe_widen_reg(struct bpf_verifier_env *env,
7722 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7723 			    struct bpf_idmap *idmap)
7724 {
7725 	if (rold->type != SCALAR_VALUE)
7726 		return;
7727 	if (rold->type != rcur->type)
7728 		return;
7729 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7730 		return;
7731 	__mark_reg_unknown(env, rcur);
7732 }
7733 
7734 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7735 				   struct bpf_verifier_state *old,
7736 				   struct bpf_verifier_state *cur)
7737 {
7738 	struct bpf_func_state *fold, *fcur;
7739 	int i, fr;
7740 
7741 	reset_idmap_scratch(env);
7742 	for (fr = old->curframe; fr >= 0; fr--) {
7743 		fold = old->frame[fr];
7744 		fcur = cur->frame[fr];
7745 
7746 		for (i = 0; i < MAX_BPF_REG; i++)
7747 			maybe_widen_reg(env,
7748 					&fold->regs[i],
7749 					&fcur->regs[i],
7750 					&env->idmap_scratch);
7751 
7752 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7753 			if (!is_spilled_reg(&fold->stack[i]) ||
7754 			    !is_spilled_reg(&fcur->stack[i]))
7755 				continue;
7756 
7757 			maybe_widen_reg(env,
7758 					&fold->stack[i].spilled_ptr,
7759 					&fcur->stack[i].spilled_ptr,
7760 					&env->idmap_scratch);
7761 		}
7762 	}
7763 	return 0;
7764 }
7765 
7766 /* process_iter_next_call() is called when verifier gets to iterator's next
7767  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7768  * to it as just "iter_next()" in comments below.
7769  *
7770  * BPF verifier relies on a crucial contract for any iter_next()
7771  * implementation: it should *eventually* return NULL, and once that happens
7772  * it should keep returning NULL. That is, once iterator exhausts elements to
7773  * iterate, it should never reset or spuriously return new elements.
7774  *
7775  * With the assumption of such contract, process_iter_next_call() simulates
7776  * a fork in the verifier state to validate loop logic correctness and safety
7777  * without having to simulate infinite amount of iterations.
7778  *
7779  * In current state, we first assume that iter_next() returned NULL and
7780  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7781  * conditions we should not form an infinite loop and should eventually reach
7782  * exit.
7783  *
7784  * Besides that, we also fork current state and enqueue it for later
7785  * verification. In a forked state we keep iterator state as ACTIVE
7786  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7787  * also bump iteration depth to prevent erroneous infinite loop detection
7788  * later on (see iter_active_depths_differ() comment for details). In this
7789  * state we assume that we'll eventually loop back to another iter_next()
7790  * calls (it could be in exactly same location or in some other instruction,
7791  * it doesn't matter, we don't make any unnecessary assumptions about this,
7792  * everything revolves around iterator state in a stack slot, not which
7793  * instruction is calling iter_next()). When that happens, we either will come
7794  * to iter_next() with equivalent state and can conclude that next iteration
7795  * will proceed in exactly the same way as we just verified, so it's safe to
7796  * assume that loop converges. If not, we'll go on another iteration
7797  * simulation with a different input state, until all possible starting states
7798  * are validated or we reach maximum number of instructions limit.
7799  *
7800  * This way, we will either exhaustively discover all possible input states
7801  * that iterator loop can start with and eventually will converge, or we'll
7802  * effectively regress into bounded loop simulation logic and either reach
7803  * maximum number of instructions if loop is not provably convergent, or there
7804  * is some statically known limit on number of iterations (e.g., if there is
7805  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7806  *
7807  * Iteration convergence logic in is_state_visited() relies on exact
7808  * states comparison, which ignores read and precision marks.
7809  * This is necessary because read and precision marks are not finalized
7810  * while in the loop. Exact comparison might preclude convergence for
7811  * simple programs like below:
7812  *
7813  *     i = 0;
7814  *     while(iter_next(&it))
7815  *       i++;
7816  *
7817  * At each iteration step i++ would produce a new distinct state and
7818  * eventually instruction processing limit would be reached.
7819  *
7820  * To avoid such behavior speculatively forget (widen) range for
7821  * imprecise scalar registers, if those registers were not precise at the
7822  * end of the previous iteration and do not match exactly.
7823  *
7824  * This is a conservative heuristic that allows to verify wide range of programs,
7825  * however it precludes verification of programs that conjure an
7826  * imprecise value on the first loop iteration and use it as precise on a second.
7827  * For example, the following safe program would fail to verify:
7828  *
7829  *     struct bpf_num_iter it;
7830  *     int arr[10];
7831  *     int i = 0, a = 0;
7832  *     bpf_iter_num_new(&it, 0, 10);
7833  *     while (bpf_iter_num_next(&it)) {
7834  *       if (a == 0) {
7835  *         a = 1;
7836  *         i = 7; // Because i changed verifier would forget
7837  *                // it's range on second loop entry.
7838  *       } else {
7839  *         arr[i] = 42; // This would fail to verify.
7840  *       }
7841  *     }
7842  *     bpf_iter_num_destroy(&it);
7843  */
7844 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7845 				  struct bpf_kfunc_call_arg_meta *meta)
7846 {
7847 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7848 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7849 	struct bpf_reg_state *cur_iter, *queued_iter;
7850 	int iter_frameno = meta->iter.frameno;
7851 	int iter_spi = meta->iter.spi;
7852 
7853 	BTF_TYPE_EMIT(struct bpf_iter);
7854 
7855 	cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7856 
7857 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7858 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7859 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7860 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7861 		return -EFAULT;
7862 	}
7863 
7864 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7865 		/* Because iter_next() call is a checkpoint is_state_visitied()
7866 		 * should guarantee parent state with same call sites and insn_idx.
7867 		 */
7868 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7869 		    !same_callsites(cur_st->parent, cur_st)) {
7870 			verbose(env, "bug: bad parent state for iter next call");
7871 			return -EFAULT;
7872 		}
7873 		/* Note cur_st->parent in the call below, it is necessary to skip
7874 		 * checkpoint created for cur_st by is_state_visited()
7875 		 * right at this instruction.
7876 		 */
7877 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7878 		/* branch out active iter state */
7879 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7880 		if (!queued_st)
7881 			return -ENOMEM;
7882 
7883 		queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7884 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7885 		queued_iter->iter.depth++;
7886 		if (prev_st)
7887 			widen_imprecise_scalars(env, prev_st, queued_st);
7888 
7889 		queued_fr = queued_st->frame[queued_st->curframe];
7890 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7891 	}
7892 
7893 	/* switch to DRAINED state, but keep the depth unchanged */
7894 	/* mark current iter state as drained and assume returned NULL */
7895 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7896 	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7897 
7898 	return 0;
7899 }
7900 
7901 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7902 {
7903 	return type == ARG_CONST_SIZE ||
7904 	       type == ARG_CONST_SIZE_OR_ZERO;
7905 }
7906 
7907 static bool arg_type_is_release(enum bpf_arg_type type)
7908 {
7909 	return type & OBJ_RELEASE;
7910 }
7911 
7912 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7913 {
7914 	return base_type(type) == ARG_PTR_TO_DYNPTR;
7915 }
7916 
7917 static int int_ptr_type_to_size(enum bpf_arg_type type)
7918 {
7919 	if (type == ARG_PTR_TO_INT)
7920 		return sizeof(u32);
7921 	else if (type == ARG_PTR_TO_LONG)
7922 		return sizeof(u64);
7923 
7924 	return -EINVAL;
7925 }
7926 
7927 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7928 				 const struct bpf_call_arg_meta *meta,
7929 				 enum bpf_arg_type *arg_type)
7930 {
7931 	if (!meta->map_ptr) {
7932 		/* kernel subsystem misconfigured verifier */
7933 		verbose(env, "invalid map_ptr to access map->type\n");
7934 		return -EACCES;
7935 	}
7936 
7937 	switch (meta->map_ptr->map_type) {
7938 	case BPF_MAP_TYPE_SOCKMAP:
7939 	case BPF_MAP_TYPE_SOCKHASH:
7940 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7941 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7942 		} else {
7943 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
7944 			return -EINVAL;
7945 		}
7946 		break;
7947 	case BPF_MAP_TYPE_BLOOM_FILTER:
7948 		if (meta->func_id == BPF_FUNC_map_peek_elem)
7949 			*arg_type = ARG_PTR_TO_MAP_VALUE;
7950 		break;
7951 	default:
7952 		break;
7953 	}
7954 	return 0;
7955 }
7956 
7957 struct bpf_reg_types {
7958 	const enum bpf_reg_type types[10];
7959 	u32 *btf_id;
7960 };
7961 
7962 static const struct bpf_reg_types sock_types = {
7963 	.types = {
7964 		PTR_TO_SOCK_COMMON,
7965 		PTR_TO_SOCKET,
7966 		PTR_TO_TCP_SOCK,
7967 		PTR_TO_XDP_SOCK,
7968 	},
7969 };
7970 
7971 #ifdef CONFIG_NET
7972 static const struct bpf_reg_types btf_id_sock_common_types = {
7973 	.types = {
7974 		PTR_TO_SOCK_COMMON,
7975 		PTR_TO_SOCKET,
7976 		PTR_TO_TCP_SOCK,
7977 		PTR_TO_XDP_SOCK,
7978 		PTR_TO_BTF_ID,
7979 		PTR_TO_BTF_ID | PTR_TRUSTED,
7980 	},
7981 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7982 };
7983 #endif
7984 
7985 static const struct bpf_reg_types mem_types = {
7986 	.types = {
7987 		PTR_TO_STACK,
7988 		PTR_TO_PACKET,
7989 		PTR_TO_PACKET_META,
7990 		PTR_TO_MAP_KEY,
7991 		PTR_TO_MAP_VALUE,
7992 		PTR_TO_MEM,
7993 		PTR_TO_MEM | MEM_RINGBUF,
7994 		PTR_TO_BUF,
7995 		PTR_TO_BTF_ID | PTR_TRUSTED,
7996 	},
7997 };
7998 
7999 static const struct bpf_reg_types int_ptr_types = {
8000 	.types = {
8001 		PTR_TO_STACK,
8002 		PTR_TO_PACKET,
8003 		PTR_TO_PACKET_META,
8004 		PTR_TO_MAP_KEY,
8005 		PTR_TO_MAP_VALUE,
8006 	},
8007 };
8008 
8009 static const struct bpf_reg_types spin_lock_types = {
8010 	.types = {
8011 		PTR_TO_MAP_VALUE,
8012 		PTR_TO_BTF_ID | MEM_ALLOC,
8013 	}
8014 };
8015 
8016 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8017 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8018 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8019 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8020 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8021 static const struct bpf_reg_types btf_ptr_types = {
8022 	.types = {
8023 		PTR_TO_BTF_ID,
8024 		PTR_TO_BTF_ID | PTR_TRUSTED,
8025 		PTR_TO_BTF_ID | MEM_RCU,
8026 	},
8027 };
8028 static const struct bpf_reg_types percpu_btf_ptr_types = {
8029 	.types = {
8030 		PTR_TO_BTF_ID | MEM_PERCPU,
8031 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8032 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8033 	}
8034 };
8035 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8036 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8037 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8038 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8039 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8040 static const struct bpf_reg_types dynptr_types = {
8041 	.types = {
8042 		PTR_TO_STACK,
8043 		CONST_PTR_TO_DYNPTR,
8044 	}
8045 };
8046 
8047 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8048 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8049 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8050 	[ARG_CONST_SIZE]		= &scalar_types,
8051 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8052 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8053 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8054 	[ARG_PTR_TO_CTX]		= &context_types,
8055 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8056 #ifdef CONFIG_NET
8057 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8058 #endif
8059 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8060 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8061 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8062 	[ARG_PTR_TO_MEM]		= &mem_types,
8063 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8064 	[ARG_PTR_TO_INT]		= &int_ptr_types,
8065 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
8066 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8067 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8068 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8069 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8070 	[ARG_PTR_TO_TIMER]		= &timer_types,
8071 	[ARG_PTR_TO_KPTR]		= &kptr_types,
8072 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8073 };
8074 
8075 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8076 			  enum bpf_arg_type arg_type,
8077 			  const u32 *arg_btf_id,
8078 			  struct bpf_call_arg_meta *meta)
8079 {
8080 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8081 	enum bpf_reg_type expected, type = reg->type;
8082 	const struct bpf_reg_types *compatible;
8083 	int i, j;
8084 
8085 	compatible = compatible_reg_types[base_type(arg_type)];
8086 	if (!compatible) {
8087 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8088 		return -EFAULT;
8089 	}
8090 
8091 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8092 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8093 	 *
8094 	 * Same for MAYBE_NULL:
8095 	 *
8096 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8097 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8098 	 *
8099 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8100 	 *
8101 	 * Therefore we fold these flags depending on the arg_type before comparison.
8102 	 */
8103 	if (arg_type & MEM_RDONLY)
8104 		type &= ~MEM_RDONLY;
8105 	if (arg_type & PTR_MAYBE_NULL)
8106 		type &= ~PTR_MAYBE_NULL;
8107 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8108 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8109 
8110 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) {
8111 		type &= ~MEM_ALLOC;
8112 		type &= ~MEM_PERCPU;
8113 	}
8114 
8115 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8116 		expected = compatible->types[i];
8117 		if (expected == NOT_INIT)
8118 			break;
8119 
8120 		if (type == expected)
8121 			goto found;
8122 	}
8123 
8124 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8125 	for (j = 0; j + 1 < i; j++)
8126 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8127 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8128 	return -EACCES;
8129 
8130 found:
8131 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8132 		return 0;
8133 
8134 	if (compatible == &mem_types) {
8135 		if (!(arg_type & MEM_RDONLY)) {
8136 			verbose(env,
8137 				"%s() may write into memory pointed by R%d type=%s\n",
8138 				func_id_name(meta->func_id),
8139 				regno, reg_type_str(env, reg->type));
8140 			return -EACCES;
8141 		}
8142 		return 0;
8143 	}
8144 
8145 	switch ((int)reg->type) {
8146 	case PTR_TO_BTF_ID:
8147 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8148 	case PTR_TO_BTF_ID | MEM_RCU:
8149 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8150 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8151 	{
8152 		/* For bpf_sk_release, it needs to match against first member
8153 		 * 'struct sock_common', hence make an exception for it. This
8154 		 * allows bpf_sk_release to work for multiple socket types.
8155 		 */
8156 		bool strict_type_match = arg_type_is_release(arg_type) &&
8157 					 meta->func_id != BPF_FUNC_sk_release;
8158 
8159 		if (type_may_be_null(reg->type) &&
8160 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8161 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8162 			return -EACCES;
8163 		}
8164 
8165 		if (!arg_btf_id) {
8166 			if (!compatible->btf_id) {
8167 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8168 				return -EFAULT;
8169 			}
8170 			arg_btf_id = compatible->btf_id;
8171 		}
8172 
8173 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8174 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8175 				return -EACCES;
8176 		} else {
8177 			if (arg_btf_id == BPF_PTR_POISON) {
8178 				verbose(env, "verifier internal error:");
8179 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8180 					regno);
8181 				return -EACCES;
8182 			}
8183 
8184 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8185 						  btf_vmlinux, *arg_btf_id,
8186 						  strict_type_match)) {
8187 				verbose(env, "R%d is of type %s but %s is expected\n",
8188 					regno, btf_type_name(reg->btf, reg->btf_id),
8189 					btf_type_name(btf_vmlinux, *arg_btf_id));
8190 				return -EACCES;
8191 			}
8192 		}
8193 		break;
8194 	}
8195 	case PTR_TO_BTF_ID | MEM_ALLOC:
8196 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8197 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8198 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8199 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8200 			return -EFAULT;
8201 		}
8202 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8203 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8204 				return -EACCES;
8205 		}
8206 		break;
8207 	case PTR_TO_BTF_ID | MEM_PERCPU:
8208 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8209 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8210 		/* Handled by helper specific checks */
8211 		break;
8212 	default:
8213 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8214 		return -EFAULT;
8215 	}
8216 	return 0;
8217 }
8218 
8219 static struct btf_field *
8220 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8221 {
8222 	struct btf_field *field;
8223 	struct btf_record *rec;
8224 
8225 	rec = reg_btf_record(reg);
8226 	if (!rec)
8227 		return NULL;
8228 
8229 	field = btf_record_find(rec, off, fields);
8230 	if (!field)
8231 		return NULL;
8232 
8233 	return field;
8234 }
8235 
8236 int check_func_arg_reg_off(struct bpf_verifier_env *env,
8237 			   const struct bpf_reg_state *reg, int regno,
8238 			   enum bpf_arg_type arg_type)
8239 {
8240 	u32 type = reg->type;
8241 
8242 	/* When referenced register is passed to release function, its fixed
8243 	 * offset must be 0.
8244 	 *
8245 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8246 	 * meta->release_regno.
8247 	 */
8248 	if (arg_type_is_release(arg_type)) {
8249 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8250 		 * may not directly point to the object being released, but to
8251 		 * dynptr pointing to such object, which might be at some offset
8252 		 * on the stack. In that case, we simply to fallback to the
8253 		 * default handling.
8254 		 */
8255 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8256 			return 0;
8257 
8258 		/* Doing check_ptr_off_reg check for the offset will catch this
8259 		 * because fixed_off_ok is false, but checking here allows us
8260 		 * to give the user a better error message.
8261 		 */
8262 		if (reg->off) {
8263 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8264 				regno);
8265 			return -EINVAL;
8266 		}
8267 		return __check_ptr_off_reg(env, reg, regno, false);
8268 	}
8269 
8270 	switch (type) {
8271 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8272 	case PTR_TO_STACK:
8273 	case PTR_TO_PACKET:
8274 	case PTR_TO_PACKET_META:
8275 	case PTR_TO_MAP_KEY:
8276 	case PTR_TO_MAP_VALUE:
8277 	case PTR_TO_MEM:
8278 	case PTR_TO_MEM | MEM_RDONLY:
8279 	case PTR_TO_MEM | MEM_RINGBUF:
8280 	case PTR_TO_BUF:
8281 	case PTR_TO_BUF | MEM_RDONLY:
8282 	case SCALAR_VALUE:
8283 		return 0;
8284 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8285 	 * fixed offset.
8286 	 */
8287 	case PTR_TO_BTF_ID:
8288 	case PTR_TO_BTF_ID | MEM_ALLOC:
8289 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8290 	case PTR_TO_BTF_ID | MEM_RCU:
8291 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8292 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8293 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8294 		 * its fixed offset must be 0. In the other cases, fixed offset
8295 		 * can be non-zero. This was already checked above. So pass
8296 		 * fixed_off_ok as true to allow fixed offset for all other
8297 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8298 		 * still need to do checks instead of returning.
8299 		 */
8300 		return __check_ptr_off_reg(env, reg, regno, true);
8301 	default:
8302 		return __check_ptr_off_reg(env, reg, regno, false);
8303 	}
8304 }
8305 
8306 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8307 						const struct bpf_func_proto *fn,
8308 						struct bpf_reg_state *regs)
8309 {
8310 	struct bpf_reg_state *state = NULL;
8311 	int i;
8312 
8313 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8314 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8315 			if (state) {
8316 				verbose(env, "verifier internal error: multiple dynptr args\n");
8317 				return NULL;
8318 			}
8319 			state = &regs[BPF_REG_1 + i];
8320 		}
8321 
8322 	if (!state)
8323 		verbose(env, "verifier internal error: no dynptr arg found\n");
8324 
8325 	return state;
8326 }
8327 
8328 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8329 {
8330 	struct bpf_func_state *state = func(env, reg);
8331 	int spi;
8332 
8333 	if (reg->type == CONST_PTR_TO_DYNPTR)
8334 		return reg->id;
8335 	spi = dynptr_get_spi(env, reg);
8336 	if (spi < 0)
8337 		return spi;
8338 	return state->stack[spi].spilled_ptr.id;
8339 }
8340 
8341 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8342 {
8343 	struct bpf_func_state *state = func(env, reg);
8344 	int spi;
8345 
8346 	if (reg->type == CONST_PTR_TO_DYNPTR)
8347 		return reg->ref_obj_id;
8348 	spi = dynptr_get_spi(env, reg);
8349 	if (spi < 0)
8350 		return spi;
8351 	return state->stack[spi].spilled_ptr.ref_obj_id;
8352 }
8353 
8354 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8355 					    struct bpf_reg_state *reg)
8356 {
8357 	struct bpf_func_state *state = func(env, reg);
8358 	int spi;
8359 
8360 	if (reg->type == CONST_PTR_TO_DYNPTR)
8361 		return reg->dynptr.type;
8362 
8363 	spi = __get_spi(reg->off);
8364 	if (spi < 0) {
8365 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8366 		return BPF_DYNPTR_TYPE_INVALID;
8367 	}
8368 
8369 	return state->stack[spi].spilled_ptr.dynptr.type;
8370 }
8371 
8372 static int check_reg_const_str(struct bpf_verifier_env *env,
8373 			       struct bpf_reg_state *reg, u32 regno)
8374 {
8375 	struct bpf_map *map = reg->map_ptr;
8376 	int err;
8377 	int map_off;
8378 	u64 map_addr;
8379 	char *str_ptr;
8380 
8381 	if (reg->type != PTR_TO_MAP_VALUE)
8382 		return -EINVAL;
8383 
8384 	if (!bpf_map_is_rdonly(map)) {
8385 		verbose(env, "R%d does not point to a readonly map'\n", regno);
8386 		return -EACCES;
8387 	}
8388 
8389 	if (!tnum_is_const(reg->var_off)) {
8390 		verbose(env, "R%d is not a constant address'\n", regno);
8391 		return -EACCES;
8392 	}
8393 
8394 	if (!map->ops->map_direct_value_addr) {
8395 		verbose(env, "no direct value access support for this map type\n");
8396 		return -EACCES;
8397 	}
8398 
8399 	err = check_map_access(env, regno, reg->off,
8400 			       map->value_size - reg->off, false,
8401 			       ACCESS_HELPER);
8402 	if (err)
8403 		return err;
8404 
8405 	map_off = reg->off + reg->var_off.value;
8406 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8407 	if (err) {
8408 		verbose(env, "direct value access on string failed\n");
8409 		return err;
8410 	}
8411 
8412 	str_ptr = (char *)(long)(map_addr);
8413 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8414 		verbose(env, "string is not zero-terminated\n");
8415 		return -EINVAL;
8416 	}
8417 	return 0;
8418 }
8419 
8420 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8421 			  struct bpf_call_arg_meta *meta,
8422 			  const struct bpf_func_proto *fn,
8423 			  int insn_idx)
8424 {
8425 	u32 regno = BPF_REG_1 + arg;
8426 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8427 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8428 	enum bpf_reg_type type = reg->type;
8429 	u32 *arg_btf_id = NULL;
8430 	int err = 0;
8431 
8432 	if (arg_type == ARG_DONTCARE)
8433 		return 0;
8434 
8435 	err = check_reg_arg(env, regno, SRC_OP);
8436 	if (err)
8437 		return err;
8438 
8439 	if (arg_type == ARG_ANYTHING) {
8440 		if (is_pointer_value(env, regno)) {
8441 			verbose(env, "R%d leaks addr into helper function\n",
8442 				regno);
8443 			return -EACCES;
8444 		}
8445 		return 0;
8446 	}
8447 
8448 	if (type_is_pkt_pointer(type) &&
8449 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8450 		verbose(env, "helper access to the packet is not allowed\n");
8451 		return -EACCES;
8452 	}
8453 
8454 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8455 		err = resolve_map_arg_type(env, meta, &arg_type);
8456 		if (err)
8457 			return err;
8458 	}
8459 
8460 	if (register_is_null(reg) && type_may_be_null(arg_type))
8461 		/* A NULL register has a SCALAR_VALUE type, so skip
8462 		 * type checking.
8463 		 */
8464 		goto skip_type_check;
8465 
8466 	/* arg_btf_id and arg_size are in a union. */
8467 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8468 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8469 		arg_btf_id = fn->arg_btf_id[arg];
8470 
8471 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8472 	if (err)
8473 		return err;
8474 
8475 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8476 	if (err)
8477 		return err;
8478 
8479 skip_type_check:
8480 	if (arg_type_is_release(arg_type)) {
8481 		if (arg_type_is_dynptr(arg_type)) {
8482 			struct bpf_func_state *state = func(env, reg);
8483 			int spi;
8484 
8485 			/* Only dynptr created on stack can be released, thus
8486 			 * the get_spi and stack state checks for spilled_ptr
8487 			 * should only be done before process_dynptr_func for
8488 			 * PTR_TO_STACK.
8489 			 */
8490 			if (reg->type == PTR_TO_STACK) {
8491 				spi = dynptr_get_spi(env, reg);
8492 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8493 					verbose(env, "arg %d is an unacquired reference\n", regno);
8494 					return -EINVAL;
8495 				}
8496 			} else {
8497 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8498 				return -EINVAL;
8499 			}
8500 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8501 			verbose(env, "R%d must be referenced when passed to release function\n",
8502 				regno);
8503 			return -EINVAL;
8504 		}
8505 		if (meta->release_regno) {
8506 			verbose(env, "verifier internal error: more than one release argument\n");
8507 			return -EFAULT;
8508 		}
8509 		meta->release_regno = regno;
8510 	}
8511 
8512 	if (reg->ref_obj_id) {
8513 		if (meta->ref_obj_id) {
8514 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8515 				regno, reg->ref_obj_id,
8516 				meta->ref_obj_id);
8517 			return -EFAULT;
8518 		}
8519 		meta->ref_obj_id = reg->ref_obj_id;
8520 	}
8521 
8522 	switch (base_type(arg_type)) {
8523 	case ARG_CONST_MAP_PTR:
8524 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8525 		if (meta->map_ptr) {
8526 			/* Use map_uid (which is unique id of inner map) to reject:
8527 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8528 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8529 			 * if (inner_map1 && inner_map2) {
8530 			 *     timer = bpf_map_lookup_elem(inner_map1);
8531 			 *     if (timer)
8532 			 *         // mismatch would have been allowed
8533 			 *         bpf_timer_init(timer, inner_map2);
8534 			 * }
8535 			 *
8536 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8537 			 */
8538 			if (meta->map_ptr != reg->map_ptr ||
8539 			    meta->map_uid != reg->map_uid) {
8540 				verbose(env,
8541 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8542 					meta->map_uid, reg->map_uid);
8543 				return -EINVAL;
8544 			}
8545 		}
8546 		meta->map_ptr = reg->map_ptr;
8547 		meta->map_uid = reg->map_uid;
8548 		break;
8549 	case ARG_PTR_TO_MAP_KEY:
8550 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8551 		 * check that [key, key + map->key_size) are within
8552 		 * stack limits and initialized
8553 		 */
8554 		if (!meta->map_ptr) {
8555 			/* in function declaration map_ptr must come before
8556 			 * map_key, so that it's verified and known before
8557 			 * we have to check map_key here. Otherwise it means
8558 			 * that kernel subsystem misconfigured verifier
8559 			 */
8560 			verbose(env, "invalid map_ptr to access map->key\n");
8561 			return -EACCES;
8562 		}
8563 		err = check_helper_mem_access(env, regno,
8564 					      meta->map_ptr->key_size, false,
8565 					      NULL);
8566 		break;
8567 	case ARG_PTR_TO_MAP_VALUE:
8568 		if (type_may_be_null(arg_type) && register_is_null(reg))
8569 			return 0;
8570 
8571 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8572 		 * check [value, value + map->value_size) validity
8573 		 */
8574 		if (!meta->map_ptr) {
8575 			/* kernel subsystem misconfigured verifier */
8576 			verbose(env, "invalid map_ptr to access map->value\n");
8577 			return -EACCES;
8578 		}
8579 		meta->raw_mode = arg_type & MEM_UNINIT;
8580 		err = check_helper_mem_access(env, regno,
8581 					      meta->map_ptr->value_size, false,
8582 					      meta);
8583 		break;
8584 	case ARG_PTR_TO_PERCPU_BTF_ID:
8585 		if (!reg->btf_id) {
8586 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8587 			return -EACCES;
8588 		}
8589 		meta->ret_btf = reg->btf;
8590 		meta->ret_btf_id = reg->btf_id;
8591 		break;
8592 	case ARG_PTR_TO_SPIN_LOCK:
8593 		if (in_rbtree_lock_required_cb(env)) {
8594 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8595 			return -EACCES;
8596 		}
8597 		if (meta->func_id == BPF_FUNC_spin_lock) {
8598 			err = process_spin_lock(env, regno, true);
8599 			if (err)
8600 				return err;
8601 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8602 			err = process_spin_lock(env, regno, false);
8603 			if (err)
8604 				return err;
8605 		} else {
8606 			verbose(env, "verifier internal error\n");
8607 			return -EFAULT;
8608 		}
8609 		break;
8610 	case ARG_PTR_TO_TIMER:
8611 		err = process_timer_func(env, regno, meta);
8612 		if (err)
8613 			return err;
8614 		break;
8615 	case ARG_PTR_TO_FUNC:
8616 		meta->subprogno = reg->subprogno;
8617 		break;
8618 	case ARG_PTR_TO_MEM:
8619 		/* The access to this pointer is only checked when we hit the
8620 		 * next is_mem_size argument below.
8621 		 */
8622 		meta->raw_mode = arg_type & MEM_UNINIT;
8623 		if (arg_type & MEM_FIXED_SIZE) {
8624 			err = check_helper_mem_access(env, regno,
8625 						      fn->arg_size[arg], false,
8626 						      meta);
8627 		}
8628 		break;
8629 	case ARG_CONST_SIZE:
8630 		err = check_mem_size_reg(env, reg, regno, false, meta);
8631 		break;
8632 	case ARG_CONST_SIZE_OR_ZERO:
8633 		err = check_mem_size_reg(env, reg, regno, true, meta);
8634 		break;
8635 	case ARG_PTR_TO_DYNPTR:
8636 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8637 		if (err)
8638 			return err;
8639 		break;
8640 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8641 		if (!tnum_is_const(reg->var_off)) {
8642 			verbose(env, "R%d is not a known constant'\n",
8643 				regno);
8644 			return -EACCES;
8645 		}
8646 		meta->mem_size = reg->var_off.value;
8647 		err = mark_chain_precision(env, regno);
8648 		if (err)
8649 			return err;
8650 		break;
8651 	case ARG_PTR_TO_INT:
8652 	case ARG_PTR_TO_LONG:
8653 	{
8654 		int size = int_ptr_type_to_size(arg_type);
8655 
8656 		err = check_helper_mem_access(env, regno, size, false, meta);
8657 		if (err)
8658 			return err;
8659 		err = check_ptr_alignment(env, reg, 0, size, true);
8660 		break;
8661 	}
8662 	case ARG_PTR_TO_CONST_STR:
8663 	{
8664 		err = check_reg_const_str(env, reg, regno);
8665 		if (err)
8666 			return err;
8667 		break;
8668 	}
8669 	case ARG_PTR_TO_KPTR:
8670 		err = process_kptr_func(env, regno, meta);
8671 		if (err)
8672 			return err;
8673 		break;
8674 	}
8675 
8676 	return err;
8677 }
8678 
8679 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8680 {
8681 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8682 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8683 
8684 	if (func_id != BPF_FUNC_map_update_elem)
8685 		return false;
8686 
8687 	/* It's not possible to get access to a locked struct sock in these
8688 	 * contexts, so updating is safe.
8689 	 */
8690 	switch (type) {
8691 	case BPF_PROG_TYPE_TRACING:
8692 		if (eatype == BPF_TRACE_ITER)
8693 			return true;
8694 		break;
8695 	case BPF_PROG_TYPE_SOCKET_FILTER:
8696 	case BPF_PROG_TYPE_SCHED_CLS:
8697 	case BPF_PROG_TYPE_SCHED_ACT:
8698 	case BPF_PROG_TYPE_XDP:
8699 	case BPF_PROG_TYPE_SK_REUSEPORT:
8700 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8701 	case BPF_PROG_TYPE_SK_LOOKUP:
8702 		return true;
8703 	default:
8704 		break;
8705 	}
8706 
8707 	verbose(env, "cannot update sockmap in this context\n");
8708 	return false;
8709 }
8710 
8711 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8712 {
8713 	return env->prog->jit_requested &&
8714 	       bpf_jit_supports_subprog_tailcalls();
8715 }
8716 
8717 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8718 					struct bpf_map *map, int func_id)
8719 {
8720 	if (!map)
8721 		return 0;
8722 
8723 	/* We need a two way check, first is from map perspective ... */
8724 	switch (map->map_type) {
8725 	case BPF_MAP_TYPE_PROG_ARRAY:
8726 		if (func_id != BPF_FUNC_tail_call)
8727 			goto error;
8728 		break;
8729 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8730 		if (func_id != BPF_FUNC_perf_event_read &&
8731 		    func_id != BPF_FUNC_perf_event_output &&
8732 		    func_id != BPF_FUNC_skb_output &&
8733 		    func_id != BPF_FUNC_perf_event_read_value &&
8734 		    func_id != BPF_FUNC_xdp_output)
8735 			goto error;
8736 		break;
8737 	case BPF_MAP_TYPE_RINGBUF:
8738 		if (func_id != BPF_FUNC_ringbuf_output &&
8739 		    func_id != BPF_FUNC_ringbuf_reserve &&
8740 		    func_id != BPF_FUNC_ringbuf_query &&
8741 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8742 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8743 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8744 			goto error;
8745 		break;
8746 	case BPF_MAP_TYPE_USER_RINGBUF:
8747 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8748 			goto error;
8749 		break;
8750 	case BPF_MAP_TYPE_STACK_TRACE:
8751 		if (func_id != BPF_FUNC_get_stackid)
8752 			goto error;
8753 		break;
8754 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8755 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8756 		    func_id != BPF_FUNC_current_task_under_cgroup)
8757 			goto error;
8758 		break;
8759 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8760 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8761 		if (func_id != BPF_FUNC_get_local_storage)
8762 			goto error;
8763 		break;
8764 	case BPF_MAP_TYPE_DEVMAP:
8765 	case BPF_MAP_TYPE_DEVMAP_HASH:
8766 		if (func_id != BPF_FUNC_redirect_map &&
8767 		    func_id != BPF_FUNC_map_lookup_elem)
8768 			goto error;
8769 		break;
8770 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8771 	 * appear.
8772 	 */
8773 	case BPF_MAP_TYPE_CPUMAP:
8774 		if (func_id != BPF_FUNC_redirect_map)
8775 			goto error;
8776 		break;
8777 	case BPF_MAP_TYPE_XSKMAP:
8778 		if (func_id != BPF_FUNC_redirect_map &&
8779 		    func_id != BPF_FUNC_map_lookup_elem)
8780 			goto error;
8781 		break;
8782 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8783 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8784 		if (func_id != BPF_FUNC_map_lookup_elem)
8785 			goto error;
8786 		break;
8787 	case BPF_MAP_TYPE_SOCKMAP:
8788 		if (func_id != BPF_FUNC_sk_redirect_map &&
8789 		    func_id != BPF_FUNC_sock_map_update &&
8790 		    func_id != BPF_FUNC_map_delete_elem &&
8791 		    func_id != BPF_FUNC_msg_redirect_map &&
8792 		    func_id != BPF_FUNC_sk_select_reuseport &&
8793 		    func_id != BPF_FUNC_map_lookup_elem &&
8794 		    !may_update_sockmap(env, func_id))
8795 			goto error;
8796 		break;
8797 	case BPF_MAP_TYPE_SOCKHASH:
8798 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8799 		    func_id != BPF_FUNC_sock_hash_update &&
8800 		    func_id != BPF_FUNC_map_delete_elem &&
8801 		    func_id != BPF_FUNC_msg_redirect_hash &&
8802 		    func_id != BPF_FUNC_sk_select_reuseport &&
8803 		    func_id != BPF_FUNC_map_lookup_elem &&
8804 		    !may_update_sockmap(env, func_id))
8805 			goto error;
8806 		break;
8807 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8808 		if (func_id != BPF_FUNC_sk_select_reuseport)
8809 			goto error;
8810 		break;
8811 	case BPF_MAP_TYPE_QUEUE:
8812 	case BPF_MAP_TYPE_STACK:
8813 		if (func_id != BPF_FUNC_map_peek_elem &&
8814 		    func_id != BPF_FUNC_map_pop_elem &&
8815 		    func_id != BPF_FUNC_map_push_elem)
8816 			goto error;
8817 		break;
8818 	case BPF_MAP_TYPE_SK_STORAGE:
8819 		if (func_id != BPF_FUNC_sk_storage_get &&
8820 		    func_id != BPF_FUNC_sk_storage_delete &&
8821 		    func_id != BPF_FUNC_kptr_xchg)
8822 			goto error;
8823 		break;
8824 	case BPF_MAP_TYPE_INODE_STORAGE:
8825 		if (func_id != BPF_FUNC_inode_storage_get &&
8826 		    func_id != BPF_FUNC_inode_storage_delete &&
8827 		    func_id != BPF_FUNC_kptr_xchg)
8828 			goto error;
8829 		break;
8830 	case BPF_MAP_TYPE_TASK_STORAGE:
8831 		if (func_id != BPF_FUNC_task_storage_get &&
8832 		    func_id != BPF_FUNC_task_storage_delete &&
8833 		    func_id != BPF_FUNC_kptr_xchg)
8834 			goto error;
8835 		break;
8836 	case BPF_MAP_TYPE_CGRP_STORAGE:
8837 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8838 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8839 		    func_id != BPF_FUNC_kptr_xchg)
8840 			goto error;
8841 		break;
8842 	case BPF_MAP_TYPE_BLOOM_FILTER:
8843 		if (func_id != BPF_FUNC_map_peek_elem &&
8844 		    func_id != BPF_FUNC_map_push_elem)
8845 			goto error;
8846 		break;
8847 	default:
8848 		break;
8849 	}
8850 
8851 	/* ... and second from the function itself. */
8852 	switch (func_id) {
8853 	case BPF_FUNC_tail_call:
8854 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8855 			goto error;
8856 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8857 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8858 			return -EINVAL;
8859 		}
8860 		break;
8861 	case BPF_FUNC_perf_event_read:
8862 	case BPF_FUNC_perf_event_output:
8863 	case BPF_FUNC_perf_event_read_value:
8864 	case BPF_FUNC_skb_output:
8865 	case BPF_FUNC_xdp_output:
8866 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8867 			goto error;
8868 		break;
8869 	case BPF_FUNC_ringbuf_output:
8870 	case BPF_FUNC_ringbuf_reserve:
8871 	case BPF_FUNC_ringbuf_query:
8872 	case BPF_FUNC_ringbuf_reserve_dynptr:
8873 	case BPF_FUNC_ringbuf_submit_dynptr:
8874 	case BPF_FUNC_ringbuf_discard_dynptr:
8875 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8876 			goto error;
8877 		break;
8878 	case BPF_FUNC_user_ringbuf_drain:
8879 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8880 			goto error;
8881 		break;
8882 	case BPF_FUNC_get_stackid:
8883 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8884 			goto error;
8885 		break;
8886 	case BPF_FUNC_current_task_under_cgroup:
8887 	case BPF_FUNC_skb_under_cgroup:
8888 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8889 			goto error;
8890 		break;
8891 	case BPF_FUNC_redirect_map:
8892 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8893 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8894 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8895 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8896 			goto error;
8897 		break;
8898 	case BPF_FUNC_sk_redirect_map:
8899 	case BPF_FUNC_msg_redirect_map:
8900 	case BPF_FUNC_sock_map_update:
8901 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8902 			goto error;
8903 		break;
8904 	case BPF_FUNC_sk_redirect_hash:
8905 	case BPF_FUNC_msg_redirect_hash:
8906 	case BPF_FUNC_sock_hash_update:
8907 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8908 			goto error;
8909 		break;
8910 	case BPF_FUNC_get_local_storage:
8911 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8912 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8913 			goto error;
8914 		break;
8915 	case BPF_FUNC_sk_select_reuseport:
8916 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8917 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8918 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8919 			goto error;
8920 		break;
8921 	case BPF_FUNC_map_pop_elem:
8922 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8923 		    map->map_type != BPF_MAP_TYPE_STACK)
8924 			goto error;
8925 		break;
8926 	case BPF_FUNC_map_peek_elem:
8927 	case BPF_FUNC_map_push_elem:
8928 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8929 		    map->map_type != BPF_MAP_TYPE_STACK &&
8930 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8931 			goto error;
8932 		break;
8933 	case BPF_FUNC_map_lookup_percpu_elem:
8934 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8935 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8936 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8937 			goto error;
8938 		break;
8939 	case BPF_FUNC_sk_storage_get:
8940 	case BPF_FUNC_sk_storage_delete:
8941 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8942 			goto error;
8943 		break;
8944 	case BPF_FUNC_inode_storage_get:
8945 	case BPF_FUNC_inode_storage_delete:
8946 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8947 			goto error;
8948 		break;
8949 	case BPF_FUNC_task_storage_get:
8950 	case BPF_FUNC_task_storage_delete:
8951 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8952 			goto error;
8953 		break;
8954 	case BPF_FUNC_cgrp_storage_get:
8955 	case BPF_FUNC_cgrp_storage_delete:
8956 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8957 			goto error;
8958 		break;
8959 	default:
8960 		break;
8961 	}
8962 
8963 	return 0;
8964 error:
8965 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
8966 		map->map_type, func_id_name(func_id), func_id);
8967 	return -EINVAL;
8968 }
8969 
8970 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8971 {
8972 	int count = 0;
8973 
8974 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8975 		count++;
8976 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8977 		count++;
8978 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8979 		count++;
8980 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8981 		count++;
8982 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8983 		count++;
8984 
8985 	/* We only support one arg being in raw mode at the moment,
8986 	 * which is sufficient for the helper functions we have
8987 	 * right now.
8988 	 */
8989 	return count <= 1;
8990 }
8991 
8992 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8993 {
8994 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8995 	bool has_size = fn->arg_size[arg] != 0;
8996 	bool is_next_size = false;
8997 
8998 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8999 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9000 
9001 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9002 		return is_next_size;
9003 
9004 	return has_size == is_next_size || is_next_size == is_fixed;
9005 }
9006 
9007 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9008 {
9009 	/* bpf_xxx(..., buf, len) call will access 'len'
9010 	 * bytes from memory 'buf'. Both arg types need
9011 	 * to be paired, so make sure there's no buggy
9012 	 * helper function specification.
9013 	 */
9014 	if (arg_type_is_mem_size(fn->arg1_type) ||
9015 	    check_args_pair_invalid(fn, 0) ||
9016 	    check_args_pair_invalid(fn, 1) ||
9017 	    check_args_pair_invalid(fn, 2) ||
9018 	    check_args_pair_invalid(fn, 3) ||
9019 	    check_args_pair_invalid(fn, 4))
9020 		return false;
9021 
9022 	return true;
9023 }
9024 
9025 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9026 {
9027 	int i;
9028 
9029 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9030 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9031 			return !!fn->arg_btf_id[i];
9032 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9033 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9034 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9035 		    /* arg_btf_id and arg_size are in a union. */
9036 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9037 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9038 			return false;
9039 	}
9040 
9041 	return true;
9042 }
9043 
9044 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9045 {
9046 	return check_raw_mode_ok(fn) &&
9047 	       check_arg_pair_ok(fn) &&
9048 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9049 }
9050 
9051 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9052  * are now invalid, so turn them into unknown SCALAR_VALUE.
9053  *
9054  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9055  * since these slices point to packet data.
9056  */
9057 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9058 {
9059 	struct bpf_func_state *state;
9060 	struct bpf_reg_state *reg;
9061 
9062 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9063 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9064 			mark_reg_invalid(env, reg);
9065 	}));
9066 }
9067 
9068 enum {
9069 	AT_PKT_END = -1,
9070 	BEYOND_PKT_END = -2,
9071 };
9072 
9073 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9074 {
9075 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9076 	struct bpf_reg_state *reg = &state->regs[regn];
9077 
9078 	if (reg->type != PTR_TO_PACKET)
9079 		/* PTR_TO_PACKET_META is not supported yet */
9080 		return;
9081 
9082 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9083 	 * How far beyond pkt_end it goes is unknown.
9084 	 * if (!range_open) it's the case of pkt >= pkt_end
9085 	 * if (range_open) it's the case of pkt > pkt_end
9086 	 * hence this pointer is at least 1 byte bigger than pkt_end
9087 	 */
9088 	if (range_open)
9089 		reg->range = BEYOND_PKT_END;
9090 	else
9091 		reg->range = AT_PKT_END;
9092 }
9093 
9094 /* The pointer with the specified id has released its reference to kernel
9095  * resources. Identify all copies of the same pointer and clear the reference.
9096  */
9097 static int release_reference(struct bpf_verifier_env *env,
9098 			     int ref_obj_id)
9099 {
9100 	struct bpf_func_state *state;
9101 	struct bpf_reg_state *reg;
9102 	int err;
9103 
9104 	err = release_reference_state(cur_func(env), ref_obj_id);
9105 	if (err)
9106 		return err;
9107 
9108 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9109 		if (reg->ref_obj_id == ref_obj_id)
9110 			mark_reg_invalid(env, reg);
9111 	}));
9112 
9113 	return 0;
9114 }
9115 
9116 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9117 {
9118 	struct bpf_func_state *unused;
9119 	struct bpf_reg_state *reg;
9120 
9121 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9122 		if (type_is_non_owning_ref(reg->type))
9123 			mark_reg_invalid(env, reg);
9124 	}));
9125 }
9126 
9127 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9128 				    struct bpf_reg_state *regs)
9129 {
9130 	int i;
9131 
9132 	/* after the call registers r0 - r5 were scratched */
9133 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9134 		mark_reg_not_init(env, regs, caller_saved[i]);
9135 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9136 	}
9137 }
9138 
9139 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9140 				   struct bpf_func_state *caller,
9141 				   struct bpf_func_state *callee,
9142 				   int insn_idx);
9143 
9144 static int set_callee_state(struct bpf_verifier_env *env,
9145 			    struct bpf_func_state *caller,
9146 			    struct bpf_func_state *callee, int insn_idx);
9147 
9148 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9149 			    set_callee_state_fn set_callee_state_cb,
9150 			    struct bpf_verifier_state *state)
9151 {
9152 	struct bpf_func_state *caller, *callee;
9153 	int err;
9154 
9155 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9156 		verbose(env, "the call stack of %d frames is too deep\n",
9157 			state->curframe + 2);
9158 		return -E2BIG;
9159 	}
9160 
9161 	if (state->frame[state->curframe + 1]) {
9162 		verbose(env, "verifier bug. Frame %d already allocated\n",
9163 			state->curframe + 1);
9164 		return -EFAULT;
9165 	}
9166 
9167 	caller = state->frame[state->curframe];
9168 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9169 	if (!callee)
9170 		return -ENOMEM;
9171 	state->frame[state->curframe + 1] = callee;
9172 
9173 	/* callee cannot access r0, r6 - r9 for reading and has to write
9174 	 * into its own stack before reading from it.
9175 	 * callee can read/write into caller's stack
9176 	 */
9177 	init_func_state(env, callee,
9178 			/* remember the callsite, it will be used by bpf_exit */
9179 			callsite,
9180 			state->curframe + 1 /* frameno within this callchain */,
9181 			subprog /* subprog number within this prog */);
9182 	/* Transfer references to the callee */
9183 	err = copy_reference_state(callee, caller);
9184 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9185 	if (err)
9186 		goto err_out;
9187 
9188 	/* only increment it after check_reg_arg() finished */
9189 	state->curframe++;
9190 
9191 	return 0;
9192 
9193 err_out:
9194 	free_func_state(callee);
9195 	state->frame[state->curframe + 1] = NULL;
9196 	return err;
9197 }
9198 
9199 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9200 			      int insn_idx, int subprog,
9201 			      set_callee_state_fn set_callee_state_cb)
9202 {
9203 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9204 	struct bpf_func_state *caller, *callee;
9205 	int err;
9206 
9207 	caller = state->frame[state->curframe];
9208 	err = btf_check_subprog_call(env, subprog, caller->regs);
9209 	if (err == -EFAULT)
9210 		return err;
9211 
9212 	/* set_callee_state is used for direct subprog calls, but we are
9213 	 * interested in validating only BPF helpers that can call subprogs as
9214 	 * callbacks
9215 	 */
9216 	env->subprog_info[subprog].is_cb = true;
9217 	if (bpf_pseudo_kfunc_call(insn) &&
9218 	    !is_sync_callback_calling_kfunc(insn->imm)) {
9219 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9220 			func_id_name(insn->imm), insn->imm);
9221 		return -EFAULT;
9222 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9223 		   !is_callback_calling_function(insn->imm)) { /* helper */
9224 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9225 			func_id_name(insn->imm), insn->imm);
9226 		return -EFAULT;
9227 	}
9228 
9229 	if (insn->code == (BPF_JMP | BPF_CALL) &&
9230 	    insn->src_reg == 0 &&
9231 	    insn->imm == BPF_FUNC_timer_set_callback) {
9232 		struct bpf_verifier_state *async_cb;
9233 
9234 		/* there is no real recursion here. timer callbacks are async */
9235 		env->subprog_info[subprog].is_async_cb = true;
9236 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9237 					 insn_idx, subprog);
9238 		if (!async_cb)
9239 			return -EFAULT;
9240 		callee = async_cb->frame[0];
9241 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9242 
9243 		/* Convert bpf_timer_set_callback() args into timer callback args */
9244 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9245 		if (err)
9246 			return err;
9247 
9248 		return 0;
9249 	}
9250 
9251 	/* for callback functions enqueue entry to callback and
9252 	 * proceed with next instruction within current frame.
9253 	 */
9254 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9255 	if (!callback_state)
9256 		return -ENOMEM;
9257 
9258 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9259 			       callback_state);
9260 	if (err)
9261 		return err;
9262 
9263 	callback_state->callback_unroll_depth++;
9264 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9265 	caller->callback_depth = 0;
9266 	return 0;
9267 }
9268 
9269 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9270 			   int *insn_idx)
9271 {
9272 	struct bpf_verifier_state *state = env->cur_state;
9273 	struct bpf_func_state *caller;
9274 	int err, subprog, target_insn;
9275 
9276 	target_insn = *insn_idx + insn->imm + 1;
9277 	subprog = find_subprog(env, target_insn);
9278 	if (subprog < 0) {
9279 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9280 		return -EFAULT;
9281 	}
9282 
9283 	caller = state->frame[state->curframe];
9284 	err = btf_check_subprog_call(env, subprog, caller->regs);
9285 	if (err == -EFAULT)
9286 		return err;
9287 	if (subprog_is_global(env, subprog)) {
9288 		const char *sub_name = subprog_name(env, subprog);
9289 
9290 		if (err) {
9291 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
9292 				subprog, sub_name);
9293 			return err;
9294 		}
9295 
9296 		verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
9297 			subprog, sub_name);
9298 		/* mark global subprog for verifying after main prog */
9299 		subprog_aux(env, subprog)->called = true;
9300 		clear_caller_saved_regs(env, caller->regs);
9301 
9302 		/* All global functions return a 64-bit SCALAR_VALUE */
9303 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9304 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9305 
9306 		/* continue with next insn after call */
9307 		return 0;
9308 	}
9309 
9310 	/* for regular function entry setup new frame and continue
9311 	 * from that frame.
9312 	 */
9313 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9314 	if (err)
9315 		return err;
9316 
9317 	clear_caller_saved_regs(env, caller->regs);
9318 
9319 	/* and go analyze first insn of the callee */
9320 	*insn_idx = env->subprog_info[subprog].start - 1;
9321 
9322 	if (env->log.level & BPF_LOG_LEVEL) {
9323 		verbose(env, "caller:\n");
9324 		print_verifier_state(env, caller, true);
9325 		verbose(env, "callee:\n");
9326 		print_verifier_state(env, state->frame[state->curframe], true);
9327 	}
9328 
9329 	return 0;
9330 }
9331 
9332 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9333 				   struct bpf_func_state *caller,
9334 				   struct bpf_func_state *callee)
9335 {
9336 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9337 	 *      void *callback_ctx, u64 flags);
9338 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9339 	 *      void *callback_ctx);
9340 	 */
9341 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9342 
9343 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9344 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9345 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9346 
9347 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9348 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9349 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9350 
9351 	/* pointer to stack or null */
9352 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9353 
9354 	/* unused */
9355 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9356 	return 0;
9357 }
9358 
9359 static int set_callee_state(struct bpf_verifier_env *env,
9360 			    struct bpf_func_state *caller,
9361 			    struct bpf_func_state *callee, int insn_idx)
9362 {
9363 	int i;
9364 
9365 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9366 	 * pointers, which connects us up to the liveness chain
9367 	 */
9368 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9369 		callee->regs[i] = caller->regs[i];
9370 	return 0;
9371 }
9372 
9373 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9374 				       struct bpf_func_state *caller,
9375 				       struct bpf_func_state *callee,
9376 				       int insn_idx)
9377 {
9378 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9379 	struct bpf_map *map;
9380 	int err;
9381 
9382 	if (bpf_map_ptr_poisoned(insn_aux)) {
9383 		verbose(env, "tail_call abusing map_ptr\n");
9384 		return -EINVAL;
9385 	}
9386 
9387 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9388 	if (!map->ops->map_set_for_each_callback_args ||
9389 	    !map->ops->map_for_each_callback) {
9390 		verbose(env, "callback function not allowed for map\n");
9391 		return -ENOTSUPP;
9392 	}
9393 
9394 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9395 	if (err)
9396 		return err;
9397 
9398 	callee->in_callback_fn = true;
9399 	callee->callback_ret_range = tnum_range(0, 1);
9400 	return 0;
9401 }
9402 
9403 static int set_loop_callback_state(struct bpf_verifier_env *env,
9404 				   struct bpf_func_state *caller,
9405 				   struct bpf_func_state *callee,
9406 				   int insn_idx)
9407 {
9408 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9409 	 *	    u64 flags);
9410 	 * callback_fn(u32 index, void *callback_ctx);
9411 	 */
9412 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9413 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9414 
9415 	/* unused */
9416 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9417 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9418 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9419 
9420 	callee->in_callback_fn = true;
9421 	callee->callback_ret_range = tnum_range(0, 1);
9422 	return 0;
9423 }
9424 
9425 static int set_timer_callback_state(struct bpf_verifier_env *env,
9426 				    struct bpf_func_state *caller,
9427 				    struct bpf_func_state *callee,
9428 				    int insn_idx)
9429 {
9430 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9431 
9432 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9433 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9434 	 */
9435 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9436 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9437 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9438 
9439 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9440 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9441 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9442 
9443 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9444 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9445 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9446 
9447 	/* unused */
9448 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9449 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9450 	callee->in_async_callback_fn = true;
9451 	callee->callback_ret_range = tnum_range(0, 1);
9452 	return 0;
9453 }
9454 
9455 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9456 				       struct bpf_func_state *caller,
9457 				       struct bpf_func_state *callee,
9458 				       int insn_idx)
9459 {
9460 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9461 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9462 	 * (callback_fn)(struct task_struct *task,
9463 	 *               struct vm_area_struct *vma, void *callback_ctx);
9464 	 */
9465 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9466 
9467 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9468 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9469 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9470 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9471 
9472 	/* pointer to stack or null */
9473 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9474 
9475 	/* unused */
9476 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9477 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9478 	callee->in_callback_fn = true;
9479 	callee->callback_ret_range = tnum_range(0, 1);
9480 	return 0;
9481 }
9482 
9483 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9484 					   struct bpf_func_state *caller,
9485 					   struct bpf_func_state *callee,
9486 					   int insn_idx)
9487 {
9488 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9489 	 *			  callback_ctx, u64 flags);
9490 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9491 	 */
9492 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9493 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9494 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9495 
9496 	/* unused */
9497 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9498 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9499 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9500 
9501 	callee->in_callback_fn = true;
9502 	callee->callback_ret_range = tnum_range(0, 1);
9503 	return 0;
9504 }
9505 
9506 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9507 					 struct bpf_func_state *caller,
9508 					 struct bpf_func_state *callee,
9509 					 int insn_idx)
9510 {
9511 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9512 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9513 	 *
9514 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9515 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9516 	 * by this point, so look at 'root'
9517 	 */
9518 	struct btf_field *field;
9519 
9520 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9521 				      BPF_RB_ROOT);
9522 	if (!field || !field->graph_root.value_btf_id)
9523 		return -EFAULT;
9524 
9525 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9526 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9527 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9528 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9529 
9530 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9531 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9532 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9533 	callee->in_callback_fn = true;
9534 	callee->callback_ret_range = tnum_range(0, 1);
9535 	return 0;
9536 }
9537 
9538 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9539 
9540 /* Are we currently verifying the callback for a rbtree helper that must
9541  * be called with lock held? If so, no need to complain about unreleased
9542  * lock
9543  */
9544 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9545 {
9546 	struct bpf_verifier_state *state = env->cur_state;
9547 	struct bpf_insn *insn = env->prog->insnsi;
9548 	struct bpf_func_state *callee;
9549 	int kfunc_btf_id;
9550 
9551 	if (!state->curframe)
9552 		return false;
9553 
9554 	callee = state->frame[state->curframe];
9555 
9556 	if (!callee->in_callback_fn)
9557 		return false;
9558 
9559 	kfunc_btf_id = insn[callee->callsite].imm;
9560 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9561 }
9562 
9563 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9564 {
9565 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9566 	struct bpf_func_state *caller, *callee;
9567 	struct bpf_reg_state *r0;
9568 	bool in_callback_fn;
9569 	int err;
9570 
9571 	callee = state->frame[state->curframe];
9572 	r0 = &callee->regs[BPF_REG_0];
9573 	if (r0->type == PTR_TO_STACK) {
9574 		/* technically it's ok to return caller's stack pointer
9575 		 * (or caller's caller's pointer) back to the caller,
9576 		 * since these pointers are valid. Only current stack
9577 		 * pointer will be invalid as soon as function exits,
9578 		 * but let's be conservative
9579 		 */
9580 		verbose(env, "cannot return stack pointer to the caller\n");
9581 		return -EINVAL;
9582 	}
9583 
9584 	caller = state->frame[state->curframe - 1];
9585 	if (callee->in_callback_fn) {
9586 		/* enforce R0 return value range [0, 1]. */
9587 		struct tnum range = callee->callback_ret_range;
9588 
9589 		if (r0->type != SCALAR_VALUE) {
9590 			verbose(env, "R0 not a scalar value\n");
9591 			return -EACCES;
9592 		}
9593 		if (!tnum_in(range, r0->var_off)) {
9594 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9595 			return -EINVAL;
9596 		}
9597 		if (!calls_callback(env, callee->callsite)) {
9598 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9599 				*insn_idx, callee->callsite);
9600 			return -EFAULT;
9601 		}
9602 	} else {
9603 		/* return to the caller whatever r0 had in the callee */
9604 		caller->regs[BPF_REG_0] = *r0;
9605 	}
9606 
9607 	/* callback_fn frame should have released its own additions to parent's
9608 	 * reference state at this point, or check_reference_leak would
9609 	 * complain, hence it must be the same as the caller. There is no need
9610 	 * to copy it back.
9611 	 */
9612 	if (!callee->in_callback_fn) {
9613 		/* Transfer references to the caller */
9614 		err = copy_reference_state(caller, callee);
9615 		if (err)
9616 			return err;
9617 	}
9618 
9619 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9620 	 * there function call logic would reschedule callback visit. If iteration
9621 	 * converges is_state_visited() would prune that visit eventually.
9622 	 */
9623 	in_callback_fn = callee->in_callback_fn;
9624 	if (in_callback_fn)
9625 		*insn_idx = callee->callsite;
9626 	else
9627 		*insn_idx = callee->callsite + 1;
9628 
9629 	if (env->log.level & BPF_LOG_LEVEL) {
9630 		verbose(env, "returning from callee:\n");
9631 		print_verifier_state(env, callee, true);
9632 		verbose(env, "to caller at %d:\n", *insn_idx);
9633 		print_verifier_state(env, caller, true);
9634 	}
9635 	/* clear everything in the callee. In case of exceptional exits using
9636 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
9637 	free_func_state(callee);
9638 	state->frame[state->curframe--] = NULL;
9639 
9640 	/* for callbacks widen imprecise scalars to make programs like below verify:
9641 	 *
9642 	 *   struct ctx { int i; }
9643 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9644 	 *   ...
9645 	 *   struct ctx = { .i = 0; }
9646 	 *   bpf_loop(100, cb, &ctx, 0);
9647 	 *
9648 	 * This is similar to what is done in process_iter_next_call() for open
9649 	 * coded iterators.
9650 	 */
9651 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9652 	if (prev_st) {
9653 		err = widen_imprecise_scalars(env, prev_st, state);
9654 		if (err)
9655 			return err;
9656 	}
9657 	return 0;
9658 }
9659 
9660 static int do_refine_retval_range(struct bpf_verifier_env *env,
9661 				  struct bpf_reg_state *regs, int ret_type,
9662 				  int func_id,
9663 				  struct bpf_call_arg_meta *meta)
9664 {
9665 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9666 
9667 	if (ret_type != RET_INTEGER)
9668 		return 0;
9669 
9670 	switch (func_id) {
9671 	case BPF_FUNC_get_stack:
9672 	case BPF_FUNC_get_task_stack:
9673 	case BPF_FUNC_probe_read_str:
9674 	case BPF_FUNC_probe_read_kernel_str:
9675 	case BPF_FUNC_probe_read_user_str:
9676 		ret_reg->smax_value = meta->msize_max_value;
9677 		ret_reg->s32_max_value = meta->msize_max_value;
9678 		ret_reg->smin_value = -MAX_ERRNO;
9679 		ret_reg->s32_min_value = -MAX_ERRNO;
9680 		reg_bounds_sync(ret_reg);
9681 		break;
9682 	case BPF_FUNC_get_smp_processor_id:
9683 		ret_reg->umax_value = nr_cpu_ids - 1;
9684 		ret_reg->u32_max_value = nr_cpu_ids - 1;
9685 		ret_reg->smax_value = nr_cpu_ids - 1;
9686 		ret_reg->s32_max_value = nr_cpu_ids - 1;
9687 		ret_reg->umin_value = 0;
9688 		ret_reg->u32_min_value = 0;
9689 		ret_reg->smin_value = 0;
9690 		ret_reg->s32_min_value = 0;
9691 		reg_bounds_sync(ret_reg);
9692 		break;
9693 	}
9694 
9695 	return reg_bounds_sanity_check(env, ret_reg, "retval");
9696 }
9697 
9698 static int
9699 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9700 		int func_id, int insn_idx)
9701 {
9702 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9703 	struct bpf_map *map = meta->map_ptr;
9704 
9705 	if (func_id != BPF_FUNC_tail_call &&
9706 	    func_id != BPF_FUNC_map_lookup_elem &&
9707 	    func_id != BPF_FUNC_map_update_elem &&
9708 	    func_id != BPF_FUNC_map_delete_elem &&
9709 	    func_id != BPF_FUNC_map_push_elem &&
9710 	    func_id != BPF_FUNC_map_pop_elem &&
9711 	    func_id != BPF_FUNC_map_peek_elem &&
9712 	    func_id != BPF_FUNC_for_each_map_elem &&
9713 	    func_id != BPF_FUNC_redirect_map &&
9714 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9715 		return 0;
9716 
9717 	if (map == NULL) {
9718 		verbose(env, "kernel subsystem misconfigured verifier\n");
9719 		return -EINVAL;
9720 	}
9721 
9722 	/* In case of read-only, some additional restrictions
9723 	 * need to be applied in order to prevent altering the
9724 	 * state of the map from program side.
9725 	 */
9726 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9727 	    (func_id == BPF_FUNC_map_delete_elem ||
9728 	     func_id == BPF_FUNC_map_update_elem ||
9729 	     func_id == BPF_FUNC_map_push_elem ||
9730 	     func_id == BPF_FUNC_map_pop_elem)) {
9731 		verbose(env, "write into map forbidden\n");
9732 		return -EACCES;
9733 	}
9734 
9735 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9736 		bpf_map_ptr_store(aux, meta->map_ptr,
9737 				  !meta->map_ptr->bypass_spec_v1);
9738 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9739 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9740 				  !meta->map_ptr->bypass_spec_v1);
9741 	return 0;
9742 }
9743 
9744 static int
9745 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9746 		int func_id, int insn_idx)
9747 {
9748 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9749 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9750 	struct bpf_map *map = meta->map_ptr;
9751 	u64 val, max;
9752 	int err;
9753 
9754 	if (func_id != BPF_FUNC_tail_call)
9755 		return 0;
9756 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9757 		verbose(env, "kernel subsystem misconfigured verifier\n");
9758 		return -EINVAL;
9759 	}
9760 
9761 	reg = &regs[BPF_REG_3];
9762 	val = reg->var_off.value;
9763 	max = map->max_entries;
9764 
9765 	if (!(is_reg_const(reg, false) && val < max)) {
9766 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9767 		return 0;
9768 	}
9769 
9770 	err = mark_chain_precision(env, BPF_REG_3);
9771 	if (err)
9772 		return err;
9773 	if (bpf_map_key_unseen(aux))
9774 		bpf_map_key_store(aux, val);
9775 	else if (!bpf_map_key_poisoned(aux) &&
9776 		  bpf_map_key_immediate(aux) != val)
9777 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9778 	return 0;
9779 }
9780 
9781 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
9782 {
9783 	struct bpf_func_state *state = cur_func(env);
9784 	bool refs_lingering = false;
9785 	int i;
9786 
9787 	if (!exception_exit && state->frameno && !state->in_callback_fn)
9788 		return 0;
9789 
9790 	for (i = 0; i < state->acquired_refs; i++) {
9791 		if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9792 			continue;
9793 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9794 			state->refs[i].id, state->refs[i].insn_idx);
9795 		refs_lingering = true;
9796 	}
9797 	return refs_lingering ? -EINVAL : 0;
9798 }
9799 
9800 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9801 				   struct bpf_reg_state *regs)
9802 {
9803 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9804 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9805 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9806 	struct bpf_bprintf_data data = {};
9807 	int err, fmt_map_off, num_args;
9808 	u64 fmt_addr;
9809 	char *fmt;
9810 
9811 	/* data must be an array of u64 */
9812 	if (data_len_reg->var_off.value % 8)
9813 		return -EINVAL;
9814 	num_args = data_len_reg->var_off.value / 8;
9815 
9816 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9817 	 * and map_direct_value_addr is set.
9818 	 */
9819 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9820 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9821 						  fmt_map_off);
9822 	if (err) {
9823 		verbose(env, "verifier bug\n");
9824 		return -EFAULT;
9825 	}
9826 	fmt = (char *)(long)fmt_addr + fmt_map_off;
9827 
9828 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9829 	 * can focus on validating the format specifiers.
9830 	 */
9831 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9832 	if (err < 0)
9833 		verbose(env, "Invalid format string\n");
9834 
9835 	return err;
9836 }
9837 
9838 static int check_get_func_ip(struct bpf_verifier_env *env)
9839 {
9840 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9841 	int func_id = BPF_FUNC_get_func_ip;
9842 
9843 	if (type == BPF_PROG_TYPE_TRACING) {
9844 		if (!bpf_prog_has_trampoline(env->prog)) {
9845 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9846 				func_id_name(func_id), func_id);
9847 			return -ENOTSUPP;
9848 		}
9849 		return 0;
9850 	} else if (type == BPF_PROG_TYPE_KPROBE) {
9851 		return 0;
9852 	}
9853 
9854 	verbose(env, "func %s#%d not supported for program type %d\n",
9855 		func_id_name(func_id), func_id, type);
9856 	return -ENOTSUPP;
9857 }
9858 
9859 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9860 {
9861 	return &env->insn_aux_data[env->insn_idx];
9862 }
9863 
9864 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9865 {
9866 	struct bpf_reg_state *regs = cur_regs(env);
9867 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9868 	bool reg_is_null = register_is_null(reg);
9869 
9870 	if (reg_is_null)
9871 		mark_chain_precision(env, BPF_REG_4);
9872 
9873 	return reg_is_null;
9874 }
9875 
9876 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9877 {
9878 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9879 
9880 	if (!state->initialized) {
9881 		state->initialized = 1;
9882 		state->fit_for_inline = loop_flag_is_zero(env);
9883 		state->callback_subprogno = subprogno;
9884 		return;
9885 	}
9886 
9887 	if (!state->fit_for_inline)
9888 		return;
9889 
9890 	state->fit_for_inline = (loop_flag_is_zero(env) &&
9891 				 state->callback_subprogno == subprogno);
9892 }
9893 
9894 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9895 			     int *insn_idx_p)
9896 {
9897 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9898 	bool returns_cpu_specific_alloc_ptr = false;
9899 	const struct bpf_func_proto *fn = NULL;
9900 	enum bpf_return_type ret_type;
9901 	enum bpf_type_flag ret_flag;
9902 	struct bpf_reg_state *regs;
9903 	struct bpf_call_arg_meta meta;
9904 	int insn_idx = *insn_idx_p;
9905 	bool changes_data;
9906 	int i, err, func_id;
9907 
9908 	/* find function prototype */
9909 	func_id = insn->imm;
9910 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9911 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9912 			func_id);
9913 		return -EINVAL;
9914 	}
9915 
9916 	if (env->ops->get_func_proto)
9917 		fn = env->ops->get_func_proto(func_id, env->prog);
9918 	if (!fn) {
9919 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9920 			func_id);
9921 		return -EINVAL;
9922 	}
9923 
9924 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9925 	if (!env->prog->gpl_compatible && fn->gpl_only) {
9926 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9927 		return -EINVAL;
9928 	}
9929 
9930 	if (fn->allowed && !fn->allowed(env->prog)) {
9931 		verbose(env, "helper call is not allowed in probe\n");
9932 		return -EINVAL;
9933 	}
9934 
9935 	if (!env->prog->aux->sleepable && fn->might_sleep) {
9936 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
9937 		return -EINVAL;
9938 	}
9939 
9940 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
9941 	changes_data = bpf_helper_changes_pkt_data(fn->func);
9942 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9943 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9944 			func_id_name(func_id), func_id);
9945 		return -EINVAL;
9946 	}
9947 
9948 	memset(&meta, 0, sizeof(meta));
9949 	meta.pkt_access = fn->pkt_access;
9950 
9951 	err = check_func_proto(fn, func_id);
9952 	if (err) {
9953 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9954 			func_id_name(func_id), func_id);
9955 		return err;
9956 	}
9957 
9958 	if (env->cur_state->active_rcu_lock) {
9959 		if (fn->might_sleep) {
9960 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9961 				func_id_name(func_id), func_id);
9962 			return -EINVAL;
9963 		}
9964 
9965 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9966 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9967 	}
9968 
9969 	meta.func_id = func_id;
9970 	/* check args */
9971 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9972 		err = check_func_arg(env, i, &meta, fn, insn_idx);
9973 		if (err)
9974 			return err;
9975 	}
9976 
9977 	err = record_func_map(env, &meta, func_id, insn_idx);
9978 	if (err)
9979 		return err;
9980 
9981 	err = record_func_key(env, &meta, func_id, insn_idx);
9982 	if (err)
9983 		return err;
9984 
9985 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
9986 	 * is inferred from register state.
9987 	 */
9988 	for (i = 0; i < meta.access_size; i++) {
9989 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9990 				       BPF_WRITE, -1, false, false);
9991 		if (err)
9992 			return err;
9993 	}
9994 
9995 	regs = cur_regs(env);
9996 
9997 	if (meta.release_regno) {
9998 		err = -EINVAL;
9999 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10000 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10001 		 * is safe to do directly.
10002 		 */
10003 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10004 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10005 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10006 				return -EFAULT;
10007 			}
10008 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10009 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10010 			u32 ref_obj_id = meta.ref_obj_id;
10011 			bool in_rcu = in_rcu_cs(env);
10012 			struct bpf_func_state *state;
10013 			struct bpf_reg_state *reg;
10014 
10015 			err = release_reference_state(cur_func(env), ref_obj_id);
10016 			if (!err) {
10017 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10018 					if (reg->ref_obj_id == ref_obj_id) {
10019 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10020 							reg->ref_obj_id = 0;
10021 							reg->type &= ~MEM_ALLOC;
10022 							reg->type |= MEM_RCU;
10023 						} else {
10024 							mark_reg_invalid(env, reg);
10025 						}
10026 					}
10027 				}));
10028 			}
10029 		} else if (meta.ref_obj_id) {
10030 			err = release_reference(env, meta.ref_obj_id);
10031 		} else if (register_is_null(&regs[meta.release_regno])) {
10032 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10033 			 * released is NULL, which must be > R0.
10034 			 */
10035 			err = 0;
10036 		}
10037 		if (err) {
10038 			verbose(env, "func %s#%d reference has not been acquired before\n",
10039 				func_id_name(func_id), func_id);
10040 			return err;
10041 		}
10042 	}
10043 
10044 	switch (func_id) {
10045 	case BPF_FUNC_tail_call:
10046 		err = check_reference_leak(env, false);
10047 		if (err) {
10048 			verbose(env, "tail_call would lead to reference leak\n");
10049 			return err;
10050 		}
10051 		break;
10052 	case BPF_FUNC_get_local_storage:
10053 		/* check that flags argument in get_local_storage(map, flags) is 0,
10054 		 * this is required because get_local_storage() can't return an error.
10055 		 */
10056 		if (!register_is_null(&regs[BPF_REG_2])) {
10057 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10058 			return -EINVAL;
10059 		}
10060 		break;
10061 	case BPF_FUNC_for_each_map_elem:
10062 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10063 					 set_map_elem_callback_state);
10064 		break;
10065 	case BPF_FUNC_timer_set_callback:
10066 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10067 					 set_timer_callback_state);
10068 		break;
10069 	case BPF_FUNC_find_vma:
10070 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10071 					 set_find_vma_callback_state);
10072 		break;
10073 	case BPF_FUNC_snprintf:
10074 		err = check_bpf_snprintf_call(env, regs);
10075 		break;
10076 	case BPF_FUNC_loop:
10077 		update_loop_inline_state(env, meta.subprogno);
10078 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10079 		 * is finished, thus mark it precise.
10080 		 */
10081 		err = mark_chain_precision(env, BPF_REG_1);
10082 		if (err)
10083 			return err;
10084 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10085 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10086 						 set_loop_callback_state);
10087 		} else {
10088 			cur_func(env)->callback_depth = 0;
10089 			if (env->log.level & BPF_LOG_LEVEL2)
10090 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10091 					env->cur_state->curframe);
10092 		}
10093 		break;
10094 	case BPF_FUNC_dynptr_from_mem:
10095 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10096 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10097 				reg_type_str(env, regs[BPF_REG_1].type));
10098 			return -EACCES;
10099 		}
10100 		break;
10101 	case BPF_FUNC_set_retval:
10102 		if (prog_type == BPF_PROG_TYPE_LSM &&
10103 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10104 			if (!env->prog->aux->attach_func_proto->type) {
10105 				/* Make sure programs that attach to void
10106 				 * hooks don't try to modify return value.
10107 				 */
10108 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10109 				return -EINVAL;
10110 			}
10111 		}
10112 		break;
10113 	case BPF_FUNC_dynptr_data:
10114 	{
10115 		struct bpf_reg_state *reg;
10116 		int id, ref_obj_id;
10117 
10118 		reg = get_dynptr_arg_reg(env, fn, regs);
10119 		if (!reg)
10120 			return -EFAULT;
10121 
10122 
10123 		if (meta.dynptr_id) {
10124 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10125 			return -EFAULT;
10126 		}
10127 		if (meta.ref_obj_id) {
10128 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10129 			return -EFAULT;
10130 		}
10131 
10132 		id = dynptr_id(env, reg);
10133 		if (id < 0) {
10134 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10135 			return id;
10136 		}
10137 
10138 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10139 		if (ref_obj_id < 0) {
10140 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10141 			return ref_obj_id;
10142 		}
10143 
10144 		meta.dynptr_id = id;
10145 		meta.ref_obj_id = ref_obj_id;
10146 
10147 		break;
10148 	}
10149 	case BPF_FUNC_dynptr_write:
10150 	{
10151 		enum bpf_dynptr_type dynptr_type;
10152 		struct bpf_reg_state *reg;
10153 
10154 		reg = get_dynptr_arg_reg(env, fn, regs);
10155 		if (!reg)
10156 			return -EFAULT;
10157 
10158 		dynptr_type = dynptr_get_type(env, reg);
10159 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10160 			return -EFAULT;
10161 
10162 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10163 			/* this will trigger clear_all_pkt_pointers(), which will
10164 			 * invalidate all dynptr slices associated with the skb
10165 			 */
10166 			changes_data = true;
10167 
10168 		break;
10169 	}
10170 	case BPF_FUNC_per_cpu_ptr:
10171 	case BPF_FUNC_this_cpu_ptr:
10172 	{
10173 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
10174 		const struct btf_type *type;
10175 
10176 		if (reg->type & MEM_RCU) {
10177 			type = btf_type_by_id(reg->btf, reg->btf_id);
10178 			if (!type || !btf_type_is_struct(type)) {
10179 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
10180 				return -EFAULT;
10181 			}
10182 			returns_cpu_specific_alloc_ptr = true;
10183 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10184 		}
10185 		break;
10186 	}
10187 	case BPF_FUNC_user_ringbuf_drain:
10188 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10189 					 set_user_ringbuf_callback_state);
10190 		break;
10191 	}
10192 
10193 	if (err)
10194 		return err;
10195 
10196 	/* reset caller saved regs */
10197 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10198 		mark_reg_not_init(env, regs, caller_saved[i]);
10199 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10200 	}
10201 
10202 	/* helper call returns 64-bit value. */
10203 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10204 
10205 	/* update return register (already marked as written above) */
10206 	ret_type = fn->ret_type;
10207 	ret_flag = type_flag(ret_type);
10208 
10209 	switch (base_type(ret_type)) {
10210 	case RET_INTEGER:
10211 		/* sets type to SCALAR_VALUE */
10212 		mark_reg_unknown(env, regs, BPF_REG_0);
10213 		break;
10214 	case RET_VOID:
10215 		regs[BPF_REG_0].type = NOT_INIT;
10216 		break;
10217 	case RET_PTR_TO_MAP_VALUE:
10218 		/* There is no offset yet applied, variable or fixed */
10219 		mark_reg_known_zero(env, regs, BPF_REG_0);
10220 		/* remember map_ptr, so that check_map_access()
10221 		 * can check 'value_size' boundary of memory access
10222 		 * to map element returned from bpf_map_lookup_elem()
10223 		 */
10224 		if (meta.map_ptr == NULL) {
10225 			verbose(env,
10226 				"kernel subsystem misconfigured verifier\n");
10227 			return -EINVAL;
10228 		}
10229 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10230 		regs[BPF_REG_0].map_uid = meta.map_uid;
10231 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10232 		if (!type_may_be_null(ret_type) &&
10233 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10234 			regs[BPF_REG_0].id = ++env->id_gen;
10235 		}
10236 		break;
10237 	case RET_PTR_TO_SOCKET:
10238 		mark_reg_known_zero(env, regs, BPF_REG_0);
10239 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10240 		break;
10241 	case RET_PTR_TO_SOCK_COMMON:
10242 		mark_reg_known_zero(env, regs, BPF_REG_0);
10243 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10244 		break;
10245 	case RET_PTR_TO_TCP_SOCK:
10246 		mark_reg_known_zero(env, regs, BPF_REG_0);
10247 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10248 		break;
10249 	case RET_PTR_TO_MEM:
10250 		mark_reg_known_zero(env, regs, BPF_REG_0);
10251 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10252 		regs[BPF_REG_0].mem_size = meta.mem_size;
10253 		break;
10254 	case RET_PTR_TO_MEM_OR_BTF_ID:
10255 	{
10256 		const struct btf_type *t;
10257 
10258 		mark_reg_known_zero(env, regs, BPF_REG_0);
10259 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10260 		if (!btf_type_is_struct(t)) {
10261 			u32 tsize;
10262 			const struct btf_type *ret;
10263 			const char *tname;
10264 
10265 			/* resolve the type size of ksym. */
10266 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10267 			if (IS_ERR(ret)) {
10268 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10269 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10270 					tname, PTR_ERR(ret));
10271 				return -EINVAL;
10272 			}
10273 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10274 			regs[BPF_REG_0].mem_size = tsize;
10275 		} else {
10276 			if (returns_cpu_specific_alloc_ptr) {
10277 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10278 			} else {
10279 				/* MEM_RDONLY may be carried from ret_flag, but it
10280 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10281 				 * it will confuse the check of PTR_TO_BTF_ID in
10282 				 * check_mem_access().
10283 				 */
10284 				ret_flag &= ~MEM_RDONLY;
10285 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10286 			}
10287 
10288 			regs[BPF_REG_0].btf = meta.ret_btf;
10289 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10290 		}
10291 		break;
10292 	}
10293 	case RET_PTR_TO_BTF_ID:
10294 	{
10295 		struct btf *ret_btf;
10296 		int ret_btf_id;
10297 
10298 		mark_reg_known_zero(env, regs, BPF_REG_0);
10299 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10300 		if (func_id == BPF_FUNC_kptr_xchg) {
10301 			ret_btf = meta.kptr_field->kptr.btf;
10302 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10303 			if (!btf_is_kernel(ret_btf)) {
10304 				regs[BPF_REG_0].type |= MEM_ALLOC;
10305 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10306 					regs[BPF_REG_0].type |= MEM_PERCPU;
10307 			}
10308 		} else {
10309 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10310 				verbose(env, "verifier internal error:");
10311 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10312 					func_id_name(func_id));
10313 				return -EINVAL;
10314 			}
10315 			ret_btf = btf_vmlinux;
10316 			ret_btf_id = *fn->ret_btf_id;
10317 		}
10318 		if (ret_btf_id == 0) {
10319 			verbose(env, "invalid return type %u of func %s#%d\n",
10320 				base_type(ret_type), func_id_name(func_id),
10321 				func_id);
10322 			return -EINVAL;
10323 		}
10324 		regs[BPF_REG_0].btf = ret_btf;
10325 		regs[BPF_REG_0].btf_id = ret_btf_id;
10326 		break;
10327 	}
10328 	default:
10329 		verbose(env, "unknown return type %u of func %s#%d\n",
10330 			base_type(ret_type), func_id_name(func_id), func_id);
10331 		return -EINVAL;
10332 	}
10333 
10334 	if (type_may_be_null(regs[BPF_REG_0].type))
10335 		regs[BPF_REG_0].id = ++env->id_gen;
10336 
10337 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10338 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10339 			func_id_name(func_id), func_id);
10340 		return -EFAULT;
10341 	}
10342 
10343 	if (is_dynptr_ref_function(func_id))
10344 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10345 
10346 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10347 		/* For release_reference() */
10348 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10349 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10350 		int id = acquire_reference_state(env, insn_idx);
10351 
10352 		if (id < 0)
10353 			return id;
10354 		/* For mark_ptr_or_null_reg() */
10355 		regs[BPF_REG_0].id = id;
10356 		/* For release_reference() */
10357 		regs[BPF_REG_0].ref_obj_id = id;
10358 	}
10359 
10360 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
10361 	if (err)
10362 		return err;
10363 
10364 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10365 	if (err)
10366 		return err;
10367 
10368 	if ((func_id == BPF_FUNC_get_stack ||
10369 	     func_id == BPF_FUNC_get_task_stack) &&
10370 	    !env->prog->has_callchain_buf) {
10371 		const char *err_str;
10372 
10373 #ifdef CONFIG_PERF_EVENTS
10374 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10375 		err_str = "cannot get callchain buffer for func %s#%d\n";
10376 #else
10377 		err = -ENOTSUPP;
10378 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10379 #endif
10380 		if (err) {
10381 			verbose(env, err_str, func_id_name(func_id), func_id);
10382 			return err;
10383 		}
10384 
10385 		env->prog->has_callchain_buf = true;
10386 	}
10387 
10388 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10389 		env->prog->call_get_stack = true;
10390 
10391 	if (func_id == BPF_FUNC_get_func_ip) {
10392 		if (check_get_func_ip(env))
10393 			return -ENOTSUPP;
10394 		env->prog->call_get_func_ip = true;
10395 	}
10396 
10397 	if (changes_data)
10398 		clear_all_pkt_pointers(env);
10399 	return 0;
10400 }
10401 
10402 /* mark_btf_func_reg_size() is used when the reg size is determined by
10403  * the BTF func_proto's return value size and argument.
10404  */
10405 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10406 				   size_t reg_size)
10407 {
10408 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10409 
10410 	if (regno == BPF_REG_0) {
10411 		/* Function return value */
10412 		reg->live |= REG_LIVE_WRITTEN;
10413 		reg->subreg_def = reg_size == sizeof(u64) ?
10414 			DEF_NOT_SUBREG : env->insn_idx + 1;
10415 	} else {
10416 		/* Function argument */
10417 		if (reg_size == sizeof(u64)) {
10418 			mark_insn_zext(env, reg);
10419 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10420 		} else {
10421 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10422 		}
10423 	}
10424 }
10425 
10426 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10427 {
10428 	return meta->kfunc_flags & KF_ACQUIRE;
10429 }
10430 
10431 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10432 {
10433 	return meta->kfunc_flags & KF_RELEASE;
10434 }
10435 
10436 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10437 {
10438 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10439 }
10440 
10441 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10442 {
10443 	return meta->kfunc_flags & KF_SLEEPABLE;
10444 }
10445 
10446 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10447 {
10448 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10449 }
10450 
10451 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10452 {
10453 	return meta->kfunc_flags & KF_RCU;
10454 }
10455 
10456 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
10457 {
10458 	return meta->kfunc_flags & KF_RCU_PROTECTED;
10459 }
10460 
10461 static bool __kfunc_param_match_suffix(const struct btf *btf,
10462 				       const struct btf_param *arg,
10463 				       const char *suffix)
10464 {
10465 	int suffix_len = strlen(suffix), len;
10466 	const char *param_name;
10467 
10468 	/* In the future, this can be ported to use BTF tagging */
10469 	param_name = btf_name_by_offset(btf, arg->name_off);
10470 	if (str_is_empty(param_name))
10471 		return false;
10472 	len = strlen(param_name);
10473 	if (len < suffix_len)
10474 		return false;
10475 	param_name += len - suffix_len;
10476 	return !strncmp(param_name, suffix, suffix_len);
10477 }
10478 
10479 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10480 				  const struct btf_param *arg,
10481 				  const struct bpf_reg_state *reg)
10482 {
10483 	const struct btf_type *t;
10484 
10485 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10486 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10487 		return false;
10488 
10489 	return __kfunc_param_match_suffix(btf, arg, "__sz");
10490 }
10491 
10492 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10493 					const struct btf_param *arg,
10494 					const struct bpf_reg_state *reg)
10495 {
10496 	const struct btf_type *t;
10497 
10498 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10499 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10500 		return false;
10501 
10502 	return __kfunc_param_match_suffix(btf, arg, "__szk");
10503 }
10504 
10505 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10506 {
10507 	return __kfunc_param_match_suffix(btf, arg, "__opt");
10508 }
10509 
10510 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10511 {
10512 	return __kfunc_param_match_suffix(btf, arg, "__k");
10513 }
10514 
10515 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10516 {
10517 	return __kfunc_param_match_suffix(btf, arg, "__ign");
10518 }
10519 
10520 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10521 {
10522 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
10523 }
10524 
10525 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10526 {
10527 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
10528 }
10529 
10530 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10531 {
10532 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10533 }
10534 
10535 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
10536 {
10537 	return __kfunc_param_match_suffix(btf, arg, "__nullable");
10538 }
10539 
10540 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
10541 {
10542 	return __kfunc_param_match_suffix(btf, arg, "__str");
10543 }
10544 
10545 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10546 					  const struct btf_param *arg,
10547 					  const char *name)
10548 {
10549 	int len, target_len = strlen(name);
10550 	const char *param_name;
10551 
10552 	param_name = btf_name_by_offset(btf, arg->name_off);
10553 	if (str_is_empty(param_name))
10554 		return false;
10555 	len = strlen(param_name);
10556 	if (len != target_len)
10557 		return false;
10558 	if (strcmp(param_name, name))
10559 		return false;
10560 
10561 	return true;
10562 }
10563 
10564 enum {
10565 	KF_ARG_DYNPTR_ID,
10566 	KF_ARG_LIST_HEAD_ID,
10567 	KF_ARG_LIST_NODE_ID,
10568 	KF_ARG_RB_ROOT_ID,
10569 	KF_ARG_RB_NODE_ID,
10570 };
10571 
10572 BTF_ID_LIST(kf_arg_btf_ids)
10573 BTF_ID(struct, bpf_dynptr_kern)
10574 BTF_ID(struct, bpf_list_head)
10575 BTF_ID(struct, bpf_list_node)
10576 BTF_ID(struct, bpf_rb_root)
10577 BTF_ID(struct, bpf_rb_node)
10578 
10579 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10580 				    const struct btf_param *arg, int type)
10581 {
10582 	const struct btf_type *t;
10583 	u32 res_id;
10584 
10585 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10586 	if (!t)
10587 		return false;
10588 	if (!btf_type_is_ptr(t))
10589 		return false;
10590 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10591 	if (!t)
10592 		return false;
10593 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10594 }
10595 
10596 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10597 {
10598 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10599 }
10600 
10601 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10602 {
10603 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10604 }
10605 
10606 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10607 {
10608 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10609 }
10610 
10611 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10612 {
10613 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10614 }
10615 
10616 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10617 {
10618 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10619 }
10620 
10621 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10622 				  const struct btf_param *arg)
10623 {
10624 	const struct btf_type *t;
10625 
10626 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10627 	if (!t)
10628 		return false;
10629 
10630 	return true;
10631 }
10632 
10633 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10634 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10635 					const struct btf *btf,
10636 					const struct btf_type *t, int rec)
10637 {
10638 	const struct btf_type *member_type;
10639 	const struct btf_member *member;
10640 	u32 i;
10641 
10642 	if (!btf_type_is_struct(t))
10643 		return false;
10644 
10645 	for_each_member(i, t, member) {
10646 		const struct btf_array *array;
10647 
10648 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10649 		if (btf_type_is_struct(member_type)) {
10650 			if (rec >= 3) {
10651 				verbose(env, "max struct nesting depth exceeded\n");
10652 				return false;
10653 			}
10654 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10655 				return false;
10656 			continue;
10657 		}
10658 		if (btf_type_is_array(member_type)) {
10659 			array = btf_array(member_type);
10660 			if (!array->nelems)
10661 				return false;
10662 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10663 			if (!btf_type_is_scalar(member_type))
10664 				return false;
10665 			continue;
10666 		}
10667 		if (!btf_type_is_scalar(member_type))
10668 			return false;
10669 	}
10670 	return true;
10671 }
10672 
10673 enum kfunc_ptr_arg_type {
10674 	KF_ARG_PTR_TO_CTX,
10675 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10676 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10677 	KF_ARG_PTR_TO_DYNPTR,
10678 	KF_ARG_PTR_TO_ITER,
10679 	KF_ARG_PTR_TO_LIST_HEAD,
10680 	KF_ARG_PTR_TO_LIST_NODE,
10681 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10682 	KF_ARG_PTR_TO_MEM,
10683 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10684 	KF_ARG_PTR_TO_CALLBACK,
10685 	KF_ARG_PTR_TO_RB_ROOT,
10686 	KF_ARG_PTR_TO_RB_NODE,
10687 	KF_ARG_PTR_TO_NULL,
10688 	KF_ARG_PTR_TO_CONST_STR,
10689 };
10690 
10691 enum special_kfunc_type {
10692 	KF_bpf_obj_new_impl,
10693 	KF_bpf_obj_drop_impl,
10694 	KF_bpf_refcount_acquire_impl,
10695 	KF_bpf_list_push_front_impl,
10696 	KF_bpf_list_push_back_impl,
10697 	KF_bpf_list_pop_front,
10698 	KF_bpf_list_pop_back,
10699 	KF_bpf_cast_to_kern_ctx,
10700 	KF_bpf_rdonly_cast,
10701 	KF_bpf_rcu_read_lock,
10702 	KF_bpf_rcu_read_unlock,
10703 	KF_bpf_rbtree_remove,
10704 	KF_bpf_rbtree_add_impl,
10705 	KF_bpf_rbtree_first,
10706 	KF_bpf_dynptr_from_skb,
10707 	KF_bpf_dynptr_from_xdp,
10708 	KF_bpf_dynptr_slice,
10709 	KF_bpf_dynptr_slice_rdwr,
10710 	KF_bpf_dynptr_clone,
10711 	KF_bpf_percpu_obj_new_impl,
10712 	KF_bpf_percpu_obj_drop_impl,
10713 	KF_bpf_throw,
10714 	KF_bpf_iter_css_task_new,
10715 };
10716 
10717 BTF_SET_START(special_kfunc_set)
10718 BTF_ID(func, bpf_obj_new_impl)
10719 BTF_ID(func, bpf_obj_drop_impl)
10720 BTF_ID(func, bpf_refcount_acquire_impl)
10721 BTF_ID(func, bpf_list_push_front_impl)
10722 BTF_ID(func, bpf_list_push_back_impl)
10723 BTF_ID(func, bpf_list_pop_front)
10724 BTF_ID(func, bpf_list_pop_back)
10725 BTF_ID(func, bpf_cast_to_kern_ctx)
10726 BTF_ID(func, bpf_rdonly_cast)
10727 BTF_ID(func, bpf_rbtree_remove)
10728 BTF_ID(func, bpf_rbtree_add_impl)
10729 BTF_ID(func, bpf_rbtree_first)
10730 BTF_ID(func, bpf_dynptr_from_skb)
10731 BTF_ID(func, bpf_dynptr_from_xdp)
10732 BTF_ID(func, bpf_dynptr_slice)
10733 BTF_ID(func, bpf_dynptr_slice_rdwr)
10734 BTF_ID(func, bpf_dynptr_clone)
10735 BTF_ID(func, bpf_percpu_obj_new_impl)
10736 BTF_ID(func, bpf_percpu_obj_drop_impl)
10737 BTF_ID(func, bpf_throw)
10738 #ifdef CONFIG_CGROUPS
10739 BTF_ID(func, bpf_iter_css_task_new)
10740 #endif
10741 BTF_SET_END(special_kfunc_set)
10742 
10743 BTF_ID_LIST(special_kfunc_list)
10744 BTF_ID(func, bpf_obj_new_impl)
10745 BTF_ID(func, bpf_obj_drop_impl)
10746 BTF_ID(func, bpf_refcount_acquire_impl)
10747 BTF_ID(func, bpf_list_push_front_impl)
10748 BTF_ID(func, bpf_list_push_back_impl)
10749 BTF_ID(func, bpf_list_pop_front)
10750 BTF_ID(func, bpf_list_pop_back)
10751 BTF_ID(func, bpf_cast_to_kern_ctx)
10752 BTF_ID(func, bpf_rdonly_cast)
10753 BTF_ID(func, bpf_rcu_read_lock)
10754 BTF_ID(func, bpf_rcu_read_unlock)
10755 BTF_ID(func, bpf_rbtree_remove)
10756 BTF_ID(func, bpf_rbtree_add_impl)
10757 BTF_ID(func, bpf_rbtree_first)
10758 BTF_ID(func, bpf_dynptr_from_skb)
10759 BTF_ID(func, bpf_dynptr_from_xdp)
10760 BTF_ID(func, bpf_dynptr_slice)
10761 BTF_ID(func, bpf_dynptr_slice_rdwr)
10762 BTF_ID(func, bpf_dynptr_clone)
10763 BTF_ID(func, bpf_percpu_obj_new_impl)
10764 BTF_ID(func, bpf_percpu_obj_drop_impl)
10765 BTF_ID(func, bpf_throw)
10766 #ifdef CONFIG_CGROUPS
10767 BTF_ID(func, bpf_iter_css_task_new)
10768 #else
10769 BTF_ID_UNUSED
10770 #endif
10771 
10772 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10773 {
10774 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10775 	    meta->arg_owning_ref) {
10776 		return false;
10777 	}
10778 
10779 	return meta->kfunc_flags & KF_RET_NULL;
10780 }
10781 
10782 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10783 {
10784 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10785 }
10786 
10787 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10788 {
10789 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10790 }
10791 
10792 static enum kfunc_ptr_arg_type
10793 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10794 		       struct bpf_kfunc_call_arg_meta *meta,
10795 		       const struct btf_type *t, const struct btf_type *ref_t,
10796 		       const char *ref_tname, const struct btf_param *args,
10797 		       int argno, int nargs)
10798 {
10799 	u32 regno = argno + 1;
10800 	struct bpf_reg_state *regs = cur_regs(env);
10801 	struct bpf_reg_state *reg = &regs[regno];
10802 	bool arg_mem_size = false;
10803 
10804 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10805 		return KF_ARG_PTR_TO_CTX;
10806 
10807 	/* In this function, we verify the kfunc's BTF as per the argument type,
10808 	 * leaving the rest of the verification with respect to the register
10809 	 * type to our caller. When a set of conditions hold in the BTF type of
10810 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10811 	 */
10812 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10813 		return KF_ARG_PTR_TO_CTX;
10814 
10815 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10816 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10817 
10818 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10819 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10820 
10821 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10822 		return KF_ARG_PTR_TO_DYNPTR;
10823 
10824 	if (is_kfunc_arg_iter(meta, argno))
10825 		return KF_ARG_PTR_TO_ITER;
10826 
10827 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10828 		return KF_ARG_PTR_TO_LIST_HEAD;
10829 
10830 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10831 		return KF_ARG_PTR_TO_LIST_NODE;
10832 
10833 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10834 		return KF_ARG_PTR_TO_RB_ROOT;
10835 
10836 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10837 		return KF_ARG_PTR_TO_RB_NODE;
10838 
10839 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
10840 		return KF_ARG_PTR_TO_CONST_STR;
10841 
10842 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10843 		if (!btf_type_is_struct(ref_t)) {
10844 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10845 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10846 			return -EINVAL;
10847 		}
10848 		return KF_ARG_PTR_TO_BTF_ID;
10849 	}
10850 
10851 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10852 		return KF_ARG_PTR_TO_CALLBACK;
10853 
10854 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
10855 		return KF_ARG_PTR_TO_NULL;
10856 
10857 	if (argno + 1 < nargs &&
10858 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10859 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10860 		arg_mem_size = true;
10861 
10862 	/* This is the catch all argument type of register types supported by
10863 	 * check_helper_mem_access. However, we only allow when argument type is
10864 	 * pointer to scalar, or struct composed (recursively) of scalars. When
10865 	 * arg_mem_size is true, the pointer can be void *.
10866 	 */
10867 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10868 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10869 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10870 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10871 		return -EINVAL;
10872 	}
10873 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10874 }
10875 
10876 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10877 					struct bpf_reg_state *reg,
10878 					const struct btf_type *ref_t,
10879 					const char *ref_tname, u32 ref_id,
10880 					struct bpf_kfunc_call_arg_meta *meta,
10881 					int argno)
10882 {
10883 	const struct btf_type *reg_ref_t;
10884 	bool strict_type_match = false;
10885 	const struct btf *reg_btf;
10886 	const char *reg_ref_tname;
10887 	u32 reg_ref_id;
10888 
10889 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
10890 		reg_btf = reg->btf;
10891 		reg_ref_id = reg->btf_id;
10892 	} else {
10893 		reg_btf = btf_vmlinux;
10894 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10895 	}
10896 
10897 	/* Enforce strict type matching for calls to kfuncs that are acquiring
10898 	 * or releasing a reference, or are no-cast aliases. We do _not_
10899 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10900 	 * as we want to enable BPF programs to pass types that are bitwise
10901 	 * equivalent without forcing them to explicitly cast with something
10902 	 * like bpf_cast_to_kern_ctx().
10903 	 *
10904 	 * For example, say we had a type like the following:
10905 	 *
10906 	 * struct bpf_cpumask {
10907 	 *	cpumask_t cpumask;
10908 	 *	refcount_t usage;
10909 	 * };
10910 	 *
10911 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10912 	 * to a struct cpumask, so it would be safe to pass a struct
10913 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10914 	 *
10915 	 * The philosophy here is similar to how we allow scalars of different
10916 	 * types to be passed to kfuncs as long as the size is the same. The
10917 	 * only difference here is that we're simply allowing
10918 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10919 	 * resolve types.
10920 	 */
10921 	if (is_kfunc_acquire(meta) ||
10922 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
10923 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10924 		strict_type_match = true;
10925 
10926 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10927 
10928 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10929 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10930 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10931 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10932 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10933 			btf_type_str(reg_ref_t), reg_ref_tname);
10934 		return -EINVAL;
10935 	}
10936 	return 0;
10937 }
10938 
10939 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10940 {
10941 	struct bpf_verifier_state *state = env->cur_state;
10942 	struct btf_record *rec = reg_btf_record(reg);
10943 
10944 	if (!state->active_lock.ptr) {
10945 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10946 		return -EFAULT;
10947 	}
10948 
10949 	if (type_flag(reg->type) & NON_OWN_REF) {
10950 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10951 		return -EFAULT;
10952 	}
10953 
10954 	reg->type |= NON_OWN_REF;
10955 	if (rec->refcount_off >= 0)
10956 		reg->type |= MEM_RCU;
10957 
10958 	return 0;
10959 }
10960 
10961 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10962 {
10963 	struct bpf_func_state *state, *unused;
10964 	struct bpf_reg_state *reg;
10965 	int i;
10966 
10967 	state = cur_func(env);
10968 
10969 	if (!ref_obj_id) {
10970 		verbose(env, "verifier internal error: ref_obj_id is zero for "
10971 			     "owning -> non-owning conversion\n");
10972 		return -EFAULT;
10973 	}
10974 
10975 	for (i = 0; i < state->acquired_refs; i++) {
10976 		if (state->refs[i].id != ref_obj_id)
10977 			continue;
10978 
10979 		/* Clear ref_obj_id here so release_reference doesn't clobber
10980 		 * the whole reg
10981 		 */
10982 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10983 			if (reg->ref_obj_id == ref_obj_id) {
10984 				reg->ref_obj_id = 0;
10985 				ref_set_non_owning(env, reg);
10986 			}
10987 		}));
10988 		return 0;
10989 	}
10990 
10991 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10992 	return -EFAULT;
10993 }
10994 
10995 /* Implementation details:
10996  *
10997  * Each register points to some region of memory, which we define as an
10998  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10999  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11000  * allocation. The lock and the data it protects are colocated in the same
11001  * memory region.
11002  *
11003  * Hence, everytime a register holds a pointer value pointing to such
11004  * allocation, the verifier preserves a unique reg->id for it.
11005  *
11006  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11007  * bpf_spin_lock is called.
11008  *
11009  * To enable this, lock state in the verifier captures two values:
11010  *	active_lock.ptr = Register's type specific pointer
11011  *	active_lock.id  = A unique ID for each register pointer value
11012  *
11013  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11014  * supported register types.
11015  *
11016  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11017  * allocated objects is the reg->btf pointer.
11018  *
11019  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11020  * can establish the provenance of the map value statically for each distinct
11021  * lookup into such maps. They always contain a single map value hence unique
11022  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11023  *
11024  * So, in case of global variables, they use array maps with max_entries = 1,
11025  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11026  * into the same map value as max_entries is 1, as described above).
11027  *
11028  * In case of inner map lookups, the inner map pointer has same map_ptr as the
11029  * outer map pointer (in verifier context), but each lookup into an inner map
11030  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11031  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11032  * will get different reg->id assigned to each lookup, hence different
11033  * active_lock.id.
11034  *
11035  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11036  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11037  * returned from bpf_obj_new. Each allocation receives a new reg->id.
11038  */
11039 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11040 {
11041 	void *ptr;
11042 	u32 id;
11043 
11044 	switch ((int)reg->type) {
11045 	case PTR_TO_MAP_VALUE:
11046 		ptr = reg->map_ptr;
11047 		break;
11048 	case PTR_TO_BTF_ID | MEM_ALLOC:
11049 		ptr = reg->btf;
11050 		break;
11051 	default:
11052 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11053 		return -EFAULT;
11054 	}
11055 	id = reg->id;
11056 
11057 	if (!env->cur_state->active_lock.ptr)
11058 		return -EINVAL;
11059 	if (env->cur_state->active_lock.ptr != ptr ||
11060 	    env->cur_state->active_lock.id != id) {
11061 		verbose(env, "held lock and object are not in the same allocation\n");
11062 		return -EINVAL;
11063 	}
11064 	return 0;
11065 }
11066 
11067 static bool is_bpf_list_api_kfunc(u32 btf_id)
11068 {
11069 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11070 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11071 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11072 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11073 }
11074 
11075 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11076 {
11077 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11078 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11079 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11080 }
11081 
11082 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11083 {
11084 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11085 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11086 }
11087 
11088 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11089 {
11090 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11091 }
11092 
11093 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
11094 {
11095 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11096 	       insn->imm == special_kfunc_list[KF_bpf_throw];
11097 }
11098 
11099 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11100 {
11101 	return is_bpf_rbtree_api_kfunc(btf_id);
11102 }
11103 
11104 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11105 					  enum btf_field_type head_field_type,
11106 					  u32 kfunc_btf_id)
11107 {
11108 	bool ret;
11109 
11110 	switch (head_field_type) {
11111 	case BPF_LIST_HEAD:
11112 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11113 		break;
11114 	case BPF_RB_ROOT:
11115 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11116 		break;
11117 	default:
11118 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11119 			btf_field_type_name(head_field_type));
11120 		return false;
11121 	}
11122 
11123 	if (!ret)
11124 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11125 			btf_field_type_name(head_field_type));
11126 	return ret;
11127 }
11128 
11129 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11130 					  enum btf_field_type node_field_type,
11131 					  u32 kfunc_btf_id)
11132 {
11133 	bool ret;
11134 
11135 	switch (node_field_type) {
11136 	case BPF_LIST_NODE:
11137 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11138 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11139 		break;
11140 	case BPF_RB_NODE:
11141 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11142 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11143 		break;
11144 	default:
11145 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11146 			btf_field_type_name(node_field_type));
11147 		return false;
11148 	}
11149 
11150 	if (!ret)
11151 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11152 			btf_field_type_name(node_field_type));
11153 	return ret;
11154 }
11155 
11156 static int
11157 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11158 				   struct bpf_reg_state *reg, u32 regno,
11159 				   struct bpf_kfunc_call_arg_meta *meta,
11160 				   enum btf_field_type head_field_type,
11161 				   struct btf_field **head_field)
11162 {
11163 	const char *head_type_name;
11164 	struct btf_field *field;
11165 	struct btf_record *rec;
11166 	u32 head_off;
11167 
11168 	if (meta->btf != btf_vmlinux) {
11169 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11170 		return -EFAULT;
11171 	}
11172 
11173 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11174 		return -EFAULT;
11175 
11176 	head_type_name = btf_field_type_name(head_field_type);
11177 	if (!tnum_is_const(reg->var_off)) {
11178 		verbose(env,
11179 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11180 			regno, head_type_name);
11181 		return -EINVAL;
11182 	}
11183 
11184 	rec = reg_btf_record(reg);
11185 	head_off = reg->off + reg->var_off.value;
11186 	field = btf_record_find(rec, head_off, head_field_type);
11187 	if (!field) {
11188 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11189 		return -EINVAL;
11190 	}
11191 
11192 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11193 	if (check_reg_allocation_locked(env, reg)) {
11194 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11195 			rec->spin_lock_off, head_type_name);
11196 		return -EINVAL;
11197 	}
11198 
11199 	if (*head_field) {
11200 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11201 		return -EFAULT;
11202 	}
11203 	*head_field = field;
11204 	return 0;
11205 }
11206 
11207 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11208 					   struct bpf_reg_state *reg, u32 regno,
11209 					   struct bpf_kfunc_call_arg_meta *meta)
11210 {
11211 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11212 							  &meta->arg_list_head.field);
11213 }
11214 
11215 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11216 					     struct bpf_reg_state *reg, u32 regno,
11217 					     struct bpf_kfunc_call_arg_meta *meta)
11218 {
11219 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11220 							  &meta->arg_rbtree_root.field);
11221 }
11222 
11223 static int
11224 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11225 				   struct bpf_reg_state *reg, u32 regno,
11226 				   struct bpf_kfunc_call_arg_meta *meta,
11227 				   enum btf_field_type head_field_type,
11228 				   enum btf_field_type node_field_type,
11229 				   struct btf_field **node_field)
11230 {
11231 	const char *node_type_name;
11232 	const struct btf_type *et, *t;
11233 	struct btf_field *field;
11234 	u32 node_off;
11235 
11236 	if (meta->btf != btf_vmlinux) {
11237 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11238 		return -EFAULT;
11239 	}
11240 
11241 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11242 		return -EFAULT;
11243 
11244 	node_type_name = btf_field_type_name(node_field_type);
11245 	if (!tnum_is_const(reg->var_off)) {
11246 		verbose(env,
11247 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11248 			regno, node_type_name);
11249 		return -EINVAL;
11250 	}
11251 
11252 	node_off = reg->off + reg->var_off.value;
11253 	field = reg_find_field_offset(reg, node_off, node_field_type);
11254 	if (!field || field->offset != node_off) {
11255 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11256 		return -EINVAL;
11257 	}
11258 
11259 	field = *node_field;
11260 
11261 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11262 	t = btf_type_by_id(reg->btf, reg->btf_id);
11263 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11264 				  field->graph_root.value_btf_id, true)) {
11265 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11266 			"in struct %s, but arg is at offset=%d in struct %s\n",
11267 			btf_field_type_name(head_field_type),
11268 			btf_field_type_name(node_field_type),
11269 			field->graph_root.node_offset,
11270 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11271 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11272 		return -EINVAL;
11273 	}
11274 	meta->arg_btf = reg->btf;
11275 	meta->arg_btf_id = reg->btf_id;
11276 
11277 	if (node_off != field->graph_root.node_offset) {
11278 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11279 			node_off, btf_field_type_name(node_field_type),
11280 			field->graph_root.node_offset,
11281 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11282 		return -EINVAL;
11283 	}
11284 
11285 	return 0;
11286 }
11287 
11288 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11289 					   struct bpf_reg_state *reg, u32 regno,
11290 					   struct bpf_kfunc_call_arg_meta *meta)
11291 {
11292 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11293 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11294 						  &meta->arg_list_head.field);
11295 }
11296 
11297 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11298 					     struct bpf_reg_state *reg, u32 regno,
11299 					     struct bpf_kfunc_call_arg_meta *meta)
11300 {
11301 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11302 						  BPF_RB_ROOT, BPF_RB_NODE,
11303 						  &meta->arg_rbtree_root.field);
11304 }
11305 
11306 /*
11307  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
11308  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
11309  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
11310  * them can only be attached to some specific hook points.
11311  */
11312 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11313 {
11314 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11315 
11316 	switch (prog_type) {
11317 	case BPF_PROG_TYPE_LSM:
11318 		return true;
11319 	case BPF_PROG_TYPE_TRACING:
11320 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
11321 			return true;
11322 		fallthrough;
11323 	default:
11324 		return env->prog->aux->sleepable;
11325 	}
11326 }
11327 
11328 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11329 			    int insn_idx)
11330 {
11331 	const char *func_name = meta->func_name, *ref_tname;
11332 	const struct btf *btf = meta->btf;
11333 	const struct btf_param *args;
11334 	struct btf_record *rec;
11335 	u32 i, nargs;
11336 	int ret;
11337 
11338 	args = (const struct btf_param *)(meta->func_proto + 1);
11339 	nargs = btf_type_vlen(meta->func_proto);
11340 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11341 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11342 			MAX_BPF_FUNC_REG_ARGS);
11343 		return -EINVAL;
11344 	}
11345 
11346 	/* Check that BTF function arguments match actual types that the
11347 	 * verifier sees.
11348 	 */
11349 	for (i = 0; i < nargs; i++) {
11350 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11351 		const struct btf_type *t, *ref_t, *resolve_ret;
11352 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11353 		u32 regno = i + 1, ref_id, type_size;
11354 		bool is_ret_buf_sz = false;
11355 		int kf_arg_type;
11356 
11357 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11358 
11359 		if (is_kfunc_arg_ignore(btf, &args[i]))
11360 			continue;
11361 
11362 		if (btf_type_is_scalar(t)) {
11363 			if (reg->type != SCALAR_VALUE) {
11364 				verbose(env, "R%d is not a scalar\n", regno);
11365 				return -EINVAL;
11366 			}
11367 
11368 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11369 				if (meta->arg_constant.found) {
11370 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11371 					return -EFAULT;
11372 				}
11373 				if (!tnum_is_const(reg->var_off)) {
11374 					verbose(env, "R%d must be a known constant\n", regno);
11375 					return -EINVAL;
11376 				}
11377 				ret = mark_chain_precision(env, regno);
11378 				if (ret < 0)
11379 					return ret;
11380 				meta->arg_constant.found = true;
11381 				meta->arg_constant.value = reg->var_off.value;
11382 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11383 				meta->r0_rdonly = true;
11384 				is_ret_buf_sz = true;
11385 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11386 				is_ret_buf_sz = true;
11387 			}
11388 
11389 			if (is_ret_buf_sz) {
11390 				if (meta->r0_size) {
11391 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11392 					return -EINVAL;
11393 				}
11394 
11395 				if (!tnum_is_const(reg->var_off)) {
11396 					verbose(env, "R%d is not a const\n", regno);
11397 					return -EINVAL;
11398 				}
11399 
11400 				meta->r0_size = reg->var_off.value;
11401 				ret = mark_chain_precision(env, regno);
11402 				if (ret)
11403 					return ret;
11404 			}
11405 			continue;
11406 		}
11407 
11408 		if (!btf_type_is_ptr(t)) {
11409 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11410 			return -EINVAL;
11411 		}
11412 
11413 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11414 		    (register_is_null(reg) || type_may_be_null(reg->type)) &&
11415 			!is_kfunc_arg_nullable(meta->btf, &args[i])) {
11416 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11417 			return -EACCES;
11418 		}
11419 
11420 		if (reg->ref_obj_id) {
11421 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
11422 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11423 					regno, reg->ref_obj_id,
11424 					meta->ref_obj_id);
11425 				return -EFAULT;
11426 			}
11427 			meta->ref_obj_id = reg->ref_obj_id;
11428 			if (is_kfunc_release(meta))
11429 				meta->release_regno = regno;
11430 		}
11431 
11432 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11433 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11434 
11435 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11436 		if (kf_arg_type < 0)
11437 			return kf_arg_type;
11438 
11439 		switch (kf_arg_type) {
11440 		case KF_ARG_PTR_TO_NULL:
11441 			continue;
11442 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11443 		case KF_ARG_PTR_TO_BTF_ID:
11444 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11445 				break;
11446 
11447 			if (!is_trusted_reg(reg)) {
11448 				if (!is_kfunc_rcu(meta)) {
11449 					verbose(env, "R%d must be referenced or trusted\n", regno);
11450 					return -EINVAL;
11451 				}
11452 				if (!is_rcu_reg(reg)) {
11453 					verbose(env, "R%d must be a rcu pointer\n", regno);
11454 					return -EINVAL;
11455 				}
11456 			}
11457 
11458 			fallthrough;
11459 		case KF_ARG_PTR_TO_CTX:
11460 			/* Trusted arguments have the same offset checks as release arguments */
11461 			arg_type |= OBJ_RELEASE;
11462 			break;
11463 		case KF_ARG_PTR_TO_DYNPTR:
11464 		case KF_ARG_PTR_TO_ITER:
11465 		case KF_ARG_PTR_TO_LIST_HEAD:
11466 		case KF_ARG_PTR_TO_LIST_NODE:
11467 		case KF_ARG_PTR_TO_RB_ROOT:
11468 		case KF_ARG_PTR_TO_RB_NODE:
11469 		case KF_ARG_PTR_TO_MEM:
11470 		case KF_ARG_PTR_TO_MEM_SIZE:
11471 		case KF_ARG_PTR_TO_CALLBACK:
11472 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11473 		case KF_ARG_PTR_TO_CONST_STR:
11474 			/* Trusted by default */
11475 			break;
11476 		default:
11477 			WARN_ON_ONCE(1);
11478 			return -EFAULT;
11479 		}
11480 
11481 		if (is_kfunc_release(meta) && reg->ref_obj_id)
11482 			arg_type |= OBJ_RELEASE;
11483 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11484 		if (ret < 0)
11485 			return ret;
11486 
11487 		switch (kf_arg_type) {
11488 		case KF_ARG_PTR_TO_CTX:
11489 			if (reg->type != PTR_TO_CTX) {
11490 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11491 				return -EINVAL;
11492 			}
11493 
11494 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11495 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11496 				if (ret < 0)
11497 					return -EINVAL;
11498 				meta->ret_btf_id  = ret;
11499 			}
11500 			break;
11501 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11502 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
11503 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
11504 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
11505 					return -EINVAL;
11506 				}
11507 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
11508 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
11509 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
11510 					return -EINVAL;
11511 				}
11512 			} else {
11513 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11514 				return -EINVAL;
11515 			}
11516 			if (!reg->ref_obj_id) {
11517 				verbose(env, "allocated object must be referenced\n");
11518 				return -EINVAL;
11519 			}
11520 			if (meta->btf == btf_vmlinux) {
11521 				meta->arg_btf = reg->btf;
11522 				meta->arg_btf_id = reg->btf_id;
11523 			}
11524 			break;
11525 		case KF_ARG_PTR_TO_DYNPTR:
11526 		{
11527 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11528 			int clone_ref_obj_id = 0;
11529 
11530 			if (reg->type != PTR_TO_STACK &&
11531 			    reg->type != CONST_PTR_TO_DYNPTR) {
11532 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11533 				return -EINVAL;
11534 			}
11535 
11536 			if (reg->type == CONST_PTR_TO_DYNPTR)
11537 				dynptr_arg_type |= MEM_RDONLY;
11538 
11539 			if (is_kfunc_arg_uninit(btf, &args[i]))
11540 				dynptr_arg_type |= MEM_UNINIT;
11541 
11542 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11543 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11544 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11545 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
11546 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11547 				   (dynptr_arg_type & MEM_UNINIT)) {
11548 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11549 
11550 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11551 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11552 					return -EFAULT;
11553 				}
11554 
11555 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11556 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11557 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11558 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11559 					return -EFAULT;
11560 				}
11561 			}
11562 
11563 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11564 			if (ret < 0)
11565 				return ret;
11566 
11567 			if (!(dynptr_arg_type & MEM_UNINIT)) {
11568 				int id = dynptr_id(env, reg);
11569 
11570 				if (id < 0) {
11571 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11572 					return id;
11573 				}
11574 				meta->initialized_dynptr.id = id;
11575 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11576 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11577 			}
11578 
11579 			break;
11580 		}
11581 		case KF_ARG_PTR_TO_ITER:
11582 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
11583 				if (!check_css_task_iter_allowlist(env)) {
11584 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
11585 					return -EINVAL;
11586 				}
11587 			}
11588 			ret = process_iter_arg(env, regno, insn_idx, meta);
11589 			if (ret < 0)
11590 				return ret;
11591 			break;
11592 		case KF_ARG_PTR_TO_LIST_HEAD:
11593 			if (reg->type != PTR_TO_MAP_VALUE &&
11594 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11595 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11596 				return -EINVAL;
11597 			}
11598 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11599 				verbose(env, "allocated object must be referenced\n");
11600 				return -EINVAL;
11601 			}
11602 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11603 			if (ret < 0)
11604 				return ret;
11605 			break;
11606 		case KF_ARG_PTR_TO_RB_ROOT:
11607 			if (reg->type != PTR_TO_MAP_VALUE &&
11608 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11609 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11610 				return -EINVAL;
11611 			}
11612 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11613 				verbose(env, "allocated object must be referenced\n");
11614 				return -EINVAL;
11615 			}
11616 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11617 			if (ret < 0)
11618 				return ret;
11619 			break;
11620 		case KF_ARG_PTR_TO_LIST_NODE:
11621 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11622 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11623 				return -EINVAL;
11624 			}
11625 			if (!reg->ref_obj_id) {
11626 				verbose(env, "allocated object must be referenced\n");
11627 				return -EINVAL;
11628 			}
11629 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11630 			if (ret < 0)
11631 				return ret;
11632 			break;
11633 		case KF_ARG_PTR_TO_RB_NODE:
11634 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11635 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11636 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
11637 					return -EINVAL;
11638 				}
11639 				if (in_rbtree_lock_required_cb(env)) {
11640 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11641 					return -EINVAL;
11642 				}
11643 			} else {
11644 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11645 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
11646 					return -EINVAL;
11647 				}
11648 				if (!reg->ref_obj_id) {
11649 					verbose(env, "allocated object must be referenced\n");
11650 					return -EINVAL;
11651 				}
11652 			}
11653 
11654 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11655 			if (ret < 0)
11656 				return ret;
11657 			break;
11658 		case KF_ARG_PTR_TO_BTF_ID:
11659 			/* Only base_type is checked, further checks are done here */
11660 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11661 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11662 			    !reg2btf_ids[base_type(reg->type)]) {
11663 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11664 				verbose(env, "expected %s or socket\n",
11665 					reg_type_str(env, base_type(reg->type) |
11666 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11667 				return -EINVAL;
11668 			}
11669 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11670 			if (ret < 0)
11671 				return ret;
11672 			break;
11673 		case KF_ARG_PTR_TO_MEM:
11674 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11675 			if (IS_ERR(resolve_ret)) {
11676 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11677 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11678 				return -EINVAL;
11679 			}
11680 			ret = check_mem_reg(env, reg, regno, type_size);
11681 			if (ret < 0)
11682 				return ret;
11683 			break;
11684 		case KF_ARG_PTR_TO_MEM_SIZE:
11685 		{
11686 			struct bpf_reg_state *buff_reg = &regs[regno];
11687 			const struct btf_param *buff_arg = &args[i];
11688 			struct bpf_reg_state *size_reg = &regs[regno + 1];
11689 			const struct btf_param *size_arg = &args[i + 1];
11690 
11691 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11692 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11693 				if (ret < 0) {
11694 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11695 					return ret;
11696 				}
11697 			}
11698 
11699 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11700 				if (meta->arg_constant.found) {
11701 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11702 					return -EFAULT;
11703 				}
11704 				if (!tnum_is_const(size_reg->var_off)) {
11705 					verbose(env, "R%d must be a known constant\n", regno + 1);
11706 					return -EINVAL;
11707 				}
11708 				meta->arg_constant.found = true;
11709 				meta->arg_constant.value = size_reg->var_off.value;
11710 			}
11711 
11712 			/* Skip next '__sz' or '__szk' argument */
11713 			i++;
11714 			break;
11715 		}
11716 		case KF_ARG_PTR_TO_CALLBACK:
11717 			if (reg->type != PTR_TO_FUNC) {
11718 				verbose(env, "arg%d expected pointer to func\n", i);
11719 				return -EINVAL;
11720 			}
11721 			meta->subprogno = reg->subprogno;
11722 			break;
11723 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11724 			if (!type_is_ptr_alloc_obj(reg->type)) {
11725 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11726 				return -EINVAL;
11727 			}
11728 			if (!type_is_non_owning_ref(reg->type))
11729 				meta->arg_owning_ref = true;
11730 
11731 			rec = reg_btf_record(reg);
11732 			if (!rec) {
11733 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
11734 				return -EFAULT;
11735 			}
11736 
11737 			if (rec->refcount_off < 0) {
11738 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11739 				return -EINVAL;
11740 			}
11741 
11742 			meta->arg_btf = reg->btf;
11743 			meta->arg_btf_id = reg->btf_id;
11744 			break;
11745 		case KF_ARG_PTR_TO_CONST_STR:
11746 			if (reg->type != PTR_TO_MAP_VALUE) {
11747 				verbose(env, "arg#%d doesn't point to a const string\n", i);
11748 				return -EINVAL;
11749 			}
11750 			ret = check_reg_const_str(env, reg, regno);
11751 			if (ret)
11752 				return ret;
11753 			break;
11754 		}
11755 	}
11756 
11757 	if (is_kfunc_release(meta) && !meta->release_regno) {
11758 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11759 			func_name);
11760 		return -EINVAL;
11761 	}
11762 
11763 	return 0;
11764 }
11765 
11766 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11767 			    struct bpf_insn *insn,
11768 			    struct bpf_kfunc_call_arg_meta *meta,
11769 			    const char **kfunc_name)
11770 {
11771 	const struct btf_type *func, *func_proto;
11772 	u32 func_id, *kfunc_flags;
11773 	const char *func_name;
11774 	struct btf *desc_btf;
11775 
11776 	if (kfunc_name)
11777 		*kfunc_name = NULL;
11778 
11779 	if (!insn->imm)
11780 		return -EINVAL;
11781 
11782 	desc_btf = find_kfunc_desc_btf(env, insn->off);
11783 	if (IS_ERR(desc_btf))
11784 		return PTR_ERR(desc_btf);
11785 
11786 	func_id = insn->imm;
11787 	func = btf_type_by_id(desc_btf, func_id);
11788 	func_name = btf_name_by_offset(desc_btf, func->name_off);
11789 	if (kfunc_name)
11790 		*kfunc_name = func_name;
11791 	func_proto = btf_type_by_id(desc_btf, func->type);
11792 
11793 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11794 	if (!kfunc_flags) {
11795 		return -EACCES;
11796 	}
11797 
11798 	memset(meta, 0, sizeof(*meta));
11799 	meta->btf = desc_btf;
11800 	meta->func_id = func_id;
11801 	meta->kfunc_flags = *kfunc_flags;
11802 	meta->func_proto = func_proto;
11803 	meta->func_name = func_name;
11804 
11805 	return 0;
11806 }
11807 
11808 static int check_return_code(struct bpf_verifier_env *env, int regno);
11809 
11810 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11811 			    int *insn_idx_p)
11812 {
11813 	const struct btf_type *t, *ptr_type;
11814 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
11815 	struct bpf_reg_state *regs = cur_regs(env);
11816 	const char *func_name, *ptr_type_name;
11817 	bool sleepable, rcu_lock, rcu_unlock;
11818 	struct bpf_kfunc_call_arg_meta meta;
11819 	struct bpf_insn_aux_data *insn_aux;
11820 	int err, insn_idx = *insn_idx_p;
11821 	const struct btf_param *args;
11822 	const struct btf_type *ret_t;
11823 	struct btf *desc_btf;
11824 
11825 	/* skip for now, but return error when we find this in fixup_kfunc_call */
11826 	if (!insn->imm)
11827 		return 0;
11828 
11829 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11830 	if (err == -EACCES && func_name)
11831 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
11832 	if (err)
11833 		return err;
11834 	desc_btf = meta.btf;
11835 	insn_aux = &env->insn_aux_data[insn_idx];
11836 
11837 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11838 
11839 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11840 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11841 		return -EACCES;
11842 	}
11843 
11844 	sleepable = is_kfunc_sleepable(&meta);
11845 	if (sleepable && !env->prog->aux->sleepable) {
11846 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11847 		return -EACCES;
11848 	}
11849 
11850 	/* Check the arguments */
11851 	err = check_kfunc_args(env, &meta, insn_idx);
11852 	if (err < 0)
11853 		return err;
11854 
11855 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11856 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11857 					 set_rbtree_add_callback_state);
11858 		if (err) {
11859 			verbose(env, "kfunc %s#%d failed callback verification\n",
11860 				func_name, meta.func_id);
11861 			return err;
11862 		}
11863 	}
11864 
11865 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11866 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11867 
11868 	if (env->cur_state->active_rcu_lock) {
11869 		struct bpf_func_state *state;
11870 		struct bpf_reg_state *reg;
11871 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
11872 
11873 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11874 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11875 			return -EACCES;
11876 		}
11877 
11878 		if (rcu_lock) {
11879 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11880 			return -EINVAL;
11881 		} else if (rcu_unlock) {
11882 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
11883 				if (reg->type & MEM_RCU) {
11884 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11885 					reg->type |= PTR_UNTRUSTED;
11886 				}
11887 			}));
11888 			env->cur_state->active_rcu_lock = false;
11889 		} else if (sleepable) {
11890 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11891 			return -EACCES;
11892 		}
11893 	} else if (rcu_lock) {
11894 		env->cur_state->active_rcu_lock = true;
11895 	} else if (rcu_unlock) {
11896 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11897 		return -EINVAL;
11898 	}
11899 
11900 	/* In case of release function, we get register number of refcounted
11901 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11902 	 */
11903 	if (meta.release_regno) {
11904 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11905 		if (err) {
11906 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11907 				func_name, meta.func_id);
11908 			return err;
11909 		}
11910 	}
11911 
11912 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11913 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11914 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11915 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11916 		insn_aux->insert_off = regs[BPF_REG_2].off;
11917 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11918 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11919 		if (err) {
11920 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11921 				func_name, meta.func_id);
11922 			return err;
11923 		}
11924 
11925 		err = release_reference(env, release_ref_obj_id);
11926 		if (err) {
11927 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11928 				func_name, meta.func_id);
11929 			return err;
11930 		}
11931 	}
11932 
11933 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
11934 		if (!bpf_jit_supports_exceptions()) {
11935 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
11936 				func_name, meta.func_id);
11937 			return -ENOTSUPP;
11938 		}
11939 		env->seen_exception = true;
11940 
11941 		/* In the case of the default callback, the cookie value passed
11942 		 * to bpf_throw becomes the return value of the program.
11943 		 */
11944 		if (!env->exception_callback_subprog) {
11945 			err = check_return_code(env, BPF_REG_1);
11946 			if (err < 0)
11947 				return err;
11948 		}
11949 	}
11950 
11951 	for (i = 0; i < CALLER_SAVED_REGS; i++)
11952 		mark_reg_not_init(env, regs, caller_saved[i]);
11953 
11954 	/* Check return type */
11955 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11956 
11957 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11958 		/* Only exception is bpf_obj_new_impl */
11959 		if (meta.btf != btf_vmlinux ||
11960 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11961 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
11962 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11963 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11964 			return -EINVAL;
11965 		}
11966 	}
11967 
11968 	if (btf_type_is_scalar(t)) {
11969 		mark_reg_unknown(env, regs, BPF_REG_0);
11970 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11971 	} else if (btf_type_is_ptr(t)) {
11972 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11973 
11974 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11975 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
11976 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
11977 				struct btf_struct_meta *struct_meta;
11978 				struct btf *ret_btf;
11979 				u32 ret_btf_id;
11980 
11981 				if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
11982 					return -ENOMEM;
11983 
11984 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
11985 					if (!bpf_global_percpu_ma_set) {
11986 						mutex_lock(&bpf_percpu_ma_lock);
11987 						if (!bpf_global_percpu_ma_set) {
11988 							err = bpf_mem_alloc_init(&bpf_global_percpu_ma, 0, true);
11989 							if (!err)
11990 								bpf_global_percpu_ma_set = true;
11991 						}
11992 						mutex_unlock(&bpf_percpu_ma_lock);
11993 						if (err)
11994 							return err;
11995 					}
11996 				}
11997 
11998 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11999 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12000 					return -EINVAL;
12001 				}
12002 
12003 				ret_btf = env->prog->aux->btf;
12004 				ret_btf_id = meta.arg_constant.value;
12005 
12006 				/* This may be NULL due to user not supplying a BTF */
12007 				if (!ret_btf) {
12008 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12009 					return -EINVAL;
12010 				}
12011 
12012 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12013 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
12014 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12015 					return -EINVAL;
12016 				}
12017 
12018 				struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12019 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12020 					if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12021 						verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12022 						return -EINVAL;
12023 					}
12024 
12025 					if (struct_meta) {
12026 						verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12027 						return -EINVAL;
12028 					}
12029 				}
12030 
12031 				mark_reg_known_zero(env, regs, BPF_REG_0);
12032 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12033 				regs[BPF_REG_0].btf = ret_btf;
12034 				regs[BPF_REG_0].btf_id = ret_btf_id;
12035 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12036 					regs[BPF_REG_0].type |= MEM_PERCPU;
12037 
12038 				insn_aux->obj_new_size = ret_t->size;
12039 				insn_aux->kptr_struct_meta = struct_meta;
12040 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12041 				mark_reg_known_zero(env, regs, BPF_REG_0);
12042 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12043 				regs[BPF_REG_0].btf = meta.arg_btf;
12044 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
12045 
12046 				insn_aux->kptr_struct_meta =
12047 					btf_find_struct_meta(meta.arg_btf,
12048 							     meta.arg_btf_id);
12049 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12050 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12051 				struct btf_field *field = meta.arg_list_head.field;
12052 
12053 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12054 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12055 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12056 				struct btf_field *field = meta.arg_rbtree_root.field;
12057 
12058 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12059 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12060 				mark_reg_known_zero(env, regs, BPF_REG_0);
12061 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12062 				regs[BPF_REG_0].btf = desc_btf;
12063 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12064 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12065 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12066 				if (!ret_t || !btf_type_is_struct(ret_t)) {
12067 					verbose(env,
12068 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
12069 					return -EINVAL;
12070 				}
12071 
12072 				mark_reg_known_zero(env, regs, BPF_REG_0);
12073 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12074 				regs[BPF_REG_0].btf = desc_btf;
12075 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
12076 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12077 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12078 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
12079 
12080 				mark_reg_known_zero(env, regs, BPF_REG_0);
12081 
12082 				if (!meta.arg_constant.found) {
12083 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
12084 					return -EFAULT;
12085 				}
12086 
12087 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
12088 
12089 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12090 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12091 
12092 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12093 					regs[BPF_REG_0].type |= MEM_RDONLY;
12094 				} else {
12095 					/* this will set env->seen_direct_write to true */
12096 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12097 						verbose(env, "the prog does not allow writes to packet data\n");
12098 						return -EINVAL;
12099 					}
12100 				}
12101 
12102 				if (!meta.initialized_dynptr.id) {
12103 					verbose(env, "verifier internal error: no dynptr id\n");
12104 					return -EFAULT;
12105 				}
12106 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
12107 
12108 				/* we don't need to set BPF_REG_0's ref obj id
12109 				 * because packet slices are not refcounted (see
12110 				 * dynptr_type_refcounted)
12111 				 */
12112 			} else {
12113 				verbose(env, "kernel function %s unhandled dynamic return type\n",
12114 					meta.func_name);
12115 				return -EFAULT;
12116 			}
12117 		} else if (!__btf_type_is_struct(ptr_type)) {
12118 			if (!meta.r0_size) {
12119 				__u32 sz;
12120 
12121 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
12122 					meta.r0_size = sz;
12123 					meta.r0_rdonly = true;
12124 				}
12125 			}
12126 			if (!meta.r0_size) {
12127 				ptr_type_name = btf_name_by_offset(desc_btf,
12128 								   ptr_type->name_off);
12129 				verbose(env,
12130 					"kernel function %s returns pointer type %s %s is not supported\n",
12131 					func_name,
12132 					btf_type_str(ptr_type),
12133 					ptr_type_name);
12134 				return -EINVAL;
12135 			}
12136 
12137 			mark_reg_known_zero(env, regs, BPF_REG_0);
12138 			regs[BPF_REG_0].type = PTR_TO_MEM;
12139 			regs[BPF_REG_0].mem_size = meta.r0_size;
12140 
12141 			if (meta.r0_rdonly)
12142 				regs[BPF_REG_0].type |= MEM_RDONLY;
12143 
12144 			/* Ensures we don't access the memory after a release_reference() */
12145 			if (meta.ref_obj_id)
12146 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12147 		} else {
12148 			mark_reg_known_zero(env, regs, BPF_REG_0);
12149 			regs[BPF_REG_0].btf = desc_btf;
12150 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12151 			regs[BPF_REG_0].btf_id = ptr_type_id;
12152 		}
12153 
12154 		if (is_kfunc_ret_null(&meta)) {
12155 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12156 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12157 			regs[BPF_REG_0].id = ++env->id_gen;
12158 		}
12159 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12160 		if (is_kfunc_acquire(&meta)) {
12161 			int id = acquire_reference_state(env, insn_idx);
12162 
12163 			if (id < 0)
12164 				return id;
12165 			if (is_kfunc_ret_null(&meta))
12166 				regs[BPF_REG_0].id = id;
12167 			regs[BPF_REG_0].ref_obj_id = id;
12168 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12169 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12170 		}
12171 
12172 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12173 			regs[BPF_REG_0].id = ++env->id_gen;
12174 	} else if (btf_type_is_void(t)) {
12175 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12176 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
12177 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12178 				insn_aux->kptr_struct_meta =
12179 					btf_find_struct_meta(meta.arg_btf,
12180 							     meta.arg_btf_id);
12181 			}
12182 		}
12183 	}
12184 
12185 	nargs = btf_type_vlen(meta.func_proto);
12186 	args = (const struct btf_param *)(meta.func_proto + 1);
12187 	for (i = 0; i < nargs; i++) {
12188 		u32 regno = i + 1;
12189 
12190 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12191 		if (btf_type_is_ptr(t))
12192 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12193 		else
12194 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12195 			mark_btf_func_reg_size(env, regno, t->size);
12196 	}
12197 
12198 	if (is_iter_next_kfunc(&meta)) {
12199 		err = process_iter_next_call(env, insn_idx, &meta);
12200 		if (err)
12201 			return err;
12202 	}
12203 
12204 	return 0;
12205 }
12206 
12207 static bool signed_add_overflows(s64 a, s64 b)
12208 {
12209 	/* Do the add in u64, where overflow is well-defined */
12210 	s64 res = (s64)((u64)a + (u64)b);
12211 
12212 	if (b < 0)
12213 		return res > a;
12214 	return res < a;
12215 }
12216 
12217 static bool signed_add32_overflows(s32 a, s32 b)
12218 {
12219 	/* Do the add in u32, where overflow is well-defined */
12220 	s32 res = (s32)((u32)a + (u32)b);
12221 
12222 	if (b < 0)
12223 		return res > a;
12224 	return res < a;
12225 }
12226 
12227 static bool signed_sub_overflows(s64 a, s64 b)
12228 {
12229 	/* Do the sub in u64, where overflow is well-defined */
12230 	s64 res = (s64)((u64)a - (u64)b);
12231 
12232 	if (b < 0)
12233 		return res < a;
12234 	return res > a;
12235 }
12236 
12237 static bool signed_sub32_overflows(s32 a, s32 b)
12238 {
12239 	/* Do the sub in u32, where overflow is well-defined */
12240 	s32 res = (s32)((u32)a - (u32)b);
12241 
12242 	if (b < 0)
12243 		return res < a;
12244 	return res > a;
12245 }
12246 
12247 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12248 				  const struct bpf_reg_state *reg,
12249 				  enum bpf_reg_type type)
12250 {
12251 	bool known = tnum_is_const(reg->var_off);
12252 	s64 val = reg->var_off.value;
12253 	s64 smin = reg->smin_value;
12254 
12255 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12256 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12257 			reg_type_str(env, type), val);
12258 		return false;
12259 	}
12260 
12261 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12262 		verbose(env, "%s pointer offset %d is not allowed\n",
12263 			reg_type_str(env, type), reg->off);
12264 		return false;
12265 	}
12266 
12267 	if (smin == S64_MIN) {
12268 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12269 			reg_type_str(env, type));
12270 		return false;
12271 	}
12272 
12273 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12274 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12275 			smin, reg_type_str(env, type));
12276 		return false;
12277 	}
12278 
12279 	return true;
12280 }
12281 
12282 enum {
12283 	REASON_BOUNDS	= -1,
12284 	REASON_TYPE	= -2,
12285 	REASON_PATHS	= -3,
12286 	REASON_LIMIT	= -4,
12287 	REASON_STACK	= -5,
12288 };
12289 
12290 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12291 			      u32 *alu_limit, bool mask_to_left)
12292 {
12293 	u32 max = 0, ptr_limit = 0;
12294 
12295 	switch (ptr_reg->type) {
12296 	case PTR_TO_STACK:
12297 		/* Offset 0 is out-of-bounds, but acceptable start for the
12298 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12299 		 * offset where we would need to deal with min/max bounds is
12300 		 * currently prohibited for unprivileged.
12301 		 */
12302 		max = MAX_BPF_STACK + mask_to_left;
12303 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12304 		break;
12305 	case PTR_TO_MAP_VALUE:
12306 		max = ptr_reg->map_ptr->value_size;
12307 		ptr_limit = (mask_to_left ?
12308 			     ptr_reg->smin_value :
12309 			     ptr_reg->umax_value) + ptr_reg->off;
12310 		break;
12311 	default:
12312 		return REASON_TYPE;
12313 	}
12314 
12315 	if (ptr_limit >= max)
12316 		return REASON_LIMIT;
12317 	*alu_limit = ptr_limit;
12318 	return 0;
12319 }
12320 
12321 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12322 				    const struct bpf_insn *insn)
12323 {
12324 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12325 }
12326 
12327 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12328 				       u32 alu_state, u32 alu_limit)
12329 {
12330 	/* If we arrived here from different branches with different
12331 	 * state or limits to sanitize, then this won't work.
12332 	 */
12333 	if (aux->alu_state &&
12334 	    (aux->alu_state != alu_state ||
12335 	     aux->alu_limit != alu_limit))
12336 		return REASON_PATHS;
12337 
12338 	/* Corresponding fixup done in do_misc_fixups(). */
12339 	aux->alu_state = alu_state;
12340 	aux->alu_limit = alu_limit;
12341 	return 0;
12342 }
12343 
12344 static int sanitize_val_alu(struct bpf_verifier_env *env,
12345 			    struct bpf_insn *insn)
12346 {
12347 	struct bpf_insn_aux_data *aux = cur_aux(env);
12348 
12349 	if (can_skip_alu_sanitation(env, insn))
12350 		return 0;
12351 
12352 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12353 }
12354 
12355 static bool sanitize_needed(u8 opcode)
12356 {
12357 	return opcode == BPF_ADD || opcode == BPF_SUB;
12358 }
12359 
12360 struct bpf_sanitize_info {
12361 	struct bpf_insn_aux_data aux;
12362 	bool mask_to_left;
12363 };
12364 
12365 static struct bpf_verifier_state *
12366 sanitize_speculative_path(struct bpf_verifier_env *env,
12367 			  const struct bpf_insn *insn,
12368 			  u32 next_idx, u32 curr_idx)
12369 {
12370 	struct bpf_verifier_state *branch;
12371 	struct bpf_reg_state *regs;
12372 
12373 	branch = push_stack(env, next_idx, curr_idx, true);
12374 	if (branch && insn) {
12375 		regs = branch->frame[branch->curframe]->regs;
12376 		if (BPF_SRC(insn->code) == BPF_K) {
12377 			mark_reg_unknown(env, regs, insn->dst_reg);
12378 		} else if (BPF_SRC(insn->code) == BPF_X) {
12379 			mark_reg_unknown(env, regs, insn->dst_reg);
12380 			mark_reg_unknown(env, regs, insn->src_reg);
12381 		}
12382 	}
12383 	return branch;
12384 }
12385 
12386 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12387 			    struct bpf_insn *insn,
12388 			    const struct bpf_reg_state *ptr_reg,
12389 			    const struct bpf_reg_state *off_reg,
12390 			    struct bpf_reg_state *dst_reg,
12391 			    struct bpf_sanitize_info *info,
12392 			    const bool commit_window)
12393 {
12394 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12395 	struct bpf_verifier_state *vstate = env->cur_state;
12396 	bool off_is_imm = tnum_is_const(off_reg->var_off);
12397 	bool off_is_neg = off_reg->smin_value < 0;
12398 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12399 	u8 opcode = BPF_OP(insn->code);
12400 	u32 alu_state, alu_limit;
12401 	struct bpf_reg_state tmp;
12402 	bool ret;
12403 	int err;
12404 
12405 	if (can_skip_alu_sanitation(env, insn))
12406 		return 0;
12407 
12408 	/* We already marked aux for masking from non-speculative
12409 	 * paths, thus we got here in the first place. We only care
12410 	 * to explore bad access from here.
12411 	 */
12412 	if (vstate->speculative)
12413 		goto do_sim;
12414 
12415 	if (!commit_window) {
12416 		if (!tnum_is_const(off_reg->var_off) &&
12417 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12418 			return REASON_BOUNDS;
12419 
12420 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12421 				     (opcode == BPF_SUB && !off_is_neg);
12422 	}
12423 
12424 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12425 	if (err < 0)
12426 		return err;
12427 
12428 	if (commit_window) {
12429 		/* In commit phase we narrow the masking window based on
12430 		 * the observed pointer move after the simulated operation.
12431 		 */
12432 		alu_state = info->aux.alu_state;
12433 		alu_limit = abs(info->aux.alu_limit - alu_limit);
12434 	} else {
12435 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12436 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12437 		alu_state |= ptr_is_dst_reg ?
12438 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12439 
12440 		/* Limit pruning on unknown scalars to enable deep search for
12441 		 * potential masking differences from other program paths.
12442 		 */
12443 		if (!off_is_imm)
12444 			env->explore_alu_limits = true;
12445 	}
12446 
12447 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12448 	if (err < 0)
12449 		return err;
12450 do_sim:
12451 	/* If we're in commit phase, we're done here given we already
12452 	 * pushed the truncated dst_reg into the speculative verification
12453 	 * stack.
12454 	 *
12455 	 * Also, when register is a known constant, we rewrite register-based
12456 	 * operation to immediate-based, and thus do not need masking (and as
12457 	 * a consequence, do not need to simulate the zero-truncation either).
12458 	 */
12459 	if (commit_window || off_is_imm)
12460 		return 0;
12461 
12462 	/* Simulate and find potential out-of-bounds access under
12463 	 * speculative execution from truncation as a result of
12464 	 * masking when off was not within expected range. If off
12465 	 * sits in dst, then we temporarily need to move ptr there
12466 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12467 	 * for cases where we use K-based arithmetic in one direction
12468 	 * and truncated reg-based in the other in order to explore
12469 	 * bad access.
12470 	 */
12471 	if (!ptr_is_dst_reg) {
12472 		tmp = *dst_reg;
12473 		copy_register_state(dst_reg, ptr_reg);
12474 	}
12475 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12476 					env->insn_idx);
12477 	if (!ptr_is_dst_reg && ret)
12478 		*dst_reg = tmp;
12479 	return !ret ? REASON_STACK : 0;
12480 }
12481 
12482 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12483 {
12484 	struct bpf_verifier_state *vstate = env->cur_state;
12485 
12486 	/* If we simulate paths under speculation, we don't update the
12487 	 * insn as 'seen' such that when we verify unreachable paths in
12488 	 * the non-speculative domain, sanitize_dead_code() can still
12489 	 * rewrite/sanitize them.
12490 	 */
12491 	if (!vstate->speculative)
12492 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12493 }
12494 
12495 static int sanitize_err(struct bpf_verifier_env *env,
12496 			const struct bpf_insn *insn, int reason,
12497 			const struct bpf_reg_state *off_reg,
12498 			const struct bpf_reg_state *dst_reg)
12499 {
12500 	static const char *err = "pointer arithmetic with it prohibited for !root";
12501 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12502 	u32 dst = insn->dst_reg, src = insn->src_reg;
12503 
12504 	switch (reason) {
12505 	case REASON_BOUNDS:
12506 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12507 			off_reg == dst_reg ? dst : src, err);
12508 		break;
12509 	case REASON_TYPE:
12510 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12511 			off_reg == dst_reg ? src : dst, err);
12512 		break;
12513 	case REASON_PATHS:
12514 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12515 			dst, op, err);
12516 		break;
12517 	case REASON_LIMIT:
12518 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12519 			dst, op, err);
12520 		break;
12521 	case REASON_STACK:
12522 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12523 			dst, err);
12524 		break;
12525 	default:
12526 		verbose(env, "verifier internal error: unknown reason (%d)\n",
12527 			reason);
12528 		break;
12529 	}
12530 
12531 	return -EACCES;
12532 }
12533 
12534 /* check that stack access falls within stack limits and that 'reg' doesn't
12535  * have a variable offset.
12536  *
12537  * Variable offset is prohibited for unprivileged mode for simplicity since it
12538  * requires corresponding support in Spectre masking for stack ALU.  See also
12539  * retrieve_ptr_limit().
12540  *
12541  *
12542  * 'off' includes 'reg->off'.
12543  */
12544 static int check_stack_access_for_ptr_arithmetic(
12545 				struct bpf_verifier_env *env,
12546 				int regno,
12547 				const struct bpf_reg_state *reg,
12548 				int off)
12549 {
12550 	if (!tnum_is_const(reg->var_off)) {
12551 		char tn_buf[48];
12552 
12553 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12554 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12555 			regno, tn_buf, off);
12556 		return -EACCES;
12557 	}
12558 
12559 	if (off >= 0 || off < -MAX_BPF_STACK) {
12560 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
12561 			"prohibited for !root; off=%d\n", regno, off);
12562 		return -EACCES;
12563 	}
12564 
12565 	return 0;
12566 }
12567 
12568 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12569 				 const struct bpf_insn *insn,
12570 				 const struct bpf_reg_state *dst_reg)
12571 {
12572 	u32 dst = insn->dst_reg;
12573 
12574 	/* For unprivileged we require that resulting offset must be in bounds
12575 	 * in order to be able to sanitize access later on.
12576 	 */
12577 	if (env->bypass_spec_v1)
12578 		return 0;
12579 
12580 	switch (dst_reg->type) {
12581 	case PTR_TO_STACK:
12582 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12583 					dst_reg->off + dst_reg->var_off.value))
12584 			return -EACCES;
12585 		break;
12586 	case PTR_TO_MAP_VALUE:
12587 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12588 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12589 				"prohibited for !root\n", dst);
12590 			return -EACCES;
12591 		}
12592 		break;
12593 	default:
12594 		break;
12595 	}
12596 
12597 	return 0;
12598 }
12599 
12600 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12601  * Caller should also handle BPF_MOV case separately.
12602  * If we return -EACCES, caller may want to try again treating pointer as a
12603  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12604  */
12605 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12606 				   struct bpf_insn *insn,
12607 				   const struct bpf_reg_state *ptr_reg,
12608 				   const struct bpf_reg_state *off_reg)
12609 {
12610 	struct bpf_verifier_state *vstate = env->cur_state;
12611 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12612 	struct bpf_reg_state *regs = state->regs, *dst_reg;
12613 	bool known = tnum_is_const(off_reg->var_off);
12614 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12615 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12616 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12617 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12618 	struct bpf_sanitize_info info = {};
12619 	u8 opcode = BPF_OP(insn->code);
12620 	u32 dst = insn->dst_reg;
12621 	int ret;
12622 
12623 	dst_reg = &regs[dst];
12624 
12625 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12626 	    smin_val > smax_val || umin_val > umax_val) {
12627 		/* Taint dst register if offset had invalid bounds derived from
12628 		 * e.g. dead branches.
12629 		 */
12630 		__mark_reg_unknown(env, dst_reg);
12631 		return 0;
12632 	}
12633 
12634 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
12635 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
12636 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12637 			__mark_reg_unknown(env, dst_reg);
12638 			return 0;
12639 		}
12640 
12641 		verbose(env,
12642 			"R%d 32-bit pointer arithmetic prohibited\n",
12643 			dst);
12644 		return -EACCES;
12645 	}
12646 
12647 	if (ptr_reg->type & PTR_MAYBE_NULL) {
12648 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12649 			dst, reg_type_str(env, ptr_reg->type));
12650 		return -EACCES;
12651 	}
12652 
12653 	switch (base_type(ptr_reg->type)) {
12654 	case CONST_PTR_TO_MAP:
12655 		/* smin_val represents the known value */
12656 		if (known && smin_val == 0 && opcode == BPF_ADD)
12657 			break;
12658 		fallthrough;
12659 	case PTR_TO_PACKET_END:
12660 	case PTR_TO_SOCKET:
12661 	case PTR_TO_SOCK_COMMON:
12662 	case PTR_TO_TCP_SOCK:
12663 	case PTR_TO_XDP_SOCK:
12664 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12665 			dst, reg_type_str(env, ptr_reg->type));
12666 		return -EACCES;
12667 	default:
12668 		break;
12669 	}
12670 
12671 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12672 	 * The id may be overwritten later if we create a new variable offset.
12673 	 */
12674 	dst_reg->type = ptr_reg->type;
12675 	dst_reg->id = ptr_reg->id;
12676 
12677 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12678 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12679 		return -EINVAL;
12680 
12681 	/* pointer types do not carry 32-bit bounds at the moment. */
12682 	__mark_reg32_unbounded(dst_reg);
12683 
12684 	if (sanitize_needed(opcode)) {
12685 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12686 				       &info, false);
12687 		if (ret < 0)
12688 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12689 	}
12690 
12691 	switch (opcode) {
12692 	case BPF_ADD:
12693 		/* We can take a fixed offset as long as it doesn't overflow
12694 		 * the s32 'off' field
12695 		 */
12696 		if (known && (ptr_reg->off + smin_val ==
12697 			      (s64)(s32)(ptr_reg->off + smin_val))) {
12698 			/* pointer += K.  Accumulate it into fixed offset */
12699 			dst_reg->smin_value = smin_ptr;
12700 			dst_reg->smax_value = smax_ptr;
12701 			dst_reg->umin_value = umin_ptr;
12702 			dst_reg->umax_value = umax_ptr;
12703 			dst_reg->var_off = ptr_reg->var_off;
12704 			dst_reg->off = ptr_reg->off + smin_val;
12705 			dst_reg->raw = ptr_reg->raw;
12706 			break;
12707 		}
12708 		/* A new variable offset is created.  Note that off_reg->off
12709 		 * == 0, since it's a scalar.
12710 		 * dst_reg gets the pointer type and since some positive
12711 		 * integer value was added to the pointer, give it a new 'id'
12712 		 * if it's a PTR_TO_PACKET.
12713 		 * this creates a new 'base' pointer, off_reg (variable) gets
12714 		 * added into the variable offset, and we copy the fixed offset
12715 		 * from ptr_reg.
12716 		 */
12717 		if (signed_add_overflows(smin_ptr, smin_val) ||
12718 		    signed_add_overflows(smax_ptr, smax_val)) {
12719 			dst_reg->smin_value = S64_MIN;
12720 			dst_reg->smax_value = S64_MAX;
12721 		} else {
12722 			dst_reg->smin_value = smin_ptr + smin_val;
12723 			dst_reg->smax_value = smax_ptr + smax_val;
12724 		}
12725 		if (umin_ptr + umin_val < umin_ptr ||
12726 		    umax_ptr + umax_val < umax_ptr) {
12727 			dst_reg->umin_value = 0;
12728 			dst_reg->umax_value = U64_MAX;
12729 		} else {
12730 			dst_reg->umin_value = umin_ptr + umin_val;
12731 			dst_reg->umax_value = umax_ptr + umax_val;
12732 		}
12733 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12734 		dst_reg->off = ptr_reg->off;
12735 		dst_reg->raw = ptr_reg->raw;
12736 		if (reg_is_pkt_pointer(ptr_reg)) {
12737 			dst_reg->id = ++env->id_gen;
12738 			/* something was added to pkt_ptr, set range to zero */
12739 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12740 		}
12741 		break;
12742 	case BPF_SUB:
12743 		if (dst_reg == off_reg) {
12744 			/* scalar -= pointer.  Creates an unknown scalar */
12745 			verbose(env, "R%d tried to subtract pointer from scalar\n",
12746 				dst);
12747 			return -EACCES;
12748 		}
12749 		/* We don't allow subtraction from FP, because (according to
12750 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
12751 		 * be able to deal with it.
12752 		 */
12753 		if (ptr_reg->type == PTR_TO_STACK) {
12754 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
12755 				dst);
12756 			return -EACCES;
12757 		}
12758 		if (known && (ptr_reg->off - smin_val ==
12759 			      (s64)(s32)(ptr_reg->off - smin_val))) {
12760 			/* pointer -= K.  Subtract it from fixed offset */
12761 			dst_reg->smin_value = smin_ptr;
12762 			dst_reg->smax_value = smax_ptr;
12763 			dst_reg->umin_value = umin_ptr;
12764 			dst_reg->umax_value = umax_ptr;
12765 			dst_reg->var_off = ptr_reg->var_off;
12766 			dst_reg->id = ptr_reg->id;
12767 			dst_reg->off = ptr_reg->off - smin_val;
12768 			dst_reg->raw = ptr_reg->raw;
12769 			break;
12770 		}
12771 		/* A new variable offset is created.  If the subtrahend is known
12772 		 * nonnegative, then any reg->range we had before is still good.
12773 		 */
12774 		if (signed_sub_overflows(smin_ptr, smax_val) ||
12775 		    signed_sub_overflows(smax_ptr, smin_val)) {
12776 			/* Overflow possible, we know nothing */
12777 			dst_reg->smin_value = S64_MIN;
12778 			dst_reg->smax_value = S64_MAX;
12779 		} else {
12780 			dst_reg->smin_value = smin_ptr - smax_val;
12781 			dst_reg->smax_value = smax_ptr - smin_val;
12782 		}
12783 		if (umin_ptr < umax_val) {
12784 			/* Overflow possible, we know nothing */
12785 			dst_reg->umin_value = 0;
12786 			dst_reg->umax_value = U64_MAX;
12787 		} else {
12788 			/* Cannot overflow (as long as bounds are consistent) */
12789 			dst_reg->umin_value = umin_ptr - umax_val;
12790 			dst_reg->umax_value = umax_ptr - umin_val;
12791 		}
12792 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12793 		dst_reg->off = ptr_reg->off;
12794 		dst_reg->raw = ptr_reg->raw;
12795 		if (reg_is_pkt_pointer(ptr_reg)) {
12796 			dst_reg->id = ++env->id_gen;
12797 			/* something was added to pkt_ptr, set range to zero */
12798 			if (smin_val < 0)
12799 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12800 		}
12801 		break;
12802 	case BPF_AND:
12803 	case BPF_OR:
12804 	case BPF_XOR:
12805 		/* bitwise ops on pointers are troublesome, prohibit. */
12806 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12807 			dst, bpf_alu_string[opcode >> 4]);
12808 		return -EACCES;
12809 	default:
12810 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
12811 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12812 			dst, bpf_alu_string[opcode >> 4]);
12813 		return -EACCES;
12814 	}
12815 
12816 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12817 		return -EINVAL;
12818 	reg_bounds_sync(dst_reg);
12819 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12820 		return -EACCES;
12821 	if (sanitize_needed(opcode)) {
12822 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12823 				       &info, true);
12824 		if (ret < 0)
12825 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12826 	}
12827 
12828 	return 0;
12829 }
12830 
12831 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12832 				 struct bpf_reg_state *src_reg)
12833 {
12834 	s32 smin_val = src_reg->s32_min_value;
12835 	s32 smax_val = src_reg->s32_max_value;
12836 	u32 umin_val = src_reg->u32_min_value;
12837 	u32 umax_val = src_reg->u32_max_value;
12838 
12839 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12840 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12841 		dst_reg->s32_min_value = S32_MIN;
12842 		dst_reg->s32_max_value = S32_MAX;
12843 	} else {
12844 		dst_reg->s32_min_value += smin_val;
12845 		dst_reg->s32_max_value += smax_val;
12846 	}
12847 	if (dst_reg->u32_min_value + umin_val < umin_val ||
12848 	    dst_reg->u32_max_value + umax_val < umax_val) {
12849 		dst_reg->u32_min_value = 0;
12850 		dst_reg->u32_max_value = U32_MAX;
12851 	} else {
12852 		dst_reg->u32_min_value += umin_val;
12853 		dst_reg->u32_max_value += umax_val;
12854 	}
12855 }
12856 
12857 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12858 			       struct bpf_reg_state *src_reg)
12859 {
12860 	s64 smin_val = src_reg->smin_value;
12861 	s64 smax_val = src_reg->smax_value;
12862 	u64 umin_val = src_reg->umin_value;
12863 	u64 umax_val = src_reg->umax_value;
12864 
12865 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12866 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
12867 		dst_reg->smin_value = S64_MIN;
12868 		dst_reg->smax_value = S64_MAX;
12869 	} else {
12870 		dst_reg->smin_value += smin_val;
12871 		dst_reg->smax_value += smax_val;
12872 	}
12873 	if (dst_reg->umin_value + umin_val < umin_val ||
12874 	    dst_reg->umax_value + umax_val < umax_val) {
12875 		dst_reg->umin_value = 0;
12876 		dst_reg->umax_value = U64_MAX;
12877 	} else {
12878 		dst_reg->umin_value += umin_val;
12879 		dst_reg->umax_value += umax_val;
12880 	}
12881 }
12882 
12883 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12884 				 struct bpf_reg_state *src_reg)
12885 {
12886 	s32 smin_val = src_reg->s32_min_value;
12887 	s32 smax_val = src_reg->s32_max_value;
12888 	u32 umin_val = src_reg->u32_min_value;
12889 	u32 umax_val = src_reg->u32_max_value;
12890 
12891 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12892 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12893 		/* Overflow possible, we know nothing */
12894 		dst_reg->s32_min_value = S32_MIN;
12895 		dst_reg->s32_max_value = S32_MAX;
12896 	} else {
12897 		dst_reg->s32_min_value -= smax_val;
12898 		dst_reg->s32_max_value -= smin_val;
12899 	}
12900 	if (dst_reg->u32_min_value < umax_val) {
12901 		/* Overflow possible, we know nothing */
12902 		dst_reg->u32_min_value = 0;
12903 		dst_reg->u32_max_value = U32_MAX;
12904 	} else {
12905 		/* Cannot overflow (as long as bounds are consistent) */
12906 		dst_reg->u32_min_value -= umax_val;
12907 		dst_reg->u32_max_value -= umin_val;
12908 	}
12909 }
12910 
12911 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12912 			       struct bpf_reg_state *src_reg)
12913 {
12914 	s64 smin_val = src_reg->smin_value;
12915 	s64 smax_val = src_reg->smax_value;
12916 	u64 umin_val = src_reg->umin_value;
12917 	u64 umax_val = src_reg->umax_value;
12918 
12919 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12920 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12921 		/* Overflow possible, we know nothing */
12922 		dst_reg->smin_value = S64_MIN;
12923 		dst_reg->smax_value = S64_MAX;
12924 	} else {
12925 		dst_reg->smin_value -= smax_val;
12926 		dst_reg->smax_value -= smin_val;
12927 	}
12928 	if (dst_reg->umin_value < umax_val) {
12929 		/* Overflow possible, we know nothing */
12930 		dst_reg->umin_value = 0;
12931 		dst_reg->umax_value = U64_MAX;
12932 	} else {
12933 		/* Cannot overflow (as long as bounds are consistent) */
12934 		dst_reg->umin_value -= umax_val;
12935 		dst_reg->umax_value -= umin_val;
12936 	}
12937 }
12938 
12939 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12940 				 struct bpf_reg_state *src_reg)
12941 {
12942 	s32 smin_val = src_reg->s32_min_value;
12943 	u32 umin_val = src_reg->u32_min_value;
12944 	u32 umax_val = src_reg->u32_max_value;
12945 
12946 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12947 		/* Ain't nobody got time to multiply that sign */
12948 		__mark_reg32_unbounded(dst_reg);
12949 		return;
12950 	}
12951 	/* Both values are positive, so we can work with unsigned and
12952 	 * copy the result to signed (unless it exceeds S32_MAX).
12953 	 */
12954 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12955 		/* Potential overflow, we know nothing */
12956 		__mark_reg32_unbounded(dst_reg);
12957 		return;
12958 	}
12959 	dst_reg->u32_min_value *= umin_val;
12960 	dst_reg->u32_max_value *= umax_val;
12961 	if (dst_reg->u32_max_value > S32_MAX) {
12962 		/* Overflow possible, we know nothing */
12963 		dst_reg->s32_min_value = S32_MIN;
12964 		dst_reg->s32_max_value = S32_MAX;
12965 	} else {
12966 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12967 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12968 	}
12969 }
12970 
12971 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12972 			       struct bpf_reg_state *src_reg)
12973 {
12974 	s64 smin_val = src_reg->smin_value;
12975 	u64 umin_val = src_reg->umin_value;
12976 	u64 umax_val = src_reg->umax_value;
12977 
12978 	if (smin_val < 0 || dst_reg->smin_value < 0) {
12979 		/* Ain't nobody got time to multiply that sign */
12980 		__mark_reg64_unbounded(dst_reg);
12981 		return;
12982 	}
12983 	/* Both values are positive, so we can work with unsigned and
12984 	 * copy the result to signed (unless it exceeds S64_MAX).
12985 	 */
12986 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12987 		/* Potential overflow, we know nothing */
12988 		__mark_reg64_unbounded(dst_reg);
12989 		return;
12990 	}
12991 	dst_reg->umin_value *= umin_val;
12992 	dst_reg->umax_value *= umax_val;
12993 	if (dst_reg->umax_value > S64_MAX) {
12994 		/* Overflow possible, we know nothing */
12995 		dst_reg->smin_value = S64_MIN;
12996 		dst_reg->smax_value = S64_MAX;
12997 	} else {
12998 		dst_reg->smin_value = dst_reg->umin_value;
12999 		dst_reg->smax_value = dst_reg->umax_value;
13000 	}
13001 }
13002 
13003 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13004 				 struct bpf_reg_state *src_reg)
13005 {
13006 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13007 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13008 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13009 	s32 smin_val = src_reg->s32_min_value;
13010 	u32 umax_val = src_reg->u32_max_value;
13011 
13012 	if (src_known && dst_known) {
13013 		__mark_reg32_known(dst_reg, var32_off.value);
13014 		return;
13015 	}
13016 
13017 	/* We get our minimum from the var_off, since that's inherently
13018 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13019 	 */
13020 	dst_reg->u32_min_value = var32_off.value;
13021 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13022 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13023 		/* Lose signed bounds when ANDing negative numbers,
13024 		 * ain't nobody got time for that.
13025 		 */
13026 		dst_reg->s32_min_value = S32_MIN;
13027 		dst_reg->s32_max_value = S32_MAX;
13028 	} else {
13029 		/* ANDing two positives gives a positive, so safe to
13030 		 * cast result into s64.
13031 		 */
13032 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13033 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13034 	}
13035 }
13036 
13037 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
13038 			       struct bpf_reg_state *src_reg)
13039 {
13040 	bool src_known = tnum_is_const(src_reg->var_off);
13041 	bool dst_known = tnum_is_const(dst_reg->var_off);
13042 	s64 smin_val = src_reg->smin_value;
13043 	u64 umax_val = src_reg->umax_value;
13044 
13045 	if (src_known && dst_known) {
13046 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13047 		return;
13048 	}
13049 
13050 	/* We get our minimum from the var_off, since that's inherently
13051 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13052 	 */
13053 	dst_reg->umin_value = dst_reg->var_off.value;
13054 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13055 	if (dst_reg->smin_value < 0 || smin_val < 0) {
13056 		/* Lose signed bounds when ANDing negative numbers,
13057 		 * ain't nobody got time for that.
13058 		 */
13059 		dst_reg->smin_value = S64_MIN;
13060 		dst_reg->smax_value = S64_MAX;
13061 	} else {
13062 		/* ANDing two positives gives a positive, so safe to
13063 		 * cast result into s64.
13064 		 */
13065 		dst_reg->smin_value = dst_reg->umin_value;
13066 		dst_reg->smax_value = dst_reg->umax_value;
13067 	}
13068 	/* We may learn something more from the var_off */
13069 	__update_reg_bounds(dst_reg);
13070 }
13071 
13072 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13073 				struct bpf_reg_state *src_reg)
13074 {
13075 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13076 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13077 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13078 	s32 smin_val = src_reg->s32_min_value;
13079 	u32 umin_val = src_reg->u32_min_value;
13080 
13081 	if (src_known && dst_known) {
13082 		__mark_reg32_known(dst_reg, var32_off.value);
13083 		return;
13084 	}
13085 
13086 	/* We get our maximum from the var_off, and our minimum is the
13087 	 * maximum of the operands' minima
13088 	 */
13089 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13090 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13091 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13092 		/* Lose signed bounds when ORing negative numbers,
13093 		 * ain't nobody got time for that.
13094 		 */
13095 		dst_reg->s32_min_value = S32_MIN;
13096 		dst_reg->s32_max_value = S32_MAX;
13097 	} else {
13098 		/* ORing two positives gives a positive, so safe to
13099 		 * cast result into s64.
13100 		 */
13101 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13102 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13103 	}
13104 }
13105 
13106 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13107 			      struct bpf_reg_state *src_reg)
13108 {
13109 	bool src_known = tnum_is_const(src_reg->var_off);
13110 	bool dst_known = tnum_is_const(dst_reg->var_off);
13111 	s64 smin_val = src_reg->smin_value;
13112 	u64 umin_val = src_reg->umin_value;
13113 
13114 	if (src_known && dst_known) {
13115 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13116 		return;
13117 	}
13118 
13119 	/* We get our maximum from the var_off, and our minimum is the
13120 	 * maximum of the operands' minima
13121 	 */
13122 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13123 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13124 	if (dst_reg->smin_value < 0 || smin_val < 0) {
13125 		/* Lose signed bounds when ORing negative numbers,
13126 		 * ain't nobody got time for that.
13127 		 */
13128 		dst_reg->smin_value = S64_MIN;
13129 		dst_reg->smax_value = S64_MAX;
13130 	} else {
13131 		/* ORing two positives gives a positive, so safe to
13132 		 * cast result into s64.
13133 		 */
13134 		dst_reg->smin_value = dst_reg->umin_value;
13135 		dst_reg->smax_value = dst_reg->umax_value;
13136 	}
13137 	/* We may learn something more from the var_off */
13138 	__update_reg_bounds(dst_reg);
13139 }
13140 
13141 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13142 				 struct bpf_reg_state *src_reg)
13143 {
13144 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13145 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13146 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13147 	s32 smin_val = src_reg->s32_min_value;
13148 
13149 	if (src_known && dst_known) {
13150 		__mark_reg32_known(dst_reg, var32_off.value);
13151 		return;
13152 	}
13153 
13154 	/* We get both minimum and maximum from the var32_off. */
13155 	dst_reg->u32_min_value = var32_off.value;
13156 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13157 
13158 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13159 		/* XORing two positive sign numbers gives a positive,
13160 		 * so safe to cast u32 result into s32.
13161 		 */
13162 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13163 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13164 	} else {
13165 		dst_reg->s32_min_value = S32_MIN;
13166 		dst_reg->s32_max_value = S32_MAX;
13167 	}
13168 }
13169 
13170 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13171 			       struct bpf_reg_state *src_reg)
13172 {
13173 	bool src_known = tnum_is_const(src_reg->var_off);
13174 	bool dst_known = tnum_is_const(dst_reg->var_off);
13175 	s64 smin_val = src_reg->smin_value;
13176 
13177 	if (src_known && dst_known) {
13178 		/* dst_reg->var_off.value has been updated earlier */
13179 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13180 		return;
13181 	}
13182 
13183 	/* We get both minimum and maximum from the var_off. */
13184 	dst_reg->umin_value = dst_reg->var_off.value;
13185 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13186 
13187 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13188 		/* XORing two positive sign numbers gives a positive,
13189 		 * so safe to cast u64 result into s64.
13190 		 */
13191 		dst_reg->smin_value = dst_reg->umin_value;
13192 		dst_reg->smax_value = dst_reg->umax_value;
13193 	} else {
13194 		dst_reg->smin_value = S64_MIN;
13195 		dst_reg->smax_value = S64_MAX;
13196 	}
13197 
13198 	__update_reg_bounds(dst_reg);
13199 }
13200 
13201 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13202 				   u64 umin_val, u64 umax_val)
13203 {
13204 	/* We lose all sign bit information (except what we can pick
13205 	 * up from var_off)
13206 	 */
13207 	dst_reg->s32_min_value = S32_MIN;
13208 	dst_reg->s32_max_value = S32_MAX;
13209 	/* If we might shift our top bit out, then we know nothing */
13210 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13211 		dst_reg->u32_min_value = 0;
13212 		dst_reg->u32_max_value = U32_MAX;
13213 	} else {
13214 		dst_reg->u32_min_value <<= umin_val;
13215 		dst_reg->u32_max_value <<= umax_val;
13216 	}
13217 }
13218 
13219 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13220 				 struct bpf_reg_state *src_reg)
13221 {
13222 	u32 umax_val = src_reg->u32_max_value;
13223 	u32 umin_val = src_reg->u32_min_value;
13224 	/* u32 alu operation will zext upper bits */
13225 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13226 
13227 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13228 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13229 	/* Not required but being careful mark reg64 bounds as unknown so
13230 	 * that we are forced to pick them up from tnum and zext later and
13231 	 * if some path skips this step we are still safe.
13232 	 */
13233 	__mark_reg64_unbounded(dst_reg);
13234 	__update_reg32_bounds(dst_reg);
13235 }
13236 
13237 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13238 				   u64 umin_val, u64 umax_val)
13239 {
13240 	/* Special case <<32 because it is a common compiler pattern to sign
13241 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13242 	 * positive we know this shift will also be positive so we can track
13243 	 * bounds correctly. Otherwise we lose all sign bit information except
13244 	 * what we can pick up from var_off. Perhaps we can generalize this
13245 	 * later to shifts of any length.
13246 	 */
13247 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13248 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13249 	else
13250 		dst_reg->smax_value = S64_MAX;
13251 
13252 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13253 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13254 	else
13255 		dst_reg->smin_value = S64_MIN;
13256 
13257 	/* If we might shift our top bit out, then we know nothing */
13258 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13259 		dst_reg->umin_value = 0;
13260 		dst_reg->umax_value = U64_MAX;
13261 	} else {
13262 		dst_reg->umin_value <<= umin_val;
13263 		dst_reg->umax_value <<= umax_val;
13264 	}
13265 }
13266 
13267 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13268 			       struct bpf_reg_state *src_reg)
13269 {
13270 	u64 umax_val = src_reg->umax_value;
13271 	u64 umin_val = src_reg->umin_value;
13272 
13273 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13274 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13275 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13276 
13277 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13278 	/* We may learn something more from the var_off */
13279 	__update_reg_bounds(dst_reg);
13280 }
13281 
13282 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13283 				 struct bpf_reg_state *src_reg)
13284 {
13285 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13286 	u32 umax_val = src_reg->u32_max_value;
13287 	u32 umin_val = src_reg->u32_min_value;
13288 
13289 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13290 	 * be negative, then either:
13291 	 * 1) src_reg might be zero, so the sign bit of the result is
13292 	 *    unknown, so we lose our signed bounds
13293 	 * 2) it's known negative, thus the unsigned bounds capture the
13294 	 *    signed bounds
13295 	 * 3) the signed bounds cross zero, so they tell us nothing
13296 	 *    about the result
13297 	 * If the value in dst_reg is known nonnegative, then again the
13298 	 * unsigned bounds capture the signed bounds.
13299 	 * Thus, in all cases it suffices to blow away our signed bounds
13300 	 * and rely on inferring new ones from the unsigned bounds and
13301 	 * var_off of the result.
13302 	 */
13303 	dst_reg->s32_min_value = S32_MIN;
13304 	dst_reg->s32_max_value = S32_MAX;
13305 
13306 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13307 	dst_reg->u32_min_value >>= umax_val;
13308 	dst_reg->u32_max_value >>= umin_val;
13309 
13310 	__mark_reg64_unbounded(dst_reg);
13311 	__update_reg32_bounds(dst_reg);
13312 }
13313 
13314 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13315 			       struct bpf_reg_state *src_reg)
13316 {
13317 	u64 umax_val = src_reg->umax_value;
13318 	u64 umin_val = src_reg->umin_value;
13319 
13320 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13321 	 * be negative, then either:
13322 	 * 1) src_reg might be zero, so the sign bit of the result is
13323 	 *    unknown, so we lose our signed bounds
13324 	 * 2) it's known negative, thus the unsigned bounds capture the
13325 	 *    signed bounds
13326 	 * 3) the signed bounds cross zero, so they tell us nothing
13327 	 *    about the result
13328 	 * If the value in dst_reg is known nonnegative, then again the
13329 	 * unsigned bounds capture the signed bounds.
13330 	 * Thus, in all cases it suffices to blow away our signed bounds
13331 	 * and rely on inferring new ones from the unsigned bounds and
13332 	 * var_off of the result.
13333 	 */
13334 	dst_reg->smin_value = S64_MIN;
13335 	dst_reg->smax_value = S64_MAX;
13336 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13337 	dst_reg->umin_value >>= umax_val;
13338 	dst_reg->umax_value >>= umin_val;
13339 
13340 	/* Its not easy to operate on alu32 bounds here because it depends
13341 	 * on bits being shifted in. Take easy way out and mark unbounded
13342 	 * so we can recalculate later from tnum.
13343 	 */
13344 	__mark_reg32_unbounded(dst_reg);
13345 	__update_reg_bounds(dst_reg);
13346 }
13347 
13348 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13349 				  struct bpf_reg_state *src_reg)
13350 {
13351 	u64 umin_val = src_reg->u32_min_value;
13352 
13353 	/* Upon reaching here, src_known is true and
13354 	 * umax_val is equal to umin_val.
13355 	 */
13356 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13357 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13358 
13359 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13360 
13361 	/* blow away the dst_reg umin_value/umax_value and rely on
13362 	 * dst_reg var_off to refine the result.
13363 	 */
13364 	dst_reg->u32_min_value = 0;
13365 	dst_reg->u32_max_value = U32_MAX;
13366 
13367 	__mark_reg64_unbounded(dst_reg);
13368 	__update_reg32_bounds(dst_reg);
13369 }
13370 
13371 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13372 				struct bpf_reg_state *src_reg)
13373 {
13374 	u64 umin_val = src_reg->umin_value;
13375 
13376 	/* Upon reaching here, src_known is true and umax_val is equal
13377 	 * to umin_val.
13378 	 */
13379 	dst_reg->smin_value >>= umin_val;
13380 	dst_reg->smax_value >>= umin_val;
13381 
13382 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13383 
13384 	/* blow away the dst_reg umin_value/umax_value and rely on
13385 	 * dst_reg var_off to refine the result.
13386 	 */
13387 	dst_reg->umin_value = 0;
13388 	dst_reg->umax_value = U64_MAX;
13389 
13390 	/* Its not easy to operate on alu32 bounds here because it depends
13391 	 * on bits being shifted in from upper 32-bits. Take easy way out
13392 	 * and mark unbounded so we can recalculate later from tnum.
13393 	 */
13394 	__mark_reg32_unbounded(dst_reg);
13395 	__update_reg_bounds(dst_reg);
13396 }
13397 
13398 /* WARNING: This function does calculations on 64-bit values, but the actual
13399  * execution may occur on 32-bit values. Therefore, things like bitshifts
13400  * need extra checks in the 32-bit case.
13401  */
13402 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13403 				      struct bpf_insn *insn,
13404 				      struct bpf_reg_state *dst_reg,
13405 				      struct bpf_reg_state src_reg)
13406 {
13407 	struct bpf_reg_state *regs = cur_regs(env);
13408 	u8 opcode = BPF_OP(insn->code);
13409 	bool src_known;
13410 	s64 smin_val, smax_val;
13411 	u64 umin_val, umax_val;
13412 	s32 s32_min_val, s32_max_val;
13413 	u32 u32_min_val, u32_max_val;
13414 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13415 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13416 	int ret;
13417 
13418 	smin_val = src_reg.smin_value;
13419 	smax_val = src_reg.smax_value;
13420 	umin_val = src_reg.umin_value;
13421 	umax_val = src_reg.umax_value;
13422 
13423 	s32_min_val = src_reg.s32_min_value;
13424 	s32_max_val = src_reg.s32_max_value;
13425 	u32_min_val = src_reg.u32_min_value;
13426 	u32_max_val = src_reg.u32_max_value;
13427 
13428 	if (alu32) {
13429 		src_known = tnum_subreg_is_const(src_reg.var_off);
13430 		if ((src_known &&
13431 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13432 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13433 			/* Taint dst register if offset had invalid bounds
13434 			 * derived from e.g. dead branches.
13435 			 */
13436 			__mark_reg_unknown(env, dst_reg);
13437 			return 0;
13438 		}
13439 	} else {
13440 		src_known = tnum_is_const(src_reg.var_off);
13441 		if ((src_known &&
13442 		     (smin_val != smax_val || umin_val != umax_val)) ||
13443 		    smin_val > smax_val || umin_val > umax_val) {
13444 			/* Taint dst register if offset had invalid bounds
13445 			 * derived from e.g. dead branches.
13446 			 */
13447 			__mark_reg_unknown(env, dst_reg);
13448 			return 0;
13449 		}
13450 	}
13451 
13452 	if (!src_known &&
13453 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13454 		__mark_reg_unknown(env, dst_reg);
13455 		return 0;
13456 	}
13457 
13458 	if (sanitize_needed(opcode)) {
13459 		ret = sanitize_val_alu(env, insn);
13460 		if (ret < 0)
13461 			return sanitize_err(env, insn, ret, NULL, NULL);
13462 	}
13463 
13464 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13465 	 * There are two classes of instructions: The first class we track both
13466 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13467 	 * greatest amount of precision when alu operations are mixed with jmp32
13468 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13469 	 * and BPF_OR. This is possible because these ops have fairly easy to
13470 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13471 	 * See alu32 verifier tests for examples. The second class of
13472 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13473 	 * with regards to tracking sign/unsigned bounds because the bits may
13474 	 * cross subreg boundaries in the alu64 case. When this happens we mark
13475 	 * the reg unbounded in the subreg bound space and use the resulting
13476 	 * tnum to calculate an approximation of the sign/unsigned bounds.
13477 	 */
13478 	switch (opcode) {
13479 	case BPF_ADD:
13480 		scalar32_min_max_add(dst_reg, &src_reg);
13481 		scalar_min_max_add(dst_reg, &src_reg);
13482 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13483 		break;
13484 	case BPF_SUB:
13485 		scalar32_min_max_sub(dst_reg, &src_reg);
13486 		scalar_min_max_sub(dst_reg, &src_reg);
13487 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13488 		break;
13489 	case BPF_MUL:
13490 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13491 		scalar32_min_max_mul(dst_reg, &src_reg);
13492 		scalar_min_max_mul(dst_reg, &src_reg);
13493 		break;
13494 	case BPF_AND:
13495 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13496 		scalar32_min_max_and(dst_reg, &src_reg);
13497 		scalar_min_max_and(dst_reg, &src_reg);
13498 		break;
13499 	case BPF_OR:
13500 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13501 		scalar32_min_max_or(dst_reg, &src_reg);
13502 		scalar_min_max_or(dst_reg, &src_reg);
13503 		break;
13504 	case BPF_XOR:
13505 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13506 		scalar32_min_max_xor(dst_reg, &src_reg);
13507 		scalar_min_max_xor(dst_reg, &src_reg);
13508 		break;
13509 	case BPF_LSH:
13510 		if (umax_val >= insn_bitness) {
13511 			/* Shifts greater than 31 or 63 are undefined.
13512 			 * This includes shifts by a negative number.
13513 			 */
13514 			mark_reg_unknown(env, regs, insn->dst_reg);
13515 			break;
13516 		}
13517 		if (alu32)
13518 			scalar32_min_max_lsh(dst_reg, &src_reg);
13519 		else
13520 			scalar_min_max_lsh(dst_reg, &src_reg);
13521 		break;
13522 	case BPF_RSH:
13523 		if (umax_val >= insn_bitness) {
13524 			/* Shifts greater than 31 or 63 are undefined.
13525 			 * This includes shifts by a negative number.
13526 			 */
13527 			mark_reg_unknown(env, regs, insn->dst_reg);
13528 			break;
13529 		}
13530 		if (alu32)
13531 			scalar32_min_max_rsh(dst_reg, &src_reg);
13532 		else
13533 			scalar_min_max_rsh(dst_reg, &src_reg);
13534 		break;
13535 	case BPF_ARSH:
13536 		if (umax_val >= insn_bitness) {
13537 			/* Shifts greater than 31 or 63 are undefined.
13538 			 * This includes shifts by a negative number.
13539 			 */
13540 			mark_reg_unknown(env, regs, insn->dst_reg);
13541 			break;
13542 		}
13543 		if (alu32)
13544 			scalar32_min_max_arsh(dst_reg, &src_reg);
13545 		else
13546 			scalar_min_max_arsh(dst_reg, &src_reg);
13547 		break;
13548 	default:
13549 		mark_reg_unknown(env, regs, insn->dst_reg);
13550 		break;
13551 	}
13552 
13553 	/* ALU32 ops are zero extended into 64bit register */
13554 	if (alu32)
13555 		zext_32_to_64(dst_reg);
13556 	reg_bounds_sync(dst_reg);
13557 	return 0;
13558 }
13559 
13560 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13561  * and var_off.
13562  */
13563 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13564 				   struct bpf_insn *insn)
13565 {
13566 	struct bpf_verifier_state *vstate = env->cur_state;
13567 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13568 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13569 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13570 	u8 opcode = BPF_OP(insn->code);
13571 	int err;
13572 
13573 	dst_reg = &regs[insn->dst_reg];
13574 	src_reg = NULL;
13575 	if (dst_reg->type != SCALAR_VALUE)
13576 		ptr_reg = dst_reg;
13577 	else
13578 		/* Make sure ID is cleared otherwise dst_reg min/max could be
13579 		 * incorrectly propagated into other registers by find_equal_scalars()
13580 		 */
13581 		dst_reg->id = 0;
13582 	if (BPF_SRC(insn->code) == BPF_X) {
13583 		src_reg = &regs[insn->src_reg];
13584 		if (src_reg->type != SCALAR_VALUE) {
13585 			if (dst_reg->type != SCALAR_VALUE) {
13586 				/* Combining two pointers by any ALU op yields
13587 				 * an arbitrary scalar. Disallow all math except
13588 				 * pointer subtraction
13589 				 */
13590 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13591 					mark_reg_unknown(env, regs, insn->dst_reg);
13592 					return 0;
13593 				}
13594 				verbose(env, "R%d pointer %s pointer prohibited\n",
13595 					insn->dst_reg,
13596 					bpf_alu_string[opcode >> 4]);
13597 				return -EACCES;
13598 			} else {
13599 				/* scalar += pointer
13600 				 * This is legal, but we have to reverse our
13601 				 * src/dest handling in computing the range
13602 				 */
13603 				err = mark_chain_precision(env, insn->dst_reg);
13604 				if (err)
13605 					return err;
13606 				return adjust_ptr_min_max_vals(env, insn,
13607 							       src_reg, dst_reg);
13608 			}
13609 		} else if (ptr_reg) {
13610 			/* pointer += scalar */
13611 			err = mark_chain_precision(env, insn->src_reg);
13612 			if (err)
13613 				return err;
13614 			return adjust_ptr_min_max_vals(env, insn,
13615 						       dst_reg, src_reg);
13616 		} else if (dst_reg->precise) {
13617 			/* if dst_reg is precise, src_reg should be precise as well */
13618 			err = mark_chain_precision(env, insn->src_reg);
13619 			if (err)
13620 				return err;
13621 		}
13622 	} else {
13623 		/* Pretend the src is a reg with a known value, since we only
13624 		 * need to be able to read from this state.
13625 		 */
13626 		off_reg.type = SCALAR_VALUE;
13627 		__mark_reg_known(&off_reg, insn->imm);
13628 		src_reg = &off_reg;
13629 		if (ptr_reg) /* pointer += K */
13630 			return adjust_ptr_min_max_vals(env, insn,
13631 						       ptr_reg, src_reg);
13632 	}
13633 
13634 	/* Got here implies adding two SCALAR_VALUEs */
13635 	if (WARN_ON_ONCE(ptr_reg)) {
13636 		print_verifier_state(env, state, true);
13637 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
13638 		return -EINVAL;
13639 	}
13640 	if (WARN_ON(!src_reg)) {
13641 		print_verifier_state(env, state, true);
13642 		verbose(env, "verifier internal error: no src_reg\n");
13643 		return -EINVAL;
13644 	}
13645 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13646 }
13647 
13648 /* check validity of 32-bit and 64-bit arithmetic operations */
13649 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13650 {
13651 	struct bpf_reg_state *regs = cur_regs(env);
13652 	u8 opcode = BPF_OP(insn->code);
13653 	int err;
13654 
13655 	if (opcode == BPF_END || opcode == BPF_NEG) {
13656 		if (opcode == BPF_NEG) {
13657 			if (BPF_SRC(insn->code) != BPF_K ||
13658 			    insn->src_reg != BPF_REG_0 ||
13659 			    insn->off != 0 || insn->imm != 0) {
13660 				verbose(env, "BPF_NEG uses reserved fields\n");
13661 				return -EINVAL;
13662 			}
13663 		} else {
13664 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13665 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13666 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
13667 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
13668 				verbose(env, "BPF_END uses reserved fields\n");
13669 				return -EINVAL;
13670 			}
13671 		}
13672 
13673 		/* check src operand */
13674 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13675 		if (err)
13676 			return err;
13677 
13678 		if (is_pointer_value(env, insn->dst_reg)) {
13679 			verbose(env, "R%d pointer arithmetic prohibited\n",
13680 				insn->dst_reg);
13681 			return -EACCES;
13682 		}
13683 
13684 		/* check dest operand */
13685 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
13686 		if (err)
13687 			return err;
13688 
13689 	} else if (opcode == BPF_MOV) {
13690 
13691 		if (BPF_SRC(insn->code) == BPF_X) {
13692 			if (insn->imm != 0) {
13693 				verbose(env, "BPF_MOV uses reserved fields\n");
13694 				return -EINVAL;
13695 			}
13696 
13697 			if (BPF_CLASS(insn->code) == BPF_ALU) {
13698 				if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13699 					verbose(env, "BPF_MOV uses reserved fields\n");
13700 					return -EINVAL;
13701 				}
13702 			} else {
13703 				if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13704 				    insn->off != 32) {
13705 					verbose(env, "BPF_MOV uses reserved fields\n");
13706 					return -EINVAL;
13707 				}
13708 			}
13709 
13710 			/* check src operand */
13711 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13712 			if (err)
13713 				return err;
13714 		} else {
13715 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13716 				verbose(env, "BPF_MOV uses reserved fields\n");
13717 				return -EINVAL;
13718 			}
13719 		}
13720 
13721 		/* check dest operand, mark as required later */
13722 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13723 		if (err)
13724 			return err;
13725 
13726 		if (BPF_SRC(insn->code) == BPF_X) {
13727 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
13728 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13729 			bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13730 				       !tnum_is_const(src_reg->var_off);
13731 
13732 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13733 				if (insn->off == 0) {
13734 					/* case: R1 = R2
13735 					 * copy register state to dest reg
13736 					 */
13737 					if (need_id)
13738 						/* Assign src and dst registers the same ID
13739 						 * that will be used by find_equal_scalars()
13740 						 * to propagate min/max range.
13741 						 */
13742 						src_reg->id = ++env->id_gen;
13743 					copy_register_state(dst_reg, src_reg);
13744 					dst_reg->live |= REG_LIVE_WRITTEN;
13745 					dst_reg->subreg_def = DEF_NOT_SUBREG;
13746 				} else {
13747 					/* case: R1 = (s8, s16 s32)R2 */
13748 					if (is_pointer_value(env, insn->src_reg)) {
13749 						verbose(env,
13750 							"R%d sign-extension part of pointer\n",
13751 							insn->src_reg);
13752 						return -EACCES;
13753 					} else if (src_reg->type == SCALAR_VALUE) {
13754 						bool no_sext;
13755 
13756 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13757 						if (no_sext && need_id)
13758 							src_reg->id = ++env->id_gen;
13759 						copy_register_state(dst_reg, src_reg);
13760 						if (!no_sext)
13761 							dst_reg->id = 0;
13762 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13763 						dst_reg->live |= REG_LIVE_WRITTEN;
13764 						dst_reg->subreg_def = DEF_NOT_SUBREG;
13765 					} else {
13766 						mark_reg_unknown(env, regs, insn->dst_reg);
13767 					}
13768 				}
13769 			} else {
13770 				/* R1 = (u32) R2 */
13771 				if (is_pointer_value(env, insn->src_reg)) {
13772 					verbose(env,
13773 						"R%d partial copy of pointer\n",
13774 						insn->src_reg);
13775 					return -EACCES;
13776 				} else if (src_reg->type == SCALAR_VALUE) {
13777 					if (insn->off == 0) {
13778 						bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13779 
13780 						if (is_src_reg_u32 && need_id)
13781 							src_reg->id = ++env->id_gen;
13782 						copy_register_state(dst_reg, src_reg);
13783 						/* Make sure ID is cleared if src_reg is not in u32
13784 						 * range otherwise dst_reg min/max could be incorrectly
13785 						 * propagated into src_reg by find_equal_scalars()
13786 						 */
13787 						if (!is_src_reg_u32)
13788 							dst_reg->id = 0;
13789 						dst_reg->live |= REG_LIVE_WRITTEN;
13790 						dst_reg->subreg_def = env->insn_idx + 1;
13791 					} else {
13792 						/* case: W1 = (s8, s16)W2 */
13793 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13794 
13795 						if (no_sext && need_id)
13796 							src_reg->id = ++env->id_gen;
13797 						copy_register_state(dst_reg, src_reg);
13798 						if (!no_sext)
13799 							dst_reg->id = 0;
13800 						dst_reg->live |= REG_LIVE_WRITTEN;
13801 						dst_reg->subreg_def = env->insn_idx + 1;
13802 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13803 					}
13804 				} else {
13805 					mark_reg_unknown(env, regs,
13806 							 insn->dst_reg);
13807 				}
13808 				zext_32_to_64(dst_reg);
13809 				reg_bounds_sync(dst_reg);
13810 			}
13811 		} else {
13812 			/* case: R = imm
13813 			 * remember the value we stored into this reg
13814 			 */
13815 			/* clear any state __mark_reg_known doesn't set */
13816 			mark_reg_unknown(env, regs, insn->dst_reg);
13817 			regs[insn->dst_reg].type = SCALAR_VALUE;
13818 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13819 				__mark_reg_known(regs + insn->dst_reg,
13820 						 insn->imm);
13821 			} else {
13822 				__mark_reg_known(regs + insn->dst_reg,
13823 						 (u32)insn->imm);
13824 			}
13825 		}
13826 
13827 	} else if (opcode > BPF_END) {
13828 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13829 		return -EINVAL;
13830 
13831 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
13832 
13833 		if (BPF_SRC(insn->code) == BPF_X) {
13834 			if (insn->imm != 0 || insn->off > 1 ||
13835 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13836 				verbose(env, "BPF_ALU uses reserved fields\n");
13837 				return -EINVAL;
13838 			}
13839 			/* check src1 operand */
13840 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13841 			if (err)
13842 				return err;
13843 		} else {
13844 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13845 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13846 				verbose(env, "BPF_ALU uses reserved fields\n");
13847 				return -EINVAL;
13848 			}
13849 		}
13850 
13851 		/* check src2 operand */
13852 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13853 		if (err)
13854 			return err;
13855 
13856 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13857 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13858 			verbose(env, "div by zero\n");
13859 			return -EINVAL;
13860 		}
13861 
13862 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13863 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13864 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13865 
13866 			if (insn->imm < 0 || insn->imm >= size) {
13867 				verbose(env, "invalid shift %d\n", insn->imm);
13868 				return -EINVAL;
13869 			}
13870 		}
13871 
13872 		/* check dest operand */
13873 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13874 		err = err ?: adjust_reg_min_max_vals(env, insn);
13875 		if (err)
13876 			return err;
13877 	}
13878 
13879 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
13880 }
13881 
13882 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13883 				   struct bpf_reg_state *dst_reg,
13884 				   enum bpf_reg_type type,
13885 				   bool range_right_open)
13886 {
13887 	struct bpf_func_state *state;
13888 	struct bpf_reg_state *reg;
13889 	int new_range;
13890 
13891 	if (dst_reg->off < 0 ||
13892 	    (dst_reg->off == 0 && range_right_open))
13893 		/* This doesn't give us any range */
13894 		return;
13895 
13896 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
13897 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13898 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
13899 		 * than pkt_end, but that's because it's also less than pkt.
13900 		 */
13901 		return;
13902 
13903 	new_range = dst_reg->off;
13904 	if (range_right_open)
13905 		new_range++;
13906 
13907 	/* Examples for register markings:
13908 	 *
13909 	 * pkt_data in dst register:
13910 	 *
13911 	 *   r2 = r3;
13912 	 *   r2 += 8;
13913 	 *   if (r2 > pkt_end) goto <handle exception>
13914 	 *   <access okay>
13915 	 *
13916 	 *   r2 = r3;
13917 	 *   r2 += 8;
13918 	 *   if (r2 < pkt_end) goto <access okay>
13919 	 *   <handle exception>
13920 	 *
13921 	 *   Where:
13922 	 *     r2 == dst_reg, pkt_end == src_reg
13923 	 *     r2=pkt(id=n,off=8,r=0)
13924 	 *     r3=pkt(id=n,off=0,r=0)
13925 	 *
13926 	 * pkt_data in src register:
13927 	 *
13928 	 *   r2 = r3;
13929 	 *   r2 += 8;
13930 	 *   if (pkt_end >= r2) goto <access okay>
13931 	 *   <handle exception>
13932 	 *
13933 	 *   r2 = r3;
13934 	 *   r2 += 8;
13935 	 *   if (pkt_end <= r2) goto <handle exception>
13936 	 *   <access okay>
13937 	 *
13938 	 *   Where:
13939 	 *     pkt_end == dst_reg, r2 == src_reg
13940 	 *     r2=pkt(id=n,off=8,r=0)
13941 	 *     r3=pkt(id=n,off=0,r=0)
13942 	 *
13943 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13944 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13945 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
13946 	 * the check.
13947 	 */
13948 
13949 	/* If our ids match, then we must have the same max_value.  And we
13950 	 * don't care about the other reg's fixed offset, since if it's too big
13951 	 * the range won't allow anything.
13952 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13953 	 */
13954 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13955 		if (reg->type == type && reg->id == dst_reg->id)
13956 			/* keep the maximum range already checked */
13957 			reg->range = max(reg->range, new_range);
13958 	}));
13959 }
13960 
13961 /*
13962  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
13963  */
13964 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
13965 				  u8 opcode, bool is_jmp32)
13966 {
13967 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
13968 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
13969 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
13970 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
13971 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
13972 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
13973 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
13974 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
13975 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
13976 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
13977 
13978 	switch (opcode) {
13979 	case BPF_JEQ:
13980 		/* constants, umin/umax and smin/smax checks would be
13981 		 * redundant in this case because they all should match
13982 		 */
13983 		if (tnum_is_const(t1) && tnum_is_const(t2))
13984 			return t1.value == t2.value;
13985 		/* non-overlapping ranges */
13986 		if (umin1 > umax2 || umax1 < umin2)
13987 			return 0;
13988 		if (smin1 > smax2 || smax1 < smin2)
13989 			return 0;
13990 		if (!is_jmp32) {
13991 			/* if 64-bit ranges are inconclusive, see if we can
13992 			 * utilize 32-bit subrange knowledge to eliminate
13993 			 * branches that can't be taken a priori
13994 			 */
13995 			if (reg1->u32_min_value > reg2->u32_max_value ||
13996 			    reg1->u32_max_value < reg2->u32_min_value)
13997 				return 0;
13998 			if (reg1->s32_min_value > reg2->s32_max_value ||
13999 			    reg1->s32_max_value < reg2->s32_min_value)
14000 				return 0;
14001 		}
14002 		break;
14003 	case BPF_JNE:
14004 		/* constants, umin/umax and smin/smax checks would be
14005 		 * redundant in this case because they all should match
14006 		 */
14007 		if (tnum_is_const(t1) && tnum_is_const(t2))
14008 			return t1.value != t2.value;
14009 		/* non-overlapping ranges */
14010 		if (umin1 > umax2 || umax1 < umin2)
14011 			return 1;
14012 		if (smin1 > smax2 || smax1 < smin2)
14013 			return 1;
14014 		if (!is_jmp32) {
14015 			/* if 64-bit ranges are inconclusive, see if we can
14016 			 * utilize 32-bit subrange knowledge to eliminate
14017 			 * branches that can't be taken a priori
14018 			 */
14019 			if (reg1->u32_min_value > reg2->u32_max_value ||
14020 			    reg1->u32_max_value < reg2->u32_min_value)
14021 				return 1;
14022 			if (reg1->s32_min_value > reg2->s32_max_value ||
14023 			    reg1->s32_max_value < reg2->s32_min_value)
14024 				return 1;
14025 		}
14026 		break;
14027 	case BPF_JSET:
14028 		if (!is_reg_const(reg2, is_jmp32)) {
14029 			swap(reg1, reg2);
14030 			swap(t1, t2);
14031 		}
14032 		if (!is_reg_const(reg2, is_jmp32))
14033 			return -1;
14034 		if ((~t1.mask & t1.value) & t2.value)
14035 			return 1;
14036 		if (!((t1.mask | t1.value) & t2.value))
14037 			return 0;
14038 		break;
14039 	case BPF_JGT:
14040 		if (umin1 > umax2)
14041 			return 1;
14042 		else if (umax1 <= umin2)
14043 			return 0;
14044 		break;
14045 	case BPF_JSGT:
14046 		if (smin1 > smax2)
14047 			return 1;
14048 		else if (smax1 <= smin2)
14049 			return 0;
14050 		break;
14051 	case BPF_JLT:
14052 		if (umax1 < umin2)
14053 			return 1;
14054 		else if (umin1 >= umax2)
14055 			return 0;
14056 		break;
14057 	case BPF_JSLT:
14058 		if (smax1 < smin2)
14059 			return 1;
14060 		else if (smin1 >= smax2)
14061 			return 0;
14062 		break;
14063 	case BPF_JGE:
14064 		if (umin1 >= umax2)
14065 			return 1;
14066 		else if (umax1 < umin2)
14067 			return 0;
14068 		break;
14069 	case BPF_JSGE:
14070 		if (smin1 >= smax2)
14071 			return 1;
14072 		else if (smax1 < smin2)
14073 			return 0;
14074 		break;
14075 	case BPF_JLE:
14076 		if (umax1 <= umin2)
14077 			return 1;
14078 		else if (umin1 > umax2)
14079 			return 0;
14080 		break;
14081 	case BPF_JSLE:
14082 		if (smax1 <= smin2)
14083 			return 1;
14084 		else if (smin1 > smax2)
14085 			return 0;
14086 		break;
14087 	}
14088 
14089 	return -1;
14090 }
14091 
14092 static int flip_opcode(u32 opcode)
14093 {
14094 	/* How can we transform "a <op> b" into "b <op> a"? */
14095 	static const u8 opcode_flip[16] = {
14096 		/* these stay the same */
14097 		[BPF_JEQ  >> 4] = BPF_JEQ,
14098 		[BPF_JNE  >> 4] = BPF_JNE,
14099 		[BPF_JSET >> 4] = BPF_JSET,
14100 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14101 		[BPF_JGE  >> 4] = BPF_JLE,
14102 		[BPF_JGT  >> 4] = BPF_JLT,
14103 		[BPF_JLE  >> 4] = BPF_JGE,
14104 		[BPF_JLT  >> 4] = BPF_JGT,
14105 		[BPF_JSGE >> 4] = BPF_JSLE,
14106 		[BPF_JSGT >> 4] = BPF_JSLT,
14107 		[BPF_JSLE >> 4] = BPF_JSGE,
14108 		[BPF_JSLT >> 4] = BPF_JSGT
14109 	};
14110 	return opcode_flip[opcode >> 4];
14111 }
14112 
14113 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14114 				   struct bpf_reg_state *src_reg,
14115 				   u8 opcode)
14116 {
14117 	struct bpf_reg_state *pkt;
14118 
14119 	if (src_reg->type == PTR_TO_PACKET_END) {
14120 		pkt = dst_reg;
14121 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14122 		pkt = src_reg;
14123 		opcode = flip_opcode(opcode);
14124 	} else {
14125 		return -1;
14126 	}
14127 
14128 	if (pkt->range >= 0)
14129 		return -1;
14130 
14131 	switch (opcode) {
14132 	case BPF_JLE:
14133 		/* pkt <= pkt_end */
14134 		fallthrough;
14135 	case BPF_JGT:
14136 		/* pkt > pkt_end */
14137 		if (pkt->range == BEYOND_PKT_END)
14138 			/* pkt has at last one extra byte beyond pkt_end */
14139 			return opcode == BPF_JGT;
14140 		break;
14141 	case BPF_JLT:
14142 		/* pkt < pkt_end */
14143 		fallthrough;
14144 	case BPF_JGE:
14145 		/* pkt >= pkt_end */
14146 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14147 			return opcode == BPF_JGE;
14148 		break;
14149 	}
14150 	return -1;
14151 }
14152 
14153 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
14154  * and return:
14155  *  1 - branch will be taken and "goto target" will be executed
14156  *  0 - branch will not be taken and fall-through to next insn
14157  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
14158  *      range [0,10]
14159  */
14160 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14161 			   u8 opcode, bool is_jmp32)
14162 {
14163 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
14164 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
14165 
14166 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
14167 		u64 val;
14168 
14169 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
14170 		if (!is_reg_const(reg2, is_jmp32)) {
14171 			opcode = flip_opcode(opcode);
14172 			swap(reg1, reg2);
14173 		}
14174 		/* and ensure that reg2 is a constant */
14175 		if (!is_reg_const(reg2, is_jmp32))
14176 			return -1;
14177 
14178 		if (!reg_not_null(reg1))
14179 			return -1;
14180 
14181 		/* If pointer is valid tests against zero will fail so we can
14182 		 * use this to direct branch taken.
14183 		 */
14184 		val = reg_const_value(reg2, is_jmp32);
14185 		if (val != 0)
14186 			return -1;
14187 
14188 		switch (opcode) {
14189 		case BPF_JEQ:
14190 			return 0;
14191 		case BPF_JNE:
14192 			return 1;
14193 		default:
14194 			return -1;
14195 		}
14196 	}
14197 
14198 	/* now deal with two scalars, but not necessarily constants */
14199 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
14200 }
14201 
14202 /* Opcode that corresponds to a *false* branch condition.
14203  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
14204  */
14205 static u8 rev_opcode(u8 opcode)
14206 {
14207 	switch (opcode) {
14208 	case BPF_JEQ:		return BPF_JNE;
14209 	case BPF_JNE:		return BPF_JEQ;
14210 	/* JSET doesn't have it's reverse opcode in BPF, so add
14211 	 * BPF_X flag to denote the reverse of that operation
14212 	 */
14213 	case BPF_JSET:		return BPF_JSET | BPF_X;
14214 	case BPF_JSET | BPF_X:	return BPF_JSET;
14215 	case BPF_JGE:		return BPF_JLT;
14216 	case BPF_JGT:		return BPF_JLE;
14217 	case BPF_JLE:		return BPF_JGT;
14218 	case BPF_JLT:		return BPF_JGE;
14219 	case BPF_JSGE:		return BPF_JSLT;
14220 	case BPF_JSGT:		return BPF_JSLE;
14221 	case BPF_JSLE:		return BPF_JSGT;
14222 	case BPF_JSLT:		return BPF_JSGE;
14223 	default:		return 0;
14224 	}
14225 }
14226 
14227 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
14228 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14229 				u8 opcode, bool is_jmp32)
14230 {
14231 	struct tnum t;
14232 	u64 val;
14233 
14234 again:
14235 	switch (opcode) {
14236 	case BPF_JEQ:
14237 		if (is_jmp32) {
14238 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14239 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14240 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14241 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14242 			reg2->u32_min_value = reg1->u32_min_value;
14243 			reg2->u32_max_value = reg1->u32_max_value;
14244 			reg2->s32_min_value = reg1->s32_min_value;
14245 			reg2->s32_max_value = reg1->s32_max_value;
14246 
14247 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
14248 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14249 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
14250 		} else {
14251 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
14252 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14253 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
14254 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14255 			reg2->umin_value = reg1->umin_value;
14256 			reg2->umax_value = reg1->umax_value;
14257 			reg2->smin_value = reg1->smin_value;
14258 			reg2->smax_value = reg1->smax_value;
14259 
14260 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
14261 			reg2->var_off = reg1->var_off;
14262 		}
14263 		break;
14264 	case BPF_JNE:
14265 		/* we don't derive any new information for inequality yet */
14266 		break;
14267 	case BPF_JSET:
14268 		if (!is_reg_const(reg2, is_jmp32))
14269 			swap(reg1, reg2);
14270 		if (!is_reg_const(reg2, is_jmp32))
14271 			break;
14272 		val = reg_const_value(reg2, is_jmp32);
14273 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
14274 		 * requires single bit to learn something useful. E.g., if we
14275 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
14276 		 * are actually set? We can learn something definite only if
14277 		 * it's a single-bit value to begin with.
14278 		 *
14279 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
14280 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
14281 		 * bit 1 is set, which we can readily use in adjustments.
14282 		 */
14283 		if (!is_power_of_2(val))
14284 			break;
14285 		if (is_jmp32) {
14286 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
14287 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14288 		} else {
14289 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
14290 		}
14291 		break;
14292 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
14293 		if (!is_reg_const(reg2, is_jmp32))
14294 			swap(reg1, reg2);
14295 		if (!is_reg_const(reg2, is_jmp32))
14296 			break;
14297 		val = reg_const_value(reg2, is_jmp32);
14298 		if (is_jmp32) {
14299 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
14300 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14301 		} else {
14302 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
14303 		}
14304 		break;
14305 	case BPF_JLE:
14306 		if (is_jmp32) {
14307 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14308 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14309 		} else {
14310 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14311 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
14312 		}
14313 		break;
14314 	case BPF_JLT:
14315 		if (is_jmp32) {
14316 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
14317 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
14318 		} else {
14319 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
14320 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
14321 		}
14322 		break;
14323 	case BPF_JSLE:
14324 		if (is_jmp32) {
14325 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14326 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14327 		} else {
14328 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14329 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
14330 		}
14331 		break;
14332 	case BPF_JSLT:
14333 		if (is_jmp32) {
14334 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
14335 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
14336 		} else {
14337 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
14338 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
14339 		}
14340 		break;
14341 	case BPF_JGE:
14342 	case BPF_JGT:
14343 	case BPF_JSGE:
14344 	case BPF_JSGT:
14345 		/* just reuse LE/LT logic above */
14346 		opcode = flip_opcode(opcode);
14347 		swap(reg1, reg2);
14348 		goto again;
14349 	default:
14350 		return;
14351 	}
14352 }
14353 
14354 /* Adjusts the register min/max values in the case that the dst_reg and
14355  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
14356  * check, in which case we havea fake SCALAR_VALUE representing insn->imm).
14357  * Technically we can do similar adjustments for pointers to the same object,
14358  * but we don't support that right now.
14359  */
14360 static int reg_set_min_max(struct bpf_verifier_env *env,
14361 			   struct bpf_reg_state *true_reg1,
14362 			   struct bpf_reg_state *true_reg2,
14363 			   struct bpf_reg_state *false_reg1,
14364 			   struct bpf_reg_state *false_reg2,
14365 			   u8 opcode, bool is_jmp32)
14366 {
14367 	int err;
14368 
14369 	/* If either register is a pointer, we can't learn anything about its
14370 	 * variable offset from the compare (unless they were a pointer into
14371 	 * the same object, but we don't bother with that).
14372 	 */
14373 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
14374 		return 0;
14375 
14376 	/* fallthrough (FALSE) branch */
14377 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
14378 	reg_bounds_sync(false_reg1);
14379 	reg_bounds_sync(false_reg2);
14380 
14381 	/* jump (TRUE) branch */
14382 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
14383 	reg_bounds_sync(true_reg1);
14384 	reg_bounds_sync(true_reg2);
14385 
14386 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
14387 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
14388 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
14389 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
14390 	return err;
14391 }
14392 
14393 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14394 				 struct bpf_reg_state *reg, u32 id,
14395 				 bool is_null)
14396 {
14397 	if (type_may_be_null(reg->type) && reg->id == id &&
14398 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14399 		/* Old offset (both fixed and variable parts) should have been
14400 		 * known-zero, because we don't allow pointer arithmetic on
14401 		 * pointers that might be NULL. If we see this happening, don't
14402 		 * convert the register.
14403 		 *
14404 		 * But in some cases, some helpers that return local kptrs
14405 		 * advance offset for the returned pointer. In those cases, it
14406 		 * is fine to expect to see reg->off.
14407 		 */
14408 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14409 			return;
14410 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14411 		    WARN_ON_ONCE(reg->off))
14412 			return;
14413 
14414 		if (is_null) {
14415 			reg->type = SCALAR_VALUE;
14416 			/* We don't need id and ref_obj_id from this point
14417 			 * onwards anymore, thus we should better reset it,
14418 			 * so that state pruning has chances to take effect.
14419 			 */
14420 			reg->id = 0;
14421 			reg->ref_obj_id = 0;
14422 
14423 			return;
14424 		}
14425 
14426 		mark_ptr_not_null_reg(reg);
14427 
14428 		if (!reg_may_point_to_spin_lock(reg)) {
14429 			/* For not-NULL ptr, reg->ref_obj_id will be reset
14430 			 * in release_reference().
14431 			 *
14432 			 * reg->id is still used by spin_lock ptr. Other
14433 			 * than spin_lock ptr type, reg->id can be reset.
14434 			 */
14435 			reg->id = 0;
14436 		}
14437 	}
14438 }
14439 
14440 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14441  * be folded together at some point.
14442  */
14443 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14444 				  bool is_null)
14445 {
14446 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14447 	struct bpf_reg_state *regs = state->regs, *reg;
14448 	u32 ref_obj_id = regs[regno].ref_obj_id;
14449 	u32 id = regs[regno].id;
14450 
14451 	if (ref_obj_id && ref_obj_id == id && is_null)
14452 		/* regs[regno] is in the " == NULL" branch.
14453 		 * No one could have freed the reference state before
14454 		 * doing the NULL check.
14455 		 */
14456 		WARN_ON_ONCE(release_reference_state(state, id));
14457 
14458 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14459 		mark_ptr_or_null_reg(state, reg, id, is_null);
14460 	}));
14461 }
14462 
14463 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14464 				   struct bpf_reg_state *dst_reg,
14465 				   struct bpf_reg_state *src_reg,
14466 				   struct bpf_verifier_state *this_branch,
14467 				   struct bpf_verifier_state *other_branch)
14468 {
14469 	if (BPF_SRC(insn->code) != BPF_X)
14470 		return false;
14471 
14472 	/* Pointers are always 64-bit. */
14473 	if (BPF_CLASS(insn->code) == BPF_JMP32)
14474 		return false;
14475 
14476 	switch (BPF_OP(insn->code)) {
14477 	case BPF_JGT:
14478 		if ((dst_reg->type == PTR_TO_PACKET &&
14479 		     src_reg->type == PTR_TO_PACKET_END) ||
14480 		    (dst_reg->type == PTR_TO_PACKET_META &&
14481 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14482 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14483 			find_good_pkt_pointers(this_branch, dst_reg,
14484 					       dst_reg->type, false);
14485 			mark_pkt_end(other_branch, insn->dst_reg, true);
14486 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14487 			    src_reg->type == PTR_TO_PACKET) ||
14488 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14489 			    src_reg->type == PTR_TO_PACKET_META)) {
14490 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
14491 			find_good_pkt_pointers(other_branch, src_reg,
14492 					       src_reg->type, true);
14493 			mark_pkt_end(this_branch, insn->src_reg, false);
14494 		} else {
14495 			return false;
14496 		}
14497 		break;
14498 	case BPF_JLT:
14499 		if ((dst_reg->type == PTR_TO_PACKET &&
14500 		     src_reg->type == PTR_TO_PACKET_END) ||
14501 		    (dst_reg->type == PTR_TO_PACKET_META &&
14502 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14503 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14504 			find_good_pkt_pointers(other_branch, dst_reg,
14505 					       dst_reg->type, true);
14506 			mark_pkt_end(this_branch, insn->dst_reg, false);
14507 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14508 			    src_reg->type == PTR_TO_PACKET) ||
14509 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14510 			    src_reg->type == PTR_TO_PACKET_META)) {
14511 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
14512 			find_good_pkt_pointers(this_branch, src_reg,
14513 					       src_reg->type, false);
14514 			mark_pkt_end(other_branch, insn->src_reg, true);
14515 		} else {
14516 			return false;
14517 		}
14518 		break;
14519 	case BPF_JGE:
14520 		if ((dst_reg->type == PTR_TO_PACKET &&
14521 		     src_reg->type == PTR_TO_PACKET_END) ||
14522 		    (dst_reg->type == PTR_TO_PACKET_META &&
14523 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14524 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14525 			find_good_pkt_pointers(this_branch, dst_reg,
14526 					       dst_reg->type, true);
14527 			mark_pkt_end(other_branch, insn->dst_reg, false);
14528 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14529 			    src_reg->type == PTR_TO_PACKET) ||
14530 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14531 			    src_reg->type == PTR_TO_PACKET_META)) {
14532 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14533 			find_good_pkt_pointers(other_branch, src_reg,
14534 					       src_reg->type, false);
14535 			mark_pkt_end(this_branch, insn->src_reg, true);
14536 		} else {
14537 			return false;
14538 		}
14539 		break;
14540 	case BPF_JLE:
14541 		if ((dst_reg->type == PTR_TO_PACKET &&
14542 		     src_reg->type == PTR_TO_PACKET_END) ||
14543 		    (dst_reg->type == PTR_TO_PACKET_META &&
14544 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14545 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14546 			find_good_pkt_pointers(other_branch, dst_reg,
14547 					       dst_reg->type, false);
14548 			mark_pkt_end(this_branch, insn->dst_reg, true);
14549 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14550 			    src_reg->type == PTR_TO_PACKET) ||
14551 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14552 			    src_reg->type == PTR_TO_PACKET_META)) {
14553 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14554 			find_good_pkt_pointers(this_branch, src_reg,
14555 					       src_reg->type, true);
14556 			mark_pkt_end(other_branch, insn->src_reg, false);
14557 		} else {
14558 			return false;
14559 		}
14560 		break;
14561 	default:
14562 		return false;
14563 	}
14564 
14565 	return true;
14566 }
14567 
14568 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14569 			       struct bpf_reg_state *known_reg)
14570 {
14571 	struct bpf_func_state *state;
14572 	struct bpf_reg_state *reg;
14573 
14574 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14575 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14576 			copy_register_state(reg, known_reg);
14577 	}));
14578 }
14579 
14580 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14581 			     struct bpf_insn *insn, int *insn_idx)
14582 {
14583 	struct bpf_verifier_state *this_branch = env->cur_state;
14584 	struct bpf_verifier_state *other_branch;
14585 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14586 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14587 	struct bpf_reg_state *eq_branch_regs;
14588 	struct bpf_reg_state fake_reg = {};
14589 	u8 opcode = BPF_OP(insn->code);
14590 	bool is_jmp32;
14591 	int pred = -1;
14592 	int err;
14593 
14594 	/* Only conditional jumps are expected to reach here. */
14595 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
14596 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14597 		return -EINVAL;
14598 	}
14599 
14600 	/* check src2 operand */
14601 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14602 	if (err)
14603 		return err;
14604 
14605 	dst_reg = &regs[insn->dst_reg];
14606 	if (BPF_SRC(insn->code) == BPF_X) {
14607 		if (insn->imm != 0) {
14608 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14609 			return -EINVAL;
14610 		}
14611 
14612 		/* check src1 operand */
14613 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14614 		if (err)
14615 			return err;
14616 
14617 		src_reg = &regs[insn->src_reg];
14618 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14619 		    is_pointer_value(env, insn->src_reg)) {
14620 			verbose(env, "R%d pointer comparison prohibited\n",
14621 				insn->src_reg);
14622 			return -EACCES;
14623 		}
14624 	} else {
14625 		if (insn->src_reg != BPF_REG_0) {
14626 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14627 			return -EINVAL;
14628 		}
14629 		src_reg = &fake_reg;
14630 		src_reg->type = SCALAR_VALUE;
14631 		__mark_reg_known(src_reg, insn->imm);
14632 	}
14633 
14634 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14635 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
14636 	if (pred >= 0) {
14637 		/* If we get here with a dst_reg pointer type it is because
14638 		 * above is_branch_taken() special cased the 0 comparison.
14639 		 */
14640 		if (!__is_pointer_value(false, dst_reg))
14641 			err = mark_chain_precision(env, insn->dst_reg);
14642 		if (BPF_SRC(insn->code) == BPF_X && !err &&
14643 		    !__is_pointer_value(false, src_reg))
14644 			err = mark_chain_precision(env, insn->src_reg);
14645 		if (err)
14646 			return err;
14647 	}
14648 
14649 	if (pred == 1) {
14650 		/* Only follow the goto, ignore fall-through. If needed, push
14651 		 * the fall-through branch for simulation under speculative
14652 		 * execution.
14653 		 */
14654 		if (!env->bypass_spec_v1 &&
14655 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
14656 					       *insn_idx))
14657 			return -EFAULT;
14658 		if (env->log.level & BPF_LOG_LEVEL)
14659 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14660 		*insn_idx += insn->off;
14661 		return 0;
14662 	} else if (pred == 0) {
14663 		/* Only follow the fall-through branch, since that's where the
14664 		 * program will go. If needed, push the goto branch for
14665 		 * simulation under speculative execution.
14666 		 */
14667 		if (!env->bypass_spec_v1 &&
14668 		    !sanitize_speculative_path(env, insn,
14669 					       *insn_idx + insn->off + 1,
14670 					       *insn_idx))
14671 			return -EFAULT;
14672 		if (env->log.level & BPF_LOG_LEVEL)
14673 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14674 		return 0;
14675 	}
14676 
14677 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14678 				  false);
14679 	if (!other_branch)
14680 		return -EFAULT;
14681 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14682 
14683 	if (BPF_SRC(insn->code) == BPF_X) {
14684 		err = reg_set_min_max(env,
14685 				      &other_branch_regs[insn->dst_reg],
14686 				      &other_branch_regs[insn->src_reg],
14687 				      dst_reg, src_reg, opcode, is_jmp32);
14688 	} else /* BPF_SRC(insn->code) == BPF_K */ {
14689 		err = reg_set_min_max(env,
14690 				      &other_branch_regs[insn->dst_reg],
14691 				      src_reg /* fake one */,
14692 				      dst_reg, src_reg /* same fake one */,
14693 				      opcode, is_jmp32);
14694 	}
14695 	if (err)
14696 		return err;
14697 
14698 	if (BPF_SRC(insn->code) == BPF_X &&
14699 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
14700 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14701 		find_equal_scalars(this_branch, src_reg);
14702 		find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14703 	}
14704 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14705 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14706 		find_equal_scalars(this_branch, dst_reg);
14707 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14708 	}
14709 
14710 	/* if one pointer register is compared to another pointer
14711 	 * register check if PTR_MAYBE_NULL could be lifted.
14712 	 * E.g. register A - maybe null
14713 	 *      register B - not null
14714 	 * for JNE A, B, ... - A is not null in the false branch;
14715 	 * for JEQ A, B, ... - A is not null in the true branch.
14716 	 *
14717 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
14718 	 * not need to be null checked by the BPF program, i.e.,
14719 	 * could be null even without PTR_MAYBE_NULL marking, so
14720 	 * only propagate nullness when neither reg is that type.
14721 	 */
14722 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14723 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14724 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14725 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
14726 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14727 		eq_branch_regs = NULL;
14728 		switch (opcode) {
14729 		case BPF_JEQ:
14730 			eq_branch_regs = other_branch_regs;
14731 			break;
14732 		case BPF_JNE:
14733 			eq_branch_regs = regs;
14734 			break;
14735 		default:
14736 			/* do nothing */
14737 			break;
14738 		}
14739 		if (eq_branch_regs) {
14740 			if (type_may_be_null(src_reg->type))
14741 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14742 			else
14743 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14744 		}
14745 	}
14746 
14747 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14748 	 * NOTE: these optimizations below are related with pointer comparison
14749 	 *       which will never be JMP32.
14750 	 */
14751 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14752 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14753 	    type_may_be_null(dst_reg->type)) {
14754 		/* Mark all identical registers in each branch as either
14755 		 * safe or unknown depending R == 0 or R != 0 conditional.
14756 		 */
14757 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14758 				      opcode == BPF_JNE);
14759 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14760 				      opcode == BPF_JEQ);
14761 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14762 					   this_branch, other_branch) &&
14763 		   is_pointer_value(env, insn->dst_reg)) {
14764 		verbose(env, "R%d pointer comparison prohibited\n",
14765 			insn->dst_reg);
14766 		return -EACCES;
14767 	}
14768 	if (env->log.level & BPF_LOG_LEVEL)
14769 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
14770 	return 0;
14771 }
14772 
14773 /* verify BPF_LD_IMM64 instruction */
14774 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14775 {
14776 	struct bpf_insn_aux_data *aux = cur_aux(env);
14777 	struct bpf_reg_state *regs = cur_regs(env);
14778 	struct bpf_reg_state *dst_reg;
14779 	struct bpf_map *map;
14780 	int err;
14781 
14782 	if (BPF_SIZE(insn->code) != BPF_DW) {
14783 		verbose(env, "invalid BPF_LD_IMM insn\n");
14784 		return -EINVAL;
14785 	}
14786 	if (insn->off != 0) {
14787 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14788 		return -EINVAL;
14789 	}
14790 
14791 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
14792 	if (err)
14793 		return err;
14794 
14795 	dst_reg = &regs[insn->dst_reg];
14796 	if (insn->src_reg == 0) {
14797 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14798 
14799 		dst_reg->type = SCALAR_VALUE;
14800 		__mark_reg_known(&regs[insn->dst_reg], imm);
14801 		return 0;
14802 	}
14803 
14804 	/* All special src_reg cases are listed below. From this point onwards
14805 	 * we either succeed and assign a corresponding dst_reg->type after
14806 	 * zeroing the offset, or fail and reject the program.
14807 	 */
14808 	mark_reg_known_zero(env, regs, insn->dst_reg);
14809 
14810 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14811 		dst_reg->type = aux->btf_var.reg_type;
14812 		switch (base_type(dst_reg->type)) {
14813 		case PTR_TO_MEM:
14814 			dst_reg->mem_size = aux->btf_var.mem_size;
14815 			break;
14816 		case PTR_TO_BTF_ID:
14817 			dst_reg->btf = aux->btf_var.btf;
14818 			dst_reg->btf_id = aux->btf_var.btf_id;
14819 			break;
14820 		default:
14821 			verbose(env, "bpf verifier is misconfigured\n");
14822 			return -EFAULT;
14823 		}
14824 		return 0;
14825 	}
14826 
14827 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
14828 		struct bpf_prog_aux *aux = env->prog->aux;
14829 		u32 subprogno = find_subprog(env,
14830 					     env->insn_idx + insn->imm + 1);
14831 
14832 		if (!aux->func_info) {
14833 			verbose(env, "missing btf func_info\n");
14834 			return -EINVAL;
14835 		}
14836 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14837 			verbose(env, "callback function not static\n");
14838 			return -EINVAL;
14839 		}
14840 
14841 		dst_reg->type = PTR_TO_FUNC;
14842 		dst_reg->subprogno = subprogno;
14843 		return 0;
14844 	}
14845 
14846 	map = env->used_maps[aux->map_index];
14847 	dst_reg->map_ptr = map;
14848 
14849 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14850 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14851 		dst_reg->type = PTR_TO_MAP_VALUE;
14852 		dst_reg->off = aux->map_off;
14853 		WARN_ON_ONCE(map->max_entries != 1);
14854 		/* We want reg->id to be same (0) as map_value is not distinct */
14855 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14856 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14857 		dst_reg->type = CONST_PTR_TO_MAP;
14858 	} else {
14859 		verbose(env, "bpf verifier is misconfigured\n");
14860 		return -EINVAL;
14861 	}
14862 
14863 	return 0;
14864 }
14865 
14866 static bool may_access_skb(enum bpf_prog_type type)
14867 {
14868 	switch (type) {
14869 	case BPF_PROG_TYPE_SOCKET_FILTER:
14870 	case BPF_PROG_TYPE_SCHED_CLS:
14871 	case BPF_PROG_TYPE_SCHED_ACT:
14872 		return true;
14873 	default:
14874 		return false;
14875 	}
14876 }
14877 
14878 /* verify safety of LD_ABS|LD_IND instructions:
14879  * - they can only appear in the programs where ctx == skb
14880  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14881  *   preserve R6-R9, and store return value into R0
14882  *
14883  * Implicit input:
14884  *   ctx == skb == R6 == CTX
14885  *
14886  * Explicit input:
14887  *   SRC == any register
14888  *   IMM == 32-bit immediate
14889  *
14890  * Output:
14891  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14892  */
14893 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14894 {
14895 	struct bpf_reg_state *regs = cur_regs(env);
14896 	static const int ctx_reg = BPF_REG_6;
14897 	u8 mode = BPF_MODE(insn->code);
14898 	int i, err;
14899 
14900 	if (!may_access_skb(resolve_prog_type(env->prog))) {
14901 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14902 		return -EINVAL;
14903 	}
14904 
14905 	if (!env->ops->gen_ld_abs) {
14906 		verbose(env, "bpf verifier is misconfigured\n");
14907 		return -EINVAL;
14908 	}
14909 
14910 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14911 	    BPF_SIZE(insn->code) == BPF_DW ||
14912 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14913 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14914 		return -EINVAL;
14915 	}
14916 
14917 	/* check whether implicit source operand (register R6) is readable */
14918 	err = check_reg_arg(env, ctx_reg, SRC_OP);
14919 	if (err)
14920 		return err;
14921 
14922 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14923 	 * gen_ld_abs() may terminate the program at runtime, leading to
14924 	 * reference leak.
14925 	 */
14926 	err = check_reference_leak(env, false);
14927 	if (err) {
14928 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14929 		return err;
14930 	}
14931 
14932 	if (env->cur_state->active_lock.ptr) {
14933 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14934 		return -EINVAL;
14935 	}
14936 
14937 	if (env->cur_state->active_rcu_lock) {
14938 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14939 		return -EINVAL;
14940 	}
14941 
14942 	if (regs[ctx_reg].type != PTR_TO_CTX) {
14943 		verbose(env,
14944 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14945 		return -EINVAL;
14946 	}
14947 
14948 	if (mode == BPF_IND) {
14949 		/* check explicit source operand */
14950 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14951 		if (err)
14952 			return err;
14953 	}
14954 
14955 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14956 	if (err < 0)
14957 		return err;
14958 
14959 	/* reset caller saved regs to unreadable */
14960 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14961 		mark_reg_not_init(env, regs, caller_saved[i]);
14962 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14963 	}
14964 
14965 	/* mark destination R0 register as readable, since it contains
14966 	 * the value fetched from the packet.
14967 	 * Already marked as written above.
14968 	 */
14969 	mark_reg_unknown(env, regs, BPF_REG_0);
14970 	/* ld_abs load up to 32-bit skb data. */
14971 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14972 	return 0;
14973 }
14974 
14975 static int check_return_code(struct bpf_verifier_env *env, int regno)
14976 {
14977 	struct tnum enforce_attach_type_range = tnum_unknown;
14978 	const struct bpf_prog *prog = env->prog;
14979 	struct bpf_reg_state *reg;
14980 	struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
14981 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14982 	int err;
14983 	struct bpf_func_state *frame = env->cur_state->frame[0];
14984 	const bool is_subprog = frame->subprogno;
14985 
14986 	/* LSM and struct_ops func-ptr's return type could be "void" */
14987 	if (!is_subprog || frame->in_exception_callback_fn) {
14988 		switch (prog_type) {
14989 		case BPF_PROG_TYPE_LSM:
14990 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
14991 				/* See below, can be 0 or 0-1 depending on hook. */
14992 				break;
14993 			fallthrough;
14994 		case BPF_PROG_TYPE_STRUCT_OPS:
14995 			if (!prog->aux->attach_func_proto->type)
14996 				return 0;
14997 			break;
14998 		default:
14999 			break;
15000 		}
15001 	}
15002 
15003 	/* eBPF calling convention is such that R0 is used
15004 	 * to return the value from eBPF program.
15005 	 * Make sure that it's readable at this time
15006 	 * of bpf_exit, which means that program wrote
15007 	 * something into it earlier
15008 	 */
15009 	err = check_reg_arg(env, regno, SRC_OP);
15010 	if (err)
15011 		return err;
15012 
15013 	if (is_pointer_value(env, regno)) {
15014 		verbose(env, "R%d leaks addr as return value\n", regno);
15015 		return -EACCES;
15016 	}
15017 
15018 	reg = cur_regs(env) + regno;
15019 
15020 	if (frame->in_async_callback_fn) {
15021 		/* enforce return zero from async callbacks like timer */
15022 		if (reg->type != SCALAR_VALUE) {
15023 			verbose(env, "In async callback the register R%d is not a known value (%s)\n",
15024 				regno, reg_type_str(env, reg->type));
15025 			return -EINVAL;
15026 		}
15027 
15028 		if (!tnum_in(const_0, reg->var_off)) {
15029 			verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
15030 			return -EINVAL;
15031 		}
15032 		return 0;
15033 	}
15034 
15035 	if (is_subprog && !frame->in_exception_callback_fn) {
15036 		if (reg->type != SCALAR_VALUE) {
15037 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
15038 				regno, reg_type_str(env, reg->type));
15039 			return -EINVAL;
15040 		}
15041 		return 0;
15042 	}
15043 
15044 	switch (prog_type) {
15045 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15046 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15047 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15048 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
15049 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15050 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15051 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
15052 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15053 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
15054 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
15055 			range = tnum_range(1, 1);
15056 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15057 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15058 			range = tnum_range(0, 3);
15059 		break;
15060 	case BPF_PROG_TYPE_CGROUP_SKB:
15061 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15062 			range = tnum_range(0, 3);
15063 			enforce_attach_type_range = tnum_range(2, 3);
15064 		}
15065 		break;
15066 	case BPF_PROG_TYPE_CGROUP_SOCK:
15067 	case BPF_PROG_TYPE_SOCK_OPS:
15068 	case BPF_PROG_TYPE_CGROUP_DEVICE:
15069 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15070 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15071 		break;
15072 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15073 		if (!env->prog->aux->attach_btf_id)
15074 			return 0;
15075 		range = tnum_const(0);
15076 		break;
15077 	case BPF_PROG_TYPE_TRACING:
15078 		switch (env->prog->expected_attach_type) {
15079 		case BPF_TRACE_FENTRY:
15080 		case BPF_TRACE_FEXIT:
15081 			range = tnum_const(0);
15082 			break;
15083 		case BPF_TRACE_RAW_TP:
15084 		case BPF_MODIFY_RETURN:
15085 			return 0;
15086 		case BPF_TRACE_ITER:
15087 			break;
15088 		default:
15089 			return -ENOTSUPP;
15090 		}
15091 		break;
15092 	case BPF_PROG_TYPE_SK_LOOKUP:
15093 		range = tnum_range(SK_DROP, SK_PASS);
15094 		break;
15095 
15096 	case BPF_PROG_TYPE_LSM:
15097 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15098 			/* Regular BPF_PROG_TYPE_LSM programs can return
15099 			 * any value.
15100 			 */
15101 			return 0;
15102 		}
15103 		if (!env->prog->aux->attach_func_proto->type) {
15104 			/* Make sure programs that attach to void
15105 			 * hooks don't try to modify return value.
15106 			 */
15107 			range = tnum_range(1, 1);
15108 		}
15109 		break;
15110 
15111 	case BPF_PROG_TYPE_NETFILTER:
15112 		range = tnum_range(NF_DROP, NF_ACCEPT);
15113 		break;
15114 	case BPF_PROG_TYPE_EXT:
15115 		/* freplace program can return anything as its return value
15116 		 * depends on the to-be-replaced kernel func or bpf program.
15117 		 */
15118 	default:
15119 		return 0;
15120 	}
15121 
15122 	if (reg->type != SCALAR_VALUE) {
15123 		verbose(env, "At program exit the register R%d is not a known value (%s)\n",
15124 			regno, reg_type_str(env, reg->type));
15125 		return -EINVAL;
15126 	}
15127 
15128 	if (!tnum_in(range, reg->var_off)) {
15129 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
15130 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
15131 		    prog_type == BPF_PROG_TYPE_LSM &&
15132 		    !prog->aux->attach_func_proto->type)
15133 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15134 		return -EINVAL;
15135 	}
15136 
15137 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15138 	    tnum_in(enforce_attach_type_range, reg->var_off))
15139 		env->prog->enforce_expected_attach_type = 1;
15140 	return 0;
15141 }
15142 
15143 /* non-recursive DFS pseudo code
15144  * 1  procedure DFS-iterative(G,v):
15145  * 2      label v as discovered
15146  * 3      let S be a stack
15147  * 4      S.push(v)
15148  * 5      while S is not empty
15149  * 6            t <- S.peek()
15150  * 7            if t is what we're looking for:
15151  * 8                return t
15152  * 9            for all edges e in G.adjacentEdges(t) do
15153  * 10               if edge e is already labelled
15154  * 11                   continue with the next edge
15155  * 12               w <- G.adjacentVertex(t,e)
15156  * 13               if vertex w is not discovered and not explored
15157  * 14                   label e as tree-edge
15158  * 15                   label w as discovered
15159  * 16                   S.push(w)
15160  * 17                   continue at 5
15161  * 18               else if vertex w is discovered
15162  * 19                   label e as back-edge
15163  * 20               else
15164  * 21                   // vertex w is explored
15165  * 22                   label e as forward- or cross-edge
15166  * 23           label t as explored
15167  * 24           S.pop()
15168  *
15169  * convention:
15170  * 0x10 - discovered
15171  * 0x11 - discovered and fall-through edge labelled
15172  * 0x12 - discovered and fall-through and branch edges labelled
15173  * 0x20 - explored
15174  */
15175 
15176 enum {
15177 	DISCOVERED = 0x10,
15178 	EXPLORED = 0x20,
15179 	FALLTHROUGH = 1,
15180 	BRANCH = 2,
15181 };
15182 
15183 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15184 {
15185 	env->insn_aux_data[idx].prune_point = true;
15186 }
15187 
15188 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15189 {
15190 	return env->insn_aux_data[insn_idx].prune_point;
15191 }
15192 
15193 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15194 {
15195 	env->insn_aux_data[idx].force_checkpoint = true;
15196 }
15197 
15198 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15199 {
15200 	return env->insn_aux_data[insn_idx].force_checkpoint;
15201 }
15202 
15203 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15204 {
15205 	env->insn_aux_data[idx].calls_callback = true;
15206 }
15207 
15208 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15209 {
15210 	return env->insn_aux_data[insn_idx].calls_callback;
15211 }
15212 
15213 enum {
15214 	DONE_EXPLORING = 0,
15215 	KEEP_EXPLORING = 1,
15216 };
15217 
15218 /* t, w, e - match pseudo-code above:
15219  * t - index of current instruction
15220  * w - next instruction
15221  * e - edge
15222  */
15223 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15224 {
15225 	int *insn_stack = env->cfg.insn_stack;
15226 	int *insn_state = env->cfg.insn_state;
15227 
15228 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15229 		return DONE_EXPLORING;
15230 
15231 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15232 		return DONE_EXPLORING;
15233 
15234 	if (w < 0 || w >= env->prog->len) {
15235 		verbose_linfo(env, t, "%d: ", t);
15236 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15237 		return -EINVAL;
15238 	}
15239 
15240 	if (e == BRANCH) {
15241 		/* mark branch target for state pruning */
15242 		mark_prune_point(env, w);
15243 		mark_jmp_point(env, w);
15244 	}
15245 
15246 	if (insn_state[w] == 0) {
15247 		/* tree-edge */
15248 		insn_state[t] = DISCOVERED | e;
15249 		insn_state[w] = DISCOVERED;
15250 		if (env->cfg.cur_stack >= env->prog->len)
15251 			return -E2BIG;
15252 		insn_stack[env->cfg.cur_stack++] = w;
15253 		return KEEP_EXPLORING;
15254 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15255 		if (env->bpf_capable)
15256 			return DONE_EXPLORING;
15257 		verbose_linfo(env, t, "%d: ", t);
15258 		verbose_linfo(env, w, "%d: ", w);
15259 		verbose(env, "back-edge from insn %d to %d\n", t, w);
15260 		return -EINVAL;
15261 	} else if (insn_state[w] == EXPLORED) {
15262 		/* forward- or cross-edge */
15263 		insn_state[t] = DISCOVERED | e;
15264 	} else {
15265 		verbose(env, "insn state internal bug\n");
15266 		return -EFAULT;
15267 	}
15268 	return DONE_EXPLORING;
15269 }
15270 
15271 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15272 				struct bpf_verifier_env *env,
15273 				bool visit_callee)
15274 {
15275 	int ret, insn_sz;
15276 
15277 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15278 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15279 	if (ret)
15280 		return ret;
15281 
15282 	mark_prune_point(env, t + insn_sz);
15283 	/* when we exit from subprog, we need to record non-linear history */
15284 	mark_jmp_point(env, t + insn_sz);
15285 
15286 	if (visit_callee) {
15287 		mark_prune_point(env, t);
15288 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15289 	}
15290 	return ret;
15291 }
15292 
15293 /* Visits the instruction at index t and returns one of the following:
15294  *  < 0 - an error occurred
15295  *  DONE_EXPLORING - the instruction was fully explored
15296  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15297  */
15298 static int visit_insn(int t, struct bpf_verifier_env *env)
15299 {
15300 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15301 	int ret, off, insn_sz;
15302 
15303 	if (bpf_pseudo_func(insn))
15304 		return visit_func_call_insn(t, insns, env, true);
15305 
15306 	/* All non-branch instructions have a single fall-through edge. */
15307 	if (BPF_CLASS(insn->code) != BPF_JMP &&
15308 	    BPF_CLASS(insn->code) != BPF_JMP32) {
15309 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15310 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15311 	}
15312 
15313 	switch (BPF_OP(insn->code)) {
15314 	case BPF_EXIT:
15315 		return DONE_EXPLORING;
15316 
15317 	case BPF_CALL:
15318 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15319 			/* Mark this call insn as a prune point to trigger
15320 			 * is_state_visited() check before call itself is
15321 			 * processed by __check_func_call(). Otherwise new
15322 			 * async state will be pushed for further exploration.
15323 			 */
15324 			mark_prune_point(env, t);
15325 		/* For functions that invoke callbacks it is not known how many times
15326 		 * callback would be called. Verifier models callback calling functions
15327 		 * by repeatedly visiting callback bodies and returning to origin call
15328 		 * instruction.
15329 		 * In order to stop such iteration verifier needs to identify when a
15330 		 * state identical some state from a previous iteration is reached.
15331 		 * Check below forces creation of checkpoint before callback calling
15332 		 * instruction to allow search for such identical states.
15333 		 */
15334 		if (is_sync_callback_calling_insn(insn)) {
15335 			mark_calls_callback(env, t);
15336 			mark_force_checkpoint(env, t);
15337 			mark_prune_point(env, t);
15338 			mark_jmp_point(env, t);
15339 		}
15340 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15341 			struct bpf_kfunc_call_arg_meta meta;
15342 
15343 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15344 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15345 				mark_prune_point(env, t);
15346 				/* Checking and saving state checkpoints at iter_next() call
15347 				 * is crucial for fast convergence of open-coded iterator loop
15348 				 * logic, so we need to force it. If we don't do that,
15349 				 * is_state_visited() might skip saving a checkpoint, causing
15350 				 * unnecessarily long sequence of not checkpointed
15351 				 * instructions and jumps, leading to exhaustion of jump
15352 				 * history buffer, and potentially other undesired outcomes.
15353 				 * It is expected that with correct open-coded iterators
15354 				 * convergence will happen quickly, so we don't run a risk of
15355 				 * exhausting memory.
15356 				 */
15357 				mark_force_checkpoint(env, t);
15358 			}
15359 		}
15360 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15361 
15362 	case BPF_JA:
15363 		if (BPF_SRC(insn->code) != BPF_K)
15364 			return -EINVAL;
15365 
15366 		if (BPF_CLASS(insn->code) == BPF_JMP)
15367 			off = insn->off;
15368 		else
15369 			off = insn->imm;
15370 
15371 		/* unconditional jump with single edge */
15372 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15373 		if (ret)
15374 			return ret;
15375 
15376 		mark_prune_point(env, t + off + 1);
15377 		mark_jmp_point(env, t + off + 1);
15378 
15379 		return ret;
15380 
15381 	default:
15382 		/* conditional jump with two edges */
15383 		mark_prune_point(env, t);
15384 
15385 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15386 		if (ret)
15387 			return ret;
15388 
15389 		return push_insn(t, t + insn->off + 1, BRANCH, env);
15390 	}
15391 }
15392 
15393 /* non-recursive depth-first-search to detect loops in BPF program
15394  * loop == back-edge in directed graph
15395  */
15396 static int check_cfg(struct bpf_verifier_env *env)
15397 {
15398 	int insn_cnt = env->prog->len;
15399 	int *insn_stack, *insn_state;
15400 	int ex_insn_beg, i, ret = 0;
15401 	bool ex_done = false;
15402 
15403 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15404 	if (!insn_state)
15405 		return -ENOMEM;
15406 
15407 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15408 	if (!insn_stack) {
15409 		kvfree(insn_state);
15410 		return -ENOMEM;
15411 	}
15412 
15413 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15414 	insn_stack[0] = 0; /* 0 is the first instruction */
15415 	env->cfg.cur_stack = 1;
15416 
15417 walk_cfg:
15418 	while (env->cfg.cur_stack > 0) {
15419 		int t = insn_stack[env->cfg.cur_stack - 1];
15420 
15421 		ret = visit_insn(t, env);
15422 		switch (ret) {
15423 		case DONE_EXPLORING:
15424 			insn_state[t] = EXPLORED;
15425 			env->cfg.cur_stack--;
15426 			break;
15427 		case KEEP_EXPLORING:
15428 			break;
15429 		default:
15430 			if (ret > 0) {
15431 				verbose(env, "visit_insn internal bug\n");
15432 				ret = -EFAULT;
15433 			}
15434 			goto err_free;
15435 		}
15436 	}
15437 
15438 	if (env->cfg.cur_stack < 0) {
15439 		verbose(env, "pop stack internal bug\n");
15440 		ret = -EFAULT;
15441 		goto err_free;
15442 	}
15443 
15444 	if (env->exception_callback_subprog && !ex_done) {
15445 		ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
15446 
15447 		insn_state[ex_insn_beg] = DISCOVERED;
15448 		insn_stack[0] = ex_insn_beg;
15449 		env->cfg.cur_stack = 1;
15450 		ex_done = true;
15451 		goto walk_cfg;
15452 	}
15453 
15454 	for (i = 0; i < insn_cnt; i++) {
15455 		struct bpf_insn *insn = &env->prog->insnsi[i];
15456 
15457 		if (insn_state[i] != EXPLORED) {
15458 			verbose(env, "unreachable insn %d\n", i);
15459 			ret = -EINVAL;
15460 			goto err_free;
15461 		}
15462 		if (bpf_is_ldimm64(insn)) {
15463 			if (insn_state[i + 1] != 0) {
15464 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15465 				ret = -EINVAL;
15466 				goto err_free;
15467 			}
15468 			i++; /* skip second half of ldimm64 */
15469 		}
15470 	}
15471 	ret = 0; /* cfg looks good */
15472 
15473 err_free:
15474 	kvfree(insn_state);
15475 	kvfree(insn_stack);
15476 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
15477 	return ret;
15478 }
15479 
15480 static int check_abnormal_return(struct bpf_verifier_env *env)
15481 {
15482 	int i;
15483 
15484 	for (i = 1; i < env->subprog_cnt; i++) {
15485 		if (env->subprog_info[i].has_ld_abs) {
15486 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15487 			return -EINVAL;
15488 		}
15489 		if (env->subprog_info[i].has_tail_call) {
15490 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15491 			return -EINVAL;
15492 		}
15493 	}
15494 	return 0;
15495 }
15496 
15497 /* The minimum supported BTF func info size */
15498 #define MIN_BPF_FUNCINFO_SIZE	8
15499 #define MAX_FUNCINFO_REC_SIZE	252
15500 
15501 static int check_btf_func_early(struct bpf_verifier_env *env,
15502 				const union bpf_attr *attr,
15503 				bpfptr_t uattr)
15504 {
15505 	u32 krec_size = sizeof(struct bpf_func_info);
15506 	const struct btf_type *type, *func_proto;
15507 	u32 i, nfuncs, urec_size, min_size;
15508 	struct bpf_func_info *krecord;
15509 	struct bpf_prog *prog;
15510 	const struct btf *btf;
15511 	u32 prev_offset = 0;
15512 	bpfptr_t urecord;
15513 	int ret = -ENOMEM;
15514 
15515 	nfuncs = attr->func_info_cnt;
15516 	if (!nfuncs) {
15517 		if (check_abnormal_return(env))
15518 			return -EINVAL;
15519 		return 0;
15520 	}
15521 
15522 	urec_size = attr->func_info_rec_size;
15523 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15524 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
15525 	    urec_size % sizeof(u32)) {
15526 		verbose(env, "invalid func info rec size %u\n", urec_size);
15527 		return -EINVAL;
15528 	}
15529 
15530 	prog = env->prog;
15531 	btf = prog->aux->btf;
15532 
15533 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15534 	min_size = min_t(u32, krec_size, urec_size);
15535 
15536 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15537 	if (!krecord)
15538 		return -ENOMEM;
15539 
15540 	for (i = 0; i < nfuncs; i++) {
15541 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15542 		if (ret) {
15543 			if (ret == -E2BIG) {
15544 				verbose(env, "nonzero tailing record in func info");
15545 				/* set the size kernel expects so loader can zero
15546 				 * out the rest of the record.
15547 				 */
15548 				if (copy_to_bpfptr_offset(uattr,
15549 							  offsetof(union bpf_attr, func_info_rec_size),
15550 							  &min_size, sizeof(min_size)))
15551 					ret = -EFAULT;
15552 			}
15553 			goto err_free;
15554 		}
15555 
15556 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15557 			ret = -EFAULT;
15558 			goto err_free;
15559 		}
15560 
15561 		/* check insn_off */
15562 		ret = -EINVAL;
15563 		if (i == 0) {
15564 			if (krecord[i].insn_off) {
15565 				verbose(env,
15566 					"nonzero insn_off %u for the first func info record",
15567 					krecord[i].insn_off);
15568 				goto err_free;
15569 			}
15570 		} else if (krecord[i].insn_off <= prev_offset) {
15571 			verbose(env,
15572 				"same or smaller insn offset (%u) than previous func info record (%u)",
15573 				krecord[i].insn_off, prev_offset);
15574 			goto err_free;
15575 		}
15576 
15577 		/* check type_id */
15578 		type = btf_type_by_id(btf, krecord[i].type_id);
15579 		if (!type || !btf_type_is_func(type)) {
15580 			verbose(env, "invalid type id %d in func info",
15581 				krecord[i].type_id);
15582 			goto err_free;
15583 		}
15584 
15585 		func_proto = btf_type_by_id(btf, type->type);
15586 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15587 			/* btf_func_check() already verified it during BTF load */
15588 			goto err_free;
15589 
15590 		prev_offset = krecord[i].insn_off;
15591 		bpfptr_add(&urecord, urec_size);
15592 	}
15593 
15594 	prog->aux->func_info = krecord;
15595 	prog->aux->func_info_cnt = nfuncs;
15596 	return 0;
15597 
15598 err_free:
15599 	kvfree(krecord);
15600 	return ret;
15601 }
15602 
15603 static int check_btf_func(struct bpf_verifier_env *env,
15604 			  const union bpf_attr *attr,
15605 			  bpfptr_t uattr)
15606 {
15607 	const struct btf_type *type, *func_proto, *ret_type;
15608 	u32 i, nfuncs, urec_size;
15609 	struct bpf_func_info *krecord;
15610 	struct bpf_func_info_aux *info_aux = NULL;
15611 	struct bpf_prog *prog;
15612 	const struct btf *btf;
15613 	bpfptr_t urecord;
15614 	bool scalar_return;
15615 	int ret = -ENOMEM;
15616 
15617 	nfuncs = attr->func_info_cnt;
15618 	if (!nfuncs) {
15619 		if (check_abnormal_return(env))
15620 			return -EINVAL;
15621 		return 0;
15622 	}
15623 	if (nfuncs != env->subprog_cnt) {
15624 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15625 		return -EINVAL;
15626 	}
15627 
15628 	urec_size = attr->func_info_rec_size;
15629 
15630 	prog = env->prog;
15631 	btf = prog->aux->btf;
15632 
15633 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15634 
15635 	krecord = prog->aux->func_info;
15636 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15637 	if (!info_aux)
15638 		return -ENOMEM;
15639 
15640 	for (i = 0; i < nfuncs; i++) {
15641 		/* check insn_off */
15642 		ret = -EINVAL;
15643 
15644 		if (env->subprog_info[i].start != krecord[i].insn_off) {
15645 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15646 			goto err_free;
15647 		}
15648 
15649 		/* Already checked type_id */
15650 		type = btf_type_by_id(btf, krecord[i].type_id);
15651 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15652 		/* Already checked func_proto */
15653 		func_proto = btf_type_by_id(btf, type->type);
15654 
15655 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15656 		scalar_return =
15657 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15658 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15659 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15660 			goto err_free;
15661 		}
15662 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15663 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15664 			goto err_free;
15665 		}
15666 
15667 		bpfptr_add(&urecord, urec_size);
15668 	}
15669 
15670 	prog->aux->func_info_aux = info_aux;
15671 	return 0;
15672 
15673 err_free:
15674 	kfree(info_aux);
15675 	return ret;
15676 }
15677 
15678 static void adjust_btf_func(struct bpf_verifier_env *env)
15679 {
15680 	struct bpf_prog_aux *aux = env->prog->aux;
15681 	int i;
15682 
15683 	if (!aux->func_info)
15684 		return;
15685 
15686 	/* func_info is not available for hidden subprogs */
15687 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
15688 		aux->func_info[i].insn_off = env->subprog_info[i].start;
15689 }
15690 
15691 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
15692 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
15693 
15694 static int check_btf_line(struct bpf_verifier_env *env,
15695 			  const union bpf_attr *attr,
15696 			  bpfptr_t uattr)
15697 {
15698 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15699 	struct bpf_subprog_info *sub;
15700 	struct bpf_line_info *linfo;
15701 	struct bpf_prog *prog;
15702 	const struct btf *btf;
15703 	bpfptr_t ulinfo;
15704 	int err;
15705 
15706 	nr_linfo = attr->line_info_cnt;
15707 	if (!nr_linfo)
15708 		return 0;
15709 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15710 		return -EINVAL;
15711 
15712 	rec_size = attr->line_info_rec_size;
15713 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15714 	    rec_size > MAX_LINEINFO_REC_SIZE ||
15715 	    rec_size & (sizeof(u32) - 1))
15716 		return -EINVAL;
15717 
15718 	/* Need to zero it in case the userspace may
15719 	 * pass in a smaller bpf_line_info object.
15720 	 */
15721 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15722 			 GFP_KERNEL | __GFP_NOWARN);
15723 	if (!linfo)
15724 		return -ENOMEM;
15725 
15726 	prog = env->prog;
15727 	btf = prog->aux->btf;
15728 
15729 	s = 0;
15730 	sub = env->subprog_info;
15731 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15732 	expected_size = sizeof(struct bpf_line_info);
15733 	ncopy = min_t(u32, expected_size, rec_size);
15734 	for (i = 0; i < nr_linfo; i++) {
15735 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15736 		if (err) {
15737 			if (err == -E2BIG) {
15738 				verbose(env, "nonzero tailing record in line_info");
15739 				if (copy_to_bpfptr_offset(uattr,
15740 							  offsetof(union bpf_attr, line_info_rec_size),
15741 							  &expected_size, sizeof(expected_size)))
15742 					err = -EFAULT;
15743 			}
15744 			goto err_free;
15745 		}
15746 
15747 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15748 			err = -EFAULT;
15749 			goto err_free;
15750 		}
15751 
15752 		/*
15753 		 * Check insn_off to ensure
15754 		 * 1) strictly increasing AND
15755 		 * 2) bounded by prog->len
15756 		 *
15757 		 * The linfo[0].insn_off == 0 check logically falls into
15758 		 * the later "missing bpf_line_info for func..." case
15759 		 * because the first linfo[0].insn_off must be the
15760 		 * first sub also and the first sub must have
15761 		 * subprog_info[0].start == 0.
15762 		 */
15763 		if ((i && linfo[i].insn_off <= prev_offset) ||
15764 		    linfo[i].insn_off >= prog->len) {
15765 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15766 				i, linfo[i].insn_off, prev_offset,
15767 				prog->len);
15768 			err = -EINVAL;
15769 			goto err_free;
15770 		}
15771 
15772 		if (!prog->insnsi[linfo[i].insn_off].code) {
15773 			verbose(env,
15774 				"Invalid insn code at line_info[%u].insn_off\n",
15775 				i);
15776 			err = -EINVAL;
15777 			goto err_free;
15778 		}
15779 
15780 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15781 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15782 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15783 			err = -EINVAL;
15784 			goto err_free;
15785 		}
15786 
15787 		if (s != env->subprog_cnt) {
15788 			if (linfo[i].insn_off == sub[s].start) {
15789 				sub[s].linfo_idx = i;
15790 				s++;
15791 			} else if (sub[s].start < linfo[i].insn_off) {
15792 				verbose(env, "missing bpf_line_info for func#%u\n", s);
15793 				err = -EINVAL;
15794 				goto err_free;
15795 			}
15796 		}
15797 
15798 		prev_offset = linfo[i].insn_off;
15799 		bpfptr_add(&ulinfo, rec_size);
15800 	}
15801 
15802 	if (s != env->subprog_cnt) {
15803 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15804 			env->subprog_cnt - s, s);
15805 		err = -EINVAL;
15806 		goto err_free;
15807 	}
15808 
15809 	prog->aux->linfo = linfo;
15810 	prog->aux->nr_linfo = nr_linfo;
15811 
15812 	return 0;
15813 
15814 err_free:
15815 	kvfree(linfo);
15816 	return err;
15817 }
15818 
15819 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
15820 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
15821 
15822 static int check_core_relo(struct bpf_verifier_env *env,
15823 			   const union bpf_attr *attr,
15824 			   bpfptr_t uattr)
15825 {
15826 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15827 	struct bpf_core_relo core_relo = {};
15828 	struct bpf_prog *prog = env->prog;
15829 	const struct btf *btf = prog->aux->btf;
15830 	struct bpf_core_ctx ctx = {
15831 		.log = &env->log,
15832 		.btf = btf,
15833 	};
15834 	bpfptr_t u_core_relo;
15835 	int err;
15836 
15837 	nr_core_relo = attr->core_relo_cnt;
15838 	if (!nr_core_relo)
15839 		return 0;
15840 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15841 		return -EINVAL;
15842 
15843 	rec_size = attr->core_relo_rec_size;
15844 	if (rec_size < MIN_CORE_RELO_SIZE ||
15845 	    rec_size > MAX_CORE_RELO_SIZE ||
15846 	    rec_size % sizeof(u32))
15847 		return -EINVAL;
15848 
15849 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15850 	expected_size = sizeof(struct bpf_core_relo);
15851 	ncopy = min_t(u32, expected_size, rec_size);
15852 
15853 	/* Unlike func_info and line_info, copy and apply each CO-RE
15854 	 * relocation record one at a time.
15855 	 */
15856 	for (i = 0; i < nr_core_relo; i++) {
15857 		/* future proofing when sizeof(bpf_core_relo) changes */
15858 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15859 		if (err) {
15860 			if (err == -E2BIG) {
15861 				verbose(env, "nonzero tailing record in core_relo");
15862 				if (copy_to_bpfptr_offset(uattr,
15863 							  offsetof(union bpf_attr, core_relo_rec_size),
15864 							  &expected_size, sizeof(expected_size)))
15865 					err = -EFAULT;
15866 			}
15867 			break;
15868 		}
15869 
15870 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15871 			err = -EFAULT;
15872 			break;
15873 		}
15874 
15875 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15876 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15877 				i, core_relo.insn_off, prog->len);
15878 			err = -EINVAL;
15879 			break;
15880 		}
15881 
15882 		err = bpf_core_apply(&ctx, &core_relo, i,
15883 				     &prog->insnsi[core_relo.insn_off / 8]);
15884 		if (err)
15885 			break;
15886 		bpfptr_add(&u_core_relo, rec_size);
15887 	}
15888 	return err;
15889 }
15890 
15891 static int check_btf_info_early(struct bpf_verifier_env *env,
15892 				const union bpf_attr *attr,
15893 				bpfptr_t uattr)
15894 {
15895 	struct btf *btf;
15896 	int err;
15897 
15898 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
15899 		if (check_abnormal_return(env))
15900 			return -EINVAL;
15901 		return 0;
15902 	}
15903 
15904 	btf = btf_get_by_fd(attr->prog_btf_fd);
15905 	if (IS_ERR(btf))
15906 		return PTR_ERR(btf);
15907 	if (btf_is_kernel(btf)) {
15908 		btf_put(btf);
15909 		return -EACCES;
15910 	}
15911 	env->prog->aux->btf = btf;
15912 
15913 	err = check_btf_func_early(env, attr, uattr);
15914 	if (err)
15915 		return err;
15916 	return 0;
15917 }
15918 
15919 static int check_btf_info(struct bpf_verifier_env *env,
15920 			  const union bpf_attr *attr,
15921 			  bpfptr_t uattr)
15922 {
15923 	int err;
15924 
15925 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
15926 		if (check_abnormal_return(env))
15927 			return -EINVAL;
15928 		return 0;
15929 	}
15930 
15931 	err = check_btf_func(env, attr, uattr);
15932 	if (err)
15933 		return err;
15934 
15935 	err = check_btf_line(env, attr, uattr);
15936 	if (err)
15937 		return err;
15938 
15939 	err = check_core_relo(env, attr, uattr);
15940 	if (err)
15941 		return err;
15942 
15943 	return 0;
15944 }
15945 
15946 /* check %cur's range satisfies %old's */
15947 static bool range_within(struct bpf_reg_state *old,
15948 			 struct bpf_reg_state *cur)
15949 {
15950 	return old->umin_value <= cur->umin_value &&
15951 	       old->umax_value >= cur->umax_value &&
15952 	       old->smin_value <= cur->smin_value &&
15953 	       old->smax_value >= cur->smax_value &&
15954 	       old->u32_min_value <= cur->u32_min_value &&
15955 	       old->u32_max_value >= cur->u32_max_value &&
15956 	       old->s32_min_value <= cur->s32_min_value &&
15957 	       old->s32_max_value >= cur->s32_max_value;
15958 }
15959 
15960 /* If in the old state two registers had the same id, then they need to have
15961  * the same id in the new state as well.  But that id could be different from
15962  * the old state, so we need to track the mapping from old to new ids.
15963  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15964  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15965  * regs with a different old id could still have new id 9, we don't care about
15966  * that.
15967  * So we look through our idmap to see if this old id has been seen before.  If
15968  * so, we require the new id to match; otherwise, we add the id pair to the map.
15969  */
15970 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15971 {
15972 	struct bpf_id_pair *map = idmap->map;
15973 	unsigned int i;
15974 
15975 	/* either both IDs should be set or both should be zero */
15976 	if (!!old_id != !!cur_id)
15977 		return false;
15978 
15979 	if (old_id == 0) /* cur_id == 0 as well */
15980 		return true;
15981 
15982 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15983 		if (!map[i].old) {
15984 			/* Reached an empty slot; haven't seen this id before */
15985 			map[i].old = old_id;
15986 			map[i].cur = cur_id;
15987 			return true;
15988 		}
15989 		if (map[i].old == old_id)
15990 			return map[i].cur == cur_id;
15991 		if (map[i].cur == cur_id)
15992 			return false;
15993 	}
15994 	/* We ran out of idmap slots, which should be impossible */
15995 	WARN_ON_ONCE(1);
15996 	return false;
15997 }
15998 
15999 /* Similar to check_ids(), but allocate a unique temporary ID
16000  * for 'old_id' or 'cur_id' of zero.
16001  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
16002  */
16003 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16004 {
16005 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
16006 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
16007 
16008 	return check_ids(old_id, cur_id, idmap);
16009 }
16010 
16011 static void clean_func_state(struct bpf_verifier_env *env,
16012 			     struct bpf_func_state *st)
16013 {
16014 	enum bpf_reg_liveness live;
16015 	int i, j;
16016 
16017 	for (i = 0; i < BPF_REG_FP; i++) {
16018 		live = st->regs[i].live;
16019 		/* liveness must not touch this register anymore */
16020 		st->regs[i].live |= REG_LIVE_DONE;
16021 		if (!(live & REG_LIVE_READ))
16022 			/* since the register is unused, clear its state
16023 			 * to make further comparison simpler
16024 			 */
16025 			__mark_reg_not_init(env, &st->regs[i]);
16026 	}
16027 
16028 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
16029 		live = st->stack[i].spilled_ptr.live;
16030 		/* liveness must not touch this stack slot anymore */
16031 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
16032 		if (!(live & REG_LIVE_READ)) {
16033 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
16034 			for (j = 0; j < BPF_REG_SIZE; j++)
16035 				st->stack[i].slot_type[j] = STACK_INVALID;
16036 		}
16037 	}
16038 }
16039 
16040 static void clean_verifier_state(struct bpf_verifier_env *env,
16041 				 struct bpf_verifier_state *st)
16042 {
16043 	int i;
16044 
16045 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
16046 		/* all regs in this state in all frames were already marked */
16047 		return;
16048 
16049 	for (i = 0; i <= st->curframe; i++)
16050 		clean_func_state(env, st->frame[i]);
16051 }
16052 
16053 /* the parentage chains form a tree.
16054  * the verifier states are added to state lists at given insn and
16055  * pushed into state stack for future exploration.
16056  * when the verifier reaches bpf_exit insn some of the verifer states
16057  * stored in the state lists have their final liveness state already,
16058  * but a lot of states will get revised from liveness point of view when
16059  * the verifier explores other branches.
16060  * Example:
16061  * 1: r0 = 1
16062  * 2: if r1 == 100 goto pc+1
16063  * 3: r0 = 2
16064  * 4: exit
16065  * when the verifier reaches exit insn the register r0 in the state list of
16066  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
16067  * of insn 2 and goes exploring further. At the insn 4 it will walk the
16068  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
16069  *
16070  * Since the verifier pushes the branch states as it sees them while exploring
16071  * the program the condition of walking the branch instruction for the second
16072  * time means that all states below this branch were already explored and
16073  * their final liveness marks are already propagated.
16074  * Hence when the verifier completes the search of state list in is_state_visited()
16075  * we can call this clean_live_states() function to mark all liveness states
16076  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
16077  * will not be used.
16078  * This function also clears the registers and stack for states that !READ
16079  * to simplify state merging.
16080  *
16081  * Important note here that walking the same branch instruction in the callee
16082  * doesn't meant that the states are DONE. The verifier has to compare
16083  * the callsites
16084  */
16085 static void clean_live_states(struct bpf_verifier_env *env, int insn,
16086 			      struct bpf_verifier_state *cur)
16087 {
16088 	struct bpf_verifier_state_list *sl;
16089 
16090 	sl = *explored_state(env, insn);
16091 	while (sl) {
16092 		if (sl->state.branches)
16093 			goto next;
16094 		if (sl->state.insn_idx != insn ||
16095 		    !same_callsites(&sl->state, cur))
16096 			goto next;
16097 		clean_verifier_state(env, &sl->state);
16098 next:
16099 		sl = sl->next;
16100 	}
16101 }
16102 
16103 static bool regs_exact(const struct bpf_reg_state *rold,
16104 		       const struct bpf_reg_state *rcur,
16105 		       struct bpf_idmap *idmap)
16106 {
16107 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16108 	       check_ids(rold->id, rcur->id, idmap) &&
16109 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16110 }
16111 
16112 /* Returns true if (rold safe implies rcur safe) */
16113 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
16114 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
16115 {
16116 	if (exact)
16117 		return regs_exact(rold, rcur, idmap);
16118 
16119 	if (!(rold->live & REG_LIVE_READ))
16120 		/* explored state didn't use this */
16121 		return true;
16122 	if (rold->type == NOT_INIT)
16123 		/* explored state can't have used this */
16124 		return true;
16125 	if (rcur->type == NOT_INIT)
16126 		return false;
16127 
16128 	/* Enforce that register types have to match exactly, including their
16129 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16130 	 * rule.
16131 	 *
16132 	 * One can make a point that using a pointer register as unbounded
16133 	 * SCALAR would be technically acceptable, but this could lead to
16134 	 * pointer leaks because scalars are allowed to leak while pointers
16135 	 * are not. We could make this safe in special cases if root is
16136 	 * calling us, but it's probably not worth the hassle.
16137 	 *
16138 	 * Also, register types that are *not* MAYBE_NULL could technically be
16139 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16140 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16141 	 * to the same map).
16142 	 * However, if the old MAYBE_NULL register then got NULL checked,
16143 	 * doing so could have affected others with the same id, and we can't
16144 	 * check for that because we lost the id when we converted to
16145 	 * a non-MAYBE_NULL variant.
16146 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
16147 	 * non-MAYBE_NULL registers as well.
16148 	 */
16149 	if (rold->type != rcur->type)
16150 		return false;
16151 
16152 	switch (base_type(rold->type)) {
16153 	case SCALAR_VALUE:
16154 		if (env->explore_alu_limits) {
16155 			/* explore_alu_limits disables tnum_in() and range_within()
16156 			 * logic and requires everything to be strict
16157 			 */
16158 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16159 			       check_scalar_ids(rold->id, rcur->id, idmap);
16160 		}
16161 		if (!rold->precise)
16162 			return true;
16163 		/* Why check_ids() for scalar registers?
16164 		 *
16165 		 * Consider the following BPF code:
16166 		 *   1: r6 = ... unbound scalar, ID=a ...
16167 		 *   2: r7 = ... unbound scalar, ID=b ...
16168 		 *   3: if (r6 > r7) goto +1
16169 		 *   4: r6 = r7
16170 		 *   5: if (r6 > X) goto ...
16171 		 *   6: ... memory operation using r7 ...
16172 		 *
16173 		 * First verification path is [1-6]:
16174 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16175 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16176 		 *   r7 <= X, because r6 and r7 share same id.
16177 		 * Next verification path is [1-4, 6].
16178 		 *
16179 		 * Instruction (6) would be reached in two states:
16180 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16181 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16182 		 *
16183 		 * Use check_ids() to distinguish these states.
16184 		 * ---
16185 		 * Also verify that new value satisfies old value range knowledge.
16186 		 */
16187 		return range_within(rold, rcur) &&
16188 		       tnum_in(rold->var_off, rcur->var_off) &&
16189 		       check_scalar_ids(rold->id, rcur->id, idmap);
16190 	case PTR_TO_MAP_KEY:
16191 	case PTR_TO_MAP_VALUE:
16192 	case PTR_TO_MEM:
16193 	case PTR_TO_BUF:
16194 	case PTR_TO_TP_BUFFER:
16195 		/* If the new min/max/var_off satisfy the old ones and
16196 		 * everything else matches, we are OK.
16197 		 */
16198 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16199 		       range_within(rold, rcur) &&
16200 		       tnum_in(rold->var_off, rcur->var_off) &&
16201 		       check_ids(rold->id, rcur->id, idmap) &&
16202 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16203 	case PTR_TO_PACKET_META:
16204 	case PTR_TO_PACKET:
16205 		/* We must have at least as much range as the old ptr
16206 		 * did, so that any accesses which were safe before are
16207 		 * still safe.  This is true even if old range < old off,
16208 		 * since someone could have accessed through (ptr - k), or
16209 		 * even done ptr -= k in a register, to get a safe access.
16210 		 */
16211 		if (rold->range > rcur->range)
16212 			return false;
16213 		/* If the offsets don't match, we can't trust our alignment;
16214 		 * nor can we be sure that we won't fall out of range.
16215 		 */
16216 		if (rold->off != rcur->off)
16217 			return false;
16218 		/* id relations must be preserved */
16219 		if (!check_ids(rold->id, rcur->id, idmap))
16220 			return false;
16221 		/* new val must satisfy old val knowledge */
16222 		return range_within(rold, rcur) &&
16223 		       tnum_in(rold->var_off, rcur->var_off);
16224 	case PTR_TO_STACK:
16225 		/* two stack pointers are equal only if they're pointing to
16226 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16227 		 */
16228 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16229 	default:
16230 		return regs_exact(rold, rcur, idmap);
16231 	}
16232 }
16233 
16234 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16235 		      struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16236 {
16237 	int i, spi;
16238 
16239 	/* walk slots of the explored stack and ignore any additional
16240 	 * slots in the current stack, since explored(safe) state
16241 	 * didn't use them
16242 	 */
16243 	for (i = 0; i < old->allocated_stack; i++) {
16244 		struct bpf_reg_state *old_reg, *cur_reg;
16245 
16246 		spi = i / BPF_REG_SIZE;
16247 
16248 		if (exact &&
16249 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16250 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16251 			return false;
16252 
16253 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16254 			i += BPF_REG_SIZE - 1;
16255 			/* explored state didn't use this */
16256 			continue;
16257 		}
16258 
16259 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16260 			continue;
16261 
16262 		if (env->allow_uninit_stack &&
16263 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16264 			continue;
16265 
16266 		/* explored stack has more populated slots than current stack
16267 		 * and these slots were used
16268 		 */
16269 		if (i >= cur->allocated_stack)
16270 			return false;
16271 
16272 		/* if old state was safe with misc data in the stack
16273 		 * it will be safe with zero-initialized stack.
16274 		 * The opposite is not true
16275 		 */
16276 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16277 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16278 			continue;
16279 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16280 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16281 			/* Ex: old explored (safe) state has STACK_SPILL in
16282 			 * this stack slot, but current has STACK_MISC ->
16283 			 * this verifier states are not equivalent,
16284 			 * return false to continue verification of this path
16285 			 */
16286 			return false;
16287 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16288 			continue;
16289 		/* Both old and cur are having same slot_type */
16290 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16291 		case STACK_SPILL:
16292 			/* when explored and current stack slot are both storing
16293 			 * spilled registers, check that stored pointers types
16294 			 * are the same as well.
16295 			 * Ex: explored safe path could have stored
16296 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16297 			 * but current path has stored:
16298 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16299 			 * such verifier states are not equivalent.
16300 			 * return false to continue verification of this path
16301 			 */
16302 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16303 				     &cur->stack[spi].spilled_ptr, idmap, exact))
16304 				return false;
16305 			break;
16306 		case STACK_DYNPTR:
16307 			old_reg = &old->stack[spi].spilled_ptr;
16308 			cur_reg = &cur->stack[spi].spilled_ptr;
16309 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16310 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16311 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16312 				return false;
16313 			break;
16314 		case STACK_ITER:
16315 			old_reg = &old->stack[spi].spilled_ptr;
16316 			cur_reg = &cur->stack[spi].spilled_ptr;
16317 			/* iter.depth is not compared between states as it
16318 			 * doesn't matter for correctness and would otherwise
16319 			 * prevent convergence; we maintain it only to prevent
16320 			 * infinite loop check triggering, see
16321 			 * iter_active_depths_differ()
16322 			 */
16323 			if (old_reg->iter.btf != cur_reg->iter.btf ||
16324 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16325 			    old_reg->iter.state != cur_reg->iter.state ||
16326 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16327 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16328 				return false;
16329 			break;
16330 		case STACK_MISC:
16331 		case STACK_ZERO:
16332 		case STACK_INVALID:
16333 			continue;
16334 		/* Ensure that new unhandled slot types return false by default */
16335 		default:
16336 			return false;
16337 		}
16338 	}
16339 	return true;
16340 }
16341 
16342 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16343 		    struct bpf_idmap *idmap)
16344 {
16345 	int i;
16346 
16347 	if (old->acquired_refs != cur->acquired_refs)
16348 		return false;
16349 
16350 	for (i = 0; i < old->acquired_refs; i++) {
16351 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16352 			return false;
16353 	}
16354 
16355 	return true;
16356 }
16357 
16358 /* compare two verifier states
16359  *
16360  * all states stored in state_list are known to be valid, since
16361  * verifier reached 'bpf_exit' instruction through them
16362  *
16363  * this function is called when verifier exploring different branches of
16364  * execution popped from the state stack. If it sees an old state that has
16365  * more strict register state and more strict stack state then this execution
16366  * branch doesn't need to be explored further, since verifier already
16367  * concluded that more strict state leads to valid finish.
16368  *
16369  * Therefore two states are equivalent if register state is more conservative
16370  * and explored stack state is more conservative than the current one.
16371  * Example:
16372  *       explored                   current
16373  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16374  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16375  *
16376  * In other words if current stack state (one being explored) has more
16377  * valid slots than old one that already passed validation, it means
16378  * the verifier can stop exploring and conclude that current state is valid too
16379  *
16380  * Similarly with registers. If explored state has register type as invalid
16381  * whereas register type in current state is meaningful, it means that
16382  * the current state will reach 'bpf_exit' instruction safely
16383  */
16384 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16385 			      struct bpf_func_state *cur, bool exact)
16386 {
16387 	int i;
16388 
16389 	for (i = 0; i < MAX_BPF_REG; i++)
16390 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
16391 			     &env->idmap_scratch, exact))
16392 			return false;
16393 
16394 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16395 		return false;
16396 
16397 	if (!refsafe(old, cur, &env->idmap_scratch))
16398 		return false;
16399 
16400 	return true;
16401 }
16402 
16403 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16404 {
16405 	env->idmap_scratch.tmp_id_gen = env->id_gen;
16406 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16407 }
16408 
16409 static bool states_equal(struct bpf_verifier_env *env,
16410 			 struct bpf_verifier_state *old,
16411 			 struct bpf_verifier_state *cur,
16412 			 bool exact)
16413 {
16414 	int i;
16415 
16416 	if (old->curframe != cur->curframe)
16417 		return false;
16418 
16419 	reset_idmap_scratch(env);
16420 
16421 	/* Verification state from speculative execution simulation
16422 	 * must never prune a non-speculative execution one.
16423 	 */
16424 	if (old->speculative && !cur->speculative)
16425 		return false;
16426 
16427 	if (old->active_lock.ptr != cur->active_lock.ptr)
16428 		return false;
16429 
16430 	/* Old and cur active_lock's have to be either both present
16431 	 * or both absent.
16432 	 */
16433 	if (!!old->active_lock.id != !!cur->active_lock.id)
16434 		return false;
16435 
16436 	if (old->active_lock.id &&
16437 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16438 		return false;
16439 
16440 	if (old->active_rcu_lock != cur->active_rcu_lock)
16441 		return false;
16442 
16443 	/* for states to be equal callsites have to be the same
16444 	 * and all frame states need to be equivalent
16445 	 */
16446 	for (i = 0; i <= old->curframe; i++) {
16447 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
16448 			return false;
16449 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16450 			return false;
16451 	}
16452 	return true;
16453 }
16454 
16455 /* Return 0 if no propagation happened. Return negative error code if error
16456  * happened. Otherwise, return the propagated bit.
16457  */
16458 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16459 				  struct bpf_reg_state *reg,
16460 				  struct bpf_reg_state *parent_reg)
16461 {
16462 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16463 	u8 flag = reg->live & REG_LIVE_READ;
16464 	int err;
16465 
16466 	/* When comes here, read flags of PARENT_REG or REG could be any of
16467 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16468 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16469 	 */
16470 	if (parent_flag == REG_LIVE_READ64 ||
16471 	    /* Or if there is no read flag from REG. */
16472 	    !flag ||
16473 	    /* Or if the read flag from REG is the same as PARENT_REG. */
16474 	    parent_flag == flag)
16475 		return 0;
16476 
16477 	err = mark_reg_read(env, reg, parent_reg, flag);
16478 	if (err)
16479 		return err;
16480 
16481 	return flag;
16482 }
16483 
16484 /* A write screens off any subsequent reads; but write marks come from the
16485  * straight-line code between a state and its parent.  When we arrive at an
16486  * equivalent state (jump target or such) we didn't arrive by the straight-line
16487  * code, so read marks in the state must propagate to the parent regardless
16488  * of the state's write marks. That's what 'parent == state->parent' comparison
16489  * in mark_reg_read() is for.
16490  */
16491 static int propagate_liveness(struct bpf_verifier_env *env,
16492 			      const struct bpf_verifier_state *vstate,
16493 			      struct bpf_verifier_state *vparent)
16494 {
16495 	struct bpf_reg_state *state_reg, *parent_reg;
16496 	struct bpf_func_state *state, *parent;
16497 	int i, frame, err = 0;
16498 
16499 	if (vparent->curframe != vstate->curframe) {
16500 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
16501 		     vparent->curframe, vstate->curframe);
16502 		return -EFAULT;
16503 	}
16504 	/* Propagate read liveness of registers... */
16505 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16506 	for (frame = 0; frame <= vstate->curframe; frame++) {
16507 		parent = vparent->frame[frame];
16508 		state = vstate->frame[frame];
16509 		parent_reg = parent->regs;
16510 		state_reg = state->regs;
16511 		/* We don't need to worry about FP liveness, it's read-only */
16512 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16513 			err = propagate_liveness_reg(env, &state_reg[i],
16514 						     &parent_reg[i]);
16515 			if (err < 0)
16516 				return err;
16517 			if (err == REG_LIVE_READ64)
16518 				mark_insn_zext(env, &parent_reg[i]);
16519 		}
16520 
16521 		/* Propagate stack slots. */
16522 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16523 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16524 			parent_reg = &parent->stack[i].spilled_ptr;
16525 			state_reg = &state->stack[i].spilled_ptr;
16526 			err = propagate_liveness_reg(env, state_reg,
16527 						     parent_reg);
16528 			if (err < 0)
16529 				return err;
16530 		}
16531 	}
16532 	return 0;
16533 }
16534 
16535 /* find precise scalars in the previous equivalent state and
16536  * propagate them into the current state
16537  */
16538 static int propagate_precision(struct bpf_verifier_env *env,
16539 			       const struct bpf_verifier_state *old)
16540 {
16541 	struct bpf_reg_state *state_reg;
16542 	struct bpf_func_state *state;
16543 	int i, err = 0, fr;
16544 	bool first;
16545 
16546 	for (fr = old->curframe; fr >= 0; fr--) {
16547 		state = old->frame[fr];
16548 		state_reg = state->regs;
16549 		first = true;
16550 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16551 			if (state_reg->type != SCALAR_VALUE ||
16552 			    !state_reg->precise ||
16553 			    !(state_reg->live & REG_LIVE_READ))
16554 				continue;
16555 			if (env->log.level & BPF_LOG_LEVEL2) {
16556 				if (first)
16557 					verbose(env, "frame %d: propagating r%d", fr, i);
16558 				else
16559 					verbose(env, ",r%d", i);
16560 			}
16561 			bt_set_frame_reg(&env->bt, fr, i);
16562 			first = false;
16563 		}
16564 
16565 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16566 			if (!is_spilled_reg(&state->stack[i]))
16567 				continue;
16568 			state_reg = &state->stack[i].spilled_ptr;
16569 			if (state_reg->type != SCALAR_VALUE ||
16570 			    !state_reg->precise ||
16571 			    !(state_reg->live & REG_LIVE_READ))
16572 				continue;
16573 			if (env->log.level & BPF_LOG_LEVEL2) {
16574 				if (first)
16575 					verbose(env, "frame %d: propagating fp%d",
16576 						fr, (-i - 1) * BPF_REG_SIZE);
16577 				else
16578 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16579 			}
16580 			bt_set_frame_slot(&env->bt, fr, i);
16581 			first = false;
16582 		}
16583 		if (!first)
16584 			verbose(env, "\n");
16585 	}
16586 
16587 	err = mark_chain_precision_batch(env);
16588 	if (err < 0)
16589 		return err;
16590 
16591 	return 0;
16592 }
16593 
16594 static bool states_maybe_looping(struct bpf_verifier_state *old,
16595 				 struct bpf_verifier_state *cur)
16596 {
16597 	struct bpf_func_state *fold, *fcur;
16598 	int i, fr = cur->curframe;
16599 
16600 	if (old->curframe != fr)
16601 		return false;
16602 
16603 	fold = old->frame[fr];
16604 	fcur = cur->frame[fr];
16605 	for (i = 0; i < MAX_BPF_REG; i++)
16606 		if (memcmp(&fold->regs[i], &fcur->regs[i],
16607 			   offsetof(struct bpf_reg_state, parent)))
16608 			return false;
16609 	return true;
16610 }
16611 
16612 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16613 {
16614 	return env->insn_aux_data[insn_idx].is_iter_next;
16615 }
16616 
16617 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16618  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16619  * states to match, which otherwise would look like an infinite loop. So while
16620  * iter_next() calls are taken care of, we still need to be careful and
16621  * prevent erroneous and too eager declaration of "ininite loop", when
16622  * iterators are involved.
16623  *
16624  * Here's a situation in pseudo-BPF assembly form:
16625  *
16626  *   0: again:                          ; set up iter_next() call args
16627  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16628  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16629  *   3:   if r0 == 0 goto done
16630  *   4:   ... something useful here ...
16631  *   5:   goto again                    ; another iteration
16632  *   6: done:
16633  *   7:   r1 = &it
16634  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16635  *   9:   exit
16636  *
16637  * This is a typical loop. Let's assume that we have a prune point at 1:,
16638  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16639  * again`, assuming other heuristics don't get in a way).
16640  *
16641  * When we first time come to 1:, let's say we have some state X. We proceed
16642  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16643  * Now we come back to validate that forked ACTIVE state. We proceed through
16644  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16645  * are converging. But the problem is that we don't know that yet, as this
16646  * convergence has to happen at iter_next() call site only. So if nothing is
16647  * done, at 1: verifier will use bounded loop logic and declare infinite
16648  * looping (and would be *technically* correct, if not for iterator's
16649  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16650  * don't want that. So what we do in process_iter_next_call() when we go on
16651  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16652  * a different iteration. So when we suspect an infinite loop, we additionally
16653  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16654  * pretend we are not looping and wait for next iter_next() call.
16655  *
16656  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16657  * loop, because that would actually mean infinite loop, as DRAINED state is
16658  * "sticky", and so we'll keep returning into the same instruction with the
16659  * same state (at least in one of possible code paths).
16660  *
16661  * This approach allows to keep infinite loop heuristic even in the face of
16662  * active iterator. E.g., C snippet below is and will be detected as
16663  * inifintely looping:
16664  *
16665  *   struct bpf_iter_num it;
16666  *   int *p, x;
16667  *
16668  *   bpf_iter_num_new(&it, 0, 10);
16669  *   while ((p = bpf_iter_num_next(&t))) {
16670  *       x = p;
16671  *       while (x--) {} // <<-- infinite loop here
16672  *   }
16673  *
16674  */
16675 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16676 {
16677 	struct bpf_reg_state *slot, *cur_slot;
16678 	struct bpf_func_state *state;
16679 	int i, fr;
16680 
16681 	for (fr = old->curframe; fr >= 0; fr--) {
16682 		state = old->frame[fr];
16683 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16684 			if (state->stack[i].slot_type[0] != STACK_ITER)
16685 				continue;
16686 
16687 			slot = &state->stack[i].spilled_ptr;
16688 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16689 				continue;
16690 
16691 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16692 			if (cur_slot->iter.depth != slot->iter.depth)
16693 				return true;
16694 		}
16695 	}
16696 	return false;
16697 }
16698 
16699 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16700 {
16701 	struct bpf_verifier_state_list *new_sl;
16702 	struct bpf_verifier_state_list *sl, **pprev;
16703 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16704 	int i, j, n, err, states_cnt = 0;
16705 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16706 	bool add_new_state = force_new_state;
16707 	bool force_exact;
16708 
16709 	/* bpf progs typically have pruning point every 4 instructions
16710 	 * http://vger.kernel.org/bpfconf2019.html#session-1
16711 	 * Do not add new state for future pruning if the verifier hasn't seen
16712 	 * at least 2 jumps and at least 8 instructions.
16713 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16714 	 * In tests that amounts to up to 50% reduction into total verifier
16715 	 * memory consumption and 20% verifier time speedup.
16716 	 */
16717 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16718 	    env->insn_processed - env->prev_insn_processed >= 8)
16719 		add_new_state = true;
16720 
16721 	pprev = explored_state(env, insn_idx);
16722 	sl = *pprev;
16723 
16724 	clean_live_states(env, insn_idx, cur);
16725 
16726 	while (sl) {
16727 		states_cnt++;
16728 		if (sl->state.insn_idx != insn_idx)
16729 			goto next;
16730 
16731 		if (sl->state.branches) {
16732 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16733 
16734 			if (frame->in_async_callback_fn &&
16735 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16736 				/* Different async_entry_cnt means that the verifier is
16737 				 * processing another entry into async callback.
16738 				 * Seeing the same state is not an indication of infinite
16739 				 * loop or infinite recursion.
16740 				 * But finding the same state doesn't mean that it's safe
16741 				 * to stop processing the current state. The previous state
16742 				 * hasn't yet reached bpf_exit, since state.branches > 0.
16743 				 * Checking in_async_callback_fn alone is not enough either.
16744 				 * Since the verifier still needs to catch infinite loops
16745 				 * inside async callbacks.
16746 				 */
16747 				goto skip_inf_loop_check;
16748 			}
16749 			/* BPF open-coded iterators loop detection is special.
16750 			 * states_maybe_looping() logic is too simplistic in detecting
16751 			 * states that *might* be equivalent, because it doesn't know
16752 			 * about ID remapping, so don't even perform it.
16753 			 * See process_iter_next_call() and iter_active_depths_differ()
16754 			 * for overview of the logic. When current and one of parent
16755 			 * states are detected as equivalent, it's a good thing: we prove
16756 			 * convergence and can stop simulating further iterations.
16757 			 * It's safe to assume that iterator loop will finish, taking into
16758 			 * account iter_next() contract of eventually returning
16759 			 * sticky NULL result.
16760 			 *
16761 			 * Note, that states have to be compared exactly in this case because
16762 			 * read and precision marks might not be finalized inside the loop.
16763 			 * E.g. as in the program below:
16764 			 *
16765 			 *     1. r7 = -16
16766 			 *     2. r6 = bpf_get_prandom_u32()
16767 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
16768 			 *     4.   if (r6 != 42) {
16769 			 *     5.     r7 = -32
16770 			 *     6.     r6 = bpf_get_prandom_u32()
16771 			 *     7.     continue
16772 			 *     8.   }
16773 			 *     9.   r0 = r10
16774 			 *    10.   r0 += r7
16775 			 *    11.   r8 = *(u64 *)(r0 + 0)
16776 			 *    12.   r6 = bpf_get_prandom_u32()
16777 			 *    13. }
16778 			 *
16779 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
16780 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16781 			 * not have read or precision mark for r7 yet, thus inexact states
16782 			 * comparison would discard current state with r7=-32
16783 			 * => unsafe memory access at 11 would not be caught.
16784 			 */
16785 			if (is_iter_next_insn(env, insn_idx)) {
16786 				if (states_equal(env, &sl->state, cur, true)) {
16787 					struct bpf_func_state *cur_frame;
16788 					struct bpf_reg_state *iter_state, *iter_reg;
16789 					int spi;
16790 
16791 					cur_frame = cur->frame[cur->curframe];
16792 					/* btf_check_iter_kfuncs() enforces that
16793 					 * iter state pointer is always the first arg
16794 					 */
16795 					iter_reg = &cur_frame->regs[BPF_REG_1];
16796 					/* current state is valid due to states_equal(),
16797 					 * so we can assume valid iter and reg state,
16798 					 * no need for extra (re-)validations
16799 					 */
16800 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16801 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16802 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
16803 						update_loop_entry(cur, &sl->state);
16804 						goto hit;
16805 					}
16806 				}
16807 				goto skip_inf_loop_check;
16808 			}
16809 			if (calls_callback(env, insn_idx)) {
16810 				if (states_equal(env, &sl->state, cur, true))
16811 					goto hit;
16812 				goto skip_inf_loop_check;
16813 			}
16814 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
16815 			if (states_maybe_looping(&sl->state, cur) &&
16816 			    states_equal(env, &sl->state, cur, false) &&
16817 			    !iter_active_depths_differ(&sl->state, cur) &&
16818 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
16819 				verbose_linfo(env, insn_idx, "; ");
16820 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16821 				verbose(env, "cur state:");
16822 				print_verifier_state(env, cur->frame[cur->curframe], true);
16823 				verbose(env, "old state:");
16824 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
16825 				return -EINVAL;
16826 			}
16827 			/* if the verifier is processing a loop, avoid adding new state
16828 			 * too often, since different loop iterations have distinct
16829 			 * states and may not help future pruning.
16830 			 * This threshold shouldn't be too low to make sure that
16831 			 * a loop with large bound will be rejected quickly.
16832 			 * The most abusive loop will be:
16833 			 * r1 += 1
16834 			 * if r1 < 1000000 goto pc-2
16835 			 * 1M insn_procssed limit / 100 == 10k peak states.
16836 			 * This threshold shouldn't be too high either, since states
16837 			 * at the end of the loop are likely to be useful in pruning.
16838 			 */
16839 skip_inf_loop_check:
16840 			if (!force_new_state &&
16841 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
16842 			    env->insn_processed - env->prev_insn_processed < 100)
16843 				add_new_state = false;
16844 			goto miss;
16845 		}
16846 		/* If sl->state is a part of a loop and this loop's entry is a part of
16847 		 * current verification path then states have to be compared exactly.
16848 		 * 'force_exact' is needed to catch the following case:
16849 		 *
16850 		 *                initial     Here state 'succ' was processed first,
16851 		 *                  |         it was eventually tracked to produce a
16852 		 *                  V         state identical to 'hdr'.
16853 		 *     .---------> hdr        All branches from 'succ' had been explored
16854 		 *     |            |         and thus 'succ' has its .branches == 0.
16855 		 *     |            V
16856 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
16857 		 *     |    |       |         to the same instruction + callsites.
16858 		 *     |    V       V         In such case it is necessary to check
16859 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
16860 		 *     |    |       |         If 'succ' and 'cur' are a part of the
16861 		 *     |    V       V         same loop exact flag has to be set.
16862 		 *     |   succ <- cur        To check if that is the case, verify
16863 		 *     |    |                 if loop entry of 'succ' is in current
16864 		 *     |    V                 DFS path.
16865 		 *     |   ...
16866 		 *     |    |
16867 		 *     '----'
16868 		 *
16869 		 * Additional details are in the comment before get_loop_entry().
16870 		 */
16871 		loop_entry = get_loop_entry(&sl->state);
16872 		force_exact = loop_entry && loop_entry->branches > 0;
16873 		if (states_equal(env, &sl->state, cur, force_exact)) {
16874 			if (force_exact)
16875 				update_loop_entry(cur, loop_entry);
16876 hit:
16877 			sl->hit_cnt++;
16878 			/* reached equivalent register/stack state,
16879 			 * prune the search.
16880 			 * Registers read by the continuation are read by us.
16881 			 * If we have any write marks in env->cur_state, they
16882 			 * will prevent corresponding reads in the continuation
16883 			 * from reaching our parent (an explored_state).  Our
16884 			 * own state will get the read marks recorded, but
16885 			 * they'll be immediately forgotten as we're pruning
16886 			 * this state and will pop a new one.
16887 			 */
16888 			err = propagate_liveness(env, &sl->state, cur);
16889 
16890 			/* if previous state reached the exit with precision and
16891 			 * current state is equivalent to it (except precsion marks)
16892 			 * the precision needs to be propagated back in
16893 			 * the current state.
16894 			 */
16895 			err = err ? : push_jmp_history(env, cur);
16896 			err = err ? : propagate_precision(env, &sl->state);
16897 			if (err)
16898 				return err;
16899 			return 1;
16900 		}
16901 miss:
16902 		/* when new state is not going to be added do not increase miss count.
16903 		 * Otherwise several loop iterations will remove the state
16904 		 * recorded earlier. The goal of these heuristics is to have
16905 		 * states from some iterations of the loop (some in the beginning
16906 		 * and some at the end) to help pruning.
16907 		 */
16908 		if (add_new_state)
16909 			sl->miss_cnt++;
16910 		/* heuristic to determine whether this state is beneficial
16911 		 * to keep checking from state equivalence point of view.
16912 		 * Higher numbers increase max_states_per_insn and verification time,
16913 		 * but do not meaningfully decrease insn_processed.
16914 		 * 'n' controls how many times state could miss before eviction.
16915 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
16916 		 * too early would hinder iterator convergence.
16917 		 */
16918 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
16919 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
16920 			/* the state is unlikely to be useful. Remove it to
16921 			 * speed up verification
16922 			 */
16923 			*pprev = sl->next;
16924 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
16925 			    !sl->state.used_as_loop_entry) {
16926 				u32 br = sl->state.branches;
16927 
16928 				WARN_ONCE(br,
16929 					  "BUG live_done but branches_to_explore %d\n",
16930 					  br);
16931 				free_verifier_state(&sl->state, false);
16932 				kfree(sl);
16933 				env->peak_states--;
16934 			} else {
16935 				/* cannot free this state, since parentage chain may
16936 				 * walk it later. Add it for free_list instead to
16937 				 * be freed at the end of verification
16938 				 */
16939 				sl->next = env->free_list;
16940 				env->free_list = sl;
16941 			}
16942 			sl = *pprev;
16943 			continue;
16944 		}
16945 next:
16946 		pprev = &sl->next;
16947 		sl = *pprev;
16948 	}
16949 
16950 	if (env->max_states_per_insn < states_cnt)
16951 		env->max_states_per_insn = states_cnt;
16952 
16953 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16954 		return 0;
16955 
16956 	if (!add_new_state)
16957 		return 0;
16958 
16959 	/* There were no equivalent states, remember the current one.
16960 	 * Technically the current state is not proven to be safe yet,
16961 	 * but it will either reach outer most bpf_exit (which means it's safe)
16962 	 * or it will be rejected. When there are no loops the verifier won't be
16963 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16964 	 * again on the way to bpf_exit.
16965 	 * When looping the sl->state.branches will be > 0 and this state
16966 	 * will not be considered for equivalence until branches == 0.
16967 	 */
16968 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16969 	if (!new_sl)
16970 		return -ENOMEM;
16971 	env->total_states++;
16972 	env->peak_states++;
16973 	env->prev_jmps_processed = env->jmps_processed;
16974 	env->prev_insn_processed = env->insn_processed;
16975 
16976 	/* forget precise markings we inherited, see __mark_chain_precision */
16977 	if (env->bpf_capable)
16978 		mark_all_scalars_imprecise(env, cur);
16979 
16980 	/* add new state to the head of linked list */
16981 	new = &new_sl->state;
16982 	err = copy_verifier_state(new, cur);
16983 	if (err) {
16984 		free_verifier_state(new, false);
16985 		kfree(new_sl);
16986 		return err;
16987 	}
16988 	new->insn_idx = insn_idx;
16989 	WARN_ONCE(new->branches != 1,
16990 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16991 
16992 	cur->parent = new;
16993 	cur->first_insn_idx = insn_idx;
16994 	cur->dfs_depth = new->dfs_depth + 1;
16995 	clear_jmp_history(cur);
16996 	new_sl->next = *explored_state(env, insn_idx);
16997 	*explored_state(env, insn_idx) = new_sl;
16998 	/* connect new state to parentage chain. Current frame needs all
16999 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
17000 	 * to the stack implicitly by JITs) so in callers' frames connect just
17001 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
17002 	 * the state of the call instruction (with WRITTEN set), and r0 comes
17003 	 * from callee with its full parentage chain, anyway.
17004 	 */
17005 	/* clear write marks in current state: the writes we did are not writes
17006 	 * our child did, so they don't screen off its reads from us.
17007 	 * (There are no read marks in current state, because reads always mark
17008 	 * their parent and current state never has children yet.  Only
17009 	 * explored_states can get read marks.)
17010 	 */
17011 	for (j = 0; j <= cur->curframe; j++) {
17012 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
17013 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
17014 		for (i = 0; i < BPF_REG_FP; i++)
17015 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
17016 	}
17017 
17018 	/* all stack frames are accessible from callee, clear them all */
17019 	for (j = 0; j <= cur->curframe; j++) {
17020 		struct bpf_func_state *frame = cur->frame[j];
17021 		struct bpf_func_state *newframe = new->frame[j];
17022 
17023 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
17024 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
17025 			frame->stack[i].spilled_ptr.parent =
17026 						&newframe->stack[i].spilled_ptr;
17027 		}
17028 	}
17029 	return 0;
17030 }
17031 
17032 /* Return true if it's OK to have the same insn return a different type. */
17033 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
17034 {
17035 	switch (base_type(type)) {
17036 	case PTR_TO_CTX:
17037 	case PTR_TO_SOCKET:
17038 	case PTR_TO_SOCK_COMMON:
17039 	case PTR_TO_TCP_SOCK:
17040 	case PTR_TO_XDP_SOCK:
17041 	case PTR_TO_BTF_ID:
17042 		return false;
17043 	default:
17044 		return true;
17045 	}
17046 }
17047 
17048 /* If an instruction was previously used with particular pointer types, then we
17049  * need to be careful to avoid cases such as the below, where it may be ok
17050  * for one branch accessing the pointer, but not ok for the other branch:
17051  *
17052  * R1 = sock_ptr
17053  * goto X;
17054  * ...
17055  * R1 = some_other_valid_ptr;
17056  * goto X;
17057  * ...
17058  * R2 = *(u32 *)(R1 + 0);
17059  */
17060 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17061 {
17062 	return src != prev && (!reg_type_mismatch_ok(src) ||
17063 			       !reg_type_mismatch_ok(prev));
17064 }
17065 
17066 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17067 			     bool allow_trust_missmatch)
17068 {
17069 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17070 
17071 	if (*prev_type == NOT_INIT) {
17072 		/* Saw a valid insn
17073 		 * dst_reg = *(u32 *)(src_reg + off)
17074 		 * save type to validate intersecting paths
17075 		 */
17076 		*prev_type = type;
17077 	} else if (reg_type_mismatch(type, *prev_type)) {
17078 		/* Abuser program is trying to use the same insn
17079 		 * dst_reg = *(u32*) (src_reg + off)
17080 		 * with different pointer types:
17081 		 * src_reg == ctx in one branch and
17082 		 * src_reg == stack|map in some other branch.
17083 		 * Reject it.
17084 		 */
17085 		if (allow_trust_missmatch &&
17086 		    base_type(type) == PTR_TO_BTF_ID &&
17087 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
17088 			/*
17089 			 * Have to support a use case when one path through
17090 			 * the program yields TRUSTED pointer while another
17091 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
17092 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
17093 			 */
17094 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
17095 		} else {
17096 			verbose(env, "same insn cannot be used with different pointers\n");
17097 			return -EINVAL;
17098 		}
17099 	}
17100 
17101 	return 0;
17102 }
17103 
17104 static int do_check(struct bpf_verifier_env *env)
17105 {
17106 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17107 	struct bpf_verifier_state *state = env->cur_state;
17108 	struct bpf_insn *insns = env->prog->insnsi;
17109 	struct bpf_reg_state *regs;
17110 	int insn_cnt = env->prog->len;
17111 	bool do_print_state = false;
17112 	int prev_insn_idx = -1;
17113 
17114 	for (;;) {
17115 		bool exception_exit = false;
17116 		struct bpf_insn *insn;
17117 		u8 class;
17118 		int err;
17119 
17120 		env->prev_insn_idx = prev_insn_idx;
17121 		if (env->insn_idx >= insn_cnt) {
17122 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
17123 				env->insn_idx, insn_cnt);
17124 			return -EFAULT;
17125 		}
17126 
17127 		insn = &insns[env->insn_idx];
17128 		class = BPF_CLASS(insn->code);
17129 
17130 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17131 			verbose(env,
17132 				"BPF program is too large. Processed %d insn\n",
17133 				env->insn_processed);
17134 			return -E2BIG;
17135 		}
17136 
17137 		state->last_insn_idx = env->prev_insn_idx;
17138 
17139 		if (is_prune_point(env, env->insn_idx)) {
17140 			err = is_state_visited(env, env->insn_idx);
17141 			if (err < 0)
17142 				return err;
17143 			if (err == 1) {
17144 				/* found equivalent state, can prune the search */
17145 				if (env->log.level & BPF_LOG_LEVEL) {
17146 					if (do_print_state)
17147 						verbose(env, "\nfrom %d to %d%s: safe\n",
17148 							env->prev_insn_idx, env->insn_idx,
17149 							env->cur_state->speculative ?
17150 							" (speculative execution)" : "");
17151 					else
17152 						verbose(env, "%d: safe\n", env->insn_idx);
17153 				}
17154 				goto process_bpf_exit;
17155 			}
17156 		}
17157 
17158 		if (is_jmp_point(env, env->insn_idx)) {
17159 			err = push_jmp_history(env, state);
17160 			if (err)
17161 				return err;
17162 		}
17163 
17164 		if (signal_pending(current))
17165 			return -EAGAIN;
17166 
17167 		if (need_resched())
17168 			cond_resched();
17169 
17170 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17171 			verbose(env, "\nfrom %d to %d%s:",
17172 				env->prev_insn_idx, env->insn_idx,
17173 				env->cur_state->speculative ?
17174 				" (speculative execution)" : "");
17175 			print_verifier_state(env, state->frame[state->curframe], true);
17176 			do_print_state = false;
17177 		}
17178 
17179 		if (env->log.level & BPF_LOG_LEVEL) {
17180 			const struct bpf_insn_cbs cbs = {
17181 				.cb_call	= disasm_kfunc_name,
17182 				.cb_print	= verbose,
17183 				.private_data	= env,
17184 			};
17185 
17186 			if (verifier_state_scratched(env))
17187 				print_insn_state(env, state->frame[state->curframe]);
17188 
17189 			verbose_linfo(env, env->insn_idx, "; ");
17190 			env->prev_log_pos = env->log.end_pos;
17191 			verbose(env, "%d: ", env->insn_idx);
17192 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17193 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17194 			env->prev_log_pos = env->log.end_pos;
17195 		}
17196 
17197 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17198 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17199 							   env->prev_insn_idx);
17200 			if (err)
17201 				return err;
17202 		}
17203 
17204 		regs = cur_regs(env);
17205 		sanitize_mark_insn_seen(env);
17206 		prev_insn_idx = env->insn_idx;
17207 
17208 		if (class == BPF_ALU || class == BPF_ALU64) {
17209 			err = check_alu_op(env, insn);
17210 			if (err)
17211 				return err;
17212 
17213 		} else if (class == BPF_LDX) {
17214 			enum bpf_reg_type src_reg_type;
17215 
17216 			/* check for reserved fields is already done */
17217 
17218 			/* check src operand */
17219 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17220 			if (err)
17221 				return err;
17222 
17223 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17224 			if (err)
17225 				return err;
17226 
17227 			src_reg_type = regs[insn->src_reg].type;
17228 
17229 			/* check that memory (src_reg + off) is readable,
17230 			 * the state of dst_reg will be updated by this func
17231 			 */
17232 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17233 					       insn->off, BPF_SIZE(insn->code),
17234 					       BPF_READ, insn->dst_reg, false,
17235 					       BPF_MODE(insn->code) == BPF_MEMSX);
17236 			err = err ?: save_aux_ptr_type(env, src_reg_type, true);
17237 			err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], "ldx");
17238 			if (err)
17239 				return err;
17240 		} else if (class == BPF_STX) {
17241 			enum bpf_reg_type dst_reg_type;
17242 
17243 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17244 				err = check_atomic(env, env->insn_idx, insn);
17245 				if (err)
17246 					return err;
17247 				env->insn_idx++;
17248 				continue;
17249 			}
17250 
17251 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17252 				verbose(env, "BPF_STX uses reserved fields\n");
17253 				return -EINVAL;
17254 			}
17255 
17256 			/* check src1 operand */
17257 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17258 			if (err)
17259 				return err;
17260 			/* check src2 operand */
17261 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17262 			if (err)
17263 				return err;
17264 
17265 			dst_reg_type = regs[insn->dst_reg].type;
17266 
17267 			/* check that memory (dst_reg + off) is writeable */
17268 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17269 					       insn->off, BPF_SIZE(insn->code),
17270 					       BPF_WRITE, insn->src_reg, false, false);
17271 			if (err)
17272 				return err;
17273 
17274 			err = save_aux_ptr_type(env, dst_reg_type, false);
17275 			if (err)
17276 				return err;
17277 		} else if (class == BPF_ST) {
17278 			enum bpf_reg_type dst_reg_type;
17279 
17280 			if (BPF_MODE(insn->code) != BPF_MEM ||
17281 			    insn->src_reg != BPF_REG_0) {
17282 				verbose(env, "BPF_ST uses reserved fields\n");
17283 				return -EINVAL;
17284 			}
17285 			/* check src operand */
17286 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17287 			if (err)
17288 				return err;
17289 
17290 			dst_reg_type = regs[insn->dst_reg].type;
17291 
17292 			/* check that memory (dst_reg + off) is writeable */
17293 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17294 					       insn->off, BPF_SIZE(insn->code),
17295 					       BPF_WRITE, -1, false, false);
17296 			if (err)
17297 				return err;
17298 
17299 			err = save_aux_ptr_type(env, dst_reg_type, false);
17300 			if (err)
17301 				return err;
17302 		} else if (class == BPF_JMP || class == BPF_JMP32) {
17303 			u8 opcode = BPF_OP(insn->code);
17304 
17305 			env->jmps_processed++;
17306 			if (opcode == BPF_CALL) {
17307 				if (BPF_SRC(insn->code) != BPF_K ||
17308 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17309 				     && insn->off != 0) ||
17310 				    (insn->src_reg != BPF_REG_0 &&
17311 				     insn->src_reg != BPF_PSEUDO_CALL &&
17312 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17313 				    insn->dst_reg != BPF_REG_0 ||
17314 				    class == BPF_JMP32) {
17315 					verbose(env, "BPF_CALL uses reserved fields\n");
17316 					return -EINVAL;
17317 				}
17318 
17319 				if (env->cur_state->active_lock.ptr) {
17320 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17321 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
17322 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17323 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17324 						verbose(env, "function calls are not allowed while holding a lock\n");
17325 						return -EINVAL;
17326 					}
17327 				}
17328 				if (insn->src_reg == BPF_PSEUDO_CALL) {
17329 					err = check_func_call(env, insn, &env->insn_idx);
17330 				} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17331 					err = check_kfunc_call(env, insn, &env->insn_idx);
17332 					if (!err && is_bpf_throw_kfunc(insn)) {
17333 						exception_exit = true;
17334 						goto process_bpf_exit_full;
17335 					}
17336 				} else {
17337 					err = check_helper_call(env, insn, &env->insn_idx);
17338 				}
17339 				if (err)
17340 					return err;
17341 
17342 				mark_reg_scratched(env, BPF_REG_0);
17343 			} else if (opcode == BPF_JA) {
17344 				if (BPF_SRC(insn->code) != BPF_K ||
17345 				    insn->src_reg != BPF_REG_0 ||
17346 				    insn->dst_reg != BPF_REG_0 ||
17347 				    (class == BPF_JMP && insn->imm != 0) ||
17348 				    (class == BPF_JMP32 && insn->off != 0)) {
17349 					verbose(env, "BPF_JA uses reserved fields\n");
17350 					return -EINVAL;
17351 				}
17352 
17353 				if (class == BPF_JMP)
17354 					env->insn_idx += insn->off + 1;
17355 				else
17356 					env->insn_idx += insn->imm + 1;
17357 				continue;
17358 
17359 			} else if (opcode == BPF_EXIT) {
17360 				if (BPF_SRC(insn->code) != BPF_K ||
17361 				    insn->imm != 0 ||
17362 				    insn->src_reg != BPF_REG_0 ||
17363 				    insn->dst_reg != BPF_REG_0 ||
17364 				    class == BPF_JMP32) {
17365 					verbose(env, "BPF_EXIT uses reserved fields\n");
17366 					return -EINVAL;
17367 				}
17368 process_bpf_exit_full:
17369 				if (env->cur_state->active_lock.ptr &&
17370 				    !in_rbtree_lock_required_cb(env)) {
17371 					verbose(env, "bpf_spin_unlock is missing\n");
17372 					return -EINVAL;
17373 				}
17374 
17375 				if (env->cur_state->active_rcu_lock &&
17376 				    !in_rbtree_lock_required_cb(env)) {
17377 					verbose(env, "bpf_rcu_read_unlock is missing\n");
17378 					return -EINVAL;
17379 				}
17380 
17381 				/* We must do check_reference_leak here before
17382 				 * prepare_func_exit to handle the case when
17383 				 * state->curframe > 0, it may be a callback
17384 				 * function, for which reference_state must
17385 				 * match caller reference state when it exits.
17386 				 */
17387 				err = check_reference_leak(env, exception_exit);
17388 				if (err)
17389 					return err;
17390 
17391 				/* The side effect of the prepare_func_exit
17392 				 * which is being skipped is that it frees
17393 				 * bpf_func_state. Typically, process_bpf_exit
17394 				 * will only be hit with outermost exit.
17395 				 * copy_verifier_state in pop_stack will handle
17396 				 * freeing of any extra bpf_func_state left over
17397 				 * from not processing all nested function
17398 				 * exits. We also skip return code checks as
17399 				 * they are not needed for exceptional exits.
17400 				 */
17401 				if (exception_exit)
17402 					goto process_bpf_exit;
17403 
17404 				if (state->curframe) {
17405 					/* exit from nested function */
17406 					err = prepare_func_exit(env, &env->insn_idx);
17407 					if (err)
17408 						return err;
17409 					do_print_state = true;
17410 					continue;
17411 				}
17412 
17413 				err = check_return_code(env, BPF_REG_0);
17414 				if (err)
17415 					return err;
17416 process_bpf_exit:
17417 				mark_verifier_state_scratched(env);
17418 				update_branch_counts(env, env->cur_state);
17419 				err = pop_stack(env, &prev_insn_idx,
17420 						&env->insn_idx, pop_log);
17421 				if (err < 0) {
17422 					if (err != -ENOENT)
17423 						return err;
17424 					break;
17425 				} else {
17426 					do_print_state = true;
17427 					continue;
17428 				}
17429 			} else {
17430 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
17431 				if (err)
17432 					return err;
17433 			}
17434 		} else if (class == BPF_LD) {
17435 			u8 mode = BPF_MODE(insn->code);
17436 
17437 			if (mode == BPF_ABS || mode == BPF_IND) {
17438 				err = check_ld_abs(env, insn);
17439 				if (err)
17440 					return err;
17441 
17442 			} else if (mode == BPF_IMM) {
17443 				err = check_ld_imm(env, insn);
17444 				if (err)
17445 					return err;
17446 
17447 				env->insn_idx++;
17448 				sanitize_mark_insn_seen(env);
17449 			} else {
17450 				verbose(env, "invalid BPF_LD mode\n");
17451 				return -EINVAL;
17452 			}
17453 		} else {
17454 			verbose(env, "unknown insn class %d\n", class);
17455 			return -EINVAL;
17456 		}
17457 
17458 		env->insn_idx++;
17459 	}
17460 
17461 	return 0;
17462 }
17463 
17464 static int find_btf_percpu_datasec(struct btf *btf)
17465 {
17466 	const struct btf_type *t;
17467 	const char *tname;
17468 	int i, n;
17469 
17470 	/*
17471 	 * Both vmlinux and module each have their own ".data..percpu"
17472 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17473 	 * types to look at only module's own BTF types.
17474 	 */
17475 	n = btf_nr_types(btf);
17476 	if (btf_is_module(btf))
17477 		i = btf_nr_types(btf_vmlinux);
17478 	else
17479 		i = 1;
17480 
17481 	for(; i < n; i++) {
17482 		t = btf_type_by_id(btf, i);
17483 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17484 			continue;
17485 
17486 		tname = btf_name_by_offset(btf, t->name_off);
17487 		if (!strcmp(tname, ".data..percpu"))
17488 			return i;
17489 	}
17490 
17491 	return -ENOENT;
17492 }
17493 
17494 /* replace pseudo btf_id with kernel symbol address */
17495 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17496 			       struct bpf_insn *insn,
17497 			       struct bpf_insn_aux_data *aux)
17498 {
17499 	const struct btf_var_secinfo *vsi;
17500 	const struct btf_type *datasec;
17501 	struct btf_mod_pair *btf_mod;
17502 	const struct btf_type *t;
17503 	const char *sym_name;
17504 	bool percpu = false;
17505 	u32 type, id = insn->imm;
17506 	struct btf *btf;
17507 	s32 datasec_id;
17508 	u64 addr;
17509 	int i, btf_fd, err;
17510 
17511 	btf_fd = insn[1].imm;
17512 	if (btf_fd) {
17513 		btf = btf_get_by_fd(btf_fd);
17514 		if (IS_ERR(btf)) {
17515 			verbose(env, "invalid module BTF object FD specified.\n");
17516 			return -EINVAL;
17517 		}
17518 	} else {
17519 		if (!btf_vmlinux) {
17520 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17521 			return -EINVAL;
17522 		}
17523 		btf = btf_vmlinux;
17524 		btf_get(btf);
17525 	}
17526 
17527 	t = btf_type_by_id(btf, id);
17528 	if (!t) {
17529 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17530 		err = -ENOENT;
17531 		goto err_put;
17532 	}
17533 
17534 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17535 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17536 		err = -EINVAL;
17537 		goto err_put;
17538 	}
17539 
17540 	sym_name = btf_name_by_offset(btf, t->name_off);
17541 	addr = kallsyms_lookup_name(sym_name);
17542 	if (!addr) {
17543 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17544 			sym_name);
17545 		err = -ENOENT;
17546 		goto err_put;
17547 	}
17548 	insn[0].imm = (u32)addr;
17549 	insn[1].imm = addr >> 32;
17550 
17551 	if (btf_type_is_func(t)) {
17552 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17553 		aux->btf_var.mem_size = 0;
17554 		goto check_btf;
17555 	}
17556 
17557 	datasec_id = find_btf_percpu_datasec(btf);
17558 	if (datasec_id > 0) {
17559 		datasec = btf_type_by_id(btf, datasec_id);
17560 		for_each_vsi(i, datasec, vsi) {
17561 			if (vsi->type == id) {
17562 				percpu = true;
17563 				break;
17564 			}
17565 		}
17566 	}
17567 
17568 	type = t->type;
17569 	t = btf_type_skip_modifiers(btf, type, NULL);
17570 	if (percpu) {
17571 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17572 		aux->btf_var.btf = btf;
17573 		aux->btf_var.btf_id = type;
17574 	} else if (!btf_type_is_struct(t)) {
17575 		const struct btf_type *ret;
17576 		const char *tname;
17577 		u32 tsize;
17578 
17579 		/* resolve the type size of ksym. */
17580 		ret = btf_resolve_size(btf, t, &tsize);
17581 		if (IS_ERR(ret)) {
17582 			tname = btf_name_by_offset(btf, t->name_off);
17583 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17584 				tname, PTR_ERR(ret));
17585 			err = -EINVAL;
17586 			goto err_put;
17587 		}
17588 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17589 		aux->btf_var.mem_size = tsize;
17590 	} else {
17591 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
17592 		aux->btf_var.btf = btf;
17593 		aux->btf_var.btf_id = type;
17594 	}
17595 check_btf:
17596 	/* check whether we recorded this BTF (and maybe module) already */
17597 	for (i = 0; i < env->used_btf_cnt; i++) {
17598 		if (env->used_btfs[i].btf == btf) {
17599 			btf_put(btf);
17600 			return 0;
17601 		}
17602 	}
17603 
17604 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
17605 		err = -E2BIG;
17606 		goto err_put;
17607 	}
17608 
17609 	btf_mod = &env->used_btfs[env->used_btf_cnt];
17610 	btf_mod->btf = btf;
17611 	btf_mod->module = NULL;
17612 
17613 	/* if we reference variables from kernel module, bump its refcount */
17614 	if (btf_is_module(btf)) {
17615 		btf_mod->module = btf_try_get_module(btf);
17616 		if (!btf_mod->module) {
17617 			err = -ENXIO;
17618 			goto err_put;
17619 		}
17620 	}
17621 
17622 	env->used_btf_cnt++;
17623 
17624 	return 0;
17625 err_put:
17626 	btf_put(btf);
17627 	return err;
17628 }
17629 
17630 static bool is_tracing_prog_type(enum bpf_prog_type type)
17631 {
17632 	switch (type) {
17633 	case BPF_PROG_TYPE_KPROBE:
17634 	case BPF_PROG_TYPE_TRACEPOINT:
17635 	case BPF_PROG_TYPE_PERF_EVENT:
17636 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17637 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17638 		return true;
17639 	default:
17640 		return false;
17641 	}
17642 }
17643 
17644 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17645 					struct bpf_map *map,
17646 					struct bpf_prog *prog)
17647 
17648 {
17649 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17650 
17651 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17652 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
17653 		if (is_tracing_prog_type(prog_type)) {
17654 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17655 			return -EINVAL;
17656 		}
17657 	}
17658 
17659 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17660 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17661 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17662 			return -EINVAL;
17663 		}
17664 
17665 		if (is_tracing_prog_type(prog_type)) {
17666 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17667 			return -EINVAL;
17668 		}
17669 	}
17670 
17671 	if (btf_record_has_field(map->record, BPF_TIMER)) {
17672 		if (is_tracing_prog_type(prog_type)) {
17673 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
17674 			return -EINVAL;
17675 		}
17676 	}
17677 
17678 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17679 	    !bpf_offload_prog_map_match(prog, map)) {
17680 		verbose(env, "offload device mismatch between prog and map\n");
17681 		return -EINVAL;
17682 	}
17683 
17684 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17685 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17686 		return -EINVAL;
17687 	}
17688 
17689 	if (prog->aux->sleepable)
17690 		switch (map->map_type) {
17691 		case BPF_MAP_TYPE_HASH:
17692 		case BPF_MAP_TYPE_LRU_HASH:
17693 		case BPF_MAP_TYPE_ARRAY:
17694 		case BPF_MAP_TYPE_PERCPU_HASH:
17695 		case BPF_MAP_TYPE_PERCPU_ARRAY:
17696 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17697 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17698 		case BPF_MAP_TYPE_HASH_OF_MAPS:
17699 		case BPF_MAP_TYPE_RINGBUF:
17700 		case BPF_MAP_TYPE_USER_RINGBUF:
17701 		case BPF_MAP_TYPE_INODE_STORAGE:
17702 		case BPF_MAP_TYPE_SK_STORAGE:
17703 		case BPF_MAP_TYPE_TASK_STORAGE:
17704 		case BPF_MAP_TYPE_CGRP_STORAGE:
17705 			break;
17706 		default:
17707 			verbose(env,
17708 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17709 			return -EINVAL;
17710 		}
17711 
17712 	return 0;
17713 }
17714 
17715 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17716 {
17717 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17718 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17719 }
17720 
17721 /* find and rewrite pseudo imm in ld_imm64 instructions:
17722  *
17723  * 1. if it accesses map FD, replace it with actual map pointer.
17724  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17725  *
17726  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17727  */
17728 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17729 {
17730 	struct bpf_insn *insn = env->prog->insnsi;
17731 	int insn_cnt = env->prog->len;
17732 	int i, j, err;
17733 
17734 	err = bpf_prog_calc_tag(env->prog);
17735 	if (err)
17736 		return err;
17737 
17738 	for (i = 0; i < insn_cnt; i++, insn++) {
17739 		if (BPF_CLASS(insn->code) == BPF_LDX &&
17740 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17741 		    insn->imm != 0)) {
17742 			verbose(env, "BPF_LDX uses reserved fields\n");
17743 			return -EINVAL;
17744 		}
17745 
17746 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17747 			struct bpf_insn_aux_data *aux;
17748 			struct bpf_map *map;
17749 			struct fd f;
17750 			u64 addr;
17751 			u32 fd;
17752 
17753 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
17754 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17755 			    insn[1].off != 0) {
17756 				verbose(env, "invalid bpf_ld_imm64 insn\n");
17757 				return -EINVAL;
17758 			}
17759 
17760 			if (insn[0].src_reg == 0)
17761 				/* valid generic load 64-bit imm */
17762 				goto next_insn;
17763 
17764 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17765 				aux = &env->insn_aux_data[i];
17766 				err = check_pseudo_btf_id(env, insn, aux);
17767 				if (err)
17768 					return err;
17769 				goto next_insn;
17770 			}
17771 
17772 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17773 				aux = &env->insn_aux_data[i];
17774 				aux->ptr_type = PTR_TO_FUNC;
17775 				goto next_insn;
17776 			}
17777 
17778 			/* In final convert_pseudo_ld_imm64() step, this is
17779 			 * converted into regular 64-bit imm load insn.
17780 			 */
17781 			switch (insn[0].src_reg) {
17782 			case BPF_PSEUDO_MAP_VALUE:
17783 			case BPF_PSEUDO_MAP_IDX_VALUE:
17784 				break;
17785 			case BPF_PSEUDO_MAP_FD:
17786 			case BPF_PSEUDO_MAP_IDX:
17787 				if (insn[1].imm == 0)
17788 					break;
17789 				fallthrough;
17790 			default:
17791 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17792 				return -EINVAL;
17793 			}
17794 
17795 			switch (insn[0].src_reg) {
17796 			case BPF_PSEUDO_MAP_IDX_VALUE:
17797 			case BPF_PSEUDO_MAP_IDX:
17798 				if (bpfptr_is_null(env->fd_array)) {
17799 					verbose(env, "fd_idx without fd_array is invalid\n");
17800 					return -EPROTO;
17801 				}
17802 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
17803 							    insn[0].imm * sizeof(fd),
17804 							    sizeof(fd)))
17805 					return -EFAULT;
17806 				break;
17807 			default:
17808 				fd = insn[0].imm;
17809 				break;
17810 			}
17811 
17812 			f = fdget(fd);
17813 			map = __bpf_map_get(f);
17814 			if (IS_ERR(map)) {
17815 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
17816 					insn[0].imm);
17817 				return PTR_ERR(map);
17818 			}
17819 
17820 			err = check_map_prog_compatibility(env, map, env->prog);
17821 			if (err) {
17822 				fdput(f);
17823 				return err;
17824 			}
17825 
17826 			aux = &env->insn_aux_data[i];
17827 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17828 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17829 				addr = (unsigned long)map;
17830 			} else {
17831 				u32 off = insn[1].imm;
17832 
17833 				if (off >= BPF_MAX_VAR_OFF) {
17834 					verbose(env, "direct value offset of %u is not allowed\n", off);
17835 					fdput(f);
17836 					return -EINVAL;
17837 				}
17838 
17839 				if (!map->ops->map_direct_value_addr) {
17840 					verbose(env, "no direct value access support for this map type\n");
17841 					fdput(f);
17842 					return -EINVAL;
17843 				}
17844 
17845 				err = map->ops->map_direct_value_addr(map, &addr, off);
17846 				if (err) {
17847 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17848 						map->value_size, off);
17849 					fdput(f);
17850 					return err;
17851 				}
17852 
17853 				aux->map_off = off;
17854 				addr += off;
17855 			}
17856 
17857 			insn[0].imm = (u32)addr;
17858 			insn[1].imm = addr >> 32;
17859 
17860 			/* check whether we recorded this map already */
17861 			for (j = 0; j < env->used_map_cnt; j++) {
17862 				if (env->used_maps[j] == map) {
17863 					aux->map_index = j;
17864 					fdput(f);
17865 					goto next_insn;
17866 				}
17867 			}
17868 
17869 			if (env->used_map_cnt >= MAX_USED_MAPS) {
17870 				fdput(f);
17871 				return -E2BIG;
17872 			}
17873 
17874 			/* hold the map. If the program is rejected by verifier,
17875 			 * the map will be released by release_maps() or it
17876 			 * will be used by the valid program until it's unloaded
17877 			 * and all maps are released in free_used_maps()
17878 			 */
17879 			bpf_map_inc(map);
17880 
17881 			aux->map_index = env->used_map_cnt;
17882 			env->used_maps[env->used_map_cnt++] = map;
17883 
17884 			if (bpf_map_is_cgroup_storage(map) &&
17885 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
17886 				verbose(env, "only one cgroup storage of each type is allowed\n");
17887 				fdput(f);
17888 				return -EBUSY;
17889 			}
17890 
17891 			fdput(f);
17892 next_insn:
17893 			insn++;
17894 			i++;
17895 			continue;
17896 		}
17897 
17898 		/* Basic sanity check before we invest more work here. */
17899 		if (!bpf_opcode_in_insntable(insn->code)) {
17900 			verbose(env, "unknown opcode %02x\n", insn->code);
17901 			return -EINVAL;
17902 		}
17903 	}
17904 
17905 	/* now all pseudo BPF_LD_IMM64 instructions load valid
17906 	 * 'struct bpf_map *' into a register instead of user map_fd.
17907 	 * These pointers will be used later by verifier to validate map access.
17908 	 */
17909 	return 0;
17910 }
17911 
17912 /* drop refcnt of maps used by the rejected program */
17913 static void release_maps(struct bpf_verifier_env *env)
17914 {
17915 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
17916 			     env->used_map_cnt);
17917 }
17918 
17919 /* drop refcnt of maps used by the rejected program */
17920 static void release_btfs(struct bpf_verifier_env *env)
17921 {
17922 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17923 			     env->used_btf_cnt);
17924 }
17925 
17926 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17927 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17928 {
17929 	struct bpf_insn *insn = env->prog->insnsi;
17930 	int insn_cnt = env->prog->len;
17931 	int i;
17932 
17933 	for (i = 0; i < insn_cnt; i++, insn++) {
17934 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17935 			continue;
17936 		if (insn->src_reg == BPF_PSEUDO_FUNC)
17937 			continue;
17938 		insn->src_reg = 0;
17939 	}
17940 }
17941 
17942 /* single env->prog->insni[off] instruction was replaced with the range
17943  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17944  * [0, off) and [off, end) to new locations, so the patched range stays zero
17945  */
17946 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17947 				 struct bpf_insn_aux_data *new_data,
17948 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
17949 {
17950 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17951 	struct bpf_insn *insn = new_prog->insnsi;
17952 	u32 old_seen = old_data[off].seen;
17953 	u32 prog_len;
17954 	int i;
17955 
17956 	/* aux info at OFF always needs adjustment, no matter fast path
17957 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17958 	 * original insn at old prog.
17959 	 */
17960 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17961 
17962 	if (cnt == 1)
17963 		return;
17964 	prog_len = new_prog->len;
17965 
17966 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17967 	memcpy(new_data + off + cnt - 1, old_data + off,
17968 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17969 	for (i = off; i < off + cnt - 1; i++) {
17970 		/* Expand insni[off]'s seen count to the patched range. */
17971 		new_data[i].seen = old_seen;
17972 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
17973 	}
17974 	env->insn_aux_data = new_data;
17975 	vfree(old_data);
17976 }
17977 
17978 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17979 {
17980 	int i;
17981 
17982 	if (len == 1)
17983 		return;
17984 	/* NOTE: fake 'exit' subprog should be updated as well. */
17985 	for (i = 0; i <= env->subprog_cnt; i++) {
17986 		if (env->subprog_info[i].start <= off)
17987 			continue;
17988 		env->subprog_info[i].start += len - 1;
17989 	}
17990 }
17991 
17992 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17993 {
17994 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17995 	int i, sz = prog->aux->size_poke_tab;
17996 	struct bpf_jit_poke_descriptor *desc;
17997 
17998 	for (i = 0; i < sz; i++) {
17999 		desc = &tab[i];
18000 		if (desc->insn_idx <= off)
18001 			continue;
18002 		desc->insn_idx += len - 1;
18003 	}
18004 }
18005 
18006 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
18007 					    const struct bpf_insn *patch, u32 len)
18008 {
18009 	struct bpf_prog *new_prog;
18010 	struct bpf_insn_aux_data *new_data = NULL;
18011 
18012 	if (len > 1) {
18013 		new_data = vzalloc(array_size(env->prog->len + len - 1,
18014 					      sizeof(struct bpf_insn_aux_data)));
18015 		if (!new_data)
18016 			return NULL;
18017 	}
18018 
18019 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
18020 	if (IS_ERR(new_prog)) {
18021 		if (PTR_ERR(new_prog) == -ERANGE)
18022 			verbose(env,
18023 				"insn %d cannot be patched due to 16-bit range\n",
18024 				env->insn_aux_data[off].orig_idx);
18025 		vfree(new_data);
18026 		return NULL;
18027 	}
18028 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
18029 	adjust_subprog_starts(env, off, len);
18030 	adjust_poke_descs(new_prog, off, len);
18031 	return new_prog;
18032 }
18033 
18034 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
18035 					      u32 off, u32 cnt)
18036 {
18037 	int i, j;
18038 
18039 	/* find first prog starting at or after off (first to remove) */
18040 	for (i = 0; i < env->subprog_cnt; i++)
18041 		if (env->subprog_info[i].start >= off)
18042 			break;
18043 	/* find first prog starting at or after off + cnt (first to stay) */
18044 	for (j = i; j < env->subprog_cnt; j++)
18045 		if (env->subprog_info[j].start >= off + cnt)
18046 			break;
18047 	/* if j doesn't start exactly at off + cnt, we are just removing
18048 	 * the front of previous prog
18049 	 */
18050 	if (env->subprog_info[j].start != off + cnt)
18051 		j--;
18052 
18053 	if (j > i) {
18054 		struct bpf_prog_aux *aux = env->prog->aux;
18055 		int move;
18056 
18057 		/* move fake 'exit' subprog as well */
18058 		move = env->subprog_cnt + 1 - j;
18059 
18060 		memmove(env->subprog_info + i,
18061 			env->subprog_info + j,
18062 			sizeof(*env->subprog_info) * move);
18063 		env->subprog_cnt -= j - i;
18064 
18065 		/* remove func_info */
18066 		if (aux->func_info) {
18067 			move = aux->func_info_cnt - j;
18068 
18069 			memmove(aux->func_info + i,
18070 				aux->func_info + j,
18071 				sizeof(*aux->func_info) * move);
18072 			aux->func_info_cnt -= j - i;
18073 			/* func_info->insn_off is set after all code rewrites,
18074 			 * in adjust_btf_func() - no need to adjust
18075 			 */
18076 		}
18077 	} else {
18078 		/* convert i from "first prog to remove" to "first to adjust" */
18079 		if (env->subprog_info[i].start == off)
18080 			i++;
18081 	}
18082 
18083 	/* update fake 'exit' subprog as well */
18084 	for (; i <= env->subprog_cnt; i++)
18085 		env->subprog_info[i].start -= cnt;
18086 
18087 	return 0;
18088 }
18089 
18090 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
18091 				      u32 cnt)
18092 {
18093 	struct bpf_prog *prog = env->prog;
18094 	u32 i, l_off, l_cnt, nr_linfo;
18095 	struct bpf_line_info *linfo;
18096 
18097 	nr_linfo = prog->aux->nr_linfo;
18098 	if (!nr_linfo)
18099 		return 0;
18100 
18101 	linfo = prog->aux->linfo;
18102 
18103 	/* find first line info to remove, count lines to be removed */
18104 	for (i = 0; i < nr_linfo; i++)
18105 		if (linfo[i].insn_off >= off)
18106 			break;
18107 
18108 	l_off = i;
18109 	l_cnt = 0;
18110 	for (; i < nr_linfo; i++)
18111 		if (linfo[i].insn_off < off + cnt)
18112 			l_cnt++;
18113 		else
18114 			break;
18115 
18116 	/* First live insn doesn't match first live linfo, it needs to "inherit"
18117 	 * last removed linfo.  prog is already modified, so prog->len == off
18118 	 * means no live instructions after (tail of the program was removed).
18119 	 */
18120 	if (prog->len != off && l_cnt &&
18121 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
18122 		l_cnt--;
18123 		linfo[--i].insn_off = off + cnt;
18124 	}
18125 
18126 	/* remove the line info which refer to the removed instructions */
18127 	if (l_cnt) {
18128 		memmove(linfo + l_off, linfo + i,
18129 			sizeof(*linfo) * (nr_linfo - i));
18130 
18131 		prog->aux->nr_linfo -= l_cnt;
18132 		nr_linfo = prog->aux->nr_linfo;
18133 	}
18134 
18135 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
18136 	for (i = l_off; i < nr_linfo; i++)
18137 		linfo[i].insn_off -= cnt;
18138 
18139 	/* fix up all subprogs (incl. 'exit') which start >= off */
18140 	for (i = 0; i <= env->subprog_cnt; i++)
18141 		if (env->subprog_info[i].linfo_idx > l_off) {
18142 			/* program may have started in the removed region but
18143 			 * may not be fully removed
18144 			 */
18145 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18146 				env->subprog_info[i].linfo_idx -= l_cnt;
18147 			else
18148 				env->subprog_info[i].linfo_idx = l_off;
18149 		}
18150 
18151 	return 0;
18152 }
18153 
18154 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18155 {
18156 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18157 	unsigned int orig_prog_len = env->prog->len;
18158 	int err;
18159 
18160 	if (bpf_prog_is_offloaded(env->prog->aux))
18161 		bpf_prog_offload_remove_insns(env, off, cnt);
18162 
18163 	err = bpf_remove_insns(env->prog, off, cnt);
18164 	if (err)
18165 		return err;
18166 
18167 	err = adjust_subprog_starts_after_remove(env, off, cnt);
18168 	if (err)
18169 		return err;
18170 
18171 	err = bpf_adj_linfo_after_remove(env, off, cnt);
18172 	if (err)
18173 		return err;
18174 
18175 	memmove(aux_data + off,	aux_data + off + cnt,
18176 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18177 
18178 	return 0;
18179 }
18180 
18181 /* The verifier does more data flow analysis than llvm and will not
18182  * explore branches that are dead at run time. Malicious programs can
18183  * have dead code too. Therefore replace all dead at-run-time code
18184  * with 'ja -1'.
18185  *
18186  * Just nops are not optimal, e.g. if they would sit at the end of the
18187  * program and through another bug we would manage to jump there, then
18188  * we'd execute beyond program memory otherwise. Returning exception
18189  * code also wouldn't work since we can have subprogs where the dead
18190  * code could be located.
18191  */
18192 static void sanitize_dead_code(struct bpf_verifier_env *env)
18193 {
18194 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18195 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18196 	struct bpf_insn *insn = env->prog->insnsi;
18197 	const int insn_cnt = env->prog->len;
18198 	int i;
18199 
18200 	for (i = 0; i < insn_cnt; i++) {
18201 		if (aux_data[i].seen)
18202 			continue;
18203 		memcpy(insn + i, &trap, sizeof(trap));
18204 		aux_data[i].zext_dst = false;
18205 	}
18206 }
18207 
18208 static bool insn_is_cond_jump(u8 code)
18209 {
18210 	u8 op;
18211 
18212 	op = BPF_OP(code);
18213 	if (BPF_CLASS(code) == BPF_JMP32)
18214 		return op != BPF_JA;
18215 
18216 	if (BPF_CLASS(code) != BPF_JMP)
18217 		return false;
18218 
18219 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18220 }
18221 
18222 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18223 {
18224 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18225 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18226 	struct bpf_insn *insn = env->prog->insnsi;
18227 	const int insn_cnt = env->prog->len;
18228 	int i;
18229 
18230 	for (i = 0; i < insn_cnt; i++, insn++) {
18231 		if (!insn_is_cond_jump(insn->code))
18232 			continue;
18233 
18234 		if (!aux_data[i + 1].seen)
18235 			ja.off = insn->off;
18236 		else if (!aux_data[i + 1 + insn->off].seen)
18237 			ja.off = 0;
18238 		else
18239 			continue;
18240 
18241 		if (bpf_prog_is_offloaded(env->prog->aux))
18242 			bpf_prog_offload_replace_insn(env, i, &ja);
18243 
18244 		memcpy(insn, &ja, sizeof(ja));
18245 	}
18246 }
18247 
18248 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18249 {
18250 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18251 	int insn_cnt = env->prog->len;
18252 	int i, err;
18253 
18254 	for (i = 0; i < insn_cnt; i++) {
18255 		int j;
18256 
18257 		j = 0;
18258 		while (i + j < insn_cnt && !aux_data[i + j].seen)
18259 			j++;
18260 		if (!j)
18261 			continue;
18262 
18263 		err = verifier_remove_insns(env, i, j);
18264 		if (err)
18265 			return err;
18266 		insn_cnt = env->prog->len;
18267 	}
18268 
18269 	return 0;
18270 }
18271 
18272 static int opt_remove_nops(struct bpf_verifier_env *env)
18273 {
18274 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18275 	struct bpf_insn *insn = env->prog->insnsi;
18276 	int insn_cnt = env->prog->len;
18277 	int i, err;
18278 
18279 	for (i = 0; i < insn_cnt; i++) {
18280 		if (memcmp(&insn[i], &ja, sizeof(ja)))
18281 			continue;
18282 
18283 		err = verifier_remove_insns(env, i, 1);
18284 		if (err)
18285 			return err;
18286 		insn_cnt--;
18287 		i--;
18288 	}
18289 
18290 	return 0;
18291 }
18292 
18293 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18294 					 const union bpf_attr *attr)
18295 {
18296 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18297 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18298 	int i, patch_len, delta = 0, len = env->prog->len;
18299 	struct bpf_insn *insns = env->prog->insnsi;
18300 	struct bpf_prog *new_prog;
18301 	bool rnd_hi32;
18302 
18303 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18304 	zext_patch[1] = BPF_ZEXT_REG(0);
18305 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18306 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18307 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18308 	for (i = 0; i < len; i++) {
18309 		int adj_idx = i + delta;
18310 		struct bpf_insn insn;
18311 		int load_reg;
18312 
18313 		insn = insns[adj_idx];
18314 		load_reg = insn_def_regno(&insn);
18315 		if (!aux[adj_idx].zext_dst) {
18316 			u8 code, class;
18317 			u32 imm_rnd;
18318 
18319 			if (!rnd_hi32)
18320 				continue;
18321 
18322 			code = insn.code;
18323 			class = BPF_CLASS(code);
18324 			if (load_reg == -1)
18325 				continue;
18326 
18327 			/* NOTE: arg "reg" (the fourth one) is only used for
18328 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
18329 			 *       here.
18330 			 */
18331 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18332 				if (class == BPF_LD &&
18333 				    BPF_MODE(code) == BPF_IMM)
18334 					i++;
18335 				continue;
18336 			}
18337 
18338 			/* ctx load could be transformed into wider load. */
18339 			if (class == BPF_LDX &&
18340 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
18341 				continue;
18342 
18343 			imm_rnd = get_random_u32();
18344 			rnd_hi32_patch[0] = insn;
18345 			rnd_hi32_patch[1].imm = imm_rnd;
18346 			rnd_hi32_patch[3].dst_reg = load_reg;
18347 			patch = rnd_hi32_patch;
18348 			patch_len = 4;
18349 			goto apply_patch_buffer;
18350 		}
18351 
18352 		/* Add in an zero-extend instruction if a) the JIT has requested
18353 		 * it or b) it's a CMPXCHG.
18354 		 *
18355 		 * The latter is because: BPF_CMPXCHG always loads a value into
18356 		 * R0, therefore always zero-extends. However some archs'
18357 		 * equivalent instruction only does this load when the
18358 		 * comparison is successful. This detail of CMPXCHG is
18359 		 * orthogonal to the general zero-extension behaviour of the
18360 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
18361 		 */
18362 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18363 			continue;
18364 
18365 		/* Zero-extension is done by the caller. */
18366 		if (bpf_pseudo_kfunc_call(&insn))
18367 			continue;
18368 
18369 		if (WARN_ON(load_reg == -1)) {
18370 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18371 			return -EFAULT;
18372 		}
18373 
18374 		zext_patch[0] = insn;
18375 		zext_patch[1].dst_reg = load_reg;
18376 		zext_patch[1].src_reg = load_reg;
18377 		patch = zext_patch;
18378 		patch_len = 2;
18379 apply_patch_buffer:
18380 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18381 		if (!new_prog)
18382 			return -ENOMEM;
18383 		env->prog = new_prog;
18384 		insns = new_prog->insnsi;
18385 		aux = env->insn_aux_data;
18386 		delta += patch_len - 1;
18387 	}
18388 
18389 	return 0;
18390 }
18391 
18392 /* convert load instructions that access fields of a context type into a
18393  * sequence of instructions that access fields of the underlying structure:
18394  *     struct __sk_buff    -> struct sk_buff
18395  *     struct bpf_sock_ops -> struct sock
18396  */
18397 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18398 {
18399 	const struct bpf_verifier_ops *ops = env->ops;
18400 	int i, cnt, size, ctx_field_size, delta = 0;
18401 	const int insn_cnt = env->prog->len;
18402 	struct bpf_insn insn_buf[16], *insn;
18403 	u32 target_size, size_default, off;
18404 	struct bpf_prog *new_prog;
18405 	enum bpf_access_type type;
18406 	bool is_narrower_load;
18407 
18408 	if (ops->gen_prologue || env->seen_direct_write) {
18409 		if (!ops->gen_prologue) {
18410 			verbose(env, "bpf verifier is misconfigured\n");
18411 			return -EINVAL;
18412 		}
18413 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18414 					env->prog);
18415 		if (cnt >= ARRAY_SIZE(insn_buf)) {
18416 			verbose(env, "bpf verifier is misconfigured\n");
18417 			return -EINVAL;
18418 		} else if (cnt) {
18419 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18420 			if (!new_prog)
18421 				return -ENOMEM;
18422 
18423 			env->prog = new_prog;
18424 			delta += cnt - 1;
18425 		}
18426 	}
18427 
18428 	if (bpf_prog_is_offloaded(env->prog->aux))
18429 		return 0;
18430 
18431 	insn = env->prog->insnsi + delta;
18432 
18433 	for (i = 0; i < insn_cnt; i++, insn++) {
18434 		bpf_convert_ctx_access_t convert_ctx_access;
18435 		u8 mode;
18436 
18437 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18438 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18439 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18440 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18441 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18442 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18443 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18444 			type = BPF_READ;
18445 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18446 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18447 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18448 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18449 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18450 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18451 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18452 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18453 			type = BPF_WRITE;
18454 		} else {
18455 			continue;
18456 		}
18457 
18458 		if (type == BPF_WRITE &&
18459 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
18460 			struct bpf_insn patch[] = {
18461 				*insn,
18462 				BPF_ST_NOSPEC(),
18463 			};
18464 
18465 			cnt = ARRAY_SIZE(patch);
18466 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18467 			if (!new_prog)
18468 				return -ENOMEM;
18469 
18470 			delta    += cnt - 1;
18471 			env->prog = new_prog;
18472 			insn      = new_prog->insnsi + i + delta;
18473 			continue;
18474 		}
18475 
18476 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18477 		case PTR_TO_CTX:
18478 			if (!ops->convert_ctx_access)
18479 				continue;
18480 			convert_ctx_access = ops->convert_ctx_access;
18481 			break;
18482 		case PTR_TO_SOCKET:
18483 		case PTR_TO_SOCK_COMMON:
18484 			convert_ctx_access = bpf_sock_convert_ctx_access;
18485 			break;
18486 		case PTR_TO_TCP_SOCK:
18487 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18488 			break;
18489 		case PTR_TO_XDP_SOCK:
18490 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18491 			break;
18492 		case PTR_TO_BTF_ID:
18493 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18494 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18495 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18496 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18497 		 * any faults for loads into such types. BPF_WRITE is disallowed
18498 		 * for this case.
18499 		 */
18500 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18501 			if (type == BPF_READ) {
18502 				if (BPF_MODE(insn->code) == BPF_MEM)
18503 					insn->code = BPF_LDX | BPF_PROBE_MEM |
18504 						     BPF_SIZE((insn)->code);
18505 				else
18506 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18507 						     BPF_SIZE((insn)->code);
18508 				env->prog->aux->num_exentries++;
18509 			}
18510 			continue;
18511 		default:
18512 			continue;
18513 		}
18514 
18515 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18516 		size = BPF_LDST_BYTES(insn);
18517 		mode = BPF_MODE(insn->code);
18518 
18519 		/* If the read access is a narrower load of the field,
18520 		 * convert to a 4/8-byte load, to minimum program type specific
18521 		 * convert_ctx_access changes. If conversion is successful,
18522 		 * we will apply proper mask to the result.
18523 		 */
18524 		is_narrower_load = size < ctx_field_size;
18525 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18526 		off = insn->off;
18527 		if (is_narrower_load) {
18528 			u8 size_code;
18529 
18530 			if (type == BPF_WRITE) {
18531 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18532 				return -EINVAL;
18533 			}
18534 
18535 			size_code = BPF_H;
18536 			if (ctx_field_size == 4)
18537 				size_code = BPF_W;
18538 			else if (ctx_field_size == 8)
18539 				size_code = BPF_DW;
18540 
18541 			insn->off = off & ~(size_default - 1);
18542 			insn->code = BPF_LDX | BPF_MEM | size_code;
18543 		}
18544 
18545 		target_size = 0;
18546 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18547 					 &target_size);
18548 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18549 		    (ctx_field_size && !target_size)) {
18550 			verbose(env, "bpf verifier is misconfigured\n");
18551 			return -EINVAL;
18552 		}
18553 
18554 		if (is_narrower_load && size < target_size) {
18555 			u8 shift = bpf_ctx_narrow_access_offset(
18556 				off, size, size_default) * 8;
18557 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18558 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18559 				return -EINVAL;
18560 			}
18561 			if (ctx_field_size <= 4) {
18562 				if (shift)
18563 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18564 									insn->dst_reg,
18565 									shift);
18566 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18567 								(1 << size * 8) - 1);
18568 			} else {
18569 				if (shift)
18570 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18571 									insn->dst_reg,
18572 									shift);
18573 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18574 								(1ULL << size * 8) - 1);
18575 			}
18576 		}
18577 		if (mode == BPF_MEMSX)
18578 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18579 						       insn->dst_reg, insn->dst_reg,
18580 						       size * 8, 0);
18581 
18582 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18583 		if (!new_prog)
18584 			return -ENOMEM;
18585 
18586 		delta += cnt - 1;
18587 
18588 		/* keep walking new program and skip insns we just inserted */
18589 		env->prog = new_prog;
18590 		insn      = new_prog->insnsi + i + delta;
18591 	}
18592 
18593 	return 0;
18594 }
18595 
18596 static int jit_subprogs(struct bpf_verifier_env *env)
18597 {
18598 	struct bpf_prog *prog = env->prog, **func, *tmp;
18599 	int i, j, subprog_start, subprog_end = 0, len, subprog;
18600 	struct bpf_map *map_ptr;
18601 	struct bpf_insn *insn;
18602 	void *old_bpf_func;
18603 	int err, num_exentries;
18604 
18605 	if (env->subprog_cnt <= 1)
18606 		return 0;
18607 
18608 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18609 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18610 			continue;
18611 
18612 		/* Upon error here we cannot fall back to interpreter but
18613 		 * need a hard reject of the program. Thus -EFAULT is
18614 		 * propagated in any case.
18615 		 */
18616 		subprog = find_subprog(env, i + insn->imm + 1);
18617 		if (subprog < 0) {
18618 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18619 				  i + insn->imm + 1);
18620 			return -EFAULT;
18621 		}
18622 		/* temporarily remember subprog id inside insn instead of
18623 		 * aux_data, since next loop will split up all insns into funcs
18624 		 */
18625 		insn->off = subprog;
18626 		/* remember original imm in case JIT fails and fallback
18627 		 * to interpreter will be needed
18628 		 */
18629 		env->insn_aux_data[i].call_imm = insn->imm;
18630 		/* point imm to __bpf_call_base+1 from JITs point of view */
18631 		insn->imm = 1;
18632 		if (bpf_pseudo_func(insn))
18633 			/* jit (e.g. x86_64) may emit fewer instructions
18634 			 * if it learns a u32 imm is the same as a u64 imm.
18635 			 * Force a non zero here.
18636 			 */
18637 			insn[1].imm = 1;
18638 	}
18639 
18640 	err = bpf_prog_alloc_jited_linfo(prog);
18641 	if (err)
18642 		goto out_undo_insn;
18643 
18644 	err = -ENOMEM;
18645 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18646 	if (!func)
18647 		goto out_undo_insn;
18648 
18649 	for (i = 0; i < env->subprog_cnt; i++) {
18650 		subprog_start = subprog_end;
18651 		subprog_end = env->subprog_info[i + 1].start;
18652 
18653 		len = subprog_end - subprog_start;
18654 		/* bpf_prog_run() doesn't call subprogs directly,
18655 		 * hence main prog stats include the runtime of subprogs.
18656 		 * subprogs don't have IDs and not reachable via prog_get_next_id
18657 		 * func[i]->stats will never be accessed and stays NULL
18658 		 */
18659 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18660 		if (!func[i])
18661 			goto out_free;
18662 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18663 		       len * sizeof(struct bpf_insn));
18664 		func[i]->type = prog->type;
18665 		func[i]->len = len;
18666 		if (bpf_prog_calc_tag(func[i]))
18667 			goto out_free;
18668 		func[i]->is_func = 1;
18669 		func[i]->aux->func_idx = i;
18670 		/* Below members will be freed only at prog->aux */
18671 		func[i]->aux->btf = prog->aux->btf;
18672 		func[i]->aux->func_info = prog->aux->func_info;
18673 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18674 		func[i]->aux->poke_tab = prog->aux->poke_tab;
18675 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18676 
18677 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
18678 			struct bpf_jit_poke_descriptor *poke;
18679 
18680 			poke = &prog->aux->poke_tab[j];
18681 			if (poke->insn_idx < subprog_end &&
18682 			    poke->insn_idx >= subprog_start)
18683 				poke->aux = func[i]->aux;
18684 		}
18685 
18686 		func[i]->aux->name[0] = 'F';
18687 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18688 		func[i]->jit_requested = 1;
18689 		func[i]->blinding_requested = prog->blinding_requested;
18690 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18691 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18692 		func[i]->aux->linfo = prog->aux->linfo;
18693 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18694 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18695 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18696 		num_exentries = 0;
18697 		insn = func[i]->insnsi;
18698 		for (j = 0; j < func[i]->len; j++, insn++) {
18699 			if (BPF_CLASS(insn->code) == BPF_LDX &&
18700 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18701 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18702 				num_exentries++;
18703 		}
18704 		func[i]->aux->num_exentries = num_exentries;
18705 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18706 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
18707 		if (!i)
18708 			func[i]->aux->exception_boundary = env->seen_exception;
18709 		func[i] = bpf_int_jit_compile(func[i]);
18710 		if (!func[i]->jited) {
18711 			err = -ENOTSUPP;
18712 			goto out_free;
18713 		}
18714 		cond_resched();
18715 	}
18716 
18717 	/* at this point all bpf functions were successfully JITed
18718 	 * now populate all bpf_calls with correct addresses and
18719 	 * run last pass of JIT
18720 	 */
18721 	for (i = 0; i < env->subprog_cnt; i++) {
18722 		insn = func[i]->insnsi;
18723 		for (j = 0; j < func[i]->len; j++, insn++) {
18724 			if (bpf_pseudo_func(insn)) {
18725 				subprog = insn->off;
18726 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18727 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18728 				continue;
18729 			}
18730 			if (!bpf_pseudo_call(insn))
18731 				continue;
18732 			subprog = insn->off;
18733 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18734 		}
18735 
18736 		/* we use the aux data to keep a list of the start addresses
18737 		 * of the JITed images for each function in the program
18738 		 *
18739 		 * for some architectures, such as powerpc64, the imm field
18740 		 * might not be large enough to hold the offset of the start
18741 		 * address of the callee's JITed image from __bpf_call_base
18742 		 *
18743 		 * in such cases, we can lookup the start address of a callee
18744 		 * by using its subprog id, available from the off field of
18745 		 * the call instruction, as an index for this list
18746 		 */
18747 		func[i]->aux->func = func;
18748 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
18749 		func[i]->aux->real_func_cnt = env->subprog_cnt;
18750 	}
18751 	for (i = 0; i < env->subprog_cnt; i++) {
18752 		old_bpf_func = func[i]->bpf_func;
18753 		tmp = bpf_int_jit_compile(func[i]);
18754 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18755 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18756 			err = -ENOTSUPP;
18757 			goto out_free;
18758 		}
18759 		cond_resched();
18760 	}
18761 
18762 	/* finally lock prog and jit images for all functions and
18763 	 * populate kallsysm. Begin at the first subprogram, since
18764 	 * bpf_prog_load will add the kallsyms for the main program.
18765 	 */
18766 	for (i = 1; i < env->subprog_cnt; i++) {
18767 		bpf_prog_lock_ro(func[i]);
18768 		bpf_prog_kallsyms_add(func[i]);
18769 	}
18770 
18771 	/* Last step: make now unused interpreter insns from main
18772 	 * prog consistent for later dump requests, so they can
18773 	 * later look the same as if they were interpreted only.
18774 	 */
18775 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18776 		if (bpf_pseudo_func(insn)) {
18777 			insn[0].imm = env->insn_aux_data[i].call_imm;
18778 			insn[1].imm = insn->off;
18779 			insn->off = 0;
18780 			continue;
18781 		}
18782 		if (!bpf_pseudo_call(insn))
18783 			continue;
18784 		insn->off = env->insn_aux_data[i].call_imm;
18785 		subprog = find_subprog(env, i + insn->off + 1);
18786 		insn->imm = subprog;
18787 	}
18788 
18789 	prog->jited = 1;
18790 	prog->bpf_func = func[0]->bpf_func;
18791 	prog->jited_len = func[0]->jited_len;
18792 	prog->aux->extable = func[0]->aux->extable;
18793 	prog->aux->num_exentries = func[0]->aux->num_exentries;
18794 	prog->aux->func = func;
18795 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
18796 	prog->aux->real_func_cnt = env->subprog_cnt;
18797 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
18798 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
18799 	bpf_prog_jit_attempt_done(prog);
18800 	return 0;
18801 out_free:
18802 	/* We failed JIT'ing, so at this point we need to unregister poke
18803 	 * descriptors from subprogs, so that kernel is not attempting to
18804 	 * patch it anymore as we're freeing the subprog JIT memory.
18805 	 */
18806 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18807 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18808 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18809 	}
18810 	/* At this point we're guaranteed that poke descriptors are not
18811 	 * live anymore. We can just unlink its descriptor table as it's
18812 	 * released with the main prog.
18813 	 */
18814 	for (i = 0; i < env->subprog_cnt; i++) {
18815 		if (!func[i])
18816 			continue;
18817 		func[i]->aux->poke_tab = NULL;
18818 		bpf_jit_free(func[i]);
18819 	}
18820 	kfree(func);
18821 out_undo_insn:
18822 	/* cleanup main prog to be interpreted */
18823 	prog->jit_requested = 0;
18824 	prog->blinding_requested = 0;
18825 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18826 		if (!bpf_pseudo_call(insn))
18827 			continue;
18828 		insn->off = 0;
18829 		insn->imm = env->insn_aux_data[i].call_imm;
18830 	}
18831 	bpf_prog_jit_attempt_done(prog);
18832 	return err;
18833 }
18834 
18835 static int fixup_call_args(struct bpf_verifier_env *env)
18836 {
18837 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18838 	struct bpf_prog *prog = env->prog;
18839 	struct bpf_insn *insn = prog->insnsi;
18840 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18841 	int i, depth;
18842 #endif
18843 	int err = 0;
18844 
18845 	if (env->prog->jit_requested &&
18846 	    !bpf_prog_is_offloaded(env->prog->aux)) {
18847 		err = jit_subprogs(env);
18848 		if (err == 0)
18849 			return 0;
18850 		if (err == -EFAULT)
18851 			return err;
18852 	}
18853 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18854 	if (has_kfunc_call) {
18855 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18856 		return -EINVAL;
18857 	}
18858 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18859 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
18860 		 * have to be rejected, since interpreter doesn't support them yet.
18861 		 */
18862 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18863 		return -EINVAL;
18864 	}
18865 	for (i = 0; i < prog->len; i++, insn++) {
18866 		if (bpf_pseudo_func(insn)) {
18867 			/* When JIT fails the progs with callback calls
18868 			 * have to be rejected, since interpreter doesn't support them yet.
18869 			 */
18870 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
18871 			return -EINVAL;
18872 		}
18873 
18874 		if (!bpf_pseudo_call(insn))
18875 			continue;
18876 		depth = get_callee_stack_depth(env, insn, i);
18877 		if (depth < 0)
18878 			return depth;
18879 		bpf_patch_call_args(insn, depth);
18880 	}
18881 	err = 0;
18882 #endif
18883 	return err;
18884 }
18885 
18886 /* replace a generic kfunc with a specialized version if necessary */
18887 static void specialize_kfunc(struct bpf_verifier_env *env,
18888 			     u32 func_id, u16 offset, unsigned long *addr)
18889 {
18890 	struct bpf_prog *prog = env->prog;
18891 	bool seen_direct_write;
18892 	void *xdp_kfunc;
18893 	bool is_rdonly;
18894 
18895 	if (bpf_dev_bound_kfunc_id(func_id)) {
18896 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18897 		if (xdp_kfunc) {
18898 			*addr = (unsigned long)xdp_kfunc;
18899 			return;
18900 		}
18901 		/* fallback to default kfunc when not supported by netdev */
18902 	}
18903 
18904 	if (offset)
18905 		return;
18906 
18907 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18908 		seen_direct_write = env->seen_direct_write;
18909 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18910 
18911 		if (is_rdonly)
18912 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18913 
18914 		/* restore env->seen_direct_write to its original value, since
18915 		 * may_access_direct_pkt_data mutates it
18916 		 */
18917 		env->seen_direct_write = seen_direct_write;
18918 	}
18919 }
18920 
18921 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18922 					    u16 struct_meta_reg,
18923 					    u16 node_offset_reg,
18924 					    struct bpf_insn *insn,
18925 					    struct bpf_insn *insn_buf,
18926 					    int *cnt)
18927 {
18928 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18929 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18930 
18931 	insn_buf[0] = addr[0];
18932 	insn_buf[1] = addr[1];
18933 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18934 	insn_buf[3] = *insn;
18935 	*cnt = 4;
18936 }
18937 
18938 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18939 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18940 {
18941 	const struct bpf_kfunc_desc *desc;
18942 
18943 	if (!insn->imm) {
18944 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18945 		return -EINVAL;
18946 	}
18947 
18948 	*cnt = 0;
18949 
18950 	/* insn->imm has the btf func_id. Replace it with an offset relative to
18951 	 * __bpf_call_base, unless the JIT needs to call functions that are
18952 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18953 	 */
18954 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18955 	if (!desc) {
18956 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18957 			insn->imm);
18958 		return -EFAULT;
18959 	}
18960 
18961 	if (!bpf_jit_supports_far_kfunc_call())
18962 		insn->imm = BPF_CALL_IMM(desc->addr);
18963 	if (insn->off)
18964 		return 0;
18965 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
18966 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
18967 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18968 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18969 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18970 
18971 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
18972 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
18973 				insn_idx);
18974 			return -EFAULT;
18975 		}
18976 
18977 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18978 		insn_buf[1] = addr[0];
18979 		insn_buf[2] = addr[1];
18980 		insn_buf[3] = *insn;
18981 		*cnt = 4;
18982 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18983 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
18984 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18985 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18986 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18987 
18988 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
18989 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
18990 				insn_idx);
18991 			return -EFAULT;
18992 		}
18993 
18994 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
18995 		    !kptr_struct_meta) {
18996 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18997 				insn_idx);
18998 			return -EFAULT;
18999 		}
19000 
19001 		insn_buf[0] = addr[0];
19002 		insn_buf[1] = addr[1];
19003 		insn_buf[2] = *insn;
19004 		*cnt = 3;
19005 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
19006 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
19007 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19008 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19009 		int struct_meta_reg = BPF_REG_3;
19010 		int node_offset_reg = BPF_REG_4;
19011 
19012 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
19013 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19014 			struct_meta_reg = BPF_REG_4;
19015 			node_offset_reg = BPF_REG_5;
19016 		}
19017 
19018 		if (!kptr_struct_meta) {
19019 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19020 				insn_idx);
19021 			return -EFAULT;
19022 		}
19023 
19024 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
19025 						node_offset_reg, insn, insn_buf, cnt);
19026 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
19027 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
19028 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
19029 		*cnt = 1;
19030 	}
19031 	return 0;
19032 }
19033 
19034 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
19035 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
19036 {
19037 	struct bpf_subprog_info *info = env->subprog_info;
19038 	int cnt = env->subprog_cnt;
19039 	struct bpf_prog *prog;
19040 
19041 	/* We only reserve one slot for hidden subprogs in subprog_info. */
19042 	if (env->hidden_subprog_cnt) {
19043 		verbose(env, "verifier internal error: only one hidden subprog supported\n");
19044 		return -EFAULT;
19045 	}
19046 	/* We're not patching any existing instruction, just appending the new
19047 	 * ones for the hidden subprog. Hence all of the adjustment operations
19048 	 * in bpf_patch_insn_data are no-ops.
19049 	 */
19050 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
19051 	if (!prog)
19052 		return -ENOMEM;
19053 	env->prog = prog;
19054 	info[cnt + 1].start = info[cnt].start;
19055 	info[cnt].start = prog->len - len + 1;
19056 	env->subprog_cnt++;
19057 	env->hidden_subprog_cnt++;
19058 	return 0;
19059 }
19060 
19061 /* Do various post-verification rewrites in a single program pass.
19062  * These rewrites simplify JIT and interpreter implementations.
19063  */
19064 static int do_misc_fixups(struct bpf_verifier_env *env)
19065 {
19066 	struct bpf_prog *prog = env->prog;
19067 	enum bpf_attach_type eatype = prog->expected_attach_type;
19068 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
19069 	struct bpf_insn *insn = prog->insnsi;
19070 	const struct bpf_func_proto *fn;
19071 	const int insn_cnt = prog->len;
19072 	const struct bpf_map_ops *ops;
19073 	struct bpf_insn_aux_data *aux;
19074 	struct bpf_insn insn_buf[16];
19075 	struct bpf_prog *new_prog;
19076 	struct bpf_map *map_ptr;
19077 	int i, ret, cnt, delta = 0;
19078 
19079 	if (env->seen_exception && !env->exception_callback_subprog) {
19080 		struct bpf_insn patch[] = {
19081 			env->prog->insnsi[insn_cnt - 1],
19082 			BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
19083 			BPF_EXIT_INSN(),
19084 		};
19085 
19086 		ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
19087 		if (ret < 0)
19088 			return ret;
19089 		prog = env->prog;
19090 		insn = prog->insnsi;
19091 
19092 		env->exception_callback_subprog = env->subprog_cnt - 1;
19093 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
19094 		env->subprog_info[env->exception_callback_subprog].is_cb = true;
19095 		env->subprog_info[env->exception_callback_subprog].is_async_cb = true;
19096 		env->subprog_info[env->exception_callback_subprog].is_exception_cb = true;
19097 	}
19098 
19099 	for (i = 0; i < insn_cnt; i++, insn++) {
19100 		/* Make divide-by-zero exceptions impossible. */
19101 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
19102 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
19103 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
19104 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
19105 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
19106 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
19107 			struct bpf_insn *patchlet;
19108 			struct bpf_insn chk_and_div[] = {
19109 				/* [R,W]x div 0 -> 0 */
19110 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19111 					     BPF_JNE | BPF_K, insn->src_reg,
19112 					     0, 2, 0),
19113 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
19114 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19115 				*insn,
19116 			};
19117 			struct bpf_insn chk_and_mod[] = {
19118 				/* [R,W]x mod 0 -> [R,W]x */
19119 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19120 					     BPF_JEQ | BPF_K, insn->src_reg,
19121 					     0, 1 + (is64 ? 0 : 1), 0),
19122 				*insn,
19123 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19124 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
19125 			};
19126 
19127 			patchlet = isdiv ? chk_and_div : chk_and_mod;
19128 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
19129 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
19130 
19131 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
19132 			if (!new_prog)
19133 				return -ENOMEM;
19134 
19135 			delta    += cnt - 1;
19136 			env->prog = prog = new_prog;
19137 			insn      = new_prog->insnsi + i + delta;
19138 			continue;
19139 		}
19140 
19141 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
19142 		if (BPF_CLASS(insn->code) == BPF_LD &&
19143 		    (BPF_MODE(insn->code) == BPF_ABS ||
19144 		     BPF_MODE(insn->code) == BPF_IND)) {
19145 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
19146 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19147 				verbose(env, "bpf verifier is misconfigured\n");
19148 				return -EINVAL;
19149 			}
19150 
19151 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19152 			if (!new_prog)
19153 				return -ENOMEM;
19154 
19155 			delta    += cnt - 1;
19156 			env->prog = prog = new_prog;
19157 			insn      = new_prog->insnsi + i + delta;
19158 			continue;
19159 		}
19160 
19161 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
19162 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
19163 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
19164 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
19165 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
19166 			struct bpf_insn *patch = &insn_buf[0];
19167 			bool issrc, isneg, isimm;
19168 			u32 off_reg;
19169 
19170 			aux = &env->insn_aux_data[i + delta];
19171 			if (!aux->alu_state ||
19172 			    aux->alu_state == BPF_ALU_NON_POINTER)
19173 				continue;
19174 
19175 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
19176 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
19177 				BPF_ALU_SANITIZE_SRC;
19178 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
19179 
19180 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
19181 			if (isimm) {
19182 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19183 			} else {
19184 				if (isneg)
19185 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19186 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19187 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
19188 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
19189 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
19190 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
19191 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
19192 			}
19193 			if (!issrc)
19194 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
19195 			insn->src_reg = BPF_REG_AX;
19196 			if (isneg)
19197 				insn->code = insn->code == code_add ?
19198 					     code_sub : code_add;
19199 			*patch++ = *insn;
19200 			if (issrc && isneg && !isimm)
19201 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19202 			cnt = patch - insn_buf;
19203 
19204 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19205 			if (!new_prog)
19206 				return -ENOMEM;
19207 
19208 			delta    += cnt - 1;
19209 			env->prog = prog = new_prog;
19210 			insn      = new_prog->insnsi + i + delta;
19211 			continue;
19212 		}
19213 
19214 		if (insn->code != (BPF_JMP | BPF_CALL))
19215 			continue;
19216 		if (insn->src_reg == BPF_PSEUDO_CALL)
19217 			continue;
19218 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19219 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19220 			if (ret)
19221 				return ret;
19222 			if (cnt == 0)
19223 				continue;
19224 
19225 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19226 			if (!new_prog)
19227 				return -ENOMEM;
19228 
19229 			delta	 += cnt - 1;
19230 			env->prog = prog = new_prog;
19231 			insn	  = new_prog->insnsi + i + delta;
19232 			continue;
19233 		}
19234 
19235 		if (insn->imm == BPF_FUNC_get_route_realm)
19236 			prog->dst_needed = 1;
19237 		if (insn->imm == BPF_FUNC_get_prandom_u32)
19238 			bpf_user_rnd_init_once();
19239 		if (insn->imm == BPF_FUNC_override_return)
19240 			prog->kprobe_override = 1;
19241 		if (insn->imm == BPF_FUNC_tail_call) {
19242 			/* If we tail call into other programs, we
19243 			 * cannot make any assumptions since they can
19244 			 * be replaced dynamically during runtime in
19245 			 * the program array.
19246 			 */
19247 			prog->cb_access = 1;
19248 			if (!allow_tail_call_in_subprogs(env))
19249 				prog->aux->stack_depth = MAX_BPF_STACK;
19250 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19251 
19252 			/* mark bpf_tail_call as different opcode to avoid
19253 			 * conditional branch in the interpreter for every normal
19254 			 * call and to prevent accidental JITing by JIT compiler
19255 			 * that doesn't support bpf_tail_call yet
19256 			 */
19257 			insn->imm = 0;
19258 			insn->code = BPF_JMP | BPF_TAIL_CALL;
19259 
19260 			aux = &env->insn_aux_data[i + delta];
19261 			if (env->bpf_capable && !prog->blinding_requested &&
19262 			    prog->jit_requested &&
19263 			    !bpf_map_key_poisoned(aux) &&
19264 			    !bpf_map_ptr_poisoned(aux) &&
19265 			    !bpf_map_ptr_unpriv(aux)) {
19266 				struct bpf_jit_poke_descriptor desc = {
19267 					.reason = BPF_POKE_REASON_TAIL_CALL,
19268 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19269 					.tail_call.key = bpf_map_key_immediate(aux),
19270 					.insn_idx = i + delta,
19271 				};
19272 
19273 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
19274 				if (ret < 0) {
19275 					verbose(env, "adding tail call poke descriptor failed\n");
19276 					return ret;
19277 				}
19278 
19279 				insn->imm = ret + 1;
19280 				continue;
19281 			}
19282 
19283 			if (!bpf_map_ptr_unpriv(aux))
19284 				continue;
19285 
19286 			/* instead of changing every JIT dealing with tail_call
19287 			 * emit two extra insns:
19288 			 * if (index >= max_entries) goto out;
19289 			 * index &= array->index_mask;
19290 			 * to avoid out-of-bounds cpu speculation
19291 			 */
19292 			if (bpf_map_ptr_poisoned(aux)) {
19293 				verbose(env, "tail_call abusing map_ptr\n");
19294 				return -EINVAL;
19295 			}
19296 
19297 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19298 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19299 						  map_ptr->max_entries, 2);
19300 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19301 						    container_of(map_ptr,
19302 								 struct bpf_array,
19303 								 map)->index_mask);
19304 			insn_buf[2] = *insn;
19305 			cnt = 3;
19306 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19307 			if (!new_prog)
19308 				return -ENOMEM;
19309 
19310 			delta    += cnt - 1;
19311 			env->prog = prog = new_prog;
19312 			insn      = new_prog->insnsi + i + delta;
19313 			continue;
19314 		}
19315 
19316 		if (insn->imm == BPF_FUNC_timer_set_callback) {
19317 			/* The verifier will process callback_fn as many times as necessary
19318 			 * with different maps and the register states prepared by
19319 			 * set_timer_callback_state will be accurate.
19320 			 *
19321 			 * The following use case is valid:
19322 			 *   map1 is shared by prog1, prog2, prog3.
19323 			 *   prog1 calls bpf_timer_init for some map1 elements
19324 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
19325 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
19326 			 *   prog3 calls bpf_timer_start for some map1 elements.
19327 			 *     Those that were not both bpf_timer_init-ed and
19328 			 *     bpf_timer_set_callback-ed will return -EINVAL.
19329 			 */
19330 			struct bpf_insn ld_addrs[2] = {
19331 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19332 			};
19333 
19334 			insn_buf[0] = ld_addrs[0];
19335 			insn_buf[1] = ld_addrs[1];
19336 			insn_buf[2] = *insn;
19337 			cnt = 3;
19338 
19339 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19340 			if (!new_prog)
19341 				return -ENOMEM;
19342 
19343 			delta    += cnt - 1;
19344 			env->prog = prog = new_prog;
19345 			insn      = new_prog->insnsi + i + delta;
19346 			goto patch_call_imm;
19347 		}
19348 
19349 		if (is_storage_get_function(insn->imm)) {
19350 			if (!env->prog->aux->sleepable ||
19351 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
19352 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19353 			else
19354 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19355 			insn_buf[1] = *insn;
19356 			cnt = 2;
19357 
19358 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19359 			if (!new_prog)
19360 				return -ENOMEM;
19361 
19362 			delta += cnt - 1;
19363 			env->prog = prog = new_prog;
19364 			insn = new_prog->insnsi + i + delta;
19365 			goto patch_call_imm;
19366 		}
19367 
19368 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
19369 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
19370 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
19371 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
19372 			 */
19373 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
19374 			insn_buf[1] = *insn;
19375 			cnt = 2;
19376 
19377 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19378 			if (!new_prog)
19379 				return -ENOMEM;
19380 
19381 			delta += cnt - 1;
19382 			env->prog = prog = new_prog;
19383 			insn = new_prog->insnsi + i + delta;
19384 			goto patch_call_imm;
19385 		}
19386 
19387 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19388 		 * and other inlining handlers are currently limited to 64 bit
19389 		 * only.
19390 		 */
19391 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19392 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
19393 		     insn->imm == BPF_FUNC_map_update_elem ||
19394 		     insn->imm == BPF_FUNC_map_delete_elem ||
19395 		     insn->imm == BPF_FUNC_map_push_elem   ||
19396 		     insn->imm == BPF_FUNC_map_pop_elem    ||
19397 		     insn->imm == BPF_FUNC_map_peek_elem   ||
19398 		     insn->imm == BPF_FUNC_redirect_map    ||
19399 		     insn->imm == BPF_FUNC_for_each_map_elem ||
19400 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19401 			aux = &env->insn_aux_data[i + delta];
19402 			if (bpf_map_ptr_poisoned(aux))
19403 				goto patch_call_imm;
19404 
19405 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19406 			ops = map_ptr->ops;
19407 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
19408 			    ops->map_gen_lookup) {
19409 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19410 				if (cnt == -EOPNOTSUPP)
19411 					goto patch_map_ops_generic;
19412 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19413 					verbose(env, "bpf verifier is misconfigured\n");
19414 					return -EINVAL;
19415 				}
19416 
19417 				new_prog = bpf_patch_insn_data(env, i + delta,
19418 							       insn_buf, cnt);
19419 				if (!new_prog)
19420 					return -ENOMEM;
19421 
19422 				delta    += cnt - 1;
19423 				env->prog = prog = new_prog;
19424 				insn      = new_prog->insnsi + i + delta;
19425 				continue;
19426 			}
19427 
19428 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19429 				     (void *(*)(struct bpf_map *map, void *key))NULL));
19430 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19431 				     (long (*)(struct bpf_map *map, void *key))NULL));
19432 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19433 				     (long (*)(struct bpf_map *map, void *key, void *value,
19434 					      u64 flags))NULL));
19435 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19436 				     (long (*)(struct bpf_map *map, void *value,
19437 					      u64 flags))NULL));
19438 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19439 				     (long (*)(struct bpf_map *map, void *value))NULL));
19440 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19441 				     (long (*)(struct bpf_map *map, void *value))NULL));
19442 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
19443 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19444 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19445 				     (long (*)(struct bpf_map *map,
19446 					      bpf_callback_t callback_fn,
19447 					      void *callback_ctx,
19448 					      u64 flags))NULL));
19449 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19450 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19451 
19452 patch_map_ops_generic:
19453 			switch (insn->imm) {
19454 			case BPF_FUNC_map_lookup_elem:
19455 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19456 				continue;
19457 			case BPF_FUNC_map_update_elem:
19458 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19459 				continue;
19460 			case BPF_FUNC_map_delete_elem:
19461 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19462 				continue;
19463 			case BPF_FUNC_map_push_elem:
19464 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19465 				continue;
19466 			case BPF_FUNC_map_pop_elem:
19467 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19468 				continue;
19469 			case BPF_FUNC_map_peek_elem:
19470 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19471 				continue;
19472 			case BPF_FUNC_redirect_map:
19473 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
19474 				continue;
19475 			case BPF_FUNC_for_each_map_elem:
19476 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19477 				continue;
19478 			case BPF_FUNC_map_lookup_percpu_elem:
19479 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19480 				continue;
19481 			}
19482 
19483 			goto patch_call_imm;
19484 		}
19485 
19486 		/* Implement bpf_jiffies64 inline. */
19487 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19488 		    insn->imm == BPF_FUNC_jiffies64) {
19489 			struct bpf_insn ld_jiffies_addr[2] = {
19490 				BPF_LD_IMM64(BPF_REG_0,
19491 					     (unsigned long)&jiffies),
19492 			};
19493 
19494 			insn_buf[0] = ld_jiffies_addr[0];
19495 			insn_buf[1] = ld_jiffies_addr[1];
19496 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19497 						  BPF_REG_0, 0);
19498 			cnt = 3;
19499 
19500 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19501 						       cnt);
19502 			if (!new_prog)
19503 				return -ENOMEM;
19504 
19505 			delta    += cnt - 1;
19506 			env->prog = prog = new_prog;
19507 			insn      = new_prog->insnsi + i + delta;
19508 			continue;
19509 		}
19510 
19511 		/* Implement bpf_get_func_arg inline. */
19512 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19513 		    insn->imm == BPF_FUNC_get_func_arg) {
19514 			/* Load nr_args from ctx - 8 */
19515 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19516 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19517 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19518 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19519 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19520 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19521 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19522 			insn_buf[7] = BPF_JMP_A(1);
19523 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19524 			cnt = 9;
19525 
19526 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19527 			if (!new_prog)
19528 				return -ENOMEM;
19529 
19530 			delta    += cnt - 1;
19531 			env->prog = prog = new_prog;
19532 			insn      = new_prog->insnsi + i + delta;
19533 			continue;
19534 		}
19535 
19536 		/* Implement bpf_get_func_ret inline. */
19537 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19538 		    insn->imm == BPF_FUNC_get_func_ret) {
19539 			if (eatype == BPF_TRACE_FEXIT ||
19540 			    eatype == BPF_MODIFY_RETURN) {
19541 				/* Load nr_args from ctx - 8 */
19542 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19543 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19544 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19545 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19546 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19547 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19548 				cnt = 6;
19549 			} else {
19550 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19551 				cnt = 1;
19552 			}
19553 
19554 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19555 			if (!new_prog)
19556 				return -ENOMEM;
19557 
19558 			delta    += cnt - 1;
19559 			env->prog = prog = new_prog;
19560 			insn      = new_prog->insnsi + i + delta;
19561 			continue;
19562 		}
19563 
19564 		/* Implement get_func_arg_cnt inline. */
19565 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19566 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
19567 			/* Load nr_args from ctx - 8 */
19568 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19569 
19570 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19571 			if (!new_prog)
19572 				return -ENOMEM;
19573 
19574 			env->prog = prog = new_prog;
19575 			insn      = new_prog->insnsi + i + delta;
19576 			continue;
19577 		}
19578 
19579 		/* Implement bpf_get_func_ip inline. */
19580 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19581 		    insn->imm == BPF_FUNC_get_func_ip) {
19582 			/* Load IP address from ctx - 16 */
19583 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19584 
19585 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19586 			if (!new_prog)
19587 				return -ENOMEM;
19588 
19589 			env->prog = prog = new_prog;
19590 			insn      = new_prog->insnsi + i + delta;
19591 			continue;
19592 		}
19593 
19594 patch_call_imm:
19595 		fn = env->ops->get_func_proto(insn->imm, env->prog);
19596 		/* all functions that have prototype and verifier allowed
19597 		 * programs to call them, must be real in-kernel functions
19598 		 */
19599 		if (!fn->func) {
19600 			verbose(env,
19601 				"kernel subsystem misconfigured func %s#%d\n",
19602 				func_id_name(insn->imm), insn->imm);
19603 			return -EFAULT;
19604 		}
19605 		insn->imm = fn->func - __bpf_call_base;
19606 	}
19607 
19608 	/* Since poke tab is now finalized, publish aux to tracker. */
19609 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19610 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19611 		if (!map_ptr->ops->map_poke_track ||
19612 		    !map_ptr->ops->map_poke_untrack ||
19613 		    !map_ptr->ops->map_poke_run) {
19614 			verbose(env, "bpf verifier is misconfigured\n");
19615 			return -EINVAL;
19616 		}
19617 
19618 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19619 		if (ret < 0) {
19620 			verbose(env, "tracking tail call prog failed\n");
19621 			return ret;
19622 		}
19623 	}
19624 
19625 	sort_kfunc_descs_by_imm_off(env->prog);
19626 
19627 	return 0;
19628 }
19629 
19630 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19631 					int position,
19632 					s32 stack_base,
19633 					u32 callback_subprogno,
19634 					u32 *cnt)
19635 {
19636 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19637 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19638 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19639 	int reg_loop_max = BPF_REG_6;
19640 	int reg_loop_cnt = BPF_REG_7;
19641 	int reg_loop_ctx = BPF_REG_8;
19642 
19643 	struct bpf_prog *new_prog;
19644 	u32 callback_start;
19645 	u32 call_insn_offset;
19646 	s32 callback_offset;
19647 
19648 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
19649 	 * be careful to modify this code in sync.
19650 	 */
19651 	struct bpf_insn insn_buf[] = {
19652 		/* Return error and jump to the end of the patch if
19653 		 * expected number of iterations is too big.
19654 		 */
19655 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19656 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19657 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19658 		/* spill R6, R7, R8 to use these as loop vars */
19659 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19660 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19661 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19662 		/* initialize loop vars */
19663 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19664 		BPF_MOV32_IMM(reg_loop_cnt, 0),
19665 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19666 		/* loop header,
19667 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
19668 		 */
19669 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19670 		/* callback call,
19671 		 * correct callback offset would be set after patching
19672 		 */
19673 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19674 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19675 		BPF_CALL_REL(0),
19676 		/* increment loop counter */
19677 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19678 		/* jump to loop header if callback returned 0 */
19679 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19680 		/* return value of bpf_loop,
19681 		 * set R0 to the number of iterations
19682 		 */
19683 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19684 		/* restore original values of R6, R7, R8 */
19685 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19686 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19687 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19688 	};
19689 
19690 	*cnt = ARRAY_SIZE(insn_buf);
19691 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19692 	if (!new_prog)
19693 		return new_prog;
19694 
19695 	/* callback start is known only after patching */
19696 	callback_start = env->subprog_info[callback_subprogno].start;
19697 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19698 	call_insn_offset = position + 12;
19699 	callback_offset = callback_start - call_insn_offset - 1;
19700 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
19701 
19702 	return new_prog;
19703 }
19704 
19705 static bool is_bpf_loop_call(struct bpf_insn *insn)
19706 {
19707 	return insn->code == (BPF_JMP | BPF_CALL) &&
19708 		insn->src_reg == 0 &&
19709 		insn->imm == BPF_FUNC_loop;
19710 }
19711 
19712 /* For all sub-programs in the program (including main) check
19713  * insn_aux_data to see if there are bpf_loop calls that require
19714  * inlining. If such calls are found the calls are replaced with a
19715  * sequence of instructions produced by `inline_bpf_loop` function and
19716  * subprog stack_depth is increased by the size of 3 registers.
19717  * This stack space is used to spill values of the R6, R7, R8.  These
19718  * registers are used to store the loop bound, counter and context
19719  * variables.
19720  */
19721 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19722 {
19723 	struct bpf_subprog_info *subprogs = env->subprog_info;
19724 	int i, cur_subprog = 0, cnt, delta = 0;
19725 	struct bpf_insn *insn = env->prog->insnsi;
19726 	int insn_cnt = env->prog->len;
19727 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
19728 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19729 	u16 stack_depth_extra = 0;
19730 
19731 	for (i = 0; i < insn_cnt; i++, insn++) {
19732 		struct bpf_loop_inline_state *inline_state =
19733 			&env->insn_aux_data[i + delta].loop_inline_state;
19734 
19735 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19736 			struct bpf_prog *new_prog;
19737 
19738 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19739 			new_prog = inline_bpf_loop(env,
19740 						   i + delta,
19741 						   -(stack_depth + stack_depth_extra),
19742 						   inline_state->callback_subprogno,
19743 						   &cnt);
19744 			if (!new_prog)
19745 				return -ENOMEM;
19746 
19747 			delta     += cnt - 1;
19748 			env->prog  = new_prog;
19749 			insn       = new_prog->insnsi + i + delta;
19750 		}
19751 
19752 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19753 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
19754 			cur_subprog++;
19755 			stack_depth = subprogs[cur_subprog].stack_depth;
19756 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19757 			stack_depth_extra = 0;
19758 		}
19759 	}
19760 
19761 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19762 
19763 	return 0;
19764 }
19765 
19766 static void free_states(struct bpf_verifier_env *env)
19767 {
19768 	struct bpf_verifier_state_list *sl, *sln;
19769 	int i;
19770 
19771 	sl = env->free_list;
19772 	while (sl) {
19773 		sln = sl->next;
19774 		free_verifier_state(&sl->state, false);
19775 		kfree(sl);
19776 		sl = sln;
19777 	}
19778 	env->free_list = NULL;
19779 
19780 	if (!env->explored_states)
19781 		return;
19782 
19783 	for (i = 0; i < state_htab_size(env); i++) {
19784 		sl = env->explored_states[i];
19785 
19786 		while (sl) {
19787 			sln = sl->next;
19788 			free_verifier_state(&sl->state, false);
19789 			kfree(sl);
19790 			sl = sln;
19791 		}
19792 		env->explored_states[i] = NULL;
19793 	}
19794 }
19795 
19796 static int do_check_common(struct bpf_verifier_env *env, int subprog, bool is_ex_cb)
19797 {
19798 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19799 	struct bpf_verifier_state *state;
19800 	struct bpf_reg_state *regs;
19801 	int ret, i;
19802 
19803 	env->prev_linfo = NULL;
19804 	env->pass_cnt++;
19805 
19806 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19807 	if (!state)
19808 		return -ENOMEM;
19809 	state->curframe = 0;
19810 	state->speculative = false;
19811 	state->branches = 1;
19812 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19813 	if (!state->frame[0]) {
19814 		kfree(state);
19815 		return -ENOMEM;
19816 	}
19817 	env->cur_state = state;
19818 	init_func_state(env, state->frame[0],
19819 			BPF_MAIN_FUNC /* callsite */,
19820 			0 /* frameno */,
19821 			subprog);
19822 	state->first_insn_idx = env->subprog_info[subprog].start;
19823 	state->last_insn_idx = -1;
19824 
19825 	regs = state->frame[state->curframe]->regs;
19826 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19827 		ret = btf_prepare_func_args(env, subprog, regs, is_ex_cb);
19828 		if (ret)
19829 			goto out;
19830 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19831 			if (regs[i].type == PTR_TO_CTX)
19832 				mark_reg_known_zero(env, regs, i);
19833 			else if (regs[i].type == SCALAR_VALUE)
19834 				mark_reg_unknown(env, regs, i);
19835 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
19836 				const u32 mem_size = regs[i].mem_size;
19837 
19838 				mark_reg_known_zero(env, regs, i);
19839 				regs[i].mem_size = mem_size;
19840 				regs[i].id = ++env->id_gen;
19841 			}
19842 		}
19843 		if (is_ex_cb) {
19844 			state->frame[0]->in_exception_callback_fn = true;
19845 			env->subprog_info[subprog].is_cb = true;
19846 			env->subprog_info[subprog].is_async_cb = true;
19847 			env->subprog_info[subprog].is_exception_cb = true;
19848 		}
19849 	} else {
19850 		/* 1st arg to a function */
19851 		regs[BPF_REG_1].type = PTR_TO_CTX;
19852 		mark_reg_known_zero(env, regs, BPF_REG_1);
19853 		ret = btf_check_subprog_arg_match(env, subprog, regs);
19854 		if (ret == -EFAULT)
19855 			/* unlikely verifier bug. abort.
19856 			 * ret == 0 and ret < 0 are sadly acceptable for
19857 			 * main() function due to backward compatibility.
19858 			 * Like socket filter program may be written as:
19859 			 * int bpf_prog(struct pt_regs *ctx)
19860 			 * and never dereference that ctx in the program.
19861 			 * 'struct pt_regs' is a type mismatch for socket
19862 			 * filter that should be using 'struct __sk_buff'.
19863 			 */
19864 			goto out;
19865 	}
19866 
19867 	ret = do_check(env);
19868 out:
19869 	/* check for NULL is necessary, since cur_state can be freed inside
19870 	 * do_check() under memory pressure.
19871 	 */
19872 	if (env->cur_state) {
19873 		free_verifier_state(env->cur_state, true);
19874 		env->cur_state = NULL;
19875 	}
19876 	while (!pop_stack(env, NULL, NULL, false));
19877 	if (!ret && pop_log)
19878 		bpf_vlog_reset(&env->log, 0);
19879 	free_states(env);
19880 	return ret;
19881 }
19882 
19883 /* Lazily verify all global functions based on their BTF, if they are called
19884  * from main BPF program or any of subprograms transitively.
19885  * BPF global subprogs called from dead code are not validated.
19886  * All callable global functions must pass verification.
19887  * Otherwise the whole program is rejected.
19888  * Consider:
19889  * int bar(int);
19890  * int foo(int f)
19891  * {
19892  *    return bar(f);
19893  * }
19894  * int bar(int b)
19895  * {
19896  *    ...
19897  * }
19898  * foo() will be verified first for R1=any_scalar_value. During verification it
19899  * will be assumed that bar() already verified successfully and call to bar()
19900  * from foo() will be checked for type match only. Later bar() will be verified
19901  * independently to check that it's safe for R1=any_scalar_value.
19902  */
19903 static int do_check_subprogs(struct bpf_verifier_env *env)
19904 {
19905 	struct bpf_prog_aux *aux = env->prog->aux;
19906 	struct bpf_func_info_aux *sub_aux;
19907 	int i, ret, new_cnt;
19908 
19909 	if (!aux->func_info)
19910 		return 0;
19911 
19912 	/* exception callback is presumed to be always called */
19913 	if (env->exception_callback_subprog)
19914 		subprog_aux(env, env->exception_callback_subprog)->called = true;
19915 
19916 again:
19917 	new_cnt = 0;
19918 	for (i = 1; i < env->subprog_cnt; i++) {
19919 		if (!subprog_is_global(env, i))
19920 			continue;
19921 
19922 		sub_aux = subprog_aux(env, i);
19923 		if (!sub_aux->called || sub_aux->verified)
19924 			continue;
19925 
19926 		env->insn_idx = env->subprog_info[i].start;
19927 		WARN_ON_ONCE(env->insn_idx == 0);
19928 		ret = do_check_common(env, i, env->exception_callback_subprog == i);
19929 		if (ret) {
19930 			return ret;
19931 		} else if (env->log.level & BPF_LOG_LEVEL) {
19932 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
19933 				i, subprog_name(env, i));
19934 		}
19935 
19936 		/* We verified new global subprog, it might have called some
19937 		 * more global subprogs that we haven't verified yet, so we
19938 		 * need to do another pass over subprogs to verify those.
19939 		 */
19940 		sub_aux->verified = true;
19941 		new_cnt++;
19942 	}
19943 
19944 	/* We can't loop forever as we verify at least one global subprog on
19945 	 * each pass.
19946 	 */
19947 	if (new_cnt)
19948 		goto again;
19949 
19950 	return 0;
19951 }
19952 
19953 static int do_check_main(struct bpf_verifier_env *env)
19954 {
19955 	int ret;
19956 
19957 	env->insn_idx = 0;
19958 	ret = do_check_common(env, 0, false);
19959 	if (!ret)
19960 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19961 	return ret;
19962 }
19963 
19964 
19965 static void print_verification_stats(struct bpf_verifier_env *env)
19966 {
19967 	int i;
19968 
19969 	if (env->log.level & BPF_LOG_STATS) {
19970 		verbose(env, "verification time %lld usec\n",
19971 			div_u64(env->verification_time, 1000));
19972 		verbose(env, "stack depth ");
19973 		for (i = 0; i < env->subprog_cnt; i++) {
19974 			u32 depth = env->subprog_info[i].stack_depth;
19975 
19976 			verbose(env, "%d", depth);
19977 			if (i + 1 < env->subprog_cnt)
19978 				verbose(env, "+");
19979 		}
19980 		verbose(env, "\n");
19981 	}
19982 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19983 		"total_states %d peak_states %d mark_read %d\n",
19984 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19985 		env->max_states_per_insn, env->total_states,
19986 		env->peak_states, env->longest_mark_read_walk);
19987 }
19988 
19989 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19990 {
19991 	const struct btf_type *t, *func_proto;
19992 	const struct bpf_struct_ops *st_ops;
19993 	const struct btf_member *member;
19994 	struct bpf_prog *prog = env->prog;
19995 	u32 btf_id, member_idx;
19996 	const char *mname;
19997 
19998 	if (!prog->gpl_compatible) {
19999 		verbose(env, "struct ops programs must have a GPL compatible license\n");
20000 		return -EINVAL;
20001 	}
20002 
20003 	btf_id = prog->aux->attach_btf_id;
20004 	st_ops = bpf_struct_ops_find(btf_id);
20005 	if (!st_ops) {
20006 		verbose(env, "attach_btf_id %u is not a supported struct\n",
20007 			btf_id);
20008 		return -ENOTSUPP;
20009 	}
20010 
20011 	t = st_ops->type;
20012 	member_idx = prog->expected_attach_type;
20013 	if (member_idx >= btf_type_vlen(t)) {
20014 		verbose(env, "attach to invalid member idx %u of struct %s\n",
20015 			member_idx, st_ops->name);
20016 		return -EINVAL;
20017 	}
20018 
20019 	member = &btf_type_member(t)[member_idx];
20020 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
20021 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
20022 					       NULL);
20023 	if (!func_proto) {
20024 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
20025 			mname, member_idx, st_ops->name);
20026 		return -EINVAL;
20027 	}
20028 
20029 	if (st_ops->check_member) {
20030 		int err = st_ops->check_member(t, member, prog);
20031 
20032 		if (err) {
20033 			verbose(env, "attach to unsupported member %s of struct %s\n",
20034 				mname, st_ops->name);
20035 			return err;
20036 		}
20037 	}
20038 
20039 	prog->aux->attach_func_proto = func_proto;
20040 	prog->aux->attach_func_name = mname;
20041 	env->ops = st_ops->verifier_ops;
20042 
20043 	return 0;
20044 }
20045 #define SECURITY_PREFIX "security_"
20046 
20047 static int check_attach_modify_return(unsigned long addr, const char *func_name)
20048 {
20049 	if (within_error_injection_list(addr) ||
20050 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
20051 		return 0;
20052 
20053 	return -EINVAL;
20054 }
20055 
20056 /* list of non-sleepable functions that are otherwise on
20057  * ALLOW_ERROR_INJECTION list
20058  */
20059 BTF_SET_START(btf_non_sleepable_error_inject)
20060 /* Three functions below can be called from sleepable and non-sleepable context.
20061  * Assume non-sleepable from bpf safety point of view.
20062  */
20063 BTF_ID(func, __filemap_add_folio)
20064 BTF_ID(func, should_fail_alloc_page)
20065 BTF_ID(func, should_failslab)
20066 BTF_SET_END(btf_non_sleepable_error_inject)
20067 
20068 static int check_non_sleepable_error_inject(u32 btf_id)
20069 {
20070 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
20071 }
20072 
20073 int bpf_check_attach_target(struct bpf_verifier_log *log,
20074 			    const struct bpf_prog *prog,
20075 			    const struct bpf_prog *tgt_prog,
20076 			    u32 btf_id,
20077 			    struct bpf_attach_target_info *tgt_info)
20078 {
20079 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
20080 	const char prefix[] = "btf_trace_";
20081 	int ret = 0, subprog = -1, i;
20082 	const struct btf_type *t;
20083 	bool conservative = true;
20084 	const char *tname;
20085 	struct btf *btf;
20086 	long addr = 0;
20087 	struct module *mod = NULL;
20088 
20089 	if (!btf_id) {
20090 		bpf_log(log, "Tracing programs must provide btf_id\n");
20091 		return -EINVAL;
20092 	}
20093 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
20094 	if (!btf) {
20095 		bpf_log(log,
20096 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
20097 		return -EINVAL;
20098 	}
20099 	t = btf_type_by_id(btf, btf_id);
20100 	if (!t) {
20101 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
20102 		return -EINVAL;
20103 	}
20104 	tname = btf_name_by_offset(btf, t->name_off);
20105 	if (!tname) {
20106 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
20107 		return -EINVAL;
20108 	}
20109 	if (tgt_prog) {
20110 		struct bpf_prog_aux *aux = tgt_prog->aux;
20111 
20112 		if (bpf_prog_is_dev_bound(prog->aux) &&
20113 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
20114 			bpf_log(log, "Target program bound device mismatch");
20115 			return -EINVAL;
20116 		}
20117 
20118 		for (i = 0; i < aux->func_info_cnt; i++)
20119 			if (aux->func_info[i].type_id == btf_id) {
20120 				subprog = i;
20121 				break;
20122 			}
20123 		if (subprog == -1) {
20124 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
20125 			return -EINVAL;
20126 		}
20127 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
20128 			bpf_log(log,
20129 				"%s programs cannot attach to exception callback\n",
20130 				prog_extension ? "Extension" : "FENTRY/FEXIT");
20131 			return -EINVAL;
20132 		}
20133 		conservative = aux->func_info_aux[subprog].unreliable;
20134 		if (prog_extension) {
20135 			if (conservative) {
20136 				bpf_log(log,
20137 					"Cannot replace static functions\n");
20138 				return -EINVAL;
20139 			}
20140 			if (!prog->jit_requested) {
20141 				bpf_log(log,
20142 					"Extension programs should be JITed\n");
20143 				return -EINVAL;
20144 			}
20145 		}
20146 		if (!tgt_prog->jited) {
20147 			bpf_log(log, "Can attach to only JITed progs\n");
20148 			return -EINVAL;
20149 		}
20150 		if (tgt_prog->type == prog->type) {
20151 			/* Cannot fentry/fexit another fentry/fexit program.
20152 			 * Cannot attach program extension to another extension.
20153 			 * It's ok to attach fentry/fexit to extension program.
20154 			 */
20155 			bpf_log(log, "Cannot recursively attach\n");
20156 			return -EINVAL;
20157 		}
20158 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
20159 		    prog_extension &&
20160 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
20161 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
20162 			/* Program extensions can extend all program types
20163 			 * except fentry/fexit. The reason is the following.
20164 			 * The fentry/fexit programs are used for performance
20165 			 * analysis, stats and can be attached to any program
20166 			 * type except themselves. When extension program is
20167 			 * replacing XDP function it is necessary to allow
20168 			 * performance analysis of all functions. Both original
20169 			 * XDP program and its program extension. Hence
20170 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
20171 			 * allowed. If extending of fentry/fexit was allowed it
20172 			 * would be possible to create long call chain
20173 			 * fentry->extension->fentry->extension beyond
20174 			 * reasonable stack size. Hence extending fentry is not
20175 			 * allowed.
20176 			 */
20177 			bpf_log(log, "Cannot extend fentry/fexit\n");
20178 			return -EINVAL;
20179 		}
20180 	} else {
20181 		if (prog_extension) {
20182 			bpf_log(log, "Cannot replace kernel functions\n");
20183 			return -EINVAL;
20184 		}
20185 	}
20186 
20187 	switch (prog->expected_attach_type) {
20188 	case BPF_TRACE_RAW_TP:
20189 		if (tgt_prog) {
20190 			bpf_log(log,
20191 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
20192 			return -EINVAL;
20193 		}
20194 		if (!btf_type_is_typedef(t)) {
20195 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
20196 				btf_id);
20197 			return -EINVAL;
20198 		}
20199 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
20200 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
20201 				btf_id, tname);
20202 			return -EINVAL;
20203 		}
20204 		tname += sizeof(prefix) - 1;
20205 		t = btf_type_by_id(btf, t->type);
20206 		if (!btf_type_is_ptr(t))
20207 			/* should never happen in valid vmlinux build */
20208 			return -EINVAL;
20209 		t = btf_type_by_id(btf, t->type);
20210 		if (!btf_type_is_func_proto(t))
20211 			/* should never happen in valid vmlinux build */
20212 			return -EINVAL;
20213 
20214 		break;
20215 	case BPF_TRACE_ITER:
20216 		if (!btf_type_is_func(t)) {
20217 			bpf_log(log, "attach_btf_id %u is not a function\n",
20218 				btf_id);
20219 			return -EINVAL;
20220 		}
20221 		t = btf_type_by_id(btf, t->type);
20222 		if (!btf_type_is_func_proto(t))
20223 			return -EINVAL;
20224 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20225 		if (ret)
20226 			return ret;
20227 		break;
20228 	default:
20229 		if (!prog_extension)
20230 			return -EINVAL;
20231 		fallthrough;
20232 	case BPF_MODIFY_RETURN:
20233 	case BPF_LSM_MAC:
20234 	case BPF_LSM_CGROUP:
20235 	case BPF_TRACE_FENTRY:
20236 	case BPF_TRACE_FEXIT:
20237 		if (!btf_type_is_func(t)) {
20238 			bpf_log(log, "attach_btf_id %u is not a function\n",
20239 				btf_id);
20240 			return -EINVAL;
20241 		}
20242 		if (prog_extension &&
20243 		    btf_check_type_match(log, prog, btf, t))
20244 			return -EINVAL;
20245 		t = btf_type_by_id(btf, t->type);
20246 		if (!btf_type_is_func_proto(t))
20247 			return -EINVAL;
20248 
20249 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
20250 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
20251 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
20252 			return -EINVAL;
20253 
20254 		if (tgt_prog && conservative)
20255 			t = NULL;
20256 
20257 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20258 		if (ret < 0)
20259 			return ret;
20260 
20261 		if (tgt_prog) {
20262 			if (subprog == 0)
20263 				addr = (long) tgt_prog->bpf_func;
20264 			else
20265 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20266 		} else {
20267 			if (btf_is_module(btf)) {
20268 				mod = btf_try_get_module(btf);
20269 				if (mod)
20270 					addr = find_kallsyms_symbol_value(mod, tname);
20271 				else
20272 					addr = 0;
20273 			} else {
20274 				addr = kallsyms_lookup_name(tname);
20275 			}
20276 			if (!addr) {
20277 				module_put(mod);
20278 				bpf_log(log,
20279 					"The address of function %s cannot be found\n",
20280 					tname);
20281 				return -ENOENT;
20282 			}
20283 		}
20284 
20285 		if (prog->aux->sleepable) {
20286 			ret = -EINVAL;
20287 			switch (prog->type) {
20288 			case BPF_PROG_TYPE_TRACING:
20289 
20290 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
20291 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20292 				 */
20293 				if (!check_non_sleepable_error_inject(btf_id) &&
20294 				    within_error_injection_list(addr))
20295 					ret = 0;
20296 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
20297 				 * in the fmodret id set with the KF_SLEEPABLE flag.
20298 				 */
20299 				else {
20300 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20301 										prog);
20302 
20303 					if (flags && (*flags & KF_SLEEPABLE))
20304 						ret = 0;
20305 				}
20306 				break;
20307 			case BPF_PROG_TYPE_LSM:
20308 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
20309 				 * Only some of them are sleepable.
20310 				 */
20311 				if (bpf_lsm_is_sleepable_hook(btf_id))
20312 					ret = 0;
20313 				break;
20314 			default:
20315 				break;
20316 			}
20317 			if (ret) {
20318 				module_put(mod);
20319 				bpf_log(log, "%s is not sleepable\n", tname);
20320 				return ret;
20321 			}
20322 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20323 			if (tgt_prog) {
20324 				module_put(mod);
20325 				bpf_log(log, "can't modify return codes of BPF programs\n");
20326 				return -EINVAL;
20327 			}
20328 			ret = -EINVAL;
20329 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20330 			    !check_attach_modify_return(addr, tname))
20331 				ret = 0;
20332 			if (ret) {
20333 				module_put(mod);
20334 				bpf_log(log, "%s() is not modifiable\n", tname);
20335 				return ret;
20336 			}
20337 		}
20338 
20339 		break;
20340 	}
20341 	tgt_info->tgt_addr = addr;
20342 	tgt_info->tgt_name = tname;
20343 	tgt_info->tgt_type = t;
20344 	tgt_info->tgt_mod = mod;
20345 	return 0;
20346 }
20347 
20348 BTF_SET_START(btf_id_deny)
20349 BTF_ID_UNUSED
20350 #ifdef CONFIG_SMP
20351 BTF_ID(func, migrate_disable)
20352 BTF_ID(func, migrate_enable)
20353 #endif
20354 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20355 BTF_ID(func, rcu_read_unlock_strict)
20356 #endif
20357 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20358 BTF_ID(func, preempt_count_add)
20359 BTF_ID(func, preempt_count_sub)
20360 #endif
20361 #ifdef CONFIG_PREEMPT_RCU
20362 BTF_ID(func, __rcu_read_lock)
20363 BTF_ID(func, __rcu_read_unlock)
20364 #endif
20365 BTF_SET_END(btf_id_deny)
20366 
20367 static bool can_be_sleepable(struct bpf_prog *prog)
20368 {
20369 	if (prog->type == BPF_PROG_TYPE_TRACING) {
20370 		switch (prog->expected_attach_type) {
20371 		case BPF_TRACE_FENTRY:
20372 		case BPF_TRACE_FEXIT:
20373 		case BPF_MODIFY_RETURN:
20374 		case BPF_TRACE_ITER:
20375 			return true;
20376 		default:
20377 			return false;
20378 		}
20379 	}
20380 	return prog->type == BPF_PROG_TYPE_LSM ||
20381 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20382 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20383 }
20384 
20385 static int check_attach_btf_id(struct bpf_verifier_env *env)
20386 {
20387 	struct bpf_prog *prog = env->prog;
20388 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20389 	struct bpf_attach_target_info tgt_info = {};
20390 	u32 btf_id = prog->aux->attach_btf_id;
20391 	struct bpf_trampoline *tr;
20392 	int ret;
20393 	u64 key;
20394 
20395 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20396 		if (prog->aux->sleepable)
20397 			/* attach_btf_id checked to be zero already */
20398 			return 0;
20399 		verbose(env, "Syscall programs can only be sleepable\n");
20400 		return -EINVAL;
20401 	}
20402 
20403 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20404 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20405 		return -EINVAL;
20406 	}
20407 
20408 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20409 		return check_struct_ops_btf_id(env);
20410 
20411 	if (prog->type != BPF_PROG_TYPE_TRACING &&
20412 	    prog->type != BPF_PROG_TYPE_LSM &&
20413 	    prog->type != BPF_PROG_TYPE_EXT)
20414 		return 0;
20415 
20416 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20417 	if (ret)
20418 		return ret;
20419 
20420 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20421 		/* to make freplace equivalent to their targets, they need to
20422 		 * inherit env->ops and expected_attach_type for the rest of the
20423 		 * verification
20424 		 */
20425 		env->ops = bpf_verifier_ops[tgt_prog->type];
20426 		prog->expected_attach_type = tgt_prog->expected_attach_type;
20427 	}
20428 
20429 	/* store info about the attachment target that will be used later */
20430 	prog->aux->attach_func_proto = tgt_info.tgt_type;
20431 	prog->aux->attach_func_name = tgt_info.tgt_name;
20432 	prog->aux->mod = tgt_info.tgt_mod;
20433 
20434 	if (tgt_prog) {
20435 		prog->aux->saved_dst_prog_type = tgt_prog->type;
20436 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20437 	}
20438 
20439 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20440 		prog->aux->attach_btf_trace = true;
20441 		return 0;
20442 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20443 		if (!bpf_iter_prog_supported(prog))
20444 			return -EINVAL;
20445 		return 0;
20446 	}
20447 
20448 	if (prog->type == BPF_PROG_TYPE_LSM) {
20449 		ret = bpf_lsm_verify_prog(&env->log, prog);
20450 		if (ret < 0)
20451 			return ret;
20452 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
20453 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
20454 		return -EINVAL;
20455 	}
20456 
20457 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20458 	tr = bpf_trampoline_get(key, &tgt_info);
20459 	if (!tr)
20460 		return -ENOMEM;
20461 
20462 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20463 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20464 
20465 	prog->aux->dst_trampoline = tr;
20466 	return 0;
20467 }
20468 
20469 struct btf *bpf_get_btf_vmlinux(void)
20470 {
20471 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20472 		mutex_lock(&bpf_verifier_lock);
20473 		if (!btf_vmlinux)
20474 			btf_vmlinux = btf_parse_vmlinux();
20475 		mutex_unlock(&bpf_verifier_lock);
20476 	}
20477 	return btf_vmlinux;
20478 }
20479 
20480 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20481 {
20482 	u64 start_time = ktime_get_ns();
20483 	struct bpf_verifier_env *env;
20484 	int i, len, ret = -EINVAL, err;
20485 	u32 log_true_size;
20486 	bool is_priv;
20487 
20488 	/* no program is valid */
20489 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20490 		return -EINVAL;
20491 
20492 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
20493 	 * allocate/free it every time bpf_check() is called
20494 	 */
20495 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20496 	if (!env)
20497 		return -ENOMEM;
20498 
20499 	env->bt.env = env;
20500 
20501 	len = (*prog)->len;
20502 	env->insn_aux_data =
20503 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20504 	ret = -ENOMEM;
20505 	if (!env->insn_aux_data)
20506 		goto err_free_env;
20507 	for (i = 0; i < len; i++)
20508 		env->insn_aux_data[i].orig_idx = i;
20509 	env->prog = *prog;
20510 	env->ops = bpf_verifier_ops[env->prog->type];
20511 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20512 	is_priv = bpf_capable();
20513 
20514 	bpf_get_btf_vmlinux();
20515 
20516 	/* grab the mutex to protect few globals used by verifier */
20517 	if (!is_priv)
20518 		mutex_lock(&bpf_verifier_lock);
20519 
20520 	/* user could have requested verbose verifier output
20521 	 * and supplied buffer to store the verification trace
20522 	 */
20523 	ret = bpf_vlog_init(&env->log, attr->log_level,
20524 			    (char __user *) (unsigned long) attr->log_buf,
20525 			    attr->log_size);
20526 	if (ret)
20527 		goto err_unlock;
20528 
20529 	mark_verifier_state_clean(env);
20530 
20531 	if (IS_ERR(btf_vmlinux)) {
20532 		/* Either gcc or pahole or kernel are broken. */
20533 		verbose(env, "in-kernel BTF is malformed\n");
20534 		ret = PTR_ERR(btf_vmlinux);
20535 		goto skip_full_check;
20536 	}
20537 
20538 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20539 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20540 		env->strict_alignment = true;
20541 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20542 		env->strict_alignment = false;
20543 
20544 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20545 	env->allow_uninit_stack = bpf_allow_uninit_stack();
20546 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
20547 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
20548 	env->bpf_capable = bpf_capable();
20549 
20550 	if (is_priv)
20551 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20552 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
20553 
20554 	env->explored_states = kvcalloc(state_htab_size(env),
20555 				       sizeof(struct bpf_verifier_state_list *),
20556 				       GFP_USER);
20557 	ret = -ENOMEM;
20558 	if (!env->explored_states)
20559 		goto skip_full_check;
20560 
20561 	ret = check_btf_info_early(env, attr, uattr);
20562 	if (ret < 0)
20563 		goto skip_full_check;
20564 
20565 	ret = add_subprog_and_kfunc(env);
20566 	if (ret < 0)
20567 		goto skip_full_check;
20568 
20569 	ret = check_subprogs(env);
20570 	if (ret < 0)
20571 		goto skip_full_check;
20572 
20573 	ret = check_btf_info(env, attr, uattr);
20574 	if (ret < 0)
20575 		goto skip_full_check;
20576 
20577 	ret = check_attach_btf_id(env);
20578 	if (ret)
20579 		goto skip_full_check;
20580 
20581 	ret = resolve_pseudo_ldimm64(env);
20582 	if (ret < 0)
20583 		goto skip_full_check;
20584 
20585 	if (bpf_prog_is_offloaded(env->prog->aux)) {
20586 		ret = bpf_prog_offload_verifier_prep(env->prog);
20587 		if (ret)
20588 			goto skip_full_check;
20589 	}
20590 
20591 	ret = check_cfg(env);
20592 	if (ret < 0)
20593 		goto skip_full_check;
20594 
20595 	ret = do_check_main(env);
20596 	ret = ret ?: do_check_subprogs(env);
20597 
20598 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20599 		ret = bpf_prog_offload_finalize(env);
20600 
20601 skip_full_check:
20602 	kvfree(env->explored_states);
20603 
20604 	if (ret == 0)
20605 		ret = check_max_stack_depth(env);
20606 
20607 	/* instruction rewrites happen after this point */
20608 	if (ret == 0)
20609 		ret = optimize_bpf_loop(env);
20610 
20611 	if (is_priv) {
20612 		if (ret == 0)
20613 			opt_hard_wire_dead_code_branches(env);
20614 		if (ret == 0)
20615 			ret = opt_remove_dead_code(env);
20616 		if (ret == 0)
20617 			ret = opt_remove_nops(env);
20618 	} else {
20619 		if (ret == 0)
20620 			sanitize_dead_code(env);
20621 	}
20622 
20623 	if (ret == 0)
20624 		/* program is valid, convert *(u32*)(ctx + off) accesses */
20625 		ret = convert_ctx_accesses(env);
20626 
20627 	if (ret == 0)
20628 		ret = do_misc_fixups(env);
20629 
20630 	/* do 32-bit optimization after insn patching has done so those patched
20631 	 * insns could be handled correctly.
20632 	 */
20633 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20634 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20635 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20636 								     : false;
20637 	}
20638 
20639 	if (ret == 0)
20640 		ret = fixup_call_args(env);
20641 
20642 	env->verification_time = ktime_get_ns() - start_time;
20643 	print_verification_stats(env);
20644 	env->prog->aux->verified_insns = env->insn_processed;
20645 
20646 	/* preserve original error even if log finalization is successful */
20647 	err = bpf_vlog_finalize(&env->log, &log_true_size);
20648 	if (err)
20649 		ret = err;
20650 
20651 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20652 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20653 				  &log_true_size, sizeof(log_true_size))) {
20654 		ret = -EFAULT;
20655 		goto err_release_maps;
20656 	}
20657 
20658 	if (ret)
20659 		goto err_release_maps;
20660 
20661 	if (env->used_map_cnt) {
20662 		/* if program passed verifier, update used_maps in bpf_prog_info */
20663 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20664 							  sizeof(env->used_maps[0]),
20665 							  GFP_KERNEL);
20666 
20667 		if (!env->prog->aux->used_maps) {
20668 			ret = -ENOMEM;
20669 			goto err_release_maps;
20670 		}
20671 
20672 		memcpy(env->prog->aux->used_maps, env->used_maps,
20673 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
20674 		env->prog->aux->used_map_cnt = env->used_map_cnt;
20675 	}
20676 	if (env->used_btf_cnt) {
20677 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
20678 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20679 							  sizeof(env->used_btfs[0]),
20680 							  GFP_KERNEL);
20681 		if (!env->prog->aux->used_btfs) {
20682 			ret = -ENOMEM;
20683 			goto err_release_maps;
20684 		}
20685 
20686 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
20687 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20688 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20689 	}
20690 	if (env->used_map_cnt || env->used_btf_cnt) {
20691 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
20692 		 * bpf_ld_imm64 instructions
20693 		 */
20694 		convert_pseudo_ld_imm64(env);
20695 	}
20696 
20697 	adjust_btf_func(env);
20698 
20699 err_release_maps:
20700 	if (!env->prog->aux->used_maps)
20701 		/* if we didn't copy map pointers into bpf_prog_info, release
20702 		 * them now. Otherwise free_used_maps() will release them.
20703 		 */
20704 		release_maps(env);
20705 	if (!env->prog->aux->used_btfs)
20706 		release_btfs(env);
20707 
20708 	/* extension progs temporarily inherit the attach_type of their targets
20709 	   for verification purposes, so set it back to zero before returning
20710 	 */
20711 	if (env->prog->type == BPF_PROG_TYPE_EXT)
20712 		env->prog->expected_attach_type = 0;
20713 
20714 	*prog = env->prog;
20715 err_unlock:
20716 	if (!is_priv)
20717 		mutex_unlock(&bpf_verifier_lock);
20718 	vfree(env->insn_aux_data);
20719 err_free_env:
20720 	kfree(env);
20721 	return ret;
20722 }
20723