xref: /linux/kernel/bpf/verifier.c (revision 7a5f93ea5862da91488975acaa0c7abd508f192b)
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 #include <linux/trace_events.h>
32 #include <linux/kallsyms.h>
33 
34 #include "disasm.h"
35 
36 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
37 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
38 	[_id] = & _name ## _verifier_ops,
39 #define BPF_MAP_TYPE(_id, _ops)
40 #define BPF_LINK_TYPE(_id, _name)
41 #include <linux/bpf_types.h>
42 #undef BPF_PROG_TYPE
43 #undef BPF_MAP_TYPE
44 #undef BPF_LINK_TYPE
45 };
46 
47 struct bpf_mem_alloc bpf_global_percpu_ma;
48 static bool bpf_global_percpu_ma_set;
49 
50 /* bpf_check() is a static code analyzer that walks eBPF program
51  * instruction by instruction and updates register/stack state.
52  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
53  *
54  * The first pass is depth-first-search to check that the program is a DAG.
55  * It rejects the following programs:
56  * - larger than BPF_MAXINSNS insns
57  * - if loop is present (detected via back-edge)
58  * - unreachable insns exist (shouldn't be a forest. program = one function)
59  * - out of bounds or malformed jumps
60  * The second pass is all possible path descent from the 1st insn.
61  * Since it's analyzing all paths through the program, the length of the
62  * analysis is limited to 64k insn, which may be hit even if total number of
63  * insn is less then 4K, but there are too many branches that change stack/regs.
64  * Number of 'branches to be analyzed' is limited to 1k
65  *
66  * On entry to each instruction, each register has a type, and the instruction
67  * changes the types of the registers depending on instruction semantics.
68  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
69  * copied to R1.
70  *
71  * All registers are 64-bit.
72  * R0 - return register
73  * R1-R5 argument passing registers
74  * R6-R9 callee saved registers
75  * R10 - frame pointer read-only
76  *
77  * At the start of BPF program the register R1 contains a pointer to bpf_context
78  * and has type PTR_TO_CTX.
79  *
80  * Verifier tracks arithmetic operations on pointers in case:
81  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
82  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
83  * 1st insn copies R10 (which has FRAME_PTR) type into R1
84  * and 2nd arithmetic instruction is pattern matched to recognize
85  * that it wants to construct a pointer to some element within stack.
86  * So after 2nd insn, the register R1 has type PTR_TO_STACK
87  * (and -20 constant is saved for further stack bounds checking).
88  * Meaning that this reg is a pointer to stack plus known immediate constant.
89  *
90  * Most of the time the registers have SCALAR_VALUE type, which
91  * means the register has some value, but it's not a valid pointer.
92  * (like pointer plus pointer becomes SCALAR_VALUE type)
93  *
94  * When verifier sees load or store instructions the type of base register
95  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
96  * four pointer types recognized by check_mem_access() function.
97  *
98  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
99  * and the range of [ptr, ptr + map's value_size) is accessible.
100  *
101  * registers used to pass values to function calls are checked against
102  * function argument constraints.
103  *
104  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
105  * It means that the register type passed to this function must be
106  * PTR_TO_STACK and it will be used inside the function as
107  * 'pointer to map element key'
108  *
109  * For example the argument constraints for bpf_map_lookup_elem():
110  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
111  *   .arg1_type = ARG_CONST_MAP_PTR,
112  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
113  *
114  * ret_type says that this function returns 'pointer to map elem value or null'
115  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
116  * 2nd argument should be a pointer to stack, which will be used inside
117  * the helper function as a pointer to map element key.
118  *
119  * On the kernel side the helper function looks like:
120  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
121  * {
122  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
123  *    void *key = (void *) (unsigned long) r2;
124  *    void *value;
125  *
126  *    here kernel can access 'key' and 'map' pointers safely, knowing that
127  *    [key, key + map->key_size) bytes are valid and were initialized on
128  *    the stack of eBPF program.
129  * }
130  *
131  * Corresponding eBPF program may look like:
132  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
133  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
134  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
135  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
136  * here verifier looks at prototype of map_lookup_elem() and sees:
137  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
138  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
139  *
140  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
141  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
142  * and were initialized prior to this call.
143  * If it's ok, then verifier allows this BPF_CALL insn and looks at
144  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
145  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
146  * returns either pointer to map value or NULL.
147  *
148  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
149  * insn, the register holding that pointer in the true branch changes state to
150  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
151  * branch. See check_cond_jmp_op().
152  *
153  * After the call R0 is set to return type of the function and registers R1-R5
154  * are set to NOT_INIT to indicate that they are no longer readable.
155  *
156  * The following reference types represent a potential reference to a kernel
157  * resource which, after first being allocated, must be checked and freed by
158  * the BPF program:
159  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
160  *
161  * When the verifier sees a helper call return a reference type, it allocates a
162  * pointer id for the reference and stores it in the current function state.
163  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
164  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
165  * passes through a NULL-check conditional. For the branch wherein the state is
166  * changed to CONST_IMM, the verifier releases the reference.
167  *
168  * For each helper function that allocates a reference, such as
169  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
170  * bpf_sk_release(). When a reference type passes into the release function,
171  * the verifier also releases the reference. If any unchecked or unreleased
172  * reference remains at the end of the program, the verifier rejects it.
173  */
174 
175 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
176 struct bpf_verifier_stack_elem {
177 	/* verifier state is 'st'
178 	 * before processing instruction 'insn_idx'
179 	 * and after processing instruction 'prev_insn_idx'
180 	 */
181 	struct bpf_verifier_state st;
182 	int insn_idx;
183 	int prev_insn_idx;
184 	struct bpf_verifier_stack_elem *next;
185 	/* length of verifier log at the time this state was pushed on stack */
186 	u32 log_pos;
187 };
188 
189 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
190 #define BPF_COMPLEXITY_LIMIT_STATES	64
191 
192 #define BPF_MAP_KEY_POISON	(1ULL << 63)
193 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
194 
195 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
196 
197 #define BPF_PRIV_STACK_MIN_SIZE		64
198 
199 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
200 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
201 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
202 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
203 static int ref_set_non_owning(struct bpf_verifier_env *env,
204 			      struct bpf_reg_state *reg);
205 static void specialize_kfunc(struct bpf_verifier_env *env,
206 			     u32 func_id, u16 offset, unsigned long *addr);
207 static bool is_trusted_reg(const struct bpf_reg_state *reg);
208 
209 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
210 {
211 	return aux->map_ptr_state.poison;
212 }
213 
214 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
215 {
216 	return aux->map_ptr_state.unpriv;
217 }
218 
219 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
220 			      struct bpf_map *map,
221 			      bool unpriv, bool poison)
222 {
223 	unpriv |= bpf_map_ptr_unpriv(aux);
224 	aux->map_ptr_state.unpriv = unpriv;
225 	aux->map_ptr_state.poison = poison;
226 	aux->map_ptr_state.map_ptr = map;
227 }
228 
229 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
230 {
231 	return aux->map_key_state & BPF_MAP_KEY_POISON;
232 }
233 
234 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
235 {
236 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
237 }
238 
239 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
240 {
241 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
242 }
243 
244 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
245 {
246 	bool poisoned = bpf_map_key_poisoned(aux);
247 
248 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
249 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
250 }
251 
252 static bool bpf_helper_call(const struct bpf_insn *insn)
253 {
254 	return insn->code == (BPF_JMP | BPF_CALL) &&
255 	       insn->src_reg == 0;
256 }
257 
258 static bool bpf_pseudo_call(const struct bpf_insn *insn)
259 {
260 	return insn->code == (BPF_JMP | BPF_CALL) &&
261 	       insn->src_reg == BPF_PSEUDO_CALL;
262 }
263 
264 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
265 {
266 	return insn->code == (BPF_JMP | BPF_CALL) &&
267 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
268 }
269 
270 struct bpf_call_arg_meta {
271 	struct bpf_map *map_ptr;
272 	bool raw_mode;
273 	bool pkt_access;
274 	u8 release_regno;
275 	int regno;
276 	int access_size;
277 	int mem_size;
278 	u64 msize_max_value;
279 	int ref_obj_id;
280 	int dynptr_id;
281 	int map_uid;
282 	int func_id;
283 	struct btf *btf;
284 	u32 btf_id;
285 	struct btf *ret_btf;
286 	u32 ret_btf_id;
287 	u32 subprogno;
288 	struct btf_field *kptr_field;
289 };
290 
291 struct bpf_kfunc_call_arg_meta {
292 	/* In parameters */
293 	struct btf *btf;
294 	u32 func_id;
295 	u32 kfunc_flags;
296 	const struct btf_type *func_proto;
297 	const char *func_name;
298 	/* Out parameters */
299 	u32 ref_obj_id;
300 	u8 release_regno;
301 	bool r0_rdonly;
302 	u32 ret_btf_id;
303 	u64 r0_size;
304 	u32 subprogno;
305 	struct {
306 		u64 value;
307 		bool found;
308 	} arg_constant;
309 
310 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
311 	 * generally to pass info about user-defined local kptr types to later
312 	 * verification logic
313 	 *   bpf_obj_drop/bpf_percpu_obj_drop
314 	 *     Record the local kptr type to be drop'd
315 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
316 	 *     Record the local kptr type to be refcount_incr'd and use
317 	 *     arg_owning_ref to determine whether refcount_acquire should be
318 	 *     fallible
319 	 */
320 	struct btf *arg_btf;
321 	u32 arg_btf_id;
322 	bool arg_owning_ref;
323 
324 	struct {
325 		struct btf_field *field;
326 	} arg_list_head;
327 	struct {
328 		struct btf_field *field;
329 	} arg_rbtree_root;
330 	struct {
331 		enum bpf_dynptr_type type;
332 		u32 id;
333 		u32 ref_obj_id;
334 	} initialized_dynptr;
335 	struct {
336 		u8 spi;
337 		u8 frameno;
338 	} iter;
339 	struct {
340 		struct bpf_map *ptr;
341 		int uid;
342 	} map;
343 	u64 mem_size;
344 };
345 
346 struct btf *btf_vmlinux;
347 
348 static const char *btf_type_name(const struct btf *btf, u32 id)
349 {
350 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
351 }
352 
353 static DEFINE_MUTEX(bpf_verifier_lock);
354 static DEFINE_MUTEX(bpf_percpu_ma_lock);
355 
356 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
357 {
358 	struct bpf_verifier_env *env = private_data;
359 	va_list args;
360 
361 	if (!bpf_verifier_log_needed(&env->log))
362 		return;
363 
364 	va_start(args, fmt);
365 	bpf_verifier_vlog(&env->log, fmt, args);
366 	va_end(args);
367 }
368 
369 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
370 				   struct bpf_reg_state *reg,
371 				   struct bpf_retval_range range, const char *ctx,
372 				   const char *reg_name)
373 {
374 	bool unknown = true;
375 
376 	verbose(env, "%s the register %s has", ctx, reg_name);
377 	if (reg->smin_value > S64_MIN) {
378 		verbose(env, " smin=%lld", reg->smin_value);
379 		unknown = false;
380 	}
381 	if (reg->smax_value < S64_MAX) {
382 		verbose(env, " smax=%lld", reg->smax_value);
383 		unknown = false;
384 	}
385 	if (unknown)
386 		verbose(env, " unknown scalar value");
387 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
388 }
389 
390 static bool reg_not_null(const struct bpf_reg_state *reg)
391 {
392 	enum bpf_reg_type type;
393 
394 	type = reg->type;
395 	if (type_may_be_null(type))
396 		return false;
397 
398 	type = base_type(type);
399 	return type == PTR_TO_SOCKET ||
400 		type == PTR_TO_TCP_SOCK ||
401 		type == PTR_TO_MAP_VALUE ||
402 		type == PTR_TO_MAP_KEY ||
403 		type == PTR_TO_SOCK_COMMON ||
404 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
405 		type == PTR_TO_MEM;
406 }
407 
408 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
409 {
410 	struct btf_record *rec = NULL;
411 	struct btf_struct_meta *meta;
412 
413 	if (reg->type == PTR_TO_MAP_VALUE) {
414 		rec = reg->map_ptr->record;
415 	} else if (type_is_ptr_alloc_obj(reg->type)) {
416 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
417 		if (meta)
418 			rec = meta->record;
419 	}
420 	return rec;
421 }
422 
423 static bool mask_raw_tp_reg_cond(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) {
424 	return reg->type == (PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL) &&
425 	       bpf_prog_is_raw_tp(env->prog) && !reg->ref_obj_id;
426 }
427 
428 static bool mask_raw_tp_reg(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
429 {
430 	if (!mask_raw_tp_reg_cond(env, reg))
431 		return false;
432 	reg->type &= ~PTR_MAYBE_NULL;
433 	return true;
434 }
435 
436 static void unmask_raw_tp_reg(struct bpf_reg_state *reg, bool result)
437 {
438 	if (result)
439 		reg->type |= PTR_MAYBE_NULL;
440 }
441 
442 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
443 {
444 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
445 
446 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
447 }
448 
449 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
450 {
451 	struct bpf_func_info *info;
452 
453 	if (!env->prog->aux->func_info)
454 		return "";
455 
456 	info = &env->prog->aux->func_info[subprog];
457 	return btf_type_name(env->prog->aux->btf, info->type_id);
458 }
459 
460 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
461 {
462 	struct bpf_subprog_info *info = subprog_info(env, subprog);
463 
464 	info->is_cb = true;
465 	info->is_async_cb = true;
466 	info->is_exception_cb = true;
467 }
468 
469 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
470 {
471 	return subprog_info(env, subprog)->is_exception_cb;
472 }
473 
474 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
475 {
476 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
477 }
478 
479 static bool type_is_rdonly_mem(u32 type)
480 {
481 	return type & MEM_RDONLY;
482 }
483 
484 static bool is_acquire_function(enum bpf_func_id func_id,
485 				const struct bpf_map *map)
486 {
487 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
488 
489 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
490 	    func_id == BPF_FUNC_sk_lookup_udp ||
491 	    func_id == BPF_FUNC_skc_lookup_tcp ||
492 	    func_id == BPF_FUNC_ringbuf_reserve ||
493 	    func_id == BPF_FUNC_kptr_xchg)
494 		return true;
495 
496 	if (func_id == BPF_FUNC_map_lookup_elem &&
497 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
498 	     map_type == BPF_MAP_TYPE_SOCKHASH))
499 		return true;
500 
501 	return false;
502 }
503 
504 static bool is_ptr_cast_function(enum bpf_func_id func_id)
505 {
506 	return func_id == BPF_FUNC_tcp_sock ||
507 		func_id == BPF_FUNC_sk_fullsock ||
508 		func_id == BPF_FUNC_skc_to_tcp_sock ||
509 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
510 		func_id == BPF_FUNC_skc_to_udp6_sock ||
511 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
512 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
513 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
514 }
515 
516 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
517 {
518 	return func_id == BPF_FUNC_dynptr_data;
519 }
520 
521 static bool is_sync_callback_calling_kfunc(u32 btf_id);
522 static bool is_async_callback_calling_kfunc(u32 btf_id);
523 static bool is_callback_calling_kfunc(u32 btf_id);
524 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
525 
526 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id);
527 
528 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
529 {
530 	return func_id == BPF_FUNC_for_each_map_elem ||
531 	       func_id == BPF_FUNC_find_vma ||
532 	       func_id == BPF_FUNC_loop ||
533 	       func_id == BPF_FUNC_user_ringbuf_drain;
534 }
535 
536 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
537 {
538 	return func_id == BPF_FUNC_timer_set_callback;
539 }
540 
541 static bool is_callback_calling_function(enum bpf_func_id func_id)
542 {
543 	return is_sync_callback_calling_function(func_id) ||
544 	       is_async_callback_calling_function(func_id);
545 }
546 
547 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
548 {
549 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
550 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
551 }
552 
553 static bool is_async_callback_calling_insn(struct bpf_insn *insn)
554 {
555 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
556 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
557 }
558 
559 static bool is_may_goto_insn(struct bpf_insn *insn)
560 {
561 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
562 }
563 
564 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
565 {
566 	return is_may_goto_insn(&env->prog->insnsi[insn_idx]);
567 }
568 
569 static bool is_storage_get_function(enum bpf_func_id func_id)
570 {
571 	return func_id == BPF_FUNC_sk_storage_get ||
572 	       func_id == BPF_FUNC_inode_storage_get ||
573 	       func_id == BPF_FUNC_task_storage_get ||
574 	       func_id == BPF_FUNC_cgrp_storage_get;
575 }
576 
577 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
578 					const struct bpf_map *map)
579 {
580 	int ref_obj_uses = 0;
581 
582 	if (is_ptr_cast_function(func_id))
583 		ref_obj_uses++;
584 	if (is_acquire_function(func_id, map))
585 		ref_obj_uses++;
586 	if (is_dynptr_ref_function(func_id))
587 		ref_obj_uses++;
588 
589 	return ref_obj_uses > 1;
590 }
591 
592 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
593 {
594 	return BPF_CLASS(insn->code) == BPF_STX &&
595 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
596 	       insn->imm == BPF_CMPXCHG;
597 }
598 
599 static int __get_spi(s32 off)
600 {
601 	return (-off - 1) / BPF_REG_SIZE;
602 }
603 
604 static struct bpf_func_state *func(struct bpf_verifier_env *env,
605 				   const struct bpf_reg_state *reg)
606 {
607 	struct bpf_verifier_state *cur = env->cur_state;
608 
609 	return cur->frame[reg->frameno];
610 }
611 
612 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
613 {
614        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
615 
616        /* We need to check that slots between [spi - nr_slots + 1, spi] are
617 	* within [0, allocated_stack).
618 	*
619 	* Please note that the spi grows downwards. For example, a dynptr
620 	* takes the size of two stack slots; the first slot will be at
621 	* spi and the second slot will be at spi - 1.
622 	*/
623        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
624 }
625 
626 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
627 			          const char *obj_kind, int nr_slots)
628 {
629 	int off, spi;
630 
631 	if (!tnum_is_const(reg->var_off)) {
632 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
633 		return -EINVAL;
634 	}
635 
636 	off = reg->off + reg->var_off.value;
637 	if (off % BPF_REG_SIZE) {
638 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
639 		return -EINVAL;
640 	}
641 
642 	spi = __get_spi(off);
643 	if (spi + 1 < nr_slots) {
644 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
645 		return -EINVAL;
646 	}
647 
648 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
649 		return -ERANGE;
650 	return spi;
651 }
652 
653 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
654 {
655 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
656 }
657 
658 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
659 {
660 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
661 }
662 
663 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
664 {
665 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
666 	case DYNPTR_TYPE_LOCAL:
667 		return BPF_DYNPTR_TYPE_LOCAL;
668 	case DYNPTR_TYPE_RINGBUF:
669 		return BPF_DYNPTR_TYPE_RINGBUF;
670 	case DYNPTR_TYPE_SKB:
671 		return BPF_DYNPTR_TYPE_SKB;
672 	case DYNPTR_TYPE_XDP:
673 		return BPF_DYNPTR_TYPE_XDP;
674 	default:
675 		return BPF_DYNPTR_TYPE_INVALID;
676 	}
677 }
678 
679 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
680 {
681 	switch (type) {
682 	case BPF_DYNPTR_TYPE_LOCAL:
683 		return DYNPTR_TYPE_LOCAL;
684 	case BPF_DYNPTR_TYPE_RINGBUF:
685 		return DYNPTR_TYPE_RINGBUF;
686 	case BPF_DYNPTR_TYPE_SKB:
687 		return DYNPTR_TYPE_SKB;
688 	case BPF_DYNPTR_TYPE_XDP:
689 		return DYNPTR_TYPE_XDP;
690 	default:
691 		return 0;
692 	}
693 }
694 
695 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
696 {
697 	return type == BPF_DYNPTR_TYPE_RINGBUF;
698 }
699 
700 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
701 			      enum bpf_dynptr_type type,
702 			      bool first_slot, int dynptr_id);
703 
704 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
705 				struct bpf_reg_state *reg);
706 
707 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
708 				   struct bpf_reg_state *sreg1,
709 				   struct bpf_reg_state *sreg2,
710 				   enum bpf_dynptr_type type)
711 {
712 	int id = ++env->id_gen;
713 
714 	__mark_dynptr_reg(sreg1, type, true, id);
715 	__mark_dynptr_reg(sreg2, type, false, id);
716 }
717 
718 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
719 			       struct bpf_reg_state *reg,
720 			       enum bpf_dynptr_type type)
721 {
722 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
723 }
724 
725 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
726 				        struct bpf_func_state *state, int spi);
727 
728 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
729 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
730 {
731 	struct bpf_func_state *state = func(env, reg);
732 	enum bpf_dynptr_type type;
733 	int spi, i, err;
734 
735 	spi = dynptr_get_spi(env, reg);
736 	if (spi < 0)
737 		return spi;
738 
739 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
740 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
741 	 * to ensure that for the following example:
742 	 *	[d1][d1][d2][d2]
743 	 * spi    3   2   1   0
744 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
745 	 * case they do belong to same dynptr, second call won't see slot_type
746 	 * as STACK_DYNPTR and will simply skip destruction.
747 	 */
748 	err = destroy_if_dynptr_stack_slot(env, state, spi);
749 	if (err)
750 		return err;
751 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
752 	if (err)
753 		return err;
754 
755 	for (i = 0; i < BPF_REG_SIZE; i++) {
756 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
757 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
758 	}
759 
760 	type = arg_to_dynptr_type(arg_type);
761 	if (type == BPF_DYNPTR_TYPE_INVALID)
762 		return -EINVAL;
763 
764 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
765 			       &state->stack[spi - 1].spilled_ptr, type);
766 
767 	if (dynptr_type_refcounted(type)) {
768 		/* The id is used to track proper releasing */
769 		int id;
770 
771 		if (clone_ref_obj_id)
772 			id = clone_ref_obj_id;
773 		else
774 			id = acquire_reference_state(env, insn_idx);
775 
776 		if (id < 0)
777 			return id;
778 
779 		state->stack[spi].spilled_ptr.ref_obj_id = id;
780 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
781 	}
782 
783 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
784 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
785 
786 	return 0;
787 }
788 
789 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
790 {
791 	int i;
792 
793 	for (i = 0; i < BPF_REG_SIZE; i++) {
794 		state->stack[spi].slot_type[i] = STACK_INVALID;
795 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
796 	}
797 
798 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
799 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
800 
801 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
802 	 *
803 	 * While we don't allow reading STACK_INVALID, it is still possible to
804 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
805 	 * helpers or insns can do partial read of that part without failing,
806 	 * but check_stack_range_initialized, check_stack_read_var_off, and
807 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
808 	 * the slot conservatively. Hence we need to prevent those liveness
809 	 * marking walks.
810 	 *
811 	 * This was not a problem before because STACK_INVALID is only set by
812 	 * default (where the default reg state has its reg->parent as NULL), or
813 	 * in clean_live_states after REG_LIVE_DONE (at which point
814 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
815 	 * verifier state exploration (like we did above). Hence, for our case
816 	 * parentage chain will still be live (i.e. reg->parent may be
817 	 * non-NULL), while earlier reg->parent was NULL, so we need
818 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
819 	 * done later on reads or by mark_dynptr_read as well to unnecessary
820 	 * mark registers in verifier state.
821 	 */
822 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
823 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
824 }
825 
826 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
827 {
828 	struct bpf_func_state *state = func(env, reg);
829 	int spi, ref_obj_id, i;
830 
831 	spi = dynptr_get_spi(env, reg);
832 	if (spi < 0)
833 		return spi;
834 
835 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
836 		invalidate_dynptr(env, state, spi);
837 		return 0;
838 	}
839 
840 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
841 
842 	/* If the dynptr has a ref_obj_id, then we need to invalidate
843 	 * two things:
844 	 *
845 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
846 	 * 2) Any slices derived from this dynptr.
847 	 */
848 
849 	/* Invalidate any slices associated with this dynptr */
850 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
851 
852 	/* Invalidate any dynptr clones */
853 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
854 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
855 			continue;
856 
857 		/* it should always be the case that if the ref obj id
858 		 * matches then the stack slot also belongs to a
859 		 * dynptr
860 		 */
861 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
862 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
863 			return -EFAULT;
864 		}
865 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
866 			invalidate_dynptr(env, state, i);
867 	}
868 
869 	return 0;
870 }
871 
872 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
873 			       struct bpf_reg_state *reg);
874 
875 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
876 {
877 	if (!env->allow_ptr_leaks)
878 		__mark_reg_not_init(env, reg);
879 	else
880 		__mark_reg_unknown(env, reg);
881 }
882 
883 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
884 				        struct bpf_func_state *state, int spi)
885 {
886 	struct bpf_func_state *fstate;
887 	struct bpf_reg_state *dreg;
888 	int i, dynptr_id;
889 
890 	/* We always ensure that STACK_DYNPTR is never set partially,
891 	 * hence just checking for slot_type[0] is enough. This is
892 	 * different for STACK_SPILL, where it may be only set for
893 	 * 1 byte, so code has to use is_spilled_reg.
894 	 */
895 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
896 		return 0;
897 
898 	/* Reposition spi to first slot */
899 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
900 		spi = spi + 1;
901 
902 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
903 		verbose(env, "cannot overwrite referenced dynptr\n");
904 		return -EINVAL;
905 	}
906 
907 	mark_stack_slot_scratched(env, spi);
908 	mark_stack_slot_scratched(env, spi - 1);
909 
910 	/* Writing partially to one dynptr stack slot destroys both. */
911 	for (i = 0; i < BPF_REG_SIZE; i++) {
912 		state->stack[spi].slot_type[i] = STACK_INVALID;
913 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
914 	}
915 
916 	dynptr_id = state->stack[spi].spilled_ptr.id;
917 	/* Invalidate any slices associated with this dynptr */
918 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
919 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
920 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
921 			continue;
922 		if (dreg->dynptr_id == dynptr_id)
923 			mark_reg_invalid(env, dreg);
924 	}));
925 
926 	/* Do not release reference state, we are destroying dynptr on stack,
927 	 * not using some helper to release it. Just reset register.
928 	 */
929 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
930 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
931 
932 	/* Same reason as unmark_stack_slots_dynptr above */
933 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
934 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
935 
936 	return 0;
937 }
938 
939 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
940 {
941 	int spi;
942 
943 	if (reg->type == CONST_PTR_TO_DYNPTR)
944 		return false;
945 
946 	spi = dynptr_get_spi(env, reg);
947 
948 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
949 	 * error because this just means the stack state hasn't been updated yet.
950 	 * We will do check_mem_access to check and update stack bounds later.
951 	 */
952 	if (spi < 0 && spi != -ERANGE)
953 		return false;
954 
955 	/* We don't need to check if the stack slots are marked by previous
956 	 * dynptr initializations because we allow overwriting existing unreferenced
957 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
958 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
959 	 * touching are completely destructed before we reinitialize them for a new
960 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
961 	 * instead of delaying it until the end where the user will get "Unreleased
962 	 * reference" error.
963 	 */
964 	return true;
965 }
966 
967 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
968 {
969 	struct bpf_func_state *state = func(env, reg);
970 	int i, spi;
971 
972 	/* This already represents first slot of initialized bpf_dynptr.
973 	 *
974 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
975 	 * check_func_arg_reg_off's logic, so we don't need to check its
976 	 * offset and alignment.
977 	 */
978 	if (reg->type == CONST_PTR_TO_DYNPTR)
979 		return true;
980 
981 	spi = dynptr_get_spi(env, reg);
982 	if (spi < 0)
983 		return false;
984 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
985 		return false;
986 
987 	for (i = 0; i < BPF_REG_SIZE; i++) {
988 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
989 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
990 			return false;
991 	}
992 
993 	return true;
994 }
995 
996 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
997 				    enum bpf_arg_type arg_type)
998 {
999 	struct bpf_func_state *state = func(env, reg);
1000 	enum bpf_dynptr_type dynptr_type;
1001 	int spi;
1002 
1003 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1004 	if (arg_type == ARG_PTR_TO_DYNPTR)
1005 		return true;
1006 
1007 	dynptr_type = arg_to_dynptr_type(arg_type);
1008 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1009 		return reg->dynptr.type == dynptr_type;
1010 	} else {
1011 		spi = dynptr_get_spi(env, reg);
1012 		if (spi < 0)
1013 			return false;
1014 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1015 	}
1016 }
1017 
1018 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1019 
1020 static bool in_rcu_cs(struct bpf_verifier_env *env);
1021 
1022 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1023 
1024 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1025 				 struct bpf_kfunc_call_arg_meta *meta,
1026 				 struct bpf_reg_state *reg, int insn_idx,
1027 				 struct btf *btf, u32 btf_id, int nr_slots)
1028 {
1029 	struct bpf_func_state *state = func(env, reg);
1030 	int spi, i, j, id;
1031 
1032 	spi = iter_get_spi(env, reg, nr_slots);
1033 	if (spi < 0)
1034 		return spi;
1035 
1036 	id = acquire_reference_state(env, insn_idx);
1037 	if (id < 0)
1038 		return id;
1039 
1040 	for (i = 0; i < nr_slots; i++) {
1041 		struct bpf_stack_state *slot = &state->stack[spi - i];
1042 		struct bpf_reg_state *st = &slot->spilled_ptr;
1043 
1044 		__mark_reg_known_zero(st);
1045 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1046 		if (is_kfunc_rcu_protected(meta)) {
1047 			if (in_rcu_cs(env))
1048 				st->type |= MEM_RCU;
1049 			else
1050 				st->type |= PTR_UNTRUSTED;
1051 		}
1052 		st->live |= REG_LIVE_WRITTEN;
1053 		st->ref_obj_id = i == 0 ? id : 0;
1054 		st->iter.btf = btf;
1055 		st->iter.btf_id = btf_id;
1056 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1057 		st->iter.depth = 0;
1058 
1059 		for (j = 0; j < BPF_REG_SIZE; j++)
1060 			slot->slot_type[j] = STACK_ITER;
1061 
1062 		mark_stack_slot_scratched(env, spi - i);
1063 	}
1064 
1065 	return 0;
1066 }
1067 
1068 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1069 				   struct bpf_reg_state *reg, int nr_slots)
1070 {
1071 	struct bpf_func_state *state = func(env, reg);
1072 	int spi, i, j;
1073 
1074 	spi = iter_get_spi(env, reg, nr_slots);
1075 	if (spi < 0)
1076 		return spi;
1077 
1078 	for (i = 0; i < nr_slots; i++) {
1079 		struct bpf_stack_state *slot = &state->stack[spi - i];
1080 		struct bpf_reg_state *st = &slot->spilled_ptr;
1081 
1082 		if (i == 0)
1083 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1084 
1085 		__mark_reg_not_init(env, st);
1086 
1087 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1088 		st->live |= REG_LIVE_WRITTEN;
1089 
1090 		for (j = 0; j < BPF_REG_SIZE; j++)
1091 			slot->slot_type[j] = STACK_INVALID;
1092 
1093 		mark_stack_slot_scratched(env, spi - i);
1094 	}
1095 
1096 	return 0;
1097 }
1098 
1099 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1100 				     struct bpf_reg_state *reg, int nr_slots)
1101 {
1102 	struct bpf_func_state *state = func(env, reg);
1103 	int spi, i, j;
1104 
1105 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1106 	 * will do check_mem_access to check and update stack bounds later, so
1107 	 * return true for that case.
1108 	 */
1109 	spi = iter_get_spi(env, reg, nr_slots);
1110 	if (spi == -ERANGE)
1111 		return true;
1112 	if (spi < 0)
1113 		return false;
1114 
1115 	for (i = 0; i < nr_slots; i++) {
1116 		struct bpf_stack_state *slot = &state->stack[spi - i];
1117 
1118 		for (j = 0; j < BPF_REG_SIZE; j++)
1119 			if (slot->slot_type[j] == STACK_ITER)
1120 				return false;
1121 	}
1122 
1123 	return true;
1124 }
1125 
1126 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1127 				   struct btf *btf, u32 btf_id, int nr_slots)
1128 {
1129 	struct bpf_func_state *state = func(env, reg);
1130 	int spi, i, j;
1131 
1132 	spi = iter_get_spi(env, reg, nr_slots);
1133 	if (spi < 0)
1134 		return -EINVAL;
1135 
1136 	for (i = 0; i < nr_slots; i++) {
1137 		struct bpf_stack_state *slot = &state->stack[spi - i];
1138 		struct bpf_reg_state *st = &slot->spilled_ptr;
1139 
1140 		if (st->type & PTR_UNTRUSTED)
1141 			return -EPROTO;
1142 		/* only main (first) slot has ref_obj_id set */
1143 		if (i == 0 && !st->ref_obj_id)
1144 			return -EINVAL;
1145 		if (i != 0 && st->ref_obj_id)
1146 			return -EINVAL;
1147 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1148 			return -EINVAL;
1149 
1150 		for (j = 0; j < BPF_REG_SIZE; j++)
1151 			if (slot->slot_type[j] != STACK_ITER)
1152 				return -EINVAL;
1153 	}
1154 
1155 	return 0;
1156 }
1157 
1158 /* Check if given stack slot is "special":
1159  *   - spilled register state (STACK_SPILL);
1160  *   - dynptr state (STACK_DYNPTR);
1161  *   - iter state (STACK_ITER).
1162  */
1163 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1164 {
1165 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1166 
1167 	switch (type) {
1168 	case STACK_SPILL:
1169 	case STACK_DYNPTR:
1170 	case STACK_ITER:
1171 		return true;
1172 	case STACK_INVALID:
1173 	case STACK_MISC:
1174 	case STACK_ZERO:
1175 		return false;
1176 	default:
1177 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1178 		return true;
1179 	}
1180 }
1181 
1182 /* The reg state of a pointer or a bounded scalar was saved when
1183  * it was spilled to the stack.
1184  */
1185 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1186 {
1187 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1188 }
1189 
1190 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1191 {
1192 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1193 	       stack->spilled_ptr.type == SCALAR_VALUE;
1194 }
1195 
1196 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1197 {
1198 	return stack->slot_type[0] == STACK_SPILL &&
1199 	       stack->spilled_ptr.type == SCALAR_VALUE;
1200 }
1201 
1202 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1203  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1204  * more precise STACK_ZERO.
1205  * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1206  * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1207  * unnecessary as both are considered equivalent when loading data and pruning,
1208  * in case of unprivileged mode it will be incorrect to allow reads of invalid
1209  * slots.
1210  */
1211 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1212 {
1213 	if (*stype == STACK_ZERO)
1214 		return;
1215 	if (*stype == STACK_INVALID)
1216 		return;
1217 	*stype = STACK_MISC;
1218 }
1219 
1220 static void scrub_spilled_slot(u8 *stype)
1221 {
1222 	if (*stype != STACK_INVALID)
1223 		*stype = STACK_MISC;
1224 }
1225 
1226 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1227  * small to hold src. This is different from krealloc since we don't want to preserve
1228  * the contents of dst.
1229  *
1230  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1231  * not be allocated.
1232  */
1233 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1234 {
1235 	size_t alloc_bytes;
1236 	void *orig = dst;
1237 	size_t bytes;
1238 
1239 	if (ZERO_OR_NULL_PTR(src))
1240 		goto out;
1241 
1242 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1243 		return NULL;
1244 
1245 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1246 	dst = krealloc(orig, alloc_bytes, flags);
1247 	if (!dst) {
1248 		kfree(orig);
1249 		return NULL;
1250 	}
1251 
1252 	memcpy(dst, src, bytes);
1253 out:
1254 	return dst ? dst : ZERO_SIZE_PTR;
1255 }
1256 
1257 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1258  * small to hold new_n items. new items are zeroed out if the array grows.
1259  *
1260  * Contrary to krealloc_array, does not free arr if new_n is zero.
1261  */
1262 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1263 {
1264 	size_t alloc_size;
1265 	void *new_arr;
1266 
1267 	if (!new_n || old_n == new_n)
1268 		goto out;
1269 
1270 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1271 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1272 	if (!new_arr) {
1273 		kfree(arr);
1274 		return NULL;
1275 	}
1276 	arr = new_arr;
1277 
1278 	if (new_n > old_n)
1279 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1280 
1281 out:
1282 	return arr ? arr : ZERO_SIZE_PTR;
1283 }
1284 
1285 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1286 {
1287 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1288 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1289 	if (!dst->refs)
1290 		return -ENOMEM;
1291 
1292 	dst->active_locks = src->active_locks;
1293 	dst->acquired_refs = src->acquired_refs;
1294 	return 0;
1295 }
1296 
1297 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1298 {
1299 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1300 
1301 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1302 				GFP_KERNEL);
1303 	if (!dst->stack)
1304 		return -ENOMEM;
1305 
1306 	dst->allocated_stack = src->allocated_stack;
1307 	return 0;
1308 }
1309 
1310 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1311 {
1312 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1313 				    sizeof(struct bpf_reference_state));
1314 	if (!state->refs)
1315 		return -ENOMEM;
1316 
1317 	state->acquired_refs = n;
1318 	return 0;
1319 }
1320 
1321 /* Possibly update state->allocated_stack to be at least size bytes. Also
1322  * possibly update the function's high-water mark in its bpf_subprog_info.
1323  */
1324 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1325 {
1326 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1327 
1328 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1329 	size = round_up(size, BPF_REG_SIZE);
1330 	n = size / BPF_REG_SIZE;
1331 
1332 	if (old_n >= n)
1333 		return 0;
1334 
1335 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1336 	if (!state->stack)
1337 		return -ENOMEM;
1338 
1339 	state->allocated_stack = size;
1340 
1341 	/* update known max for given subprogram */
1342 	if (env->subprog_info[state->subprogno].stack_depth < size)
1343 		env->subprog_info[state->subprogno].stack_depth = size;
1344 
1345 	return 0;
1346 }
1347 
1348 /* Acquire a pointer id from the env and update the state->refs to include
1349  * this new pointer reference.
1350  * On success, returns a valid pointer id to associate with the register
1351  * On failure, returns a negative errno.
1352  */
1353 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1354 {
1355 	struct bpf_func_state *state = cur_func(env);
1356 	int new_ofs = state->acquired_refs;
1357 	int id, err;
1358 
1359 	err = resize_reference_state(state, state->acquired_refs + 1);
1360 	if (err)
1361 		return err;
1362 	id = ++env->id_gen;
1363 	state->refs[new_ofs].type = REF_TYPE_PTR;
1364 	state->refs[new_ofs].id = id;
1365 	state->refs[new_ofs].insn_idx = insn_idx;
1366 
1367 	return id;
1368 }
1369 
1370 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1371 			      int id, void *ptr)
1372 {
1373 	struct bpf_func_state *state = cur_func(env);
1374 	int new_ofs = state->acquired_refs;
1375 	int err;
1376 
1377 	err = resize_reference_state(state, state->acquired_refs + 1);
1378 	if (err)
1379 		return err;
1380 	state->refs[new_ofs].type = type;
1381 	state->refs[new_ofs].id = id;
1382 	state->refs[new_ofs].insn_idx = insn_idx;
1383 	state->refs[new_ofs].ptr = ptr;
1384 
1385 	state->active_locks++;
1386 	return 0;
1387 }
1388 
1389 /* release function corresponding to acquire_reference_state(). Idempotent. */
1390 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1391 {
1392 	int i, last_idx;
1393 
1394 	last_idx = state->acquired_refs - 1;
1395 	for (i = 0; i < state->acquired_refs; i++) {
1396 		if (state->refs[i].type != REF_TYPE_PTR)
1397 			continue;
1398 		if (state->refs[i].id == ptr_id) {
1399 			if (last_idx && i != last_idx)
1400 				memcpy(&state->refs[i], &state->refs[last_idx],
1401 				       sizeof(*state->refs));
1402 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1403 			state->acquired_refs--;
1404 			return 0;
1405 		}
1406 	}
1407 	return -EINVAL;
1408 }
1409 
1410 static int release_lock_state(struct bpf_func_state *state, int type, int id, void *ptr)
1411 {
1412 	int i, last_idx;
1413 
1414 	last_idx = state->acquired_refs - 1;
1415 	for (i = 0; i < state->acquired_refs; i++) {
1416 		if (state->refs[i].type != type)
1417 			continue;
1418 		if (state->refs[i].id == id && state->refs[i].ptr == ptr) {
1419 			if (last_idx && i != last_idx)
1420 				memcpy(&state->refs[i], &state->refs[last_idx],
1421 				       sizeof(*state->refs));
1422 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1423 			state->acquired_refs--;
1424 			state->active_locks--;
1425 			return 0;
1426 		}
1427 	}
1428 	return -EINVAL;
1429 }
1430 
1431 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_env *env, enum ref_state_type type,
1432 						   int id, void *ptr)
1433 {
1434 	struct bpf_func_state *state = cur_func(env);
1435 	int i;
1436 
1437 	for (i = 0; i < state->acquired_refs; i++) {
1438 		struct bpf_reference_state *s = &state->refs[i];
1439 
1440 		if (s->type == REF_TYPE_PTR || s->type != type)
1441 			continue;
1442 
1443 		if (s->id == id && s->ptr == ptr)
1444 			return s;
1445 	}
1446 	return NULL;
1447 }
1448 
1449 static void free_func_state(struct bpf_func_state *state)
1450 {
1451 	if (!state)
1452 		return;
1453 	kfree(state->refs);
1454 	kfree(state->stack);
1455 	kfree(state);
1456 }
1457 
1458 static void free_verifier_state(struct bpf_verifier_state *state,
1459 				bool free_self)
1460 {
1461 	int i;
1462 
1463 	for (i = 0; i <= state->curframe; i++) {
1464 		free_func_state(state->frame[i]);
1465 		state->frame[i] = NULL;
1466 	}
1467 	if (free_self)
1468 		kfree(state);
1469 }
1470 
1471 /* copy verifier state from src to dst growing dst stack space
1472  * when necessary to accommodate larger src stack
1473  */
1474 static int copy_func_state(struct bpf_func_state *dst,
1475 			   const struct bpf_func_state *src)
1476 {
1477 	int err;
1478 
1479 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1480 	err = copy_reference_state(dst, src);
1481 	if (err)
1482 		return err;
1483 	return copy_stack_state(dst, src);
1484 }
1485 
1486 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1487 			       const struct bpf_verifier_state *src)
1488 {
1489 	struct bpf_func_state *dst;
1490 	int i, err;
1491 
1492 	/* if dst has more stack frames then src frame, free them, this is also
1493 	 * necessary in case of exceptional exits using bpf_throw.
1494 	 */
1495 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1496 		free_func_state(dst_state->frame[i]);
1497 		dst_state->frame[i] = NULL;
1498 	}
1499 	dst_state->speculative = src->speculative;
1500 	dst_state->active_rcu_lock = src->active_rcu_lock;
1501 	dst_state->active_preempt_lock = src->active_preempt_lock;
1502 	dst_state->in_sleepable = src->in_sleepable;
1503 	dst_state->curframe = src->curframe;
1504 	dst_state->branches = src->branches;
1505 	dst_state->parent = src->parent;
1506 	dst_state->first_insn_idx = src->first_insn_idx;
1507 	dst_state->last_insn_idx = src->last_insn_idx;
1508 	dst_state->insn_hist_start = src->insn_hist_start;
1509 	dst_state->insn_hist_end = src->insn_hist_end;
1510 	dst_state->dfs_depth = src->dfs_depth;
1511 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1512 	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1513 	dst_state->may_goto_depth = src->may_goto_depth;
1514 	for (i = 0; i <= src->curframe; i++) {
1515 		dst = dst_state->frame[i];
1516 		if (!dst) {
1517 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1518 			if (!dst)
1519 				return -ENOMEM;
1520 			dst_state->frame[i] = dst;
1521 		}
1522 		err = copy_func_state(dst, src->frame[i]);
1523 		if (err)
1524 			return err;
1525 	}
1526 	return 0;
1527 }
1528 
1529 static u32 state_htab_size(struct bpf_verifier_env *env)
1530 {
1531 	return env->prog->len;
1532 }
1533 
1534 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1535 {
1536 	struct bpf_verifier_state *cur = env->cur_state;
1537 	struct bpf_func_state *state = cur->frame[cur->curframe];
1538 
1539 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1540 }
1541 
1542 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1543 {
1544 	int fr;
1545 
1546 	if (a->curframe != b->curframe)
1547 		return false;
1548 
1549 	for (fr = a->curframe; fr >= 0; fr--)
1550 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1551 			return false;
1552 
1553 	return true;
1554 }
1555 
1556 /* Open coded iterators allow back-edges in the state graph in order to
1557  * check unbounded loops that iterators.
1558  *
1559  * In is_state_visited() it is necessary to know if explored states are
1560  * part of some loops in order to decide whether non-exact states
1561  * comparison could be used:
1562  * - non-exact states comparison establishes sub-state relation and uses
1563  *   read and precision marks to do so, these marks are propagated from
1564  *   children states and thus are not guaranteed to be final in a loop;
1565  * - exact states comparison just checks if current and explored states
1566  *   are identical (and thus form a back-edge).
1567  *
1568  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1569  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1570  * algorithm for loop structure detection and gives an overview of
1571  * relevant terminology. It also has helpful illustrations.
1572  *
1573  * [1] https://api.semanticscholar.org/CorpusID:15784067
1574  *
1575  * We use a similar algorithm but because loop nested structure is
1576  * irrelevant for verifier ours is significantly simpler and resembles
1577  * strongly connected components algorithm from Sedgewick's textbook.
1578  *
1579  * Define topmost loop entry as a first node of the loop traversed in a
1580  * depth first search starting from initial state. The goal of the loop
1581  * tracking algorithm is to associate topmost loop entries with states
1582  * derived from these entries.
1583  *
1584  * For each step in the DFS states traversal algorithm needs to identify
1585  * the following situations:
1586  *
1587  *          initial                     initial                   initial
1588  *            |                           |                         |
1589  *            V                           V                         V
1590  *           ...                         ...           .---------> hdr
1591  *            |                           |            |            |
1592  *            V                           V            |            V
1593  *           cur                     .-> succ          |    .------...
1594  *            |                      |    |            |    |       |
1595  *            V                      |    V            |    V       V
1596  *           succ                    '-- cur           |   ...     ...
1597  *                                                     |    |       |
1598  *                                                     |    V       V
1599  *                                                     |   succ <- cur
1600  *                                                     |    |
1601  *                                                     |    V
1602  *                                                     |   ...
1603  *                                                     |    |
1604  *                                                     '----'
1605  *
1606  *  (A) successor state of cur   (B) successor state of cur or it's entry
1607  *      not yet traversed            are in current DFS path, thus cur and succ
1608  *                                   are members of the same outermost loop
1609  *
1610  *                      initial                  initial
1611  *                        |                        |
1612  *                        V                        V
1613  *                       ...                      ...
1614  *                        |                        |
1615  *                        V                        V
1616  *                .------...               .------...
1617  *                |       |                |       |
1618  *                V       V                V       V
1619  *           .-> hdr     ...              ...     ...
1620  *           |    |       |                |       |
1621  *           |    V       V                V       V
1622  *           |   succ <- cur              succ <- cur
1623  *           |    |                        |
1624  *           |    V                        V
1625  *           |   ...                      ...
1626  *           |    |                        |
1627  *           '----'                       exit
1628  *
1629  * (C) successor state of cur is a part of some loop but this loop
1630  *     does not include cur or successor state is not in a loop at all.
1631  *
1632  * Algorithm could be described as the following python code:
1633  *
1634  *     traversed = set()   # Set of traversed nodes
1635  *     entries = {}        # Mapping from node to loop entry
1636  *     depths = {}         # Depth level assigned to graph node
1637  *     path = set()        # Current DFS path
1638  *
1639  *     # Find outermost loop entry known for n
1640  *     def get_loop_entry(n):
1641  *         h = entries.get(n, None)
1642  *         while h in entries and entries[h] != h:
1643  *             h = entries[h]
1644  *         return h
1645  *
1646  *     # Update n's loop entry if h's outermost entry comes
1647  *     # before n's outermost entry in current DFS path.
1648  *     def update_loop_entry(n, h):
1649  *         n1 = get_loop_entry(n) or n
1650  *         h1 = get_loop_entry(h) or h
1651  *         if h1 in path and depths[h1] <= depths[n1]:
1652  *             entries[n] = h1
1653  *
1654  *     def dfs(n, depth):
1655  *         traversed.add(n)
1656  *         path.add(n)
1657  *         depths[n] = depth
1658  *         for succ in G.successors(n):
1659  *             if succ not in traversed:
1660  *                 # Case A: explore succ and update cur's loop entry
1661  *                 #         only if succ's entry is in current DFS path.
1662  *                 dfs(succ, depth + 1)
1663  *                 h = get_loop_entry(succ)
1664  *                 update_loop_entry(n, h)
1665  *             else:
1666  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1667  *                 update_loop_entry(n, succ)
1668  *         path.remove(n)
1669  *
1670  * To adapt this algorithm for use with verifier:
1671  * - use st->branch == 0 as a signal that DFS of succ had been finished
1672  *   and cur's loop entry has to be updated (case A), handle this in
1673  *   update_branch_counts();
1674  * - use st->branch > 0 as a signal that st is in the current DFS path;
1675  * - handle cases B and C in is_state_visited();
1676  * - update topmost loop entry for intermediate states in get_loop_entry().
1677  */
1678 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1679 {
1680 	struct bpf_verifier_state *topmost = st->loop_entry, *old;
1681 
1682 	while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1683 		topmost = topmost->loop_entry;
1684 	/* Update loop entries for intermediate states to avoid this
1685 	 * traversal in future get_loop_entry() calls.
1686 	 */
1687 	while (st && st->loop_entry != topmost) {
1688 		old = st->loop_entry;
1689 		st->loop_entry = topmost;
1690 		st = old;
1691 	}
1692 	return topmost;
1693 }
1694 
1695 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1696 {
1697 	struct bpf_verifier_state *cur1, *hdr1;
1698 
1699 	cur1 = get_loop_entry(cur) ?: cur;
1700 	hdr1 = get_loop_entry(hdr) ?: hdr;
1701 	/* The head1->branches check decides between cases B and C in
1702 	 * comment for get_loop_entry(). If hdr1->branches == 0 then
1703 	 * head's topmost loop entry is not in current DFS path,
1704 	 * hence 'cur' and 'hdr' are not in the same loop and there is
1705 	 * no need to update cur->loop_entry.
1706 	 */
1707 	if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1708 		cur->loop_entry = hdr;
1709 		hdr->used_as_loop_entry = true;
1710 	}
1711 }
1712 
1713 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1714 {
1715 	while (st) {
1716 		u32 br = --st->branches;
1717 
1718 		/* br == 0 signals that DFS exploration for 'st' is finished,
1719 		 * thus it is necessary to update parent's loop entry if it
1720 		 * turned out that st is a part of some loop.
1721 		 * This is a part of 'case A' in get_loop_entry() comment.
1722 		 */
1723 		if (br == 0 && st->parent && st->loop_entry)
1724 			update_loop_entry(st->parent, st->loop_entry);
1725 
1726 		/* WARN_ON(br > 1) technically makes sense here,
1727 		 * but see comment in push_stack(), hence:
1728 		 */
1729 		WARN_ONCE((int)br < 0,
1730 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1731 			  br);
1732 		if (br)
1733 			break;
1734 		st = st->parent;
1735 	}
1736 }
1737 
1738 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1739 		     int *insn_idx, bool pop_log)
1740 {
1741 	struct bpf_verifier_state *cur = env->cur_state;
1742 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1743 	int err;
1744 
1745 	if (env->head == NULL)
1746 		return -ENOENT;
1747 
1748 	if (cur) {
1749 		err = copy_verifier_state(cur, &head->st);
1750 		if (err)
1751 			return err;
1752 	}
1753 	if (pop_log)
1754 		bpf_vlog_reset(&env->log, head->log_pos);
1755 	if (insn_idx)
1756 		*insn_idx = head->insn_idx;
1757 	if (prev_insn_idx)
1758 		*prev_insn_idx = head->prev_insn_idx;
1759 	elem = head->next;
1760 	free_verifier_state(&head->st, false);
1761 	kfree(head);
1762 	env->head = elem;
1763 	env->stack_size--;
1764 	return 0;
1765 }
1766 
1767 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1768 					     int insn_idx, int prev_insn_idx,
1769 					     bool speculative)
1770 {
1771 	struct bpf_verifier_state *cur = env->cur_state;
1772 	struct bpf_verifier_stack_elem *elem;
1773 	int err;
1774 
1775 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1776 	if (!elem)
1777 		goto err;
1778 
1779 	elem->insn_idx = insn_idx;
1780 	elem->prev_insn_idx = prev_insn_idx;
1781 	elem->next = env->head;
1782 	elem->log_pos = env->log.end_pos;
1783 	env->head = elem;
1784 	env->stack_size++;
1785 	err = copy_verifier_state(&elem->st, cur);
1786 	if (err)
1787 		goto err;
1788 	elem->st.speculative |= speculative;
1789 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1790 		verbose(env, "The sequence of %d jumps is too complex.\n",
1791 			env->stack_size);
1792 		goto err;
1793 	}
1794 	if (elem->st.parent) {
1795 		++elem->st.parent->branches;
1796 		/* WARN_ON(branches > 2) technically makes sense here,
1797 		 * but
1798 		 * 1. speculative states will bump 'branches' for non-branch
1799 		 * instructions
1800 		 * 2. is_state_visited() heuristics may decide not to create
1801 		 * a new state for a sequence of branches and all such current
1802 		 * and cloned states will be pointing to a single parent state
1803 		 * which might have large 'branches' count.
1804 		 */
1805 	}
1806 	return &elem->st;
1807 err:
1808 	free_verifier_state(env->cur_state, true);
1809 	env->cur_state = NULL;
1810 	/* pop all elements and return */
1811 	while (!pop_stack(env, NULL, NULL, false));
1812 	return NULL;
1813 }
1814 
1815 #define CALLER_SAVED_REGS 6
1816 static const int caller_saved[CALLER_SAVED_REGS] = {
1817 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1818 };
1819 
1820 /* This helper doesn't clear reg->id */
1821 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1822 {
1823 	reg->var_off = tnum_const(imm);
1824 	reg->smin_value = (s64)imm;
1825 	reg->smax_value = (s64)imm;
1826 	reg->umin_value = imm;
1827 	reg->umax_value = imm;
1828 
1829 	reg->s32_min_value = (s32)imm;
1830 	reg->s32_max_value = (s32)imm;
1831 	reg->u32_min_value = (u32)imm;
1832 	reg->u32_max_value = (u32)imm;
1833 }
1834 
1835 /* Mark the unknown part of a register (variable offset or scalar value) as
1836  * known to have the value @imm.
1837  */
1838 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1839 {
1840 	/* Clear off and union(map_ptr, range) */
1841 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1842 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1843 	reg->id = 0;
1844 	reg->ref_obj_id = 0;
1845 	___mark_reg_known(reg, imm);
1846 }
1847 
1848 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1849 {
1850 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1851 	reg->s32_min_value = (s32)imm;
1852 	reg->s32_max_value = (s32)imm;
1853 	reg->u32_min_value = (u32)imm;
1854 	reg->u32_max_value = (u32)imm;
1855 }
1856 
1857 /* Mark the 'variable offset' part of a register as zero.  This should be
1858  * used only on registers holding a pointer type.
1859  */
1860 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1861 {
1862 	__mark_reg_known(reg, 0);
1863 }
1864 
1865 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1866 {
1867 	__mark_reg_known(reg, 0);
1868 	reg->type = SCALAR_VALUE;
1869 	/* all scalars are assumed imprecise initially (unless unprivileged,
1870 	 * in which case everything is forced to be precise)
1871 	 */
1872 	reg->precise = !env->bpf_capable;
1873 }
1874 
1875 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1876 				struct bpf_reg_state *regs, u32 regno)
1877 {
1878 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1879 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1880 		/* Something bad happened, let's kill all regs */
1881 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1882 			__mark_reg_not_init(env, regs + regno);
1883 		return;
1884 	}
1885 	__mark_reg_known_zero(regs + regno);
1886 }
1887 
1888 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1889 			      bool first_slot, int dynptr_id)
1890 {
1891 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1892 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1893 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1894 	 */
1895 	__mark_reg_known_zero(reg);
1896 	reg->type = CONST_PTR_TO_DYNPTR;
1897 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1898 	reg->id = dynptr_id;
1899 	reg->dynptr.type = type;
1900 	reg->dynptr.first_slot = first_slot;
1901 }
1902 
1903 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1904 {
1905 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1906 		const struct bpf_map *map = reg->map_ptr;
1907 
1908 		if (map->inner_map_meta) {
1909 			reg->type = CONST_PTR_TO_MAP;
1910 			reg->map_ptr = map->inner_map_meta;
1911 			/* transfer reg's id which is unique for every map_lookup_elem
1912 			 * as UID of the inner map.
1913 			 */
1914 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1915 				reg->map_uid = reg->id;
1916 			if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE))
1917 				reg->map_uid = reg->id;
1918 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1919 			reg->type = PTR_TO_XDP_SOCK;
1920 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1921 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1922 			reg->type = PTR_TO_SOCKET;
1923 		} else {
1924 			reg->type = PTR_TO_MAP_VALUE;
1925 		}
1926 		return;
1927 	}
1928 
1929 	reg->type &= ~PTR_MAYBE_NULL;
1930 }
1931 
1932 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1933 				struct btf_field_graph_root *ds_head)
1934 {
1935 	__mark_reg_known_zero(&regs[regno]);
1936 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1937 	regs[regno].btf = ds_head->btf;
1938 	regs[regno].btf_id = ds_head->value_btf_id;
1939 	regs[regno].off = ds_head->node_offset;
1940 }
1941 
1942 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1943 {
1944 	return type_is_pkt_pointer(reg->type);
1945 }
1946 
1947 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1948 {
1949 	return reg_is_pkt_pointer(reg) ||
1950 	       reg->type == PTR_TO_PACKET_END;
1951 }
1952 
1953 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1954 {
1955 	return base_type(reg->type) == PTR_TO_MEM &&
1956 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1957 }
1958 
1959 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1960 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1961 				    enum bpf_reg_type which)
1962 {
1963 	/* The register can already have a range from prior markings.
1964 	 * This is fine as long as it hasn't been advanced from its
1965 	 * origin.
1966 	 */
1967 	return reg->type == which &&
1968 	       reg->id == 0 &&
1969 	       reg->off == 0 &&
1970 	       tnum_equals_const(reg->var_off, 0);
1971 }
1972 
1973 /* Reset the min/max bounds of a register */
1974 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1975 {
1976 	reg->smin_value = S64_MIN;
1977 	reg->smax_value = S64_MAX;
1978 	reg->umin_value = 0;
1979 	reg->umax_value = U64_MAX;
1980 
1981 	reg->s32_min_value = S32_MIN;
1982 	reg->s32_max_value = S32_MAX;
1983 	reg->u32_min_value = 0;
1984 	reg->u32_max_value = U32_MAX;
1985 }
1986 
1987 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1988 {
1989 	reg->smin_value = S64_MIN;
1990 	reg->smax_value = S64_MAX;
1991 	reg->umin_value = 0;
1992 	reg->umax_value = U64_MAX;
1993 }
1994 
1995 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1996 {
1997 	reg->s32_min_value = S32_MIN;
1998 	reg->s32_max_value = S32_MAX;
1999 	reg->u32_min_value = 0;
2000 	reg->u32_max_value = U32_MAX;
2001 }
2002 
2003 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2004 {
2005 	struct tnum var32_off = tnum_subreg(reg->var_off);
2006 
2007 	/* min signed is max(sign bit) | min(other bits) */
2008 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2009 			var32_off.value | (var32_off.mask & S32_MIN));
2010 	/* max signed is min(sign bit) | max(other bits) */
2011 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2012 			var32_off.value | (var32_off.mask & S32_MAX));
2013 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2014 	reg->u32_max_value = min(reg->u32_max_value,
2015 				 (u32)(var32_off.value | var32_off.mask));
2016 }
2017 
2018 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2019 {
2020 	/* min signed is max(sign bit) | min(other bits) */
2021 	reg->smin_value = max_t(s64, reg->smin_value,
2022 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2023 	/* max signed is min(sign bit) | max(other bits) */
2024 	reg->smax_value = min_t(s64, reg->smax_value,
2025 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2026 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2027 	reg->umax_value = min(reg->umax_value,
2028 			      reg->var_off.value | reg->var_off.mask);
2029 }
2030 
2031 static void __update_reg_bounds(struct bpf_reg_state *reg)
2032 {
2033 	__update_reg32_bounds(reg);
2034 	__update_reg64_bounds(reg);
2035 }
2036 
2037 /* Uses signed min/max values to inform unsigned, and vice-versa */
2038 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2039 {
2040 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
2041 	 * bits to improve our u32/s32 boundaries.
2042 	 *
2043 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
2044 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
2045 	 * [10, 20] range. But this property holds for any 64-bit range as
2046 	 * long as upper 32 bits in that entire range of values stay the same.
2047 	 *
2048 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
2049 	 * in decimal) has the same upper 32 bits throughout all the values in
2050 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
2051 	 * range.
2052 	 *
2053 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
2054 	 * following the rules outlined below about u64/s64 correspondence
2055 	 * (which equally applies to u32 vs s32 correspondence). In general it
2056 	 * depends on actual hexadecimal values of 32-bit range. They can form
2057 	 * only valid u32, or only valid s32 ranges in some cases.
2058 	 *
2059 	 * So we use all these insights to derive bounds for subregisters here.
2060 	 */
2061 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
2062 		/* u64 to u32 casting preserves validity of low 32 bits as
2063 		 * a range, if upper 32 bits are the same
2064 		 */
2065 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
2066 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
2067 
2068 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
2069 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2070 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2071 		}
2072 	}
2073 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2074 		/* low 32 bits should form a proper u32 range */
2075 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2076 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2077 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2078 		}
2079 		/* low 32 bits should form a proper s32 range */
2080 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2081 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2082 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2083 		}
2084 	}
2085 	/* Special case where upper bits form a small sequence of two
2086 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2087 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
2088 	 * going from negative numbers to positive numbers. E.g., let's say we
2089 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2090 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2091 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2092 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2093 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2094 	 * upper 32 bits. As a random example, s64 range
2095 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2096 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2097 	 */
2098 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2099 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2100 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2101 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2102 	}
2103 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2104 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2105 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2106 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2107 	}
2108 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2109 	 * try to learn from that
2110 	 */
2111 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2112 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2113 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2114 	}
2115 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2116 	 * are the same, so combine.  This works even in the negative case, e.g.
2117 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2118 	 */
2119 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2120 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2121 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2122 	}
2123 }
2124 
2125 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2126 {
2127 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2128 	 * try to learn from that. Let's do a bit of ASCII art to see when
2129 	 * this is happening. Let's take u64 range first:
2130 	 *
2131 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2132 	 * |-------------------------------|--------------------------------|
2133 	 *
2134 	 * Valid u64 range is formed when umin and umax are anywhere in the
2135 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2136 	 * straightforward. Let's see how s64 range maps onto the same range
2137 	 * of values, annotated below the line for comparison:
2138 	 *
2139 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2140 	 * |-------------------------------|--------------------------------|
2141 	 * 0                        S64_MAX S64_MIN                        -1
2142 	 *
2143 	 * So s64 values basically start in the middle and they are logically
2144 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2145 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2146 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2147 	 * more visually as mapped to sign-agnostic range of hex values.
2148 	 *
2149 	 *  u64 start                                               u64 end
2150 	 *  _______________________________________________________________
2151 	 * /                                                               \
2152 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2153 	 * |-------------------------------|--------------------------------|
2154 	 * 0                        S64_MAX S64_MIN                        -1
2155 	 *                                / \
2156 	 * >------------------------------   ------------------------------->
2157 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2158 	 *
2159 	 * What this means is that, in general, we can't always derive
2160 	 * something new about u64 from any random s64 range, and vice versa.
2161 	 *
2162 	 * But we can do that in two particular cases. One is when entire
2163 	 * u64/s64 range is *entirely* contained within left half of the above
2164 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2165 	 *
2166 	 * |-------------------------------|--------------------------------|
2167 	 *     ^                   ^            ^                 ^
2168 	 *     A                   B            C                 D
2169 	 *
2170 	 * [A, B] and [C, D] are contained entirely in their respective halves
2171 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2172 	 * will be non-negative both as u64 and s64 (and in fact it will be
2173 	 * identical ranges no matter the signedness). [C, D] treated as s64
2174 	 * will be a range of negative values, while in u64 it will be
2175 	 * non-negative range of values larger than 0x8000000000000000.
2176 	 *
2177 	 * Now, any other range here can't be represented in both u64 and s64
2178 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2179 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2180 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2181 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2182 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2183 	 * ranges as u64. Currently reg_state can't represent two segments per
2184 	 * numeric domain, so in such situations we can only derive maximal
2185 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2186 	 *
2187 	 * So we use these facts to derive umin/umax from smin/smax and vice
2188 	 * versa only if they stay within the same "half". This is equivalent
2189 	 * to checking sign bit: lower half will have sign bit as zero, upper
2190 	 * half have sign bit 1. Below in code we simplify this by just
2191 	 * casting umin/umax as smin/smax and checking if they form valid
2192 	 * range, and vice versa. Those are equivalent checks.
2193 	 */
2194 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2195 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2196 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2197 	}
2198 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2199 	 * are the same, so combine.  This works even in the negative case, e.g.
2200 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2201 	 */
2202 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2203 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2204 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2205 	}
2206 }
2207 
2208 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2209 {
2210 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2211 	 * values on both sides of 64-bit range in hope to have tighter range.
2212 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2213 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2214 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2215 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2216 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2217 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2218 	 * We just need to make sure that derived bounds we are intersecting
2219 	 * with are well-formed ranges in respective s64 or u64 domain, just
2220 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2221 	 */
2222 	__u64 new_umin, new_umax;
2223 	__s64 new_smin, new_smax;
2224 
2225 	/* u32 -> u64 tightening, it's always well-formed */
2226 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2227 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2228 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2229 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2230 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2231 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2232 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2233 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2234 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2235 
2236 	/* if s32 can be treated as valid u32 range, we can use it as well */
2237 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2238 		/* s32 -> u64 tightening */
2239 		new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2240 		new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2241 		reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2242 		reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2243 		/* s32 -> s64 tightening */
2244 		new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2245 		new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2246 		reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2247 		reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2248 	}
2249 
2250 	/* Here we would like to handle a special case after sign extending load,
2251 	 * when upper bits for a 64-bit range are all 1s or all 0s.
2252 	 *
2253 	 * Upper bits are all 1s when register is in a range:
2254 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff]
2255 	 * Upper bits are all 0s when register is in a range:
2256 	 *   [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff]
2257 	 * Together this forms are continuous range:
2258 	 *   [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff]
2259 	 *
2260 	 * Now, suppose that register range is in fact tighter:
2261 	 *   [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R)
2262 	 * Also suppose that it's 32-bit range is positive,
2263 	 * meaning that lower 32-bits of the full 64-bit register
2264 	 * are in the range:
2265 	 *   [0x0000_0000, 0x7fff_ffff] (W)
2266 	 *
2267 	 * If this happens, then any value in a range:
2268 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff]
2269 	 * is smaller than a lowest bound of the range (R):
2270 	 *   0xffff_ffff_8000_0000
2271 	 * which means that upper bits of the full 64-bit register
2272 	 * can't be all 1s, when lower bits are in range (W).
2273 	 *
2274 	 * Note that:
2275 	 *  - 0xffff_ffff_8000_0000 == (s64)S32_MIN
2276 	 *  - 0x0000_0000_7fff_ffff == (s64)S32_MAX
2277 	 * These relations are used in the conditions below.
2278 	 */
2279 	if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) {
2280 		reg->smin_value = reg->s32_min_value;
2281 		reg->smax_value = reg->s32_max_value;
2282 		reg->umin_value = reg->s32_min_value;
2283 		reg->umax_value = reg->s32_max_value;
2284 		reg->var_off = tnum_intersect(reg->var_off,
2285 					      tnum_range(reg->smin_value, reg->smax_value));
2286 	}
2287 }
2288 
2289 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2290 {
2291 	__reg32_deduce_bounds(reg);
2292 	__reg64_deduce_bounds(reg);
2293 	__reg_deduce_mixed_bounds(reg);
2294 }
2295 
2296 /* Attempts to improve var_off based on unsigned min/max information */
2297 static void __reg_bound_offset(struct bpf_reg_state *reg)
2298 {
2299 	struct tnum var64_off = tnum_intersect(reg->var_off,
2300 					       tnum_range(reg->umin_value,
2301 							  reg->umax_value));
2302 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2303 					       tnum_range(reg->u32_min_value,
2304 							  reg->u32_max_value));
2305 
2306 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2307 }
2308 
2309 static void reg_bounds_sync(struct bpf_reg_state *reg)
2310 {
2311 	/* We might have learned new bounds from the var_off. */
2312 	__update_reg_bounds(reg);
2313 	/* We might have learned something about the sign bit. */
2314 	__reg_deduce_bounds(reg);
2315 	__reg_deduce_bounds(reg);
2316 	/* We might have learned some bits from the bounds. */
2317 	__reg_bound_offset(reg);
2318 	/* Intersecting with the old var_off might have improved our bounds
2319 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2320 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2321 	 */
2322 	__update_reg_bounds(reg);
2323 }
2324 
2325 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2326 				   struct bpf_reg_state *reg, const char *ctx)
2327 {
2328 	const char *msg;
2329 
2330 	if (reg->umin_value > reg->umax_value ||
2331 	    reg->smin_value > reg->smax_value ||
2332 	    reg->u32_min_value > reg->u32_max_value ||
2333 	    reg->s32_min_value > reg->s32_max_value) {
2334 		    msg = "range bounds violation";
2335 		    goto out;
2336 	}
2337 
2338 	if (tnum_is_const(reg->var_off)) {
2339 		u64 uval = reg->var_off.value;
2340 		s64 sval = (s64)uval;
2341 
2342 		if (reg->umin_value != uval || reg->umax_value != uval ||
2343 		    reg->smin_value != sval || reg->smax_value != sval) {
2344 			msg = "const tnum out of sync with range bounds";
2345 			goto out;
2346 		}
2347 	}
2348 
2349 	if (tnum_subreg_is_const(reg->var_off)) {
2350 		u32 uval32 = tnum_subreg(reg->var_off).value;
2351 		s32 sval32 = (s32)uval32;
2352 
2353 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2354 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2355 			msg = "const subreg tnum out of sync with range bounds";
2356 			goto out;
2357 		}
2358 	}
2359 
2360 	return 0;
2361 out:
2362 	verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2363 		"s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n",
2364 		ctx, msg, reg->umin_value, reg->umax_value,
2365 		reg->smin_value, reg->smax_value,
2366 		reg->u32_min_value, reg->u32_max_value,
2367 		reg->s32_min_value, reg->s32_max_value,
2368 		reg->var_off.value, reg->var_off.mask);
2369 	if (env->test_reg_invariants)
2370 		return -EFAULT;
2371 	__mark_reg_unbounded(reg);
2372 	return 0;
2373 }
2374 
2375 static bool __reg32_bound_s64(s32 a)
2376 {
2377 	return a >= 0 && a <= S32_MAX;
2378 }
2379 
2380 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2381 {
2382 	reg->umin_value = reg->u32_min_value;
2383 	reg->umax_value = reg->u32_max_value;
2384 
2385 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2386 	 * be positive otherwise set to worse case bounds and refine later
2387 	 * from tnum.
2388 	 */
2389 	if (__reg32_bound_s64(reg->s32_min_value) &&
2390 	    __reg32_bound_s64(reg->s32_max_value)) {
2391 		reg->smin_value = reg->s32_min_value;
2392 		reg->smax_value = reg->s32_max_value;
2393 	} else {
2394 		reg->smin_value = 0;
2395 		reg->smax_value = U32_MAX;
2396 	}
2397 }
2398 
2399 /* Mark a register as having a completely unknown (scalar) value. */
2400 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2401 {
2402 	/*
2403 	 * Clear type, off, and union(map_ptr, range) and
2404 	 * padding between 'type' and union
2405 	 */
2406 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2407 	reg->type = SCALAR_VALUE;
2408 	reg->id = 0;
2409 	reg->ref_obj_id = 0;
2410 	reg->var_off = tnum_unknown;
2411 	reg->frameno = 0;
2412 	reg->precise = false;
2413 	__mark_reg_unbounded(reg);
2414 }
2415 
2416 /* Mark a register as having a completely unknown (scalar) value,
2417  * initialize .precise as true when not bpf capable.
2418  */
2419 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2420 			       struct bpf_reg_state *reg)
2421 {
2422 	__mark_reg_unknown_imprecise(reg);
2423 	reg->precise = !env->bpf_capable;
2424 }
2425 
2426 static void mark_reg_unknown(struct bpf_verifier_env *env,
2427 			     struct bpf_reg_state *regs, u32 regno)
2428 {
2429 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2430 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2431 		/* Something bad happened, let's kill all regs except FP */
2432 		for (regno = 0; regno < BPF_REG_FP; regno++)
2433 			__mark_reg_not_init(env, regs + regno);
2434 		return;
2435 	}
2436 	__mark_reg_unknown(env, regs + regno);
2437 }
2438 
2439 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2440 				struct bpf_reg_state *regs,
2441 				u32 regno,
2442 				s32 s32_min,
2443 				s32 s32_max)
2444 {
2445 	struct bpf_reg_state *reg = regs + regno;
2446 
2447 	reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min);
2448 	reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max);
2449 
2450 	reg->smin_value = max_t(s64, reg->smin_value, s32_min);
2451 	reg->smax_value = min_t(s64, reg->smax_value, s32_max);
2452 
2453 	reg_bounds_sync(reg);
2454 
2455 	return reg_bounds_sanity_check(env, reg, "s32_range");
2456 }
2457 
2458 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2459 				struct bpf_reg_state *reg)
2460 {
2461 	__mark_reg_unknown(env, reg);
2462 	reg->type = NOT_INIT;
2463 }
2464 
2465 static void mark_reg_not_init(struct bpf_verifier_env *env,
2466 			      struct bpf_reg_state *regs, u32 regno)
2467 {
2468 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2469 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2470 		/* Something bad happened, let's kill all regs except FP */
2471 		for (regno = 0; regno < BPF_REG_FP; regno++)
2472 			__mark_reg_not_init(env, regs + regno);
2473 		return;
2474 	}
2475 	__mark_reg_not_init(env, regs + regno);
2476 }
2477 
2478 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2479 			    struct bpf_reg_state *regs, u32 regno,
2480 			    enum bpf_reg_type reg_type,
2481 			    struct btf *btf, u32 btf_id,
2482 			    enum bpf_type_flag flag)
2483 {
2484 	if (reg_type == SCALAR_VALUE) {
2485 		mark_reg_unknown(env, regs, regno);
2486 		return;
2487 	}
2488 	mark_reg_known_zero(env, regs, regno);
2489 	regs[regno].type = PTR_TO_BTF_ID | flag;
2490 	regs[regno].btf = btf;
2491 	regs[regno].btf_id = btf_id;
2492 	if (type_may_be_null(flag))
2493 		regs[regno].id = ++env->id_gen;
2494 }
2495 
2496 #define DEF_NOT_SUBREG	(0)
2497 static void init_reg_state(struct bpf_verifier_env *env,
2498 			   struct bpf_func_state *state)
2499 {
2500 	struct bpf_reg_state *regs = state->regs;
2501 	int i;
2502 
2503 	for (i = 0; i < MAX_BPF_REG; i++) {
2504 		mark_reg_not_init(env, regs, i);
2505 		regs[i].live = REG_LIVE_NONE;
2506 		regs[i].parent = NULL;
2507 		regs[i].subreg_def = DEF_NOT_SUBREG;
2508 	}
2509 
2510 	/* frame pointer */
2511 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2512 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2513 	regs[BPF_REG_FP].frameno = state->frameno;
2514 }
2515 
2516 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2517 {
2518 	return (struct bpf_retval_range){ minval, maxval };
2519 }
2520 
2521 #define BPF_MAIN_FUNC (-1)
2522 static void init_func_state(struct bpf_verifier_env *env,
2523 			    struct bpf_func_state *state,
2524 			    int callsite, int frameno, int subprogno)
2525 {
2526 	state->callsite = callsite;
2527 	state->frameno = frameno;
2528 	state->subprogno = subprogno;
2529 	state->callback_ret_range = retval_range(0, 0);
2530 	init_reg_state(env, state);
2531 	mark_verifier_state_scratched(env);
2532 }
2533 
2534 /* Similar to push_stack(), but for async callbacks */
2535 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2536 						int insn_idx, int prev_insn_idx,
2537 						int subprog, bool is_sleepable)
2538 {
2539 	struct bpf_verifier_stack_elem *elem;
2540 	struct bpf_func_state *frame;
2541 
2542 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2543 	if (!elem)
2544 		goto err;
2545 
2546 	elem->insn_idx = insn_idx;
2547 	elem->prev_insn_idx = prev_insn_idx;
2548 	elem->next = env->head;
2549 	elem->log_pos = env->log.end_pos;
2550 	env->head = elem;
2551 	env->stack_size++;
2552 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2553 		verbose(env,
2554 			"The sequence of %d jumps is too complex for async cb.\n",
2555 			env->stack_size);
2556 		goto err;
2557 	}
2558 	/* Unlike push_stack() do not copy_verifier_state().
2559 	 * The caller state doesn't matter.
2560 	 * This is async callback. It starts in a fresh stack.
2561 	 * Initialize it similar to do_check_common().
2562 	 * But we do need to make sure to not clobber insn_hist, so we keep
2563 	 * chaining insn_hist_start/insn_hist_end indices as for a normal
2564 	 * child state.
2565 	 */
2566 	elem->st.branches = 1;
2567 	elem->st.in_sleepable = is_sleepable;
2568 	elem->st.insn_hist_start = env->cur_state->insn_hist_end;
2569 	elem->st.insn_hist_end = elem->st.insn_hist_start;
2570 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2571 	if (!frame)
2572 		goto err;
2573 	init_func_state(env, frame,
2574 			BPF_MAIN_FUNC /* callsite */,
2575 			0 /* frameno within this callchain */,
2576 			subprog /* subprog number within this prog */);
2577 	elem->st.frame[0] = frame;
2578 	return &elem->st;
2579 err:
2580 	free_verifier_state(env->cur_state, true);
2581 	env->cur_state = NULL;
2582 	/* pop all elements and return */
2583 	while (!pop_stack(env, NULL, NULL, false));
2584 	return NULL;
2585 }
2586 
2587 
2588 enum reg_arg_type {
2589 	SRC_OP,		/* register is used as source operand */
2590 	DST_OP,		/* register is used as destination operand */
2591 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2592 };
2593 
2594 static int cmp_subprogs(const void *a, const void *b)
2595 {
2596 	return ((struct bpf_subprog_info *)a)->start -
2597 	       ((struct bpf_subprog_info *)b)->start;
2598 }
2599 
2600 static int find_subprog(struct bpf_verifier_env *env, int off)
2601 {
2602 	struct bpf_subprog_info *p;
2603 
2604 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2605 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2606 	if (!p)
2607 		return -ENOENT;
2608 	return p - env->subprog_info;
2609 
2610 }
2611 
2612 static int add_subprog(struct bpf_verifier_env *env, int off)
2613 {
2614 	int insn_cnt = env->prog->len;
2615 	int ret;
2616 
2617 	if (off >= insn_cnt || off < 0) {
2618 		verbose(env, "call to invalid destination\n");
2619 		return -EINVAL;
2620 	}
2621 	ret = find_subprog(env, off);
2622 	if (ret >= 0)
2623 		return ret;
2624 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2625 		verbose(env, "too many subprograms\n");
2626 		return -E2BIG;
2627 	}
2628 	/* determine subprog starts. The end is one before the next starts */
2629 	env->subprog_info[env->subprog_cnt++].start = off;
2630 	sort(env->subprog_info, env->subprog_cnt,
2631 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2632 	return env->subprog_cnt - 1;
2633 }
2634 
2635 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2636 {
2637 	struct bpf_prog_aux *aux = env->prog->aux;
2638 	struct btf *btf = aux->btf;
2639 	const struct btf_type *t;
2640 	u32 main_btf_id, id;
2641 	const char *name;
2642 	int ret, i;
2643 
2644 	/* Non-zero func_info_cnt implies valid btf */
2645 	if (!aux->func_info_cnt)
2646 		return 0;
2647 	main_btf_id = aux->func_info[0].type_id;
2648 
2649 	t = btf_type_by_id(btf, main_btf_id);
2650 	if (!t) {
2651 		verbose(env, "invalid btf id for main subprog in func_info\n");
2652 		return -EINVAL;
2653 	}
2654 
2655 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2656 	if (IS_ERR(name)) {
2657 		ret = PTR_ERR(name);
2658 		/* If there is no tag present, there is no exception callback */
2659 		if (ret == -ENOENT)
2660 			ret = 0;
2661 		else if (ret == -EEXIST)
2662 			verbose(env, "multiple exception callback tags for main subprog\n");
2663 		return ret;
2664 	}
2665 
2666 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2667 	if (ret < 0) {
2668 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2669 		return ret;
2670 	}
2671 	id = ret;
2672 	t = btf_type_by_id(btf, id);
2673 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2674 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2675 		return -EINVAL;
2676 	}
2677 	ret = 0;
2678 	for (i = 0; i < aux->func_info_cnt; i++) {
2679 		if (aux->func_info[i].type_id != id)
2680 			continue;
2681 		ret = aux->func_info[i].insn_off;
2682 		/* Further func_info and subprog checks will also happen
2683 		 * later, so assume this is the right insn_off for now.
2684 		 */
2685 		if (!ret) {
2686 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2687 			ret = -EINVAL;
2688 		}
2689 	}
2690 	if (!ret) {
2691 		verbose(env, "exception callback type id not found in func_info\n");
2692 		ret = -EINVAL;
2693 	}
2694 	return ret;
2695 }
2696 
2697 #define MAX_KFUNC_DESCS 256
2698 #define MAX_KFUNC_BTFS	256
2699 
2700 struct bpf_kfunc_desc {
2701 	struct btf_func_model func_model;
2702 	u32 func_id;
2703 	s32 imm;
2704 	u16 offset;
2705 	unsigned long addr;
2706 };
2707 
2708 struct bpf_kfunc_btf {
2709 	struct btf *btf;
2710 	struct module *module;
2711 	u16 offset;
2712 };
2713 
2714 struct bpf_kfunc_desc_tab {
2715 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2716 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2717 	 * available, therefore at the end of verification do_misc_fixups()
2718 	 * sorts this by imm and offset.
2719 	 */
2720 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2721 	u32 nr_descs;
2722 };
2723 
2724 struct bpf_kfunc_btf_tab {
2725 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2726 	u32 nr_descs;
2727 };
2728 
2729 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2730 {
2731 	const struct bpf_kfunc_desc *d0 = a;
2732 	const struct bpf_kfunc_desc *d1 = b;
2733 
2734 	/* func_id is not greater than BTF_MAX_TYPE */
2735 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2736 }
2737 
2738 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2739 {
2740 	const struct bpf_kfunc_btf *d0 = a;
2741 	const struct bpf_kfunc_btf *d1 = b;
2742 
2743 	return d0->offset - d1->offset;
2744 }
2745 
2746 static const struct bpf_kfunc_desc *
2747 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2748 {
2749 	struct bpf_kfunc_desc desc = {
2750 		.func_id = func_id,
2751 		.offset = offset,
2752 	};
2753 	struct bpf_kfunc_desc_tab *tab;
2754 
2755 	tab = prog->aux->kfunc_tab;
2756 	return bsearch(&desc, tab->descs, tab->nr_descs,
2757 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2758 }
2759 
2760 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2761 		       u16 btf_fd_idx, u8 **func_addr)
2762 {
2763 	const struct bpf_kfunc_desc *desc;
2764 
2765 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2766 	if (!desc)
2767 		return -EFAULT;
2768 
2769 	*func_addr = (u8 *)desc->addr;
2770 	return 0;
2771 }
2772 
2773 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2774 					 s16 offset)
2775 {
2776 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2777 	struct bpf_kfunc_btf_tab *tab;
2778 	struct bpf_kfunc_btf *b;
2779 	struct module *mod;
2780 	struct btf *btf;
2781 	int btf_fd;
2782 
2783 	tab = env->prog->aux->kfunc_btf_tab;
2784 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2785 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2786 	if (!b) {
2787 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2788 			verbose(env, "too many different module BTFs\n");
2789 			return ERR_PTR(-E2BIG);
2790 		}
2791 
2792 		if (bpfptr_is_null(env->fd_array)) {
2793 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2794 			return ERR_PTR(-EPROTO);
2795 		}
2796 
2797 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2798 					    offset * sizeof(btf_fd),
2799 					    sizeof(btf_fd)))
2800 			return ERR_PTR(-EFAULT);
2801 
2802 		btf = btf_get_by_fd(btf_fd);
2803 		if (IS_ERR(btf)) {
2804 			verbose(env, "invalid module BTF fd specified\n");
2805 			return btf;
2806 		}
2807 
2808 		if (!btf_is_module(btf)) {
2809 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2810 			btf_put(btf);
2811 			return ERR_PTR(-EINVAL);
2812 		}
2813 
2814 		mod = btf_try_get_module(btf);
2815 		if (!mod) {
2816 			btf_put(btf);
2817 			return ERR_PTR(-ENXIO);
2818 		}
2819 
2820 		b = &tab->descs[tab->nr_descs++];
2821 		b->btf = btf;
2822 		b->module = mod;
2823 		b->offset = offset;
2824 
2825 		/* sort() reorders entries by value, so b may no longer point
2826 		 * to the right entry after this
2827 		 */
2828 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2829 		     kfunc_btf_cmp_by_off, NULL);
2830 	} else {
2831 		btf = b->btf;
2832 	}
2833 
2834 	return btf;
2835 }
2836 
2837 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2838 {
2839 	if (!tab)
2840 		return;
2841 
2842 	while (tab->nr_descs--) {
2843 		module_put(tab->descs[tab->nr_descs].module);
2844 		btf_put(tab->descs[tab->nr_descs].btf);
2845 	}
2846 	kfree(tab);
2847 }
2848 
2849 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2850 {
2851 	if (offset) {
2852 		if (offset < 0) {
2853 			/* In the future, this can be allowed to increase limit
2854 			 * of fd index into fd_array, interpreted as u16.
2855 			 */
2856 			verbose(env, "negative offset disallowed for kernel module function call\n");
2857 			return ERR_PTR(-EINVAL);
2858 		}
2859 
2860 		return __find_kfunc_desc_btf(env, offset);
2861 	}
2862 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2863 }
2864 
2865 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2866 {
2867 	const struct btf_type *func, *func_proto;
2868 	struct bpf_kfunc_btf_tab *btf_tab;
2869 	struct bpf_kfunc_desc_tab *tab;
2870 	struct bpf_prog_aux *prog_aux;
2871 	struct bpf_kfunc_desc *desc;
2872 	const char *func_name;
2873 	struct btf *desc_btf;
2874 	unsigned long call_imm;
2875 	unsigned long addr;
2876 	int err;
2877 
2878 	prog_aux = env->prog->aux;
2879 	tab = prog_aux->kfunc_tab;
2880 	btf_tab = prog_aux->kfunc_btf_tab;
2881 	if (!tab) {
2882 		if (!btf_vmlinux) {
2883 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2884 			return -ENOTSUPP;
2885 		}
2886 
2887 		if (!env->prog->jit_requested) {
2888 			verbose(env, "JIT is required for calling kernel function\n");
2889 			return -ENOTSUPP;
2890 		}
2891 
2892 		if (!bpf_jit_supports_kfunc_call()) {
2893 			verbose(env, "JIT does not support calling kernel function\n");
2894 			return -ENOTSUPP;
2895 		}
2896 
2897 		if (!env->prog->gpl_compatible) {
2898 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2899 			return -EINVAL;
2900 		}
2901 
2902 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2903 		if (!tab)
2904 			return -ENOMEM;
2905 		prog_aux->kfunc_tab = tab;
2906 	}
2907 
2908 	/* func_id == 0 is always invalid, but instead of returning an error, be
2909 	 * conservative and wait until the code elimination pass before returning
2910 	 * error, so that invalid calls that get pruned out can be in BPF programs
2911 	 * loaded from userspace.  It is also required that offset be untouched
2912 	 * for such calls.
2913 	 */
2914 	if (!func_id && !offset)
2915 		return 0;
2916 
2917 	if (!btf_tab && offset) {
2918 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2919 		if (!btf_tab)
2920 			return -ENOMEM;
2921 		prog_aux->kfunc_btf_tab = btf_tab;
2922 	}
2923 
2924 	desc_btf = find_kfunc_desc_btf(env, offset);
2925 	if (IS_ERR(desc_btf)) {
2926 		verbose(env, "failed to find BTF for kernel function\n");
2927 		return PTR_ERR(desc_btf);
2928 	}
2929 
2930 	if (find_kfunc_desc(env->prog, func_id, offset))
2931 		return 0;
2932 
2933 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2934 		verbose(env, "too many different kernel function calls\n");
2935 		return -E2BIG;
2936 	}
2937 
2938 	func = btf_type_by_id(desc_btf, func_id);
2939 	if (!func || !btf_type_is_func(func)) {
2940 		verbose(env, "kernel btf_id %u is not a function\n",
2941 			func_id);
2942 		return -EINVAL;
2943 	}
2944 	func_proto = btf_type_by_id(desc_btf, func->type);
2945 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2946 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2947 			func_id);
2948 		return -EINVAL;
2949 	}
2950 
2951 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2952 	addr = kallsyms_lookup_name(func_name);
2953 	if (!addr) {
2954 		verbose(env, "cannot find address for kernel function %s\n",
2955 			func_name);
2956 		return -EINVAL;
2957 	}
2958 	specialize_kfunc(env, func_id, offset, &addr);
2959 
2960 	if (bpf_jit_supports_far_kfunc_call()) {
2961 		call_imm = func_id;
2962 	} else {
2963 		call_imm = BPF_CALL_IMM(addr);
2964 		/* Check whether the relative offset overflows desc->imm */
2965 		if ((unsigned long)(s32)call_imm != call_imm) {
2966 			verbose(env, "address of kernel function %s is out of range\n",
2967 				func_name);
2968 			return -EINVAL;
2969 		}
2970 	}
2971 
2972 	if (bpf_dev_bound_kfunc_id(func_id)) {
2973 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2974 		if (err)
2975 			return err;
2976 	}
2977 
2978 	desc = &tab->descs[tab->nr_descs++];
2979 	desc->func_id = func_id;
2980 	desc->imm = call_imm;
2981 	desc->offset = offset;
2982 	desc->addr = addr;
2983 	err = btf_distill_func_proto(&env->log, desc_btf,
2984 				     func_proto, func_name,
2985 				     &desc->func_model);
2986 	if (!err)
2987 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2988 		     kfunc_desc_cmp_by_id_off, NULL);
2989 	return err;
2990 }
2991 
2992 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2993 {
2994 	const struct bpf_kfunc_desc *d0 = a;
2995 	const struct bpf_kfunc_desc *d1 = b;
2996 
2997 	if (d0->imm != d1->imm)
2998 		return d0->imm < d1->imm ? -1 : 1;
2999 	if (d0->offset != d1->offset)
3000 		return d0->offset < d1->offset ? -1 : 1;
3001 	return 0;
3002 }
3003 
3004 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
3005 {
3006 	struct bpf_kfunc_desc_tab *tab;
3007 
3008 	tab = prog->aux->kfunc_tab;
3009 	if (!tab)
3010 		return;
3011 
3012 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3013 	     kfunc_desc_cmp_by_imm_off, NULL);
3014 }
3015 
3016 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
3017 {
3018 	return !!prog->aux->kfunc_tab;
3019 }
3020 
3021 const struct btf_func_model *
3022 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3023 			 const struct bpf_insn *insn)
3024 {
3025 	const struct bpf_kfunc_desc desc = {
3026 		.imm = insn->imm,
3027 		.offset = insn->off,
3028 	};
3029 	const struct bpf_kfunc_desc *res;
3030 	struct bpf_kfunc_desc_tab *tab;
3031 
3032 	tab = prog->aux->kfunc_tab;
3033 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3034 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3035 
3036 	return res ? &res->func_model : NULL;
3037 }
3038 
3039 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3040 {
3041 	struct bpf_subprog_info *subprog = env->subprog_info;
3042 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3043 	struct bpf_insn *insn = env->prog->insnsi;
3044 
3045 	/* Add entry function. */
3046 	ret = add_subprog(env, 0);
3047 	if (ret)
3048 		return ret;
3049 
3050 	for (i = 0; i < insn_cnt; i++, insn++) {
3051 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3052 		    !bpf_pseudo_kfunc_call(insn))
3053 			continue;
3054 
3055 		if (!env->bpf_capable) {
3056 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3057 			return -EPERM;
3058 		}
3059 
3060 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3061 			ret = add_subprog(env, i + insn->imm + 1);
3062 		else
3063 			ret = add_kfunc_call(env, insn->imm, insn->off);
3064 
3065 		if (ret < 0)
3066 			return ret;
3067 	}
3068 
3069 	ret = bpf_find_exception_callback_insn_off(env);
3070 	if (ret < 0)
3071 		return ret;
3072 	ex_cb_insn = ret;
3073 
3074 	/* If ex_cb_insn > 0, this means that the main program has a subprog
3075 	 * marked using BTF decl tag to serve as the exception callback.
3076 	 */
3077 	if (ex_cb_insn) {
3078 		ret = add_subprog(env, ex_cb_insn);
3079 		if (ret < 0)
3080 			return ret;
3081 		for (i = 1; i < env->subprog_cnt; i++) {
3082 			if (env->subprog_info[i].start != ex_cb_insn)
3083 				continue;
3084 			env->exception_callback_subprog = i;
3085 			mark_subprog_exc_cb(env, i);
3086 			break;
3087 		}
3088 	}
3089 
3090 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3091 	 * logic. 'subprog_cnt' should not be increased.
3092 	 */
3093 	subprog[env->subprog_cnt].start = insn_cnt;
3094 
3095 	if (env->log.level & BPF_LOG_LEVEL2)
3096 		for (i = 0; i < env->subprog_cnt; i++)
3097 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3098 
3099 	return 0;
3100 }
3101 
3102 static int check_subprogs(struct bpf_verifier_env *env)
3103 {
3104 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3105 	struct bpf_subprog_info *subprog = env->subprog_info;
3106 	struct bpf_insn *insn = env->prog->insnsi;
3107 	int insn_cnt = env->prog->len;
3108 
3109 	/* now check that all jumps are within the same subprog */
3110 	subprog_start = subprog[cur_subprog].start;
3111 	subprog_end = subprog[cur_subprog + 1].start;
3112 	for (i = 0; i < insn_cnt; i++) {
3113 		u8 code = insn[i].code;
3114 
3115 		if (code == (BPF_JMP | BPF_CALL) &&
3116 		    insn[i].src_reg == 0 &&
3117 		    insn[i].imm == BPF_FUNC_tail_call) {
3118 			subprog[cur_subprog].has_tail_call = true;
3119 			subprog[cur_subprog].tail_call_reachable = true;
3120 		}
3121 		if (BPF_CLASS(code) == BPF_LD &&
3122 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3123 			subprog[cur_subprog].has_ld_abs = true;
3124 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3125 			goto next;
3126 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3127 			goto next;
3128 		if (code == (BPF_JMP32 | BPF_JA))
3129 			off = i + insn[i].imm + 1;
3130 		else
3131 			off = i + insn[i].off + 1;
3132 		if (off < subprog_start || off >= subprog_end) {
3133 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3134 			return -EINVAL;
3135 		}
3136 next:
3137 		if (i == subprog_end - 1) {
3138 			/* to avoid fall-through from one subprog into another
3139 			 * the last insn of the subprog should be either exit
3140 			 * or unconditional jump back or bpf_throw call
3141 			 */
3142 			if (code != (BPF_JMP | BPF_EXIT) &&
3143 			    code != (BPF_JMP32 | BPF_JA) &&
3144 			    code != (BPF_JMP | BPF_JA)) {
3145 				verbose(env, "last insn is not an exit or jmp\n");
3146 				return -EINVAL;
3147 			}
3148 			subprog_start = subprog_end;
3149 			cur_subprog++;
3150 			if (cur_subprog < env->subprog_cnt)
3151 				subprog_end = subprog[cur_subprog + 1].start;
3152 		}
3153 	}
3154 	return 0;
3155 }
3156 
3157 /* Parentage chain of this register (or stack slot) should take care of all
3158  * issues like callee-saved registers, stack slot allocation time, etc.
3159  */
3160 static int mark_reg_read(struct bpf_verifier_env *env,
3161 			 const struct bpf_reg_state *state,
3162 			 struct bpf_reg_state *parent, u8 flag)
3163 {
3164 	bool writes = parent == state->parent; /* Observe write marks */
3165 	int cnt = 0;
3166 
3167 	while (parent) {
3168 		/* if read wasn't screened by an earlier write ... */
3169 		if (writes && state->live & REG_LIVE_WRITTEN)
3170 			break;
3171 		if (parent->live & REG_LIVE_DONE) {
3172 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3173 				reg_type_str(env, parent->type),
3174 				parent->var_off.value, parent->off);
3175 			return -EFAULT;
3176 		}
3177 		/* The first condition is more likely to be true than the
3178 		 * second, checked it first.
3179 		 */
3180 		if ((parent->live & REG_LIVE_READ) == flag ||
3181 		    parent->live & REG_LIVE_READ64)
3182 			/* The parentage chain never changes and
3183 			 * this parent was already marked as LIVE_READ.
3184 			 * There is no need to keep walking the chain again and
3185 			 * keep re-marking all parents as LIVE_READ.
3186 			 * This case happens when the same register is read
3187 			 * multiple times without writes into it in-between.
3188 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3189 			 * then no need to set the weak REG_LIVE_READ32.
3190 			 */
3191 			break;
3192 		/* ... then we depend on parent's value */
3193 		parent->live |= flag;
3194 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3195 		if (flag == REG_LIVE_READ64)
3196 			parent->live &= ~REG_LIVE_READ32;
3197 		state = parent;
3198 		parent = state->parent;
3199 		writes = true;
3200 		cnt++;
3201 	}
3202 
3203 	if (env->longest_mark_read_walk < cnt)
3204 		env->longest_mark_read_walk = cnt;
3205 	return 0;
3206 }
3207 
3208 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3209 {
3210 	struct bpf_func_state *state = func(env, reg);
3211 	int spi, ret;
3212 
3213 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3214 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3215 	 * check_kfunc_call.
3216 	 */
3217 	if (reg->type == CONST_PTR_TO_DYNPTR)
3218 		return 0;
3219 	spi = dynptr_get_spi(env, reg);
3220 	if (spi < 0)
3221 		return spi;
3222 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3223 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3224 	 * read.
3225 	 */
3226 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3227 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3228 	if (ret)
3229 		return ret;
3230 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3231 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3232 }
3233 
3234 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3235 			  int spi, int nr_slots)
3236 {
3237 	struct bpf_func_state *state = func(env, reg);
3238 	int err, i;
3239 
3240 	for (i = 0; i < nr_slots; i++) {
3241 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3242 
3243 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3244 		if (err)
3245 			return err;
3246 
3247 		mark_stack_slot_scratched(env, spi - i);
3248 	}
3249 
3250 	return 0;
3251 }
3252 
3253 /* This function is supposed to be used by the following 32-bit optimization
3254  * code only. It returns TRUE if the source or destination register operates
3255  * on 64-bit, otherwise return FALSE.
3256  */
3257 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3258 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3259 {
3260 	u8 code, class, op;
3261 
3262 	code = insn->code;
3263 	class = BPF_CLASS(code);
3264 	op = BPF_OP(code);
3265 	if (class == BPF_JMP) {
3266 		/* BPF_EXIT for "main" will reach here. Return TRUE
3267 		 * conservatively.
3268 		 */
3269 		if (op == BPF_EXIT)
3270 			return true;
3271 		if (op == BPF_CALL) {
3272 			/* BPF to BPF call will reach here because of marking
3273 			 * caller saved clobber with DST_OP_NO_MARK for which we
3274 			 * don't care the register def because they are anyway
3275 			 * marked as NOT_INIT already.
3276 			 */
3277 			if (insn->src_reg == BPF_PSEUDO_CALL)
3278 				return false;
3279 			/* Helper call will reach here because of arg type
3280 			 * check, conservatively return TRUE.
3281 			 */
3282 			if (t == SRC_OP)
3283 				return true;
3284 
3285 			return false;
3286 		}
3287 	}
3288 
3289 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3290 		return false;
3291 
3292 	if (class == BPF_ALU64 || class == BPF_JMP ||
3293 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3294 		return true;
3295 
3296 	if (class == BPF_ALU || class == BPF_JMP32)
3297 		return false;
3298 
3299 	if (class == BPF_LDX) {
3300 		if (t != SRC_OP)
3301 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3302 		/* LDX source must be ptr. */
3303 		return true;
3304 	}
3305 
3306 	if (class == BPF_STX) {
3307 		/* BPF_STX (including atomic variants) has multiple source
3308 		 * operands, one of which is a ptr. Check whether the caller is
3309 		 * asking about it.
3310 		 */
3311 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3312 			return true;
3313 		return BPF_SIZE(code) == BPF_DW;
3314 	}
3315 
3316 	if (class == BPF_LD) {
3317 		u8 mode = BPF_MODE(code);
3318 
3319 		/* LD_IMM64 */
3320 		if (mode == BPF_IMM)
3321 			return true;
3322 
3323 		/* Both LD_IND and LD_ABS return 32-bit data. */
3324 		if (t != SRC_OP)
3325 			return  false;
3326 
3327 		/* Implicit ctx ptr. */
3328 		if (regno == BPF_REG_6)
3329 			return true;
3330 
3331 		/* Explicit source could be any width. */
3332 		return true;
3333 	}
3334 
3335 	if (class == BPF_ST)
3336 		/* The only source register for BPF_ST is a ptr. */
3337 		return true;
3338 
3339 	/* Conservatively return true at default. */
3340 	return true;
3341 }
3342 
3343 /* Return the regno defined by the insn, or -1. */
3344 static int insn_def_regno(const struct bpf_insn *insn)
3345 {
3346 	switch (BPF_CLASS(insn->code)) {
3347 	case BPF_JMP:
3348 	case BPF_JMP32:
3349 	case BPF_ST:
3350 		return -1;
3351 	case BPF_STX:
3352 		if ((BPF_MODE(insn->code) == BPF_ATOMIC ||
3353 		     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) &&
3354 		    (insn->imm & BPF_FETCH)) {
3355 			if (insn->imm == BPF_CMPXCHG)
3356 				return BPF_REG_0;
3357 			else
3358 				return insn->src_reg;
3359 		} else {
3360 			return -1;
3361 		}
3362 	default:
3363 		return insn->dst_reg;
3364 	}
3365 }
3366 
3367 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3368 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3369 {
3370 	int dst_reg = insn_def_regno(insn);
3371 
3372 	if (dst_reg == -1)
3373 		return false;
3374 
3375 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3376 }
3377 
3378 static void mark_insn_zext(struct bpf_verifier_env *env,
3379 			   struct bpf_reg_state *reg)
3380 {
3381 	s32 def_idx = reg->subreg_def;
3382 
3383 	if (def_idx == DEF_NOT_SUBREG)
3384 		return;
3385 
3386 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3387 	/* The dst will be zero extended, so won't be sub-register anymore. */
3388 	reg->subreg_def = DEF_NOT_SUBREG;
3389 }
3390 
3391 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3392 			   enum reg_arg_type t)
3393 {
3394 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3395 	struct bpf_reg_state *reg;
3396 	bool rw64;
3397 
3398 	if (regno >= MAX_BPF_REG) {
3399 		verbose(env, "R%d is invalid\n", regno);
3400 		return -EINVAL;
3401 	}
3402 
3403 	mark_reg_scratched(env, regno);
3404 
3405 	reg = &regs[regno];
3406 	rw64 = is_reg64(env, insn, regno, reg, t);
3407 	if (t == SRC_OP) {
3408 		/* check whether register used as source operand can be read */
3409 		if (reg->type == NOT_INIT) {
3410 			verbose(env, "R%d !read_ok\n", regno);
3411 			return -EACCES;
3412 		}
3413 		/* We don't need to worry about FP liveness because it's read-only */
3414 		if (regno == BPF_REG_FP)
3415 			return 0;
3416 
3417 		if (rw64)
3418 			mark_insn_zext(env, reg);
3419 
3420 		return mark_reg_read(env, reg, reg->parent,
3421 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3422 	} else {
3423 		/* check whether register used as dest operand can be written to */
3424 		if (regno == BPF_REG_FP) {
3425 			verbose(env, "frame pointer is read only\n");
3426 			return -EACCES;
3427 		}
3428 		reg->live |= REG_LIVE_WRITTEN;
3429 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3430 		if (t == DST_OP)
3431 			mark_reg_unknown(env, regs, regno);
3432 	}
3433 	return 0;
3434 }
3435 
3436 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3437 			 enum reg_arg_type t)
3438 {
3439 	struct bpf_verifier_state *vstate = env->cur_state;
3440 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3441 
3442 	return __check_reg_arg(env, state->regs, regno, t);
3443 }
3444 
3445 static int insn_stack_access_flags(int frameno, int spi)
3446 {
3447 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3448 }
3449 
3450 static int insn_stack_access_spi(int insn_flags)
3451 {
3452 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3453 }
3454 
3455 static int insn_stack_access_frameno(int insn_flags)
3456 {
3457 	return insn_flags & INSN_F_FRAMENO_MASK;
3458 }
3459 
3460 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3461 {
3462 	env->insn_aux_data[idx].jmp_point = true;
3463 }
3464 
3465 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3466 {
3467 	return env->insn_aux_data[insn_idx].jmp_point;
3468 }
3469 
3470 #define LR_FRAMENO_BITS	3
3471 #define LR_SPI_BITS	6
3472 #define LR_ENTRY_BITS	(LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3473 #define LR_SIZE_BITS	4
3474 #define LR_FRAMENO_MASK	((1ull << LR_FRAMENO_BITS) - 1)
3475 #define LR_SPI_MASK	((1ull << LR_SPI_BITS)     - 1)
3476 #define LR_SIZE_MASK	((1ull << LR_SIZE_BITS)    - 1)
3477 #define LR_SPI_OFF	LR_FRAMENO_BITS
3478 #define LR_IS_REG_OFF	(LR_SPI_BITS + LR_FRAMENO_BITS)
3479 #define LINKED_REGS_MAX	6
3480 
3481 struct linked_reg {
3482 	u8 frameno;
3483 	union {
3484 		u8 spi;
3485 		u8 regno;
3486 	};
3487 	bool is_reg;
3488 };
3489 
3490 struct linked_regs {
3491 	int cnt;
3492 	struct linked_reg entries[LINKED_REGS_MAX];
3493 };
3494 
3495 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3496 {
3497 	if (s->cnt < LINKED_REGS_MAX)
3498 		return &s->entries[s->cnt++];
3499 
3500 	return NULL;
3501 }
3502 
3503 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track
3504  * number of elements currently in stack.
3505  * Pack one history entry for linked registers as 10 bits in the following format:
3506  * - 3-bits frameno
3507  * - 6-bits spi_or_reg
3508  * - 1-bit  is_reg
3509  */
3510 static u64 linked_regs_pack(struct linked_regs *s)
3511 {
3512 	u64 val = 0;
3513 	int i;
3514 
3515 	for (i = 0; i < s->cnt; ++i) {
3516 		struct linked_reg *e = &s->entries[i];
3517 		u64 tmp = 0;
3518 
3519 		tmp |= e->frameno;
3520 		tmp |= e->spi << LR_SPI_OFF;
3521 		tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
3522 
3523 		val <<= LR_ENTRY_BITS;
3524 		val |= tmp;
3525 	}
3526 	val <<= LR_SIZE_BITS;
3527 	val |= s->cnt;
3528 	return val;
3529 }
3530 
3531 static void linked_regs_unpack(u64 val, struct linked_regs *s)
3532 {
3533 	int i;
3534 
3535 	s->cnt = val & LR_SIZE_MASK;
3536 	val >>= LR_SIZE_BITS;
3537 
3538 	for (i = 0; i < s->cnt; ++i) {
3539 		struct linked_reg *e = &s->entries[i];
3540 
3541 		e->frameno =  val & LR_FRAMENO_MASK;
3542 		e->spi     = (val >> LR_SPI_OFF) & LR_SPI_MASK;
3543 		e->is_reg  = (val >> LR_IS_REG_OFF) & 0x1;
3544 		val >>= LR_ENTRY_BITS;
3545 	}
3546 }
3547 
3548 /* for any branch, call, exit record the history of jmps in the given state */
3549 static int push_insn_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3550 			     int insn_flags, u64 linked_regs)
3551 {
3552 	struct bpf_insn_hist_entry *p;
3553 	size_t alloc_size;
3554 
3555 	/* combine instruction flags if we already recorded this instruction */
3556 	if (env->cur_hist_ent) {
3557 		/* atomic instructions push insn_flags twice, for READ and
3558 		 * WRITE sides, but they should agree on stack slot
3559 		 */
3560 		WARN_ONCE((env->cur_hist_ent->flags & insn_flags) &&
3561 			  (env->cur_hist_ent->flags & insn_flags) != insn_flags,
3562 			  "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n",
3563 			  env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3564 		env->cur_hist_ent->flags |= insn_flags;
3565 		WARN_ONCE(env->cur_hist_ent->linked_regs != 0,
3566 			  "verifier insn history bug: insn_idx %d linked_regs != 0: %#llx\n",
3567 			  env->insn_idx, env->cur_hist_ent->linked_regs);
3568 		env->cur_hist_ent->linked_regs = linked_regs;
3569 		return 0;
3570 	}
3571 
3572 	if (cur->insn_hist_end + 1 > env->insn_hist_cap) {
3573 		alloc_size = size_mul(cur->insn_hist_end + 1, sizeof(*p));
3574 		p = kvrealloc(env->insn_hist, alloc_size, GFP_USER);
3575 		if (!p)
3576 			return -ENOMEM;
3577 		env->insn_hist = p;
3578 		env->insn_hist_cap = alloc_size / sizeof(*p);
3579 	}
3580 
3581 	p = &env->insn_hist[cur->insn_hist_end];
3582 	p->idx = env->insn_idx;
3583 	p->prev_idx = env->prev_insn_idx;
3584 	p->flags = insn_flags;
3585 	p->linked_regs = linked_regs;
3586 
3587 	cur->insn_hist_end++;
3588 	env->cur_hist_ent = p;
3589 
3590 	return 0;
3591 }
3592 
3593 static struct bpf_insn_hist_entry *get_insn_hist_entry(struct bpf_verifier_env *env,
3594 						       u32 hist_start, u32 hist_end, int insn_idx)
3595 {
3596 	if (hist_end > hist_start && env->insn_hist[hist_end - 1].idx == insn_idx)
3597 		return &env->insn_hist[hist_end - 1];
3598 	return NULL;
3599 }
3600 
3601 /* Backtrack one insn at a time. If idx is not at the top of recorded
3602  * history then previous instruction came from straight line execution.
3603  * Return -ENOENT if we exhausted all instructions within given state.
3604  *
3605  * It's legal to have a bit of a looping with the same starting and ending
3606  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3607  * instruction index is the same as state's first_idx doesn't mean we are
3608  * done. If there is still some jump history left, we should keep going. We
3609  * need to take into account that we might have a jump history between given
3610  * state's parent and itself, due to checkpointing. In this case, we'll have
3611  * history entry recording a jump from last instruction of parent state and
3612  * first instruction of given state.
3613  */
3614 static int get_prev_insn_idx(const struct bpf_verifier_env *env,
3615 			     struct bpf_verifier_state *st,
3616 			     int insn_idx, u32 hist_start, u32 *hist_endp)
3617 {
3618 	u32 hist_end = *hist_endp;
3619 	u32 cnt = hist_end - hist_start;
3620 
3621 	if (insn_idx == st->first_insn_idx) {
3622 		if (cnt == 0)
3623 			return -ENOENT;
3624 		if (cnt == 1 && env->insn_hist[hist_start].idx == insn_idx)
3625 			return -ENOENT;
3626 	}
3627 
3628 	if (cnt && env->insn_hist[hist_end - 1].idx == insn_idx) {
3629 		(*hist_endp)--;
3630 		return env->insn_hist[hist_end - 1].prev_idx;
3631 	} else {
3632 		return insn_idx - 1;
3633 	}
3634 }
3635 
3636 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3637 {
3638 	const struct btf_type *func;
3639 	struct btf *desc_btf;
3640 
3641 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3642 		return NULL;
3643 
3644 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3645 	if (IS_ERR(desc_btf))
3646 		return "<error>";
3647 
3648 	func = btf_type_by_id(desc_btf, insn->imm);
3649 	return btf_name_by_offset(desc_btf, func->name_off);
3650 }
3651 
3652 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3653 {
3654 	bt->frame = frame;
3655 }
3656 
3657 static inline void bt_reset(struct backtrack_state *bt)
3658 {
3659 	struct bpf_verifier_env *env = bt->env;
3660 
3661 	memset(bt, 0, sizeof(*bt));
3662 	bt->env = env;
3663 }
3664 
3665 static inline u32 bt_empty(struct backtrack_state *bt)
3666 {
3667 	u64 mask = 0;
3668 	int i;
3669 
3670 	for (i = 0; i <= bt->frame; i++)
3671 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3672 
3673 	return mask == 0;
3674 }
3675 
3676 static inline int bt_subprog_enter(struct backtrack_state *bt)
3677 {
3678 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3679 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3680 		WARN_ONCE(1, "verifier backtracking bug");
3681 		return -EFAULT;
3682 	}
3683 	bt->frame++;
3684 	return 0;
3685 }
3686 
3687 static inline int bt_subprog_exit(struct backtrack_state *bt)
3688 {
3689 	if (bt->frame == 0) {
3690 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3691 		WARN_ONCE(1, "verifier backtracking bug");
3692 		return -EFAULT;
3693 	}
3694 	bt->frame--;
3695 	return 0;
3696 }
3697 
3698 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3699 {
3700 	bt->reg_masks[frame] |= 1 << reg;
3701 }
3702 
3703 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3704 {
3705 	bt->reg_masks[frame] &= ~(1 << reg);
3706 }
3707 
3708 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3709 {
3710 	bt_set_frame_reg(bt, bt->frame, reg);
3711 }
3712 
3713 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3714 {
3715 	bt_clear_frame_reg(bt, bt->frame, reg);
3716 }
3717 
3718 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3719 {
3720 	bt->stack_masks[frame] |= 1ull << slot;
3721 }
3722 
3723 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3724 {
3725 	bt->stack_masks[frame] &= ~(1ull << slot);
3726 }
3727 
3728 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3729 {
3730 	return bt->reg_masks[frame];
3731 }
3732 
3733 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3734 {
3735 	return bt->reg_masks[bt->frame];
3736 }
3737 
3738 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3739 {
3740 	return bt->stack_masks[frame];
3741 }
3742 
3743 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3744 {
3745 	return bt->stack_masks[bt->frame];
3746 }
3747 
3748 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3749 {
3750 	return bt->reg_masks[bt->frame] & (1 << reg);
3751 }
3752 
3753 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
3754 {
3755 	return bt->reg_masks[frame] & (1 << reg);
3756 }
3757 
3758 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
3759 {
3760 	return bt->stack_masks[frame] & (1ull << slot);
3761 }
3762 
3763 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3764 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3765 {
3766 	DECLARE_BITMAP(mask, 64);
3767 	bool first = true;
3768 	int i, n;
3769 
3770 	buf[0] = '\0';
3771 
3772 	bitmap_from_u64(mask, reg_mask);
3773 	for_each_set_bit(i, mask, 32) {
3774 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3775 		first = false;
3776 		buf += n;
3777 		buf_sz -= n;
3778 		if (buf_sz < 0)
3779 			break;
3780 	}
3781 }
3782 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3783 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3784 {
3785 	DECLARE_BITMAP(mask, 64);
3786 	bool first = true;
3787 	int i, n;
3788 
3789 	buf[0] = '\0';
3790 
3791 	bitmap_from_u64(mask, stack_mask);
3792 	for_each_set_bit(i, mask, 64) {
3793 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3794 		first = false;
3795 		buf += n;
3796 		buf_sz -= n;
3797 		if (buf_sz < 0)
3798 			break;
3799 	}
3800 }
3801 
3802 /* If any register R in hist->linked_regs is marked as precise in bt,
3803  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
3804  */
3805 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_insn_hist_entry *hist)
3806 {
3807 	struct linked_regs linked_regs;
3808 	bool some_precise = false;
3809 	int i;
3810 
3811 	if (!hist || hist->linked_regs == 0)
3812 		return;
3813 
3814 	linked_regs_unpack(hist->linked_regs, &linked_regs);
3815 	for (i = 0; i < linked_regs.cnt; ++i) {
3816 		struct linked_reg *e = &linked_regs.entries[i];
3817 
3818 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
3819 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
3820 			some_precise = true;
3821 			break;
3822 		}
3823 	}
3824 
3825 	if (!some_precise)
3826 		return;
3827 
3828 	for (i = 0; i < linked_regs.cnt; ++i) {
3829 		struct linked_reg *e = &linked_regs.entries[i];
3830 
3831 		if (e->is_reg)
3832 			bt_set_frame_reg(bt, e->frameno, e->regno);
3833 		else
3834 			bt_set_frame_slot(bt, e->frameno, e->spi);
3835 	}
3836 }
3837 
3838 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3839 
3840 /* For given verifier state backtrack_insn() is called from the last insn to
3841  * the first insn. Its purpose is to compute a bitmask of registers and
3842  * stack slots that needs precision in the parent verifier state.
3843  *
3844  * @idx is an index of the instruction we are currently processing;
3845  * @subseq_idx is an index of the subsequent instruction that:
3846  *   - *would be* executed next, if jump history is viewed in forward order;
3847  *   - *was* processed previously during backtracking.
3848  */
3849 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3850 			  struct bpf_insn_hist_entry *hist, struct backtrack_state *bt)
3851 {
3852 	const struct bpf_insn_cbs cbs = {
3853 		.cb_call	= disasm_kfunc_name,
3854 		.cb_print	= verbose,
3855 		.private_data	= env,
3856 	};
3857 	struct bpf_insn *insn = env->prog->insnsi + idx;
3858 	u8 class = BPF_CLASS(insn->code);
3859 	u8 opcode = BPF_OP(insn->code);
3860 	u8 mode = BPF_MODE(insn->code);
3861 	u32 dreg = insn->dst_reg;
3862 	u32 sreg = insn->src_reg;
3863 	u32 spi, i, fr;
3864 
3865 	if (insn->code == 0)
3866 		return 0;
3867 	if (env->log.level & BPF_LOG_LEVEL2) {
3868 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3869 		verbose(env, "mark_precise: frame%d: regs=%s ",
3870 			bt->frame, env->tmp_str_buf);
3871 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3872 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3873 		verbose(env, "%d: ", idx);
3874 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3875 	}
3876 
3877 	/* If there is a history record that some registers gained range at this insn,
3878 	 * propagate precision marks to those registers, so that bt_is_reg_set()
3879 	 * accounts for these registers.
3880 	 */
3881 	bt_sync_linked_regs(bt, hist);
3882 
3883 	if (class == BPF_ALU || class == BPF_ALU64) {
3884 		if (!bt_is_reg_set(bt, dreg))
3885 			return 0;
3886 		if (opcode == BPF_END || opcode == BPF_NEG) {
3887 			/* sreg is reserved and unused
3888 			 * dreg still need precision before this insn
3889 			 */
3890 			return 0;
3891 		} else if (opcode == BPF_MOV) {
3892 			if (BPF_SRC(insn->code) == BPF_X) {
3893 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3894 				 * dreg needs precision after this insn
3895 				 * sreg needs precision before this insn
3896 				 */
3897 				bt_clear_reg(bt, dreg);
3898 				if (sreg != BPF_REG_FP)
3899 					bt_set_reg(bt, sreg);
3900 			} else {
3901 				/* dreg = K
3902 				 * dreg needs precision after this insn.
3903 				 * Corresponding register is already marked
3904 				 * as precise=true in this verifier state.
3905 				 * No further markings in parent are necessary
3906 				 */
3907 				bt_clear_reg(bt, dreg);
3908 			}
3909 		} else {
3910 			if (BPF_SRC(insn->code) == BPF_X) {
3911 				/* dreg += sreg
3912 				 * both dreg and sreg need precision
3913 				 * before this insn
3914 				 */
3915 				if (sreg != BPF_REG_FP)
3916 					bt_set_reg(bt, sreg);
3917 			} /* else dreg += K
3918 			   * dreg still needs precision before this insn
3919 			   */
3920 		}
3921 	} else if (class == BPF_LDX) {
3922 		if (!bt_is_reg_set(bt, dreg))
3923 			return 0;
3924 		bt_clear_reg(bt, dreg);
3925 
3926 		/* scalars can only be spilled into stack w/o losing precision.
3927 		 * Load from any other memory can be zero extended.
3928 		 * The desire to keep that precision is already indicated
3929 		 * by 'precise' mark in corresponding register of this state.
3930 		 * No further tracking necessary.
3931 		 */
3932 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3933 			return 0;
3934 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3935 		 * that [fp - off] slot contains scalar that needs to be
3936 		 * tracked with precision
3937 		 */
3938 		spi = insn_stack_access_spi(hist->flags);
3939 		fr = insn_stack_access_frameno(hist->flags);
3940 		bt_set_frame_slot(bt, fr, spi);
3941 	} else if (class == BPF_STX || class == BPF_ST) {
3942 		if (bt_is_reg_set(bt, dreg))
3943 			/* stx & st shouldn't be using _scalar_ dst_reg
3944 			 * to access memory. It means backtracking
3945 			 * encountered a case of pointer subtraction.
3946 			 */
3947 			return -ENOTSUPP;
3948 		/* scalars can only be spilled into stack */
3949 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3950 			return 0;
3951 		spi = insn_stack_access_spi(hist->flags);
3952 		fr = insn_stack_access_frameno(hist->flags);
3953 		if (!bt_is_frame_slot_set(bt, fr, spi))
3954 			return 0;
3955 		bt_clear_frame_slot(bt, fr, spi);
3956 		if (class == BPF_STX)
3957 			bt_set_reg(bt, sreg);
3958 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3959 		if (bpf_pseudo_call(insn)) {
3960 			int subprog_insn_idx, subprog;
3961 
3962 			subprog_insn_idx = idx + insn->imm + 1;
3963 			subprog = find_subprog(env, subprog_insn_idx);
3964 			if (subprog < 0)
3965 				return -EFAULT;
3966 
3967 			if (subprog_is_global(env, subprog)) {
3968 				/* check that jump history doesn't have any
3969 				 * extra instructions from subprog; the next
3970 				 * instruction after call to global subprog
3971 				 * should be literally next instruction in
3972 				 * caller program
3973 				 */
3974 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3975 				/* r1-r5 are invalidated after subprog call,
3976 				 * so for global func call it shouldn't be set
3977 				 * anymore
3978 				 */
3979 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3980 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3981 					WARN_ONCE(1, "verifier backtracking bug");
3982 					return -EFAULT;
3983 				}
3984 				/* global subprog always sets R0 */
3985 				bt_clear_reg(bt, BPF_REG_0);
3986 				return 0;
3987 			} else {
3988 				/* static subprog call instruction, which
3989 				 * means that we are exiting current subprog,
3990 				 * so only r1-r5 could be still requested as
3991 				 * precise, r0 and r6-r10 or any stack slot in
3992 				 * the current frame should be zero by now
3993 				 */
3994 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3995 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3996 					WARN_ONCE(1, "verifier backtracking bug");
3997 					return -EFAULT;
3998 				}
3999 				/* we are now tracking register spills correctly,
4000 				 * so any instance of leftover slots is a bug
4001 				 */
4002 				if (bt_stack_mask(bt) != 0) {
4003 					verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
4004 					WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)");
4005 					return -EFAULT;
4006 				}
4007 				/* propagate r1-r5 to the caller */
4008 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
4009 					if (bt_is_reg_set(bt, i)) {
4010 						bt_clear_reg(bt, i);
4011 						bt_set_frame_reg(bt, bt->frame - 1, i);
4012 					}
4013 				}
4014 				if (bt_subprog_exit(bt))
4015 					return -EFAULT;
4016 				return 0;
4017 			}
4018 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
4019 			/* exit from callback subprog to callback-calling helper or
4020 			 * kfunc call. Use idx/subseq_idx check to discern it from
4021 			 * straight line code backtracking.
4022 			 * Unlike the subprog call handling above, we shouldn't
4023 			 * propagate precision of r1-r5 (if any requested), as they are
4024 			 * not actually arguments passed directly to callback subprogs
4025 			 */
4026 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4027 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
4028 				WARN_ONCE(1, "verifier backtracking bug");
4029 				return -EFAULT;
4030 			}
4031 			if (bt_stack_mask(bt) != 0) {
4032 				verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
4033 				WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)");
4034 				return -EFAULT;
4035 			}
4036 			/* clear r1-r5 in callback subprog's mask */
4037 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4038 				bt_clear_reg(bt, i);
4039 			if (bt_subprog_exit(bt))
4040 				return -EFAULT;
4041 			return 0;
4042 		} else if (opcode == BPF_CALL) {
4043 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
4044 			 * catch this error later. Make backtracking conservative
4045 			 * with ENOTSUPP.
4046 			 */
4047 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
4048 				return -ENOTSUPP;
4049 			/* regular helper call sets R0 */
4050 			bt_clear_reg(bt, BPF_REG_0);
4051 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4052 				/* if backtracing was looking for registers R1-R5
4053 				 * they should have been found already.
4054 				 */
4055 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
4056 				WARN_ONCE(1, "verifier backtracking bug");
4057 				return -EFAULT;
4058 			}
4059 		} else if (opcode == BPF_EXIT) {
4060 			bool r0_precise;
4061 
4062 			/* Backtracking to a nested function call, 'idx' is a part of
4063 			 * the inner frame 'subseq_idx' is a part of the outer frame.
4064 			 * In case of a regular function call, instructions giving
4065 			 * precision to registers R1-R5 should have been found already.
4066 			 * In case of a callback, it is ok to have R1-R5 marked for
4067 			 * backtracking, as these registers are set by the function
4068 			 * invoking callback.
4069 			 */
4070 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
4071 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4072 					bt_clear_reg(bt, i);
4073 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4074 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
4075 				WARN_ONCE(1, "verifier backtracking bug");
4076 				return -EFAULT;
4077 			}
4078 
4079 			/* BPF_EXIT in subprog or callback always returns
4080 			 * right after the call instruction, so by checking
4081 			 * whether the instruction at subseq_idx-1 is subprog
4082 			 * call or not we can distinguish actual exit from
4083 			 * *subprog* from exit from *callback*. In the former
4084 			 * case, we need to propagate r0 precision, if
4085 			 * necessary. In the former we never do that.
4086 			 */
4087 			r0_precise = subseq_idx - 1 >= 0 &&
4088 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
4089 				     bt_is_reg_set(bt, BPF_REG_0);
4090 
4091 			bt_clear_reg(bt, BPF_REG_0);
4092 			if (bt_subprog_enter(bt))
4093 				return -EFAULT;
4094 
4095 			if (r0_precise)
4096 				bt_set_reg(bt, BPF_REG_0);
4097 			/* r6-r9 and stack slots will stay set in caller frame
4098 			 * bitmasks until we return back from callee(s)
4099 			 */
4100 			return 0;
4101 		} else if (BPF_SRC(insn->code) == BPF_X) {
4102 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
4103 				return 0;
4104 			/* dreg <cond> sreg
4105 			 * Both dreg and sreg need precision before
4106 			 * this insn. If only sreg was marked precise
4107 			 * before it would be equally necessary to
4108 			 * propagate it to dreg.
4109 			 */
4110 			bt_set_reg(bt, dreg);
4111 			bt_set_reg(bt, sreg);
4112 		} else if (BPF_SRC(insn->code) == BPF_K) {
4113 			 /* dreg <cond> K
4114 			  * Only dreg still needs precision before
4115 			  * this insn, so for the K-based conditional
4116 			  * there is nothing new to be marked.
4117 			  */
4118 		}
4119 	} else if (class == BPF_LD) {
4120 		if (!bt_is_reg_set(bt, dreg))
4121 			return 0;
4122 		bt_clear_reg(bt, dreg);
4123 		/* It's ld_imm64 or ld_abs or ld_ind.
4124 		 * For ld_imm64 no further tracking of precision
4125 		 * into parent is necessary
4126 		 */
4127 		if (mode == BPF_IND || mode == BPF_ABS)
4128 			/* to be analyzed */
4129 			return -ENOTSUPP;
4130 	}
4131 	/* Propagate precision marks to linked registers, to account for
4132 	 * registers marked as precise in this function.
4133 	 */
4134 	bt_sync_linked_regs(bt, hist);
4135 	return 0;
4136 }
4137 
4138 /* the scalar precision tracking algorithm:
4139  * . at the start all registers have precise=false.
4140  * . scalar ranges are tracked as normal through alu and jmp insns.
4141  * . once precise value of the scalar register is used in:
4142  *   .  ptr + scalar alu
4143  *   . if (scalar cond K|scalar)
4144  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
4145  *   backtrack through the verifier states and mark all registers and
4146  *   stack slots with spilled constants that these scalar regisers
4147  *   should be precise.
4148  * . during state pruning two registers (or spilled stack slots)
4149  *   are equivalent if both are not precise.
4150  *
4151  * Note the verifier cannot simply walk register parentage chain,
4152  * since many different registers and stack slots could have been
4153  * used to compute single precise scalar.
4154  *
4155  * The approach of starting with precise=true for all registers and then
4156  * backtrack to mark a register as not precise when the verifier detects
4157  * that program doesn't care about specific value (e.g., when helper
4158  * takes register as ARG_ANYTHING parameter) is not safe.
4159  *
4160  * It's ok to walk single parentage chain of the verifier states.
4161  * It's possible that this backtracking will go all the way till 1st insn.
4162  * All other branches will be explored for needing precision later.
4163  *
4164  * The backtracking needs to deal with cases like:
4165  *   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)
4166  * r9 -= r8
4167  * r5 = r9
4168  * if r5 > 0x79f goto pc+7
4169  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4170  * r5 += 1
4171  * ...
4172  * call bpf_perf_event_output#25
4173  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4174  *
4175  * and this case:
4176  * r6 = 1
4177  * call foo // uses callee's r6 inside to compute r0
4178  * r0 += r6
4179  * if r0 == 0 goto
4180  *
4181  * to track above reg_mask/stack_mask needs to be independent for each frame.
4182  *
4183  * Also if parent's curframe > frame where backtracking started,
4184  * the verifier need to mark registers in both frames, otherwise callees
4185  * may incorrectly prune callers. This is similar to
4186  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4187  *
4188  * For now backtracking falls back into conservative marking.
4189  */
4190 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4191 				     struct bpf_verifier_state *st)
4192 {
4193 	struct bpf_func_state *func;
4194 	struct bpf_reg_state *reg;
4195 	int i, j;
4196 
4197 	if (env->log.level & BPF_LOG_LEVEL2) {
4198 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4199 			st->curframe);
4200 	}
4201 
4202 	/* big hammer: mark all scalars precise in this path.
4203 	 * pop_stack may still get !precise scalars.
4204 	 * We also skip current state and go straight to first parent state,
4205 	 * because precision markings in current non-checkpointed state are
4206 	 * not needed. See why in the comment in __mark_chain_precision below.
4207 	 */
4208 	for (st = st->parent; st; st = st->parent) {
4209 		for (i = 0; i <= st->curframe; i++) {
4210 			func = st->frame[i];
4211 			for (j = 0; j < BPF_REG_FP; j++) {
4212 				reg = &func->regs[j];
4213 				if (reg->type != SCALAR_VALUE || reg->precise)
4214 					continue;
4215 				reg->precise = true;
4216 				if (env->log.level & BPF_LOG_LEVEL2) {
4217 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4218 						i, j);
4219 				}
4220 			}
4221 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4222 				if (!is_spilled_reg(&func->stack[j]))
4223 					continue;
4224 				reg = &func->stack[j].spilled_ptr;
4225 				if (reg->type != SCALAR_VALUE || reg->precise)
4226 					continue;
4227 				reg->precise = true;
4228 				if (env->log.level & BPF_LOG_LEVEL2) {
4229 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4230 						i, -(j + 1) * 8);
4231 				}
4232 			}
4233 		}
4234 	}
4235 }
4236 
4237 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4238 {
4239 	struct bpf_func_state *func;
4240 	struct bpf_reg_state *reg;
4241 	int i, j;
4242 
4243 	for (i = 0; i <= st->curframe; i++) {
4244 		func = st->frame[i];
4245 		for (j = 0; j < BPF_REG_FP; j++) {
4246 			reg = &func->regs[j];
4247 			if (reg->type != SCALAR_VALUE)
4248 				continue;
4249 			reg->precise = false;
4250 		}
4251 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4252 			if (!is_spilled_reg(&func->stack[j]))
4253 				continue;
4254 			reg = &func->stack[j].spilled_ptr;
4255 			if (reg->type != SCALAR_VALUE)
4256 				continue;
4257 			reg->precise = false;
4258 		}
4259 	}
4260 }
4261 
4262 /*
4263  * __mark_chain_precision() backtracks BPF program instruction sequence and
4264  * chain of verifier states making sure that register *regno* (if regno >= 0)
4265  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4266  * SCALARS, as well as any other registers and slots that contribute to
4267  * a tracked state of given registers/stack slots, depending on specific BPF
4268  * assembly instructions (see backtrack_insns() for exact instruction handling
4269  * logic). This backtracking relies on recorded insn_hist and is able to
4270  * traverse entire chain of parent states. This process ends only when all the
4271  * necessary registers/slots and their transitive dependencies are marked as
4272  * precise.
4273  *
4274  * One important and subtle aspect is that precise marks *do not matter* in
4275  * the currently verified state (current state). It is important to understand
4276  * why this is the case.
4277  *
4278  * First, note that current state is the state that is not yet "checkpointed",
4279  * i.e., it is not yet put into env->explored_states, and it has no children
4280  * states as well. It's ephemeral, and can end up either a) being discarded if
4281  * compatible explored state is found at some point or BPF_EXIT instruction is
4282  * reached or b) checkpointed and put into env->explored_states, branching out
4283  * into one or more children states.
4284  *
4285  * In the former case, precise markings in current state are completely
4286  * ignored by state comparison code (see regsafe() for details). Only
4287  * checkpointed ("old") state precise markings are important, and if old
4288  * state's register/slot is precise, regsafe() assumes current state's
4289  * register/slot as precise and checks value ranges exactly and precisely. If
4290  * states turn out to be compatible, current state's necessary precise
4291  * markings and any required parent states' precise markings are enforced
4292  * after the fact with propagate_precision() logic, after the fact. But it's
4293  * important to realize that in this case, even after marking current state
4294  * registers/slots as precise, we immediately discard current state. So what
4295  * actually matters is any of the precise markings propagated into current
4296  * state's parent states, which are always checkpointed (due to b) case above).
4297  * As such, for scenario a) it doesn't matter if current state has precise
4298  * markings set or not.
4299  *
4300  * Now, for the scenario b), checkpointing and forking into child(ren)
4301  * state(s). Note that before current state gets to checkpointing step, any
4302  * processed instruction always assumes precise SCALAR register/slot
4303  * knowledge: if precise value or range is useful to prune jump branch, BPF
4304  * verifier takes this opportunity enthusiastically. Similarly, when
4305  * register's value is used to calculate offset or memory address, exact
4306  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4307  * what we mentioned above about state comparison ignoring precise markings
4308  * during state comparison, BPF verifier ignores and also assumes precise
4309  * markings *at will* during instruction verification process. But as verifier
4310  * assumes precision, it also propagates any precision dependencies across
4311  * parent states, which are not yet finalized, so can be further restricted
4312  * based on new knowledge gained from restrictions enforced by their children
4313  * states. This is so that once those parent states are finalized, i.e., when
4314  * they have no more active children state, state comparison logic in
4315  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4316  * required for correctness.
4317  *
4318  * To build a bit more intuition, note also that once a state is checkpointed,
4319  * the path we took to get to that state is not important. This is crucial
4320  * property for state pruning. When state is checkpointed and finalized at
4321  * some instruction index, it can be correctly and safely used to "short
4322  * circuit" any *compatible* state that reaches exactly the same instruction
4323  * index. I.e., if we jumped to that instruction from a completely different
4324  * code path than original finalized state was derived from, it doesn't
4325  * matter, current state can be discarded because from that instruction
4326  * forward having a compatible state will ensure we will safely reach the
4327  * exit. States describe preconditions for further exploration, but completely
4328  * forget the history of how we got here.
4329  *
4330  * This also means that even if we needed precise SCALAR range to get to
4331  * finalized state, but from that point forward *that same* SCALAR register is
4332  * never used in a precise context (i.e., it's precise value is not needed for
4333  * correctness), it's correct and safe to mark such register as "imprecise"
4334  * (i.e., precise marking set to false). This is what we rely on when we do
4335  * not set precise marking in current state. If no child state requires
4336  * precision for any given SCALAR register, it's safe to dictate that it can
4337  * be imprecise. If any child state does require this register to be precise,
4338  * we'll mark it precise later retroactively during precise markings
4339  * propagation from child state to parent states.
4340  *
4341  * Skipping precise marking setting in current state is a mild version of
4342  * relying on the above observation. But we can utilize this property even
4343  * more aggressively by proactively forgetting any precise marking in the
4344  * current state (which we inherited from the parent state), right before we
4345  * checkpoint it and branch off into new child state. This is done by
4346  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4347  * finalized states which help in short circuiting more future states.
4348  */
4349 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4350 {
4351 	struct backtrack_state *bt = &env->bt;
4352 	struct bpf_verifier_state *st = env->cur_state;
4353 	int first_idx = st->first_insn_idx;
4354 	int last_idx = env->insn_idx;
4355 	int subseq_idx = -1;
4356 	struct bpf_func_state *func;
4357 	struct bpf_reg_state *reg;
4358 	bool skip_first = true;
4359 	int i, fr, err;
4360 
4361 	if (!env->bpf_capable)
4362 		return 0;
4363 
4364 	/* set frame number from which we are starting to backtrack */
4365 	bt_init(bt, env->cur_state->curframe);
4366 
4367 	/* Do sanity checks against current state of register and/or stack
4368 	 * slot, but don't set precise flag in current state, as precision
4369 	 * tracking in the current state is unnecessary.
4370 	 */
4371 	func = st->frame[bt->frame];
4372 	if (regno >= 0) {
4373 		reg = &func->regs[regno];
4374 		if (reg->type != SCALAR_VALUE) {
4375 			WARN_ONCE(1, "backtracing misuse");
4376 			return -EFAULT;
4377 		}
4378 		bt_set_reg(bt, regno);
4379 	}
4380 
4381 	if (bt_empty(bt))
4382 		return 0;
4383 
4384 	for (;;) {
4385 		DECLARE_BITMAP(mask, 64);
4386 		u32 hist_start = st->insn_hist_start;
4387 		u32 hist_end = st->insn_hist_end;
4388 		struct bpf_insn_hist_entry *hist;
4389 
4390 		if (env->log.level & BPF_LOG_LEVEL2) {
4391 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4392 				bt->frame, last_idx, first_idx, subseq_idx);
4393 		}
4394 
4395 		if (last_idx < 0) {
4396 			/* we are at the entry into subprog, which
4397 			 * is expected for global funcs, but only if
4398 			 * requested precise registers are R1-R5
4399 			 * (which are global func's input arguments)
4400 			 */
4401 			if (st->curframe == 0 &&
4402 			    st->frame[0]->subprogno > 0 &&
4403 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4404 			    bt_stack_mask(bt) == 0 &&
4405 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4406 				bitmap_from_u64(mask, bt_reg_mask(bt));
4407 				for_each_set_bit(i, mask, 32) {
4408 					reg = &st->frame[0]->regs[i];
4409 					bt_clear_reg(bt, i);
4410 					if (reg->type == SCALAR_VALUE)
4411 						reg->precise = true;
4412 				}
4413 				return 0;
4414 			}
4415 
4416 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4417 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4418 			WARN_ONCE(1, "verifier backtracking bug");
4419 			return -EFAULT;
4420 		}
4421 
4422 		for (i = last_idx;;) {
4423 			if (skip_first) {
4424 				err = 0;
4425 				skip_first = false;
4426 			} else {
4427 				hist = get_insn_hist_entry(env, hist_start, hist_end, i);
4428 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4429 			}
4430 			if (err == -ENOTSUPP) {
4431 				mark_all_scalars_precise(env, env->cur_state);
4432 				bt_reset(bt);
4433 				return 0;
4434 			} else if (err) {
4435 				return err;
4436 			}
4437 			if (bt_empty(bt))
4438 				/* Found assignment(s) into tracked register in this state.
4439 				 * Since this state is already marked, just return.
4440 				 * Nothing to be tracked further in the parent state.
4441 				 */
4442 				return 0;
4443 			subseq_idx = i;
4444 			i = get_prev_insn_idx(env, st, i, hist_start, &hist_end);
4445 			if (i == -ENOENT)
4446 				break;
4447 			if (i >= env->prog->len) {
4448 				/* This can happen if backtracking reached insn 0
4449 				 * and there are still reg_mask or stack_mask
4450 				 * to backtrack.
4451 				 * It means the backtracking missed the spot where
4452 				 * particular register was initialized with a constant.
4453 				 */
4454 				verbose(env, "BUG backtracking idx %d\n", i);
4455 				WARN_ONCE(1, "verifier backtracking bug");
4456 				return -EFAULT;
4457 			}
4458 		}
4459 		st = st->parent;
4460 		if (!st)
4461 			break;
4462 
4463 		for (fr = bt->frame; fr >= 0; fr--) {
4464 			func = st->frame[fr];
4465 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4466 			for_each_set_bit(i, mask, 32) {
4467 				reg = &func->regs[i];
4468 				if (reg->type != SCALAR_VALUE) {
4469 					bt_clear_frame_reg(bt, fr, i);
4470 					continue;
4471 				}
4472 				if (reg->precise)
4473 					bt_clear_frame_reg(bt, fr, i);
4474 				else
4475 					reg->precise = true;
4476 			}
4477 
4478 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4479 			for_each_set_bit(i, mask, 64) {
4480 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4481 					verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n",
4482 						i, func->allocated_stack / BPF_REG_SIZE);
4483 					WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)");
4484 					return -EFAULT;
4485 				}
4486 
4487 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4488 					bt_clear_frame_slot(bt, fr, i);
4489 					continue;
4490 				}
4491 				reg = &func->stack[i].spilled_ptr;
4492 				if (reg->precise)
4493 					bt_clear_frame_slot(bt, fr, i);
4494 				else
4495 					reg->precise = true;
4496 			}
4497 			if (env->log.level & BPF_LOG_LEVEL2) {
4498 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4499 					     bt_frame_reg_mask(bt, fr));
4500 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4501 					fr, env->tmp_str_buf);
4502 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4503 					       bt_frame_stack_mask(bt, fr));
4504 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4505 				print_verifier_state(env, func, true);
4506 			}
4507 		}
4508 
4509 		if (bt_empty(bt))
4510 			return 0;
4511 
4512 		subseq_idx = first_idx;
4513 		last_idx = st->last_insn_idx;
4514 		first_idx = st->first_insn_idx;
4515 	}
4516 
4517 	/* if we still have requested precise regs or slots, we missed
4518 	 * something (e.g., stack access through non-r10 register), so
4519 	 * fallback to marking all precise
4520 	 */
4521 	if (!bt_empty(bt)) {
4522 		mark_all_scalars_precise(env, env->cur_state);
4523 		bt_reset(bt);
4524 	}
4525 
4526 	return 0;
4527 }
4528 
4529 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4530 {
4531 	return __mark_chain_precision(env, regno);
4532 }
4533 
4534 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4535  * desired reg and stack masks across all relevant frames
4536  */
4537 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4538 {
4539 	return __mark_chain_precision(env, -1);
4540 }
4541 
4542 static bool is_spillable_regtype(enum bpf_reg_type type)
4543 {
4544 	switch (base_type(type)) {
4545 	case PTR_TO_MAP_VALUE:
4546 	case PTR_TO_STACK:
4547 	case PTR_TO_CTX:
4548 	case PTR_TO_PACKET:
4549 	case PTR_TO_PACKET_META:
4550 	case PTR_TO_PACKET_END:
4551 	case PTR_TO_FLOW_KEYS:
4552 	case CONST_PTR_TO_MAP:
4553 	case PTR_TO_SOCKET:
4554 	case PTR_TO_SOCK_COMMON:
4555 	case PTR_TO_TCP_SOCK:
4556 	case PTR_TO_XDP_SOCK:
4557 	case PTR_TO_BTF_ID:
4558 	case PTR_TO_BUF:
4559 	case PTR_TO_MEM:
4560 	case PTR_TO_FUNC:
4561 	case PTR_TO_MAP_KEY:
4562 	case PTR_TO_ARENA:
4563 		return true;
4564 	default:
4565 		return false;
4566 	}
4567 }
4568 
4569 /* Does this register contain a constant zero? */
4570 static bool register_is_null(struct bpf_reg_state *reg)
4571 {
4572 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4573 }
4574 
4575 /* check if register is a constant scalar value */
4576 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4577 {
4578 	return reg->type == SCALAR_VALUE &&
4579 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4580 }
4581 
4582 /* assuming is_reg_const() is true, return constant value of a register */
4583 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4584 {
4585 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4586 }
4587 
4588 static bool __is_pointer_value(bool allow_ptr_leaks,
4589 			       const struct bpf_reg_state *reg)
4590 {
4591 	if (allow_ptr_leaks)
4592 		return false;
4593 
4594 	return reg->type != SCALAR_VALUE;
4595 }
4596 
4597 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4598 					struct bpf_reg_state *src_reg)
4599 {
4600 	if (src_reg->type != SCALAR_VALUE)
4601 		return;
4602 
4603 	if (src_reg->id & BPF_ADD_CONST) {
4604 		/*
4605 		 * The verifier is processing rX = rY insn and
4606 		 * rY->id has special linked register already.
4607 		 * Cleared it, since multiple rX += const are not supported.
4608 		 */
4609 		src_reg->id = 0;
4610 		src_reg->off = 0;
4611 	}
4612 
4613 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
4614 		/* Ensure that src_reg has a valid ID that will be copied to
4615 		 * dst_reg and then will be used by sync_linked_regs() to
4616 		 * propagate min/max range.
4617 		 */
4618 		src_reg->id = ++env->id_gen;
4619 }
4620 
4621 /* Copy src state preserving dst->parent and dst->live fields */
4622 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4623 {
4624 	struct bpf_reg_state *parent = dst->parent;
4625 	enum bpf_reg_liveness live = dst->live;
4626 
4627 	*dst = *src;
4628 	dst->parent = parent;
4629 	dst->live = live;
4630 }
4631 
4632 static void save_register_state(struct bpf_verifier_env *env,
4633 				struct bpf_func_state *state,
4634 				int spi, struct bpf_reg_state *reg,
4635 				int size)
4636 {
4637 	int i;
4638 
4639 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4640 	if (size == BPF_REG_SIZE)
4641 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4642 
4643 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4644 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4645 
4646 	/* size < 8 bytes spill */
4647 	for (; i; i--)
4648 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4649 }
4650 
4651 static bool is_bpf_st_mem(struct bpf_insn *insn)
4652 {
4653 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4654 }
4655 
4656 static int get_reg_width(struct bpf_reg_state *reg)
4657 {
4658 	return fls64(reg->umax_value);
4659 }
4660 
4661 /* See comment for mark_fastcall_pattern_for_call() */
4662 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
4663 					  struct bpf_func_state *state, int insn_idx, int off)
4664 {
4665 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
4666 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
4667 	int i;
4668 
4669 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
4670 		return;
4671 	/* access to the region [max_stack_depth .. fastcall_stack_off)
4672 	 * from something that is not a part of the fastcall pattern,
4673 	 * disable fastcall rewrites for current subprogram by setting
4674 	 * fastcall_stack_off to a value smaller than any possible offset.
4675 	 */
4676 	subprog->fastcall_stack_off = S16_MIN;
4677 	/* reset fastcall aux flags within subprogram,
4678 	 * happens at most once per subprogram
4679 	 */
4680 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
4681 		aux[i].fastcall_spills_num = 0;
4682 		aux[i].fastcall_pattern = 0;
4683 	}
4684 }
4685 
4686 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4687  * stack boundary and alignment are checked in check_mem_access()
4688  */
4689 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4690 				       /* stack frame we're writing to */
4691 				       struct bpf_func_state *state,
4692 				       int off, int size, int value_regno,
4693 				       int insn_idx)
4694 {
4695 	struct bpf_func_state *cur; /* state of the current function */
4696 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4697 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4698 	struct bpf_reg_state *reg = NULL;
4699 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
4700 
4701 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4702 	 * so it's aligned access and [off, off + size) are within stack limits
4703 	 */
4704 	if (!env->allow_ptr_leaks &&
4705 	    is_spilled_reg(&state->stack[spi]) &&
4706 	    !is_spilled_scalar_reg(&state->stack[spi]) &&
4707 	    size != BPF_REG_SIZE) {
4708 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4709 		return -EACCES;
4710 	}
4711 
4712 	cur = env->cur_state->frame[env->cur_state->curframe];
4713 	if (value_regno >= 0)
4714 		reg = &cur->regs[value_regno];
4715 	if (!env->bypass_spec_v4) {
4716 		bool sanitize = reg && is_spillable_regtype(reg->type);
4717 
4718 		for (i = 0; i < size; i++) {
4719 			u8 type = state->stack[spi].slot_type[i];
4720 
4721 			if (type != STACK_MISC && type != STACK_ZERO) {
4722 				sanitize = true;
4723 				break;
4724 			}
4725 		}
4726 
4727 		if (sanitize)
4728 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4729 	}
4730 
4731 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4732 	if (err)
4733 		return err;
4734 
4735 	check_fastcall_stack_contract(env, state, insn_idx, off);
4736 	mark_stack_slot_scratched(env, spi);
4737 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
4738 		bool reg_value_fits;
4739 
4740 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
4741 		/* Make sure that reg had an ID to build a relation on spill. */
4742 		if (reg_value_fits)
4743 			assign_scalar_id_before_mov(env, reg);
4744 		save_register_state(env, state, spi, reg, size);
4745 		/* Break the relation on a narrowing spill. */
4746 		if (!reg_value_fits)
4747 			state->stack[spi].spilled_ptr.id = 0;
4748 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4749 		   env->bpf_capable) {
4750 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
4751 
4752 		memset(tmp_reg, 0, sizeof(*tmp_reg));
4753 		__mark_reg_known(tmp_reg, insn->imm);
4754 		tmp_reg->type = SCALAR_VALUE;
4755 		save_register_state(env, state, spi, tmp_reg, size);
4756 	} else if (reg && is_spillable_regtype(reg->type)) {
4757 		/* register containing pointer is being spilled into stack */
4758 		if (size != BPF_REG_SIZE) {
4759 			verbose_linfo(env, insn_idx, "; ");
4760 			verbose(env, "invalid size of register spill\n");
4761 			return -EACCES;
4762 		}
4763 		if (state != cur && reg->type == PTR_TO_STACK) {
4764 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4765 			return -EINVAL;
4766 		}
4767 		save_register_state(env, state, spi, reg, size);
4768 	} else {
4769 		u8 type = STACK_MISC;
4770 
4771 		/* regular write of data into stack destroys any spilled ptr */
4772 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4773 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4774 		if (is_stack_slot_special(&state->stack[spi]))
4775 			for (i = 0; i < BPF_REG_SIZE; i++)
4776 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4777 
4778 		/* only mark the slot as written if all 8 bytes were written
4779 		 * otherwise read propagation may incorrectly stop too soon
4780 		 * when stack slots are partially written.
4781 		 * This heuristic means that read propagation will be
4782 		 * conservative, since it will add reg_live_read marks
4783 		 * to stack slots all the way to first state when programs
4784 		 * writes+reads less than 8 bytes
4785 		 */
4786 		if (size == BPF_REG_SIZE)
4787 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4788 
4789 		/* when we zero initialize stack slots mark them as such */
4790 		if ((reg && register_is_null(reg)) ||
4791 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4792 			/* STACK_ZERO case happened because register spill
4793 			 * wasn't properly aligned at the stack slot boundary,
4794 			 * so it's not a register spill anymore; force
4795 			 * originating register to be precise to make
4796 			 * STACK_ZERO correct for subsequent states
4797 			 */
4798 			err = mark_chain_precision(env, value_regno);
4799 			if (err)
4800 				return err;
4801 			type = STACK_ZERO;
4802 		}
4803 
4804 		/* Mark slots affected by this stack write. */
4805 		for (i = 0; i < size; i++)
4806 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
4807 		insn_flags = 0; /* not a register spill */
4808 	}
4809 
4810 	if (insn_flags)
4811 		return push_insn_history(env, env->cur_state, insn_flags, 0);
4812 	return 0;
4813 }
4814 
4815 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4816  * known to contain a variable offset.
4817  * This function checks whether the write is permitted and conservatively
4818  * tracks the effects of the write, considering that each stack slot in the
4819  * dynamic range is potentially written to.
4820  *
4821  * 'off' includes 'regno->off'.
4822  * 'value_regno' can be -1, meaning that an unknown value is being written to
4823  * the stack.
4824  *
4825  * Spilled pointers in range are not marked as written because we don't know
4826  * what's going to be actually written. This means that read propagation for
4827  * future reads cannot be terminated by this write.
4828  *
4829  * For privileged programs, uninitialized stack slots are considered
4830  * initialized by this write (even though we don't know exactly what offsets
4831  * are going to be written to). The idea is that we don't want the verifier to
4832  * reject future reads that access slots written to through variable offsets.
4833  */
4834 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4835 				     /* func where register points to */
4836 				     struct bpf_func_state *state,
4837 				     int ptr_regno, int off, int size,
4838 				     int value_regno, int insn_idx)
4839 {
4840 	struct bpf_func_state *cur; /* state of the current function */
4841 	int min_off, max_off;
4842 	int i, err;
4843 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4844 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4845 	bool writing_zero = false;
4846 	/* set if the fact that we're writing a zero is used to let any
4847 	 * stack slots remain STACK_ZERO
4848 	 */
4849 	bool zero_used = false;
4850 
4851 	cur = env->cur_state->frame[env->cur_state->curframe];
4852 	ptr_reg = &cur->regs[ptr_regno];
4853 	min_off = ptr_reg->smin_value + off;
4854 	max_off = ptr_reg->smax_value + off + size;
4855 	if (value_regno >= 0)
4856 		value_reg = &cur->regs[value_regno];
4857 	if ((value_reg && register_is_null(value_reg)) ||
4858 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4859 		writing_zero = true;
4860 
4861 	for (i = min_off; i < max_off; i++) {
4862 		int spi;
4863 
4864 		spi = __get_spi(i);
4865 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4866 		if (err)
4867 			return err;
4868 	}
4869 
4870 	check_fastcall_stack_contract(env, state, insn_idx, min_off);
4871 	/* Variable offset writes destroy any spilled pointers in range. */
4872 	for (i = min_off; i < max_off; i++) {
4873 		u8 new_type, *stype;
4874 		int slot, spi;
4875 
4876 		slot = -i - 1;
4877 		spi = slot / BPF_REG_SIZE;
4878 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4879 		mark_stack_slot_scratched(env, spi);
4880 
4881 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4882 			/* Reject the write if range we may write to has not
4883 			 * been initialized beforehand. If we didn't reject
4884 			 * here, the ptr status would be erased below (even
4885 			 * though not all slots are actually overwritten),
4886 			 * possibly opening the door to leaks.
4887 			 *
4888 			 * We do however catch STACK_INVALID case below, and
4889 			 * only allow reading possibly uninitialized memory
4890 			 * later for CAP_PERFMON, as the write may not happen to
4891 			 * that slot.
4892 			 */
4893 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4894 				insn_idx, i);
4895 			return -EINVAL;
4896 		}
4897 
4898 		/* If writing_zero and the spi slot contains a spill of value 0,
4899 		 * maintain the spill type.
4900 		 */
4901 		if (writing_zero && *stype == STACK_SPILL &&
4902 		    is_spilled_scalar_reg(&state->stack[spi])) {
4903 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
4904 
4905 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
4906 				zero_used = true;
4907 				continue;
4908 			}
4909 		}
4910 
4911 		/* Erase all other spilled pointers. */
4912 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4913 
4914 		/* Update the slot type. */
4915 		new_type = STACK_MISC;
4916 		if (writing_zero && *stype == STACK_ZERO) {
4917 			new_type = STACK_ZERO;
4918 			zero_used = true;
4919 		}
4920 		/* If the slot is STACK_INVALID, we check whether it's OK to
4921 		 * pretend that it will be initialized by this write. The slot
4922 		 * might not actually be written to, and so if we mark it as
4923 		 * initialized future reads might leak uninitialized memory.
4924 		 * For privileged programs, we will accept such reads to slots
4925 		 * that may or may not be written because, if we're reject
4926 		 * them, the error would be too confusing.
4927 		 */
4928 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4929 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4930 					insn_idx, i);
4931 			return -EINVAL;
4932 		}
4933 		*stype = new_type;
4934 	}
4935 	if (zero_used) {
4936 		/* backtracking doesn't work for STACK_ZERO yet. */
4937 		err = mark_chain_precision(env, value_regno);
4938 		if (err)
4939 			return err;
4940 	}
4941 	return 0;
4942 }
4943 
4944 /* When register 'dst_regno' is assigned some values from stack[min_off,
4945  * max_off), we set the register's type according to the types of the
4946  * respective stack slots. If all the stack values are known to be zeros, then
4947  * so is the destination reg. Otherwise, the register is considered to be
4948  * SCALAR. This function does not deal with register filling; the caller must
4949  * ensure that all spilled registers in the stack range have been marked as
4950  * read.
4951  */
4952 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4953 				/* func where src register points to */
4954 				struct bpf_func_state *ptr_state,
4955 				int min_off, int max_off, int dst_regno)
4956 {
4957 	struct bpf_verifier_state *vstate = env->cur_state;
4958 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4959 	int i, slot, spi;
4960 	u8 *stype;
4961 	int zeros = 0;
4962 
4963 	for (i = min_off; i < max_off; i++) {
4964 		slot = -i - 1;
4965 		spi = slot / BPF_REG_SIZE;
4966 		mark_stack_slot_scratched(env, spi);
4967 		stype = ptr_state->stack[spi].slot_type;
4968 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4969 			break;
4970 		zeros++;
4971 	}
4972 	if (zeros == max_off - min_off) {
4973 		/* Any access_size read into register is zero extended,
4974 		 * so the whole register == const_zero.
4975 		 */
4976 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
4977 	} else {
4978 		/* have read misc data from the stack */
4979 		mark_reg_unknown(env, state->regs, dst_regno);
4980 	}
4981 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4982 }
4983 
4984 /* Read the stack at 'off' and put the results into the register indicated by
4985  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4986  * spilled reg.
4987  *
4988  * 'dst_regno' can be -1, meaning that the read value is not going to a
4989  * register.
4990  *
4991  * The access is assumed to be within the current stack bounds.
4992  */
4993 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4994 				      /* func where src register points to */
4995 				      struct bpf_func_state *reg_state,
4996 				      int off, int size, int dst_regno)
4997 {
4998 	struct bpf_verifier_state *vstate = env->cur_state;
4999 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5000 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
5001 	struct bpf_reg_state *reg;
5002 	u8 *stype, type;
5003 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
5004 
5005 	stype = reg_state->stack[spi].slot_type;
5006 	reg = &reg_state->stack[spi].spilled_ptr;
5007 
5008 	mark_stack_slot_scratched(env, spi);
5009 	check_fastcall_stack_contract(env, state, env->insn_idx, off);
5010 
5011 	if (is_spilled_reg(&reg_state->stack[spi])) {
5012 		u8 spill_size = 1;
5013 
5014 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
5015 			spill_size++;
5016 
5017 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
5018 			if (reg->type != SCALAR_VALUE) {
5019 				verbose_linfo(env, env->insn_idx, "; ");
5020 				verbose(env, "invalid size of register fill\n");
5021 				return -EACCES;
5022 			}
5023 
5024 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5025 			if (dst_regno < 0)
5026 				return 0;
5027 
5028 			if (size <= spill_size &&
5029 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
5030 				/* The earlier check_reg_arg() has decided the
5031 				 * subreg_def for this insn.  Save it first.
5032 				 */
5033 				s32 subreg_def = state->regs[dst_regno].subreg_def;
5034 
5035 				copy_register_state(&state->regs[dst_regno], reg);
5036 				state->regs[dst_regno].subreg_def = subreg_def;
5037 
5038 				/* Break the relation on a narrowing fill.
5039 				 * coerce_reg_to_size will adjust the boundaries.
5040 				 */
5041 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
5042 					state->regs[dst_regno].id = 0;
5043 			} else {
5044 				int spill_cnt = 0, zero_cnt = 0;
5045 
5046 				for (i = 0; i < size; i++) {
5047 					type = stype[(slot - i) % BPF_REG_SIZE];
5048 					if (type == STACK_SPILL) {
5049 						spill_cnt++;
5050 						continue;
5051 					}
5052 					if (type == STACK_MISC)
5053 						continue;
5054 					if (type == STACK_ZERO) {
5055 						zero_cnt++;
5056 						continue;
5057 					}
5058 					if (type == STACK_INVALID && env->allow_uninit_stack)
5059 						continue;
5060 					verbose(env, "invalid read from stack off %d+%d size %d\n",
5061 						off, i, size);
5062 					return -EACCES;
5063 				}
5064 
5065 				if (spill_cnt == size &&
5066 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
5067 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5068 					/* this IS register fill, so keep insn_flags */
5069 				} else if (zero_cnt == size) {
5070 					/* similarly to mark_reg_stack_read(), preserve zeroes */
5071 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5072 					insn_flags = 0; /* not restoring original register state */
5073 				} else {
5074 					mark_reg_unknown(env, state->regs, dst_regno);
5075 					insn_flags = 0; /* not restoring original register state */
5076 				}
5077 			}
5078 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5079 		} else if (dst_regno >= 0) {
5080 			/* restore register state from stack */
5081 			copy_register_state(&state->regs[dst_regno], reg);
5082 			/* mark reg as written since spilled pointer state likely
5083 			 * has its liveness marks cleared by is_state_visited()
5084 			 * which resets stack/reg liveness for state transitions
5085 			 */
5086 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5087 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
5088 			/* If dst_regno==-1, the caller is asking us whether
5089 			 * it is acceptable to use this value as a SCALAR_VALUE
5090 			 * (e.g. for XADD).
5091 			 * We must not allow unprivileged callers to do that
5092 			 * with spilled pointers.
5093 			 */
5094 			verbose(env, "leaking pointer from stack off %d\n",
5095 				off);
5096 			return -EACCES;
5097 		}
5098 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5099 	} else {
5100 		for (i = 0; i < size; i++) {
5101 			type = stype[(slot - i) % BPF_REG_SIZE];
5102 			if (type == STACK_MISC)
5103 				continue;
5104 			if (type == STACK_ZERO)
5105 				continue;
5106 			if (type == STACK_INVALID && env->allow_uninit_stack)
5107 				continue;
5108 			verbose(env, "invalid read from stack off %d+%d size %d\n",
5109 				off, i, size);
5110 			return -EACCES;
5111 		}
5112 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5113 		if (dst_regno >= 0)
5114 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
5115 		insn_flags = 0; /* we are not restoring spilled register */
5116 	}
5117 	if (insn_flags)
5118 		return push_insn_history(env, env->cur_state, insn_flags, 0);
5119 	return 0;
5120 }
5121 
5122 enum bpf_access_src {
5123 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
5124 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
5125 };
5126 
5127 static int check_stack_range_initialized(struct bpf_verifier_env *env,
5128 					 int regno, int off, int access_size,
5129 					 bool zero_size_allowed,
5130 					 enum bpf_access_src type,
5131 					 struct bpf_call_arg_meta *meta);
5132 
5133 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5134 {
5135 	return cur_regs(env) + regno;
5136 }
5137 
5138 /* Read the stack at 'ptr_regno + off' and put the result into the register
5139  * 'dst_regno'.
5140  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5141  * but not its variable offset.
5142  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5143  *
5144  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5145  * filling registers (i.e. reads of spilled register cannot be detected when
5146  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5147  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5148  * offset; for a fixed offset check_stack_read_fixed_off should be used
5149  * instead.
5150  */
5151 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5152 				    int ptr_regno, int off, int size, int dst_regno)
5153 {
5154 	/* The state of the source register. */
5155 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5156 	struct bpf_func_state *ptr_state = func(env, reg);
5157 	int err;
5158 	int min_off, max_off;
5159 
5160 	/* Note that we pass a NULL meta, so raw access will not be permitted.
5161 	 */
5162 	err = check_stack_range_initialized(env, ptr_regno, off, size,
5163 					    false, ACCESS_DIRECT, NULL);
5164 	if (err)
5165 		return err;
5166 
5167 	min_off = reg->smin_value + off;
5168 	max_off = reg->smax_value + off;
5169 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5170 	check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
5171 	return 0;
5172 }
5173 
5174 /* check_stack_read dispatches to check_stack_read_fixed_off or
5175  * check_stack_read_var_off.
5176  *
5177  * The caller must ensure that the offset falls within the allocated stack
5178  * bounds.
5179  *
5180  * 'dst_regno' is a register which will receive the value from the stack. It
5181  * can be -1, meaning that the read value is not going to a register.
5182  */
5183 static int check_stack_read(struct bpf_verifier_env *env,
5184 			    int ptr_regno, int off, int size,
5185 			    int dst_regno)
5186 {
5187 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5188 	struct bpf_func_state *state = func(env, reg);
5189 	int err;
5190 	/* Some accesses are only permitted with a static offset. */
5191 	bool var_off = !tnum_is_const(reg->var_off);
5192 
5193 	/* The offset is required to be static when reads don't go to a
5194 	 * register, in order to not leak pointers (see
5195 	 * check_stack_read_fixed_off).
5196 	 */
5197 	if (dst_regno < 0 && var_off) {
5198 		char tn_buf[48];
5199 
5200 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5201 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5202 			tn_buf, off, size);
5203 		return -EACCES;
5204 	}
5205 	/* Variable offset is prohibited for unprivileged mode for simplicity
5206 	 * since it requires corresponding support in Spectre masking for stack
5207 	 * ALU. See also retrieve_ptr_limit(). The check in
5208 	 * check_stack_access_for_ptr_arithmetic() called by
5209 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5210 	 * with variable offsets, therefore no check is required here. Further,
5211 	 * just checking it here would be insufficient as speculative stack
5212 	 * writes could still lead to unsafe speculative behaviour.
5213 	 */
5214 	if (!var_off) {
5215 		off += reg->var_off.value;
5216 		err = check_stack_read_fixed_off(env, state, off, size,
5217 						 dst_regno);
5218 	} else {
5219 		/* Variable offset stack reads need more conservative handling
5220 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5221 		 * branch.
5222 		 */
5223 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5224 					       dst_regno);
5225 	}
5226 	return err;
5227 }
5228 
5229 
5230 /* check_stack_write dispatches to check_stack_write_fixed_off or
5231  * check_stack_write_var_off.
5232  *
5233  * 'ptr_regno' is the register used as a pointer into the stack.
5234  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5235  * 'value_regno' is the register whose value we're writing to the stack. It can
5236  * be -1, meaning that we're not writing from a register.
5237  *
5238  * The caller must ensure that the offset falls within the maximum stack size.
5239  */
5240 static int check_stack_write(struct bpf_verifier_env *env,
5241 			     int ptr_regno, int off, int size,
5242 			     int value_regno, int insn_idx)
5243 {
5244 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5245 	struct bpf_func_state *state = func(env, reg);
5246 	int err;
5247 
5248 	if (tnum_is_const(reg->var_off)) {
5249 		off += reg->var_off.value;
5250 		err = check_stack_write_fixed_off(env, state, off, size,
5251 						  value_regno, insn_idx);
5252 	} else {
5253 		/* Variable offset stack reads need more conservative handling
5254 		 * than fixed offset ones.
5255 		 */
5256 		err = check_stack_write_var_off(env, state,
5257 						ptr_regno, off, size,
5258 						value_regno, insn_idx);
5259 	}
5260 	return err;
5261 }
5262 
5263 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5264 				 int off, int size, enum bpf_access_type type)
5265 {
5266 	struct bpf_reg_state *regs = cur_regs(env);
5267 	struct bpf_map *map = regs[regno].map_ptr;
5268 	u32 cap = bpf_map_flags_to_cap(map);
5269 
5270 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5271 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5272 			map->value_size, off, size);
5273 		return -EACCES;
5274 	}
5275 
5276 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5277 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5278 			map->value_size, off, size);
5279 		return -EACCES;
5280 	}
5281 
5282 	return 0;
5283 }
5284 
5285 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5286 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5287 			      int off, int size, u32 mem_size,
5288 			      bool zero_size_allowed)
5289 {
5290 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5291 	struct bpf_reg_state *reg;
5292 
5293 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5294 		return 0;
5295 
5296 	reg = &cur_regs(env)[regno];
5297 	switch (reg->type) {
5298 	case PTR_TO_MAP_KEY:
5299 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5300 			mem_size, off, size);
5301 		break;
5302 	case PTR_TO_MAP_VALUE:
5303 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5304 			mem_size, off, size);
5305 		break;
5306 	case PTR_TO_PACKET:
5307 	case PTR_TO_PACKET_META:
5308 	case PTR_TO_PACKET_END:
5309 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5310 			off, size, regno, reg->id, off, mem_size);
5311 		break;
5312 	case PTR_TO_MEM:
5313 	default:
5314 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5315 			mem_size, off, size);
5316 	}
5317 
5318 	return -EACCES;
5319 }
5320 
5321 /* check read/write into a memory region with possible variable offset */
5322 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5323 				   int off, int size, u32 mem_size,
5324 				   bool zero_size_allowed)
5325 {
5326 	struct bpf_verifier_state *vstate = env->cur_state;
5327 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5328 	struct bpf_reg_state *reg = &state->regs[regno];
5329 	int err;
5330 
5331 	/* We may have adjusted the register pointing to memory region, so we
5332 	 * need to try adding each of min_value and max_value to off
5333 	 * to make sure our theoretical access will be safe.
5334 	 *
5335 	 * The minimum value is only important with signed
5336 	 * comparisons where we can't assume the floor of a
5337 	 * value is 0.  If we are using signed variables for our
5338 	 * index'es we need to make sure that whatever we use
5339 	 * will have a set floor within our range.
5340 	 */
5341 	if (reg->smin_value < 0 &&
5342 	    (reg->smin_value == S64_MIN ||
5343 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5344 	      reg->smin_value + off < 0)) {
5345 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5346 			regno);
5347 		return -EACCES;
5348 	}
5349 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5350 				 mem_size, zero_size_allowed);
5351 	if (err) {
5352 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5353 			regno);
5354 		return err;
5355 	}
5356 
5357 	/* If we haven't set a max value then we need to bail since we can't be
5358 	 * sure we won't do bad things.
5359 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5360 	 */
5361 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5362 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5363 			regno);
5364 		return -EACCES;
5365 	}
5366 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5367 				 mem_size, zero_size_allowed);
5368 	if (err) {
5369 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5370 			regno);
5371 		return err;
5372 	}
5373 
5374 	return 0;
5375 }
5376 
5377 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5378 			       const struct bpf_reg_state *reg, int regno,
5379 			       bool fixed_off_ok)
5380 {
5381 	/* Access to this pointer-typed register or passing it to a helper
5382 	 * is only allowed in its original, unmodified form.
5383 	 */
5384 
5385 	if (reg->off < 0) {
5386 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5387 			reg_type_str(env, reg->type), regno, reg->off);
5388 		return -EACCES;
5389 	}
5390 
5391 	if (!fixed_off_ok && reg->off) {
5392 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5393 			reg_type_str(env, reg->type), regno, reg->off);
5394 		return -EACCES;
5395 	}
5396 
5397 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5398 		char tn_buf[48];
5399 
5400 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5401 		verbose(env, "variable %s access var_off=%s disallowed\n",
5402 			reg_type_str(env, reg->type), tn_buf);
5403 		return -EACCES;
5404 	}
5405 
5406 	return 0;
5407 }
5408 
5409 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5410 		             const struct bpf_reg_state *reg, int regno)
5411 {
5412 	return __check_ptr_off_reg(env, reg, regno, false);
5413 }
5414 
5415 static int map_kptr_match_type(struct bpf_verifier_env *env,
5416 			       struct btf_field *kptr_field,
5417 			       struct bpf_reg_state *reg, u32 regno)
5418 {
5419 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5420 	int perm_flags;
5421 	const char *reg_name = "";
5422 
5423 	if (btf_is_kernel(reg->btf)) {
5424 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5425 
5426 		/* Only unreferenced case accepts untrusted pointers */
5427 		if (kptr_field->type == BPF_KPTR_UNREF)
5428 			perm_flags |= PTR_UNTRUSTED;
5429 	} else {
5430 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5431 		if (kptr_field->type == BPF_KPTR_PERCPU)
5432 			perm_flags |= MEM_PERCPU;
5433 	}
5434 
5435 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5436 		goto bad_type;
5437 
5438 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5439 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5440 
5441 	/* For ref_ptr case, release function check should ensure we get one
5442 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5443 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5444 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5445 	 * reg->off and reg->ref_obj_id are not needed here.
5446 	 */
5447 	if (__check_ptr_off_reg(env, reg, regno, true))
5448 		return -EACCES;
5449 
5450 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5451 	 * we also need to take into account the reg->off.
5452 	 *
5453 	 * We want to support cases like:
5454 	 *
5455 	 * struct foo {
5456 	 *         struct bar br;
5457 	 *         struct baz bz;
5458 	 * };
5459 	 *
5460 	 * struct foo *v;
5461 	 * v = func();	      // PTR_TO_BTF_ID
5462 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5463 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5464 	 *                    // first member type of struct after comparison fails
5465 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5466 	 *                    // to match type
5467 	 *
5468 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5469 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5470 	 * the struct to match type against first member of struct, i.e. reject
5471 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5472 	 * strict mode to true for type match.
5473 	 */
5474 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5475 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5476 				  kptr_field->type != BPF_KPTR_UNREF))
5477 		goto bad_type;
5478 	return 0;
5479 bad_type:
5480 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5481 		reg_type_str(env, reg->type), reg_name);
5482 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5483 	if (kptr_field->type == BPF_KPTR_UNREF)
5484 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5485 			targ_name);
5486 	else
5487 		verbose(env, "\n");
5488 	return -EINVAL;
5489 }
5490 
5491 static bool in_sleepable(struct bpf_verifier_env *env)
5492 {
5493 	return env->prog->sleepable ||
5494 	       (env->cur_state && env->cur_state->in_sleepable);
5495 }
5496 
5497 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5498  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5499  */
5500 static bool in_rcu_cs(struct bpf_verifier_env *env)
5501 {
5502 	return env->cur_state->active_rcu_lock ||
5503 	       cur_func(env)->active_locks ||
5504 	       !in_sleepable(env);
5505 }
5506 
5507 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5508 BTF_SET_START(rcu_protected_types)
5509 BTF_ID(struct, prog_test_ref_kfunc)
5510 #ifdef CONFIG_CGROUPS
5511 BTF_ID(struct, cgroup)
5512 #endif
5513 #ifdef CONFIG_BPF_JIT
5514 BTF_ID(struct, bpf_cpumask)
5515 #endif
5516 BTF_ID(struct, task_struct)
5517 BTF_ID(struct, bpf_crypto_ctx)
5518 BTF_SET_END(rcu_protected_types)
5519 
5520 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5521 {
5522 	if (!btf_is_kernel(btf))
5523 		return true;
5524 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5525 }
5526 
5527 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5528 {
5529 	struct btf_struct_meta *meta;
5530 
5531 	if (btf_is_kernel(kptr_field->kptr.btf))
5532 		return NULL;
5533 
5534 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5535 				    kptr_field->kptr.btf_id);
5536 
5537 	return meta ? meta->record : NULL;
5538 }
5539 
5540 static bool rcu_safe_kptr(const struct btf_field *field)
5541 {
5542 	const struct btf_field_kptr *kptr = &field->kptr;
5543 
5544 	return field->type == BPF_KPTR_PERCPU ||
5545 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5546 }
5547 
5548 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5549 {
5550 	struct btf_record *rec;
5551 	u32 ret;
5552 
5553 	ret = PTR_MAYBE_NULL;
5554 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5555 		ret |= MEM_RCU;
5556 		if (kptr_field->type == BPF_KPTR_PERCPU)
5557 			ret |= MEM_PERCPU;
5558 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5559 			ret |= MEM_ALLOC;
5560 
5561 		rec = kptr_pointee_btf_record(kptr_field);
5562 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5563 			ret |= NON_OWN_REF;
5564 	} else {
5565 		ret |= PTR_UNTRUSTED;
5566 	}
5567 
5568 	return ret;
5569 }
5570 
5571 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
5572 			    struct btf_field *field)
5573 {
5574 	struct bpf_reg_state *reg;
5575 	const struct btf_type *t;
5576 
5577 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
5578 	mark_reg_known_zero(env, cur_regs(env), regno);
5579 	reg = reg_state(env, regno);
5580 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
5581 	reg->mem_size = t->size;
5582 	reg->id = ++env->id_gen;
5583 
5584 	return 0;
5585 }
5586 
5587 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5588 				 int value_regno, int insn_idx,
5589 				 struct btf_field *kptr_field)
5590 {
5591 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5592 	int class = BPF_CLASS(insn->code);
5593 	struct bpf_reg_state *val_reg;
5594 
5595 	/* Things we already checked for in check_map_access and caller:
5596 	 *  - Reject cases where variable offset may touch kptr
5597 	 *  - size of access (must be BPF_DW)
5598 	 *  - tnum_is_const(reg->var_off)
5599 	 *  - kptr_field->offset == off + reg->var_off.value
5600 	 */
5601 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5602 	if (BPF_MODE(insn->code) != BPF_MEM) {
5603 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5604 		return -EACCES;
5605 	}
5606 
5607 	/* We only allow loading referenced kptr, since it will be marked as
5608 	 * untrusted, similar to unreferenced kptr.
5609 	 */
5610 	if (class != BPF_LDX &&
5611 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5612 		verbose(env, "store to referenced kptr disallowed\n");
5613 		return -EACCES;
5614 	}
5615 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
5616 		verbose(env, "store to uptr disallowed\n");
5617 		return -EACCES;
5618 	}
5619 
5620 	if (class == BPF_LDX) {
5621 		if (kptr_field->type == BPF_UPTR)
5622 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
5623 
5624 		/* We can simply mark the value_regno receiving the pointer
5625 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5626 		 */
5627 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5628 				kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5629 	} else if (class == BPF_STX) {
5630 		val_reg = reg_state(env, value_regno);
5631 		if (!register_is_null(val_reg) &&
5632 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5633 			return -EACCES;
5634 	} else if (class == BPF_ST) {
5635 		if (insn->imm) {
5636 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5637 				kptr_field->offset);
5638 			return -EACCES;
5639 		}
5640 	} else {
5641 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5642 		return -EACCES;
5643 	}
5644 	return 0;
5645 }
5646 
5647 /* check read/write into a map element with possible variable offset */
5648 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5649 			    int off, int size, bool zero_size_allowed,
5650 			    enum bpf_access_src src)
5651 {
5652 	struct bpf_verifier_state *vstate = env->cur_state;
5653 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5654 	struct bpf_reg_state *reg = &state->regs[regno];
5655 	struct bpf_map *map = reg->map_ptr;
5656 	struct btf_record *rec;
5657 	int err, i;
5658 
5659 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5660 				      zero_size_allowed);
5661 	if (err)
5662 		return err;
5663 
5664 	if (IS_ERR_OR_NULL(map->record))
5665 		return 0;
5666 	rec = map->record;
5667 	for (i = 0; i < rec->cnt; i++) {
5668 		struct btf_field *field = &rec->fields[i];
5669 		u32 p = field->offset;
5670 
5671 		/* If any part of a field  can be touched by load/store, reject
5672 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5673 		 * it is sufficient to check x1 < y2 && y1 < x2.
5674 		 */
5675 		if (reg->smin_value + off < p + field->size &&
5676 		    p < reg->umax_value + off + size) {
5677 			switch (field->type) {
5678 			case BPF_KPTR_UNREF:
5679 			case BPF_KPTR_REF:
5680 			case BPF_KPTR_PERCPU:
5681 			case BPF_UPTR:
5682 				if (src != ACCESS_DIRECT) {
5683 					verbose(env, "%s cannot be accessed indirectly by helper\n",
5684 						btf_field_type_name(field->type));
5685 					return -EACCES;
5686 				}
5687 				if (!tnum_is_const(reg->var_off)) {
5688 					verbose(env, "%s access cannot have variable offset\n",
5689 						btf_field_type_name(field->type));
5690 					return -EACCES;
5691 				}
5692 				if (p != off + reg->var_off.value) {
5693 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
5694 						btf_field_type_name(field->type),
5695 						p, off + reg->var_off.value);
5696 					return -EACCES;
5697 				}
5698 				if (size != bpf_size_to_bytes(BPF_DW)) {
5699 					verbose(env, "%s access size must be BPF_DW\n",
5700 						btf_field_type_name(field->type));
5701 					return -EACCES;
5702 				}
5703 				break;
5704 			default:
5705 				verbose(env, "%s cannot be accessed directly by load/store\n",
5706 					btf_field_type_name(field->type));
5707 				return -EACCES;
5708 			}
5709 		}
5710 	}
5711 	return 0;
5712 }
5713 
5714 #define MAX_PACKET_OFF 0xffff
5715 
5716 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5717 				       const struct bpf_call_arg_meta *meta,
5718 				       enum bpf_access_type t)
5719 {
5720 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5721 
5722 	switch (prog_type) {
5723 	/* Program types only with direct read access go here! */
5724 	case BPF_PROG_TYPE_LWT_IN:
5725 	case BPF_PROG_TYPE_LWT_OUT:
5726 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5727 	case BPF_PROG_TYPE_SK_REUSEPORT:
5728 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5729 	case BPF_PROG_TYPE_CGROUP_SKB:
5730 		if (t == BPF_WRITE)
5731 			return false;
5732 		fallthrough;
5733 
5734 	/* Program types with direct read + write access go here! */
5735 	case BPF_PROG_TYPE_SCHED_CLS:
5736 	case BPF_PROG_TYPE_SCHED_ACT:
5737 	case BPF_PROG_TYPE_XDP:
5738 	case BPF_PROG_TYPE_LWT_XMIT:
5739 	case BPF_PROG_TYPE_SK_SKB:
5740 	case BPF_PROG_TYPE_SK_MSG:
5741 		if (meta)
5742 			return meta->pkt_access;
5743 
5744 		env->seen_direct_write = true;
5745 		return true;
5746 
5747 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5748 		if (t == BPF_WRITE)
5749 			env->seen_direct_write = true;
5750 
5751 		return true;
5752 
5753 	default:
5754 		return false;
5755 	}
5756 }
5757 
5758 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5759 			       int size, bool zero_size_allowed)
5760 {
5761 	struct bpf_reg_state *regs = cur_regs(env);
5762 	struct bpf_reg_state *reg = &regs[regno];
5763 	int err;
5764 
5765 	/* We may have added a variable offset to the packet pointer; but any
5766 	 * reg->range we have comes after that.  We are only checking the fixed
5767 	 * offset.
5768 	 */
5769 
5770 	/* We don't allow negative numbers, because we aren't tracking enough
5771 	 * detail to prove they're safe.
5772 	 */
5773 	if (reg->smin_value < 0) {
5774 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5775 			regno);
5776 		return -EACCES;
5777 	}
5778 
5779 	err = reg->range < 0 ? -EINVAL :
5780 	      __check_mem_access(env, regno, off, size, reg->range,
5781 				 zero_size_allowed);
5782 	if (err) {
5783 		verbose(env, "R%d offset is outside of the packet\n", regno);
5784 		return err;
5785 	}
5786 
5787 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5788 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5789 	 * otherwise find_good_pkt_pointers would have refused to set range info
5790 	 * that __check_mem_access would have rejected this pkt access.
5791 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5792 	 */
5793 	env->prog->aux->max_pkt_offset =
5794 		max_t(u32, env->prog->aux->max_pkt_offset,
5795 		      off + reg->umax_value + size - 1);
5796 
5797 	return err;
5798 }
5799 
5800 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5801 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5802 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5803 			    struct btf **btf, u32 *btf_id, bool *is_retval, bool is_ldsx)
5804 {
5805 	struct bpf_insn_access_aux info = {
5806 		.reg_type = *reg_type,
5807 		.log = &env->log,
5808 		.is_retval = false,
5809 		.is_ldsx = is_ldsx,
5810 	};
5811 
5812 	if (env->ops->is_valid_access &&
5813 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5814 		/* A non zero info.ctx_field_size indicates that this field is a
5815 		 * candidate for later verifier transformation to load the whole
5816 		 * field and then apply a mask when accessed with a narrower
5817 		 * access than actual ctx access size. A zero info.ctx_field_size
5818 		 * will only allow for whole field access and rejects any other
5819 		 * type of narrower access.
5820 		 */
5821 		*reg_type = info.reg_type;
5822 		*is_retval = info.is_retval;
5823 
5824 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5825 			*btf = info.btf;
5826 			*btf_id = info.btf_id;
5827 		} else {
5828 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5829 		}
5830 		/* remember the offset of last byte accessed in ctx */
5831 		if (env->prog->aux->max_ctx_offset < off + size)
5832 			env->prog->aux->max_ctx_offset = off + size;
5833 		return 0;
5834 	}
5835 
5836 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5837 	return -EACCES;
5838 }
5839 
5840 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5841 				  int size)
5842 {
5843 	if (size < 0 || off < 0 ||
5844 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5845 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5846 			off, size);
5847 		return -EACCES;
5848 	}
5849 	return 0;
5850 }
5851 
5852 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5853 			     u32 regno, int off, int size,
5854 			     enum bpf_access_type t)
5855 {
5856 	struct bpf_reg_state *regs = cur_regs(env);
5857 	struct bpf_reg_state *reg = &regs[regno];
5858 	struct bpf_insn_access_aux info = {};
5859 	bool valid;
5860 
5861 	if (reg->smin_value < 0) {
5862 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5863 			regno);
5864 		return -EACCES;
5865 	}
5866 
5867 	switch (reg->type) {
5868 	case PTR_TO_SOCK_COMMON:
5869 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5870 		break;
5871 	case PTR_TO_SOCKET:
5872 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5873 		break;
5874 	case PTR_TO_TCP_SOCK:
5875 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5876 		break;
5877 	case PTR_TO_XDP_SOCK:
5878 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5879 		break;
5880 	default:
5881 		valid = false;
5882 	}
5883 
5884 
5885 	if (valid) {
5886 		env->insn_aux_data[insn_idx].ctx_field_size =
5887 			info.ctx_field_size;
5888 		return 0;
5889 	}
5890 
5891 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5892 		regno, reg_type_str(env, reg->type), off, size);
5893 
5894 	return -EACCES;
5895 }
5896 
5897 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5898 {
5899 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5900 }
5901 
5902 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5903 {
5904 	const struct bpf_reg_state *reg = reg_state(env, regno);
5905 
5906 	return reg->type == PTR_TO_CTX;
5907 }
5908 
5909 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5910 {
5911 	const struct bpf_reg_state *reg = reg_state(env, regno);
5912 
5913 	return type_is_sk_pointer(reg->type);
5914 }
5915 
5916 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5917 {
5918 	const struct bpf_reg_state *reg = reg_state(env, regno);
5919 
5920 	return type_is_pkt_pointer(reg->type);
5921 }
5922 
5923 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5924 {
5925 	const struct bpf_reg_state *reg = reg_state(env, regno);
5926 
5927 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5928 	return reg->type == PTR_TO_FLOW_KEYS;
5929 }
5930 
5931 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
5932 {
5933 	const struct bpf_reg_state *reg = reg_state(env, regno);
5934 
5935 	return reg->type == PTR_TO_ARENA;
5936 }
5937 
5938 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5939 #ifdef CONFIG_NET
5940 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5941 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5942 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5943 #endif
5944 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5945 };
5946 
5947 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5948 {
5949 	/* A referenced register is always trusted. */
5950 	if (reg->ref_obj_id)
5951 		return true;
5952 
5953 	/* Types listed in the reg2btf_ids are always trusted */
5954 	if (reg2btf_ids[base_type(reg->type)] &&
5955 	    !bpf_type_has_unsafe_modifiers(reg->type))
5956 		return true;
5957 
5958 	/* If a register is not referenced, it is trusted if it has the
5959 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5960 	 * other type modifiers may be safe, but we elect to take an opt-in
5961 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5962 	 * not.
5963 	 *
5964 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5965 	 * for whether a register is trusted.
5966 	 */
5967 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5968 	       !bpf_type_has_unsafe_modifiers(reg->type);
5969 }
5970 
5971 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5972 {
5973 	return reg->type & MEM_RCU;
5974 }
5975 
5976 static void clear_trusted_flags(enum bpf_type_flag *flag)
5977 {
5978 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5979 }
5980 
5981 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5982 				   const struct bpf_reg_state *reg,
5983 				   int off, int size, bool strict)
5984 {
5985 	struct tnum reg_off;
5986 	int ip_align;
5987 
5988 	/* Byte size accesses are always allowed. */
5989 	if (!strict || size == 1)
5990 		return 0;
5991 
5992 	/* For platforms that do not have a Kconfig enabling
5993 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5994 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5995 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5996 	 * to this code only in strict mode where we want to emulate
5997 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5998 	 * unconditional IP align value of '2'.
5999 	 */
6000 	ip_align = 2;
6001 
6002 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
6003 	if (!tnum_is_aligned(reg_off, size)) {
6004 		char tn_buf[48];
6005 
6006 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6007 		verbose(env,
6008 			"misaligned packet access off %d+%s+%d+%d size %d\n",
6009 			ip_align, tn_buf, reg->off, off, size);
6010 		return -EACCES;
6011 	}
6012 
6013 	return 0;
6014 }
6015 
6016 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
6017 				       const struct bpf_reg_state *reg,
6018 				       const char *pointer_desc,
6019 				       int off, int size, bool strict)
6020 {
6021 	struct tnum reg_off;
6022 
6023 	/* Byte size accesses are always allowed. */
6024 	if (!strict || size == 1)
6025 		return 0;
6026 
6027 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
6028 	if (!tnum_is_aligned(reg_off, size)) {
6029 		char tn_buf[48];
6030 
6031 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6032 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
6033 			pointer_desc, tn_buf, reg->off, off, size);
6034 		return -EACCES;
6035 	}
6036 
6037 	return 0;
6038 }
6039 
6040 static int check_ptr_alignment(struct bpf_verifier_env *env,
6041 			       const struct bpf_reg_state *reg, int off,
6042 			       int size, bool strict_alignment_once)
6043 {
6044 	bool strict = env->strict_alignment || strict_alignment_once;
6045 	const char *pointer_desc = "";
6046 
6047 	switch (reg->type) {
6048 	case PTR_TO_PACKET:
6049 	case PTR_TO_PACKET_META:
6050 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
6051 		 * right in front, treat it the very same way.
6052 		 */
6053 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
6054 	case PTR_TO_FLOW_KEYS:
6055 		pointer_desc = "flow keys ";
6056 		break;
6057 	case PTR_TO_MAP_KEY:
6058 		pointer_desc = "key ";
6059 		break;
6060 	case PTR_TO_MAP_VALUE:
6061 		pointer_desc = "value ";
6062 		break;
6063 	case PTR_TO_CTX:
6064 		pointer_desc = "context ";
6065 		break;
6066 	case PTR_TO_STACK:
6067 		pointer_desc = "stack ";
6068 		/* The stack spill tracking logic in check_stack_write_fixed_off()
6069 		 * and check_stack_read_fixed_off() relies on stack accesses being
6070 		 * aligned.
6071 		 */
6072 		strict = true;
6073 		break;
6074 	case PTR_TO_SOCKET:
6075 		pointer_desc = "sock ";
6076 		break;
6077 	case PTR_TO_SOCK_COMMON:
6078 		pointer_desc = "sock_common ";
6079 		break;
6080 	case PTR_TO_TCP_SOCK:
6081 		pointer_desc = "tcp_sock ";
6082 		break;
6083 	case PTR_TO_XDP_SOCK:
6084 		pointer_desc = "xdp_sock ";
6085 		break;
6086 	case PTR_TO_ARENA:
6087 		return 0;
6088 	default:
6089 		break;
6090 	}
6091 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
6092 					   strict);
6093 }
6094 
6095 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
6096 {
6097 	if (!bpf_jit_supports_private_stack())
6098 		return NO_PRIV_STACK;
6099 
6100 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
6101 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
6102 	 * explicitly.
6103 	 */
6104 	switch (prog->type) {
6105 	case BPF_PROG_TYPE_KPROBE:
6106 	case BPF_PROG_TYPE_TRACEPOINT:
6107 	case BPF_PROG_TYPE_PERF_EVENT:
6108 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6109 		return PRIV_STACK_ADAPTIVE;
6110 	case BPF_PROG_TYPE_TRACING:
6111 	case BPF_PROG_TYPE_LSM:
6112 	case BPF_PROG_TYPE_STRUCT_OPS:
6113 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
6114 			return PRIV_STACK_ADAPTIVE;
6115 		fallthrough;
6116 	default:
6117 		break;
6118 	}
6119 
6120 	return NO_PRIV_STACK;
6121 }
6122 
6123 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
6124 {
6125 	if (env->prog->jit_requested)
6126 		return round_up(stack_depth, 16);
6127 
6128 	/* round up to 32-bytes, since this is granularity
6129 	 * of interpreter stack size
6130 	 */
6131 	return round_up(max_t(u32, stack_depth, 1), 32);
6132 }
6133 
6134 /* starting from main bpf function walk all instructions of the function
6135  * and recursively walk all callees that given function can call.
6136  * Ignore jump and exit insns.
6137  * Since recursion is prevented by check_cfg() this algorithm
6138  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
6139  */
6140 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
6141 					 bool priv_stack_supported)
6142 {
6143 	struct bpf_subprog_info *subprog = env->subprog_info;
6144 	struct bpf_insn *insn = env->prog->insnsi;
6145 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
6146 	bool tail_call_reachable = false;
6147 	int ret_insn[MAX_CALL_FRAMES];
6148 	int ret_prog[MAX_CALL_FRAMES];
6149 	int j;
6150 
6151 	i = subprog[idx].start;
6152 	if (!priv_stack_supported)
6153 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6154 process_func:
6155 	/* protect against potential stack overflow that might happen when
6156 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
6157 	 * depth for such case down to 256 so that the worst case scenario
6158 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
6159 	 * 8k).
6160 	 *
6161 	 * To get the idea what might happen, see an example:
6162 	 * func1 -> sub rsp, 128
6163 	 *  subfunc1 -> sub rsp, 256
6164 	 *  tailcall1 -> add rsp, 256
6165 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
6166 	 *   subfunc2 -> sub rsp, 64
6167 	 *   subfunc22 -> sub rsp, 128
6168 	 *   tailcall2 -> add rsp, 128
6169 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
6170 	 *
6171 	 * tailcall will unwind the current stack frame but it will not get rid
6172 	 * of caller's stack as shown on the example above.
6173 	 */
6174 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
6175 		verbose(env,
6176 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
6177 			depth);
6178 		return -EACCES;
6179 	}
6180 
6181 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
6182 	if (priv_stack_supported) {
6183 		/* Request private stack support only if the subprog stack
6184 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
6185 		 * avoid jit penalty if the stack usage is small.
6186 		 */
6187 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
6188 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
6189 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
6190 	}
6191 
6192 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6193 		if (subprog_depth > MAX_BPF_STACK) {
6194 			verbose(env, "stack size of subprog %d is %d. Too large\n",
6195 				idx, subprog_depth);
6196 			return -EACCES;
6197 		}
6198 	} else {
6199 		depth += subprog_depth;
6200 		if (depth > MAX_BPF_STACK) {
6201 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
6202 				frame + 1, depth);
6203 			return -EACCES;
6204 		}
6205 	}
6206 continue_func:
6207 	subprog_end = subprog[idx + 1].start;
6208 	for (; i < subprog_end; i++) {
6209 		int next_insn, sidx;
6210 
6211 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
6212 			bool err = false;
6213 
6214 			if (!is_bpf_throw_kfunc(insn + i))
6215 				continue;
6216 			if (subprog[idx].is_cb)
6217 				err = true;
6218 			for (int c = 0; c < frame && !err; c++) {
6219 				if (subprog[ret_prog[c]].is_cb) {
6220 					err = true;
6221 					break;
6222 				}
6223 			}
6224 			if (!err)
6225 				continue;
6226 			verbose(env,
6227 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
6228 				i, idx);
6229 			return -EINVAL;
6230 		}
6231 
6232 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
6233 			continue;
6234 		/* remember insn and function to return to */
6235 		ret_insn[frame] = i + 1;
6236 		ret_prog[frame] = idx;
6237 
6238 		/* find the callee */
6239 		next_insn = i + insn[i].imm + 1;
6240 		sidx = find_subprog(env, next_insn);
6241 		if (sidx < 0) {
6242 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6243 				  next_insn);
6244 			return -EFAULT;
6245 		}
6246 		if (subprog[sidx].is_async_cb) {
6247 			if (subprog[sidx].has_tail_call) {
6248 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
6249 				return -EFAULT;
6250 			}
6251 			/* async callbacks don't increase bpf prog stack size unless called directly */
6252 			if (!bpf_pseudo_call(insn + i))
6253 				continue;
6254 			if (subprog[sidx].is_exception_cb) {
6255 				verbose(env, "insn %d cannot call exception cb directly\n", i);
6256 				return -EINVAL;
6257 			}
6258 		}
6259 		i = next_insn;
6260 		idx = sidx;
6261 		if (!priv_stack_supported)
6262 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6263 
6264 		if (subprog[idx].has_tail_call)
6265 			tail_call_reachable = true;
6266 
6267 		frame++;
6268 		if (frame >= MAX_CALL_FRAMES) {
6269 			verbose(env, "the call stack of %d frames is too deep !\n",
6270 				frame);
6271 			return -E2BIG;
6272 		}
6273 		goto process_func;
6274 	}
6275 	/* if tail call got detected across bpf2bpf calls then mark each of the
6276 	 * currently present subprog frames as tail call reachable subprogs;
6277 	 * this info will be utilized by JIT so that we will be preserving the
6278 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
6279 	 */
6280 	if (tail_call_reachable)
6281 		for (j = 0; j < frame; j++) {
6282 			if (subprog[ret_prog[j]].is_exception_cb) {
6283 				verbose(env, "cannot tail call within exception cb\n");
6284 				return -EINVAL;
6285 			}
6286 			subprog[ret_prog[j]].tail_call_reachable = true;
6287 		}
6288 	if (subprog[0].tail_call_reachable)
6289 		env->prog->aux->tail_call_reachable = true;
6290 
6291 	/* end of for() loop means the last insn of the 'subprog'
6292 	 * was reached. Doesn't matter whether it was JA or EXIT
6293 	 */
6294 	if (frame == 0)
6295 		return 0;
6296 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
6297 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6298 	frame--;
6299 	i = ret_insn[frame];
6300 	idx = ret_prog[frame];
6301 	goto continue_func;
6302 }
6303 
6304 static int check_max_stack_depth(struct bpf_verifier_env *env)
6305 {
6306 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
6307 	struct bpf_subprog_info *si = env->subprog_info;
6308 	bool priv_stack_supported;
6309 	int ret;
6310 
6311 	for (int i = 0; i < env->subprog_cnt; i++) {
6312 		if (si[i].has_tail_call) {
6313 			priv_stack_mode = NO_PRIV_STACK;
6314 			break;
6315 		}
6316 	}
6317 
6318 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
6319 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
6320 
6321 	/* All async_cb subprogs use normal kernel stack. If a particular
6322 	 * subprog appears in both main prog and async_cb subtree, that
6323 	 * subprog will use normal kernel stack to avoid potential nesting.
6324 	 * The reverse subprog traversal ensures when main prog subtree is
6325 	 * checked, the subprogs appearing in async_cb subtrees are already
6326 	 * marked as using normal kernel stack, so stack size checking can
6327 	 * be done properly.
6328 	 */
6329 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
6330 		if (!i || si[i].is_async_cb) {
6331 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
6332 			ret = check_max_stack_depth_subprog(env, i, priv_stack_supported);
6333 			if (ret < 0)
6334 				return ret;
6335 		}
6336 	}
6337 
6338 	for (int i = 0; i < env->subprog_cnt; i++) {
6339 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6340 			env->prog->aux->jits_use_priv_stack = true;
6341 			break;
6342 		}
6343 	}
6344 
6345 	return 0;
6346 }
6347 
6348 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6349 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6350 				  const struct bpf_insn *insn, int idx)
6351 {
6352 	int start = idx + insn->imm + 1, subprog;
6353 
6354 	subprog = find_subprog(env, start);
6355 	if (subprog < 0) {
6356 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6357 			  start);
6358 		return -EFAULT;
6359 	}
6360 	return env->subprog_info[subprog].stack_depth;
6361 }
6362 #endif
6363 
6364 static int __check_buffer_access(struct bpf_verifier_env *env,
6365 				 const char *buf_info,
6366 				 const struct bpf_reg_state *reg,
6367 				 int regno, int off, int size)
6368 {
6369 	if (off < 0) {
6370 		verbose(env,
6371 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6372 			regno, buf_info, off, size);
6373 		return -EACCES;
6374 	}
6375 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6376 		char tn_buf[48];
6377 
6378 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6379 		verbose(env,
6380 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6381 			regno, off, tn_buf);
6382 		return -EACCES;
6383 	}
6384 
6385 	return 0;
6386 }
6387 
6388 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6389 				  const struct bpf_reg_state *reg,
6390 				  int regno, int off, int size)
6391 {
6392 	int err;
6393 
6394 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6395 	if (err)
6396 		return err;
6397 
6398 	if (off + size > env->prog->aux->max_tp_access)
6399 		env->prog->aux->max_tp_access = off + size;
6400 
6401 	return 0;
6402 }
6403 
6404 static int check_buffer_access(struct bpf_verifier_env *env,
6405 			       const struct bpf_reg_state *reg,
6406 			       int regno, int off, int size,
6407 			       bool zero_size_allowed,
6408 			       u32 *max_access)
6409 {
6410 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6411 	int err;
6412 
6413 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6414 	if (err)
6415 		return err;
6416 
6417 	if (off + size > *max_access)
6418 		*max_access = off + size;
6419 
6420 	return 0;
6421 }
6422 
6423 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6424 static void zext_32_to_64(struct bpf_reg_state *reg)
6425 {
6426 	reg->var_off = tnum_subreg(reg->var_off);
6427 	__reg_assign_32_into_64(reg);
6428 }
6429 
6430 /* truncate register to smaller size (in bytes)
6431  * must be called with size < BPF_REG_SIZE
6432  */
6433 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6434 {
6435 	u64 mask;
6436 
6437 	/* clear high bits in bit representation */
6438 	reg->var_off = tnum_cast(reg->var_off, size);
6439 
6440 	/* fix arithmetic bounds */
6441 	mask = ((u64)1 << (size * 8)) - 1;
6442 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6443 		reg->umin_value &= mask;
6444 		reg->umax_value &= mask;
6445 	} else {
6446 		reg->umin_value = 0;
6447 		reg->umax_value = mask;
6448 	}
6449 	reg->smin_value = reg->umin_value;
6450 	reg->smax_value = reg->umax_value;
6451 
6452 	/* If size is smaller than 32bit register the 32bit register
6453 	 * values are also truncated so we push 64-bit bounds into
6454 	 * 32-bit bounds. Above were truncated < 32-bits already.
6455 	 */
6456 	if (size < 4)
6457 		__mark_reg32_unbounded(reg);
6458 
6459 	reg_bounds_sync(reg);
6460 }
6461 
6462 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6463 {
6464 	if (size == 1) {
6465 		reg->smin_value = reg->s32_min_value = S8_MIN;
6466 		reg->smax_value = reg->s32_max_value = S8_MAX;
6467 	} else if (size == 2) {
6468 		reg->smin_value = reg->s32_min_value = S16_MIN;
6469 		reg->smax_value = reg->s32_max_value = S16_MAX;
6470 	} else {
6471 		/* size == 4 */
6472 		reg->smin_value = reg->s32_min_value = S32_MIN;
6473 		reg->smax_value = reg->s32_max_value = S32_MAX;
6474 	}
6475 	reg->umin_value = reg->u32_min_value = 0;
6476 	reg->umax_value = U64_MAX;
6477 	reg->u32_max_value = U32_MAX;
6478 	reg->var_off = tnum_unknown;
6479 }
6480 
6481 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6482 {
6483 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6484 	u64 top_smax_value, top_smin_value;
6485 	u64 num_bits = size * 8;
6486 
6487 	if (tnum_is_const(reg->var_off)) {
6488 		u64_cval = reg->var_off.value;
6489 		if (size == 1)
6490 			reg->var_off = tnum_const((s8)u64_cval);
6491 		else if (size == 2)
6492 			reg->var_off = tnum_const((s16)u64_cval);
6493 		else
6494 			/* size == 4 */
6495 			reg->var_off = tnum_const((s32)u64_cval);
6496 
6497 		u64_cval = reg->var_off.value;
6498 		reg->smax_value = reg->smin_value = u64_cval;
6499 		reg->umax_value = reg->umin_value = u64_cval;
6500 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6501 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6502 		return;
6503 	}
6504 
6505 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6506 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6507 
6508 	if (top_smax_value != top_smin_value)
6509 		goto out;
6510 
6511 	/* find the s64_min and s64_min after sign extension */
6512 	if (size == 1) {
6513 		init_s64_max = (s8)reg->smax_value;
6514 		init_s64_min = (s8)reg->smin_value;
6515 	} else if (size == 2) {
6516 		init_s64_max = (s16)reg->smax_value;
6517 		init_s64_min = (s16)reg->smin_value;
6518 	} else {
6519 		init_s64_max = (s32)reg->smax_value;
6520 		init_s64_min = (s32)reg->smin_value;
6521 	}
6522 
6523 	s64_max = max(init_s64_max, init_s64_min);
6524 	s64_min = min(init_s64_max, init_s64_min);
6525 
6526 	/* both of s64_max/s64_min positive or negative */
6527 	if ((s64_max >= 0) == (s64_min >= 0)) {
6528 		reg->s32_min_value = reg->smin_value = s64_min;
6529 		reg->s32_max_value = reg->smax_value = s64_max;
6530 		reg->u32_min_value = reg->umin_value = s64_min;
6531 		reg->u32_max_value = reg->umax_value = s64_max;
6532 		reg->var_off = tnum_range(s64_min, s64_max);
6533 		return;
6534 	}
6535 
6536 out:
6537 	set_sext64_default_val(reg, size);
6538 }
6539 
6540 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6541 {
6542 	if (size == 1) {
6543 		reg->s32_min_value = S8_MIN;
6544 		reg->s32_max_value = S8_MAX;
6545 	} else {
6546 		/* size == 2 */
6547 		reg->s32_min_value = S16_MIN;
6548 		reg->s32_max_value = S16_MAX;
6549 	}
6550 	reg->u32_min_value = 0;
6551 	reg->u32_max_value = U32_MAX;
6552 	reg->var_off = tnum_subreg(tnum_unknown);
6553 }
6554 
6555 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6556 {
6557 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6558 	u32 top_smax_value, top_smin_value;
6559 	u32 num_bits = size * 8;
6560 
6561 	if (tnum_is_const(reg->var_off)) {
6562 		u32_val = reg->var_off.value;
6563 		if (size == 1)
6564 			reg->var_off = tnum_const((s8)u32_val);
6565 		else
6566 			reg->var_off = tnum_const((s16)u32_val);
6567 
6568 		u32_val = reg->var_off.value;
6569 		reg->s32_min_value = reg->s32_max_value = u32_val;
6570 		reg->u32_min_value = reg->u32_max_value = u32_val;
6571 		return;
6572 	}
6573 
6574 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6575 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6576 
6577 	if (top_smax_value != top_smin_value)
6578 		goto out;
6579 
6580 	/* find the s32_min and s32_min after sign extension */
6581 	if (size == 1) {
6582 		init_s32_max = (s8)reg->s32_max_value;
6583 		init_s32_min = (s8)reg->s32_min_value;
6584 	} else {
6585 		/* size == 2 */
6586 		init_s32_max = (s16)reg->s32_max_value;
6587 		init_s32_min = (s16)reg->s32_min_value;
6588 	}
6589 	s32_max = max(init_s32_max, init_s32_min);
6590 	s32_min = min(init_s32_max, init_s32_min);
6591 
6592 	if ((s32_min >= 0) == (s32_max >= 0)) {
6593 		reg->s32_min_value = s32_min;
6594 		reg->s32_max_value = s32_max;
6595 		reg->u32_min_value = (u32)s32_min;
6596 		reg->u32_max_value = (u32)s32_max;
6597 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6598 		return;
6599 	}
6600 
6601 out:
6602 	set_sext32_default_val(reg, size);
6603 }
6604 
6605 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6606 {
6607 	/* A map is considered read-only if the following condition are true:
6608 	 *
6609 	 * 1) BPF program side cannot change any of the map content. The
6610 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6611 	 *    and was set at map creation time.
6612 	 * 2) The map value(s) have been initialized from user space by a
6613 	 *    loader and then "frozen", such that no new map update/delete
6614 	 *    operations from syscall side are possible for the rest of
6615 	 *    the map's lifetime from that point onwards.
6616 	 * 3) Any parallel/pending map update/delete operations from syscall
6617 	 *    side have been completed. Only after that point, it's safe to
6618 	 *    assume that map value(s) are immutable.
6619 	 */
6620 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6621 	       READ_ONCE(map->frozen) &&
6622 	       !bpf_map_write_active(map);
6623 }
6624 
6625 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6626 			       bool is_ldsx)
6627 {
6628 	void *ptr;
6629 	u64 addr;
6630 	int err;
6631 
6632 	err = map->ops->map_direct_value_addr(map, &addr, off);
6633 	if (err)
6634 		return err;
6635 	ptr = (void *)(long)addr + off;
6636 
6637 	switch (size) {
6638 	case sizeof(u8):
6639 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6640 		break;
6641 	case sizeof(u16):
6642 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6643 		break;
6644 	case sizeof(u32):
6645 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6646 		break;
6647 	case sizeof(u64):
6648 		*val = *(u64 *)ptr;
6649 		break;
6650 	default:
6651 		return -EINVAL;
6652 	}
6653 	return 0;
6654 }
6655 
6656 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6657 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6658 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6659 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
6660 
6661 /*
6662  * Allow list few fields as RCU trusted or full trusted.
6663  * This logic doesn't allow mix tagging and will be removed once GCC supports
6664  * btf_type_tag.
6665  */
6666 
6667 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6668 BTF_TYPE_SAFE_RCU(struct task_struct) {
6669 	const cpumask_t *cpus_ptr;
6670 	struct css_set __rcu *cgroups;
6671 	struct task_struct __rcu *real_parent;
6672 	struct task_struct *group_leader;
6673 };
6674 
6675 BTF_TYPE_SAFE_RCU(struct cgroup) {
6676 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6677 	struct kernfs_node *kn;
6678 };
6679 
6680 BTF_TYPE_SAFE_RCU(struct css_set) {
6681 	struct cgroup *dfl_cgrp;
6682 };
6683 
6684 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6685 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6686 	struct file __rcu *exe_file;
6687 };
6688 
6689 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6690  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6691  */
6692 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6693 	struct sock *sk;
6694 };
6695 
6696 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6697 	struct sock *sk;
6698 };
6699 
6700 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6701 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6702 	struct seq_file *seq;
6703 };
6704 
6705 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6706 	struct bpf_iter_meta *meta;
6707 	struct task_struct *task;
6708 };
6709 
6710 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6711 	struct file *file;
6712 };
6713 
6714 BTF_TYPE_SAFE_TRUSTED(struct file) {
6715 	struct inode *f_inode;
6716 };
6717 
6718 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6719 	/* no negative dentry-s in places where bpf can see it */
6720 	struct inode *d_inode;
6721 };
6722 
6723 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
6724 	struct sock *sk;
6725 };
6726 
6727 static bool type_is_rcu(struct bpf_verifier_env *env,
6728 			struct bpf_reg_state *reg,
6729 			const char *field_name, u32 btf_id)
6730 {
6731 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6732 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6733 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6734 
6735 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6736 }
6737 
6738 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6739 				struct bpf_reg_state *reg,
6740 				const char *field_name, u32 btf_id)
6741 {
6742 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6743 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6744 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6745 
6746 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6747 }
6748 
6749 static bool type_is_trusted(struct bpf_verifier_env *env,
6750 			    struct bpf_reg_state *reg,
6751 			    const char *field_name, u32 btf_id)
6752 {
6753 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6754 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6755 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6756 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6757 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6758 
6759 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6760 }
6761 
6762 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
6763 				    struct bpf_reg_state *reg,
6764 				    const char *field_name, u32 btf_id)
6765 {
6766 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
6767 
6768 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
6769 					  "__safe_trusted_or_null");
6770 }
6771 
6772 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6773 				   struct bpf_reg_state *regs,
6774 				   int regno, int off, int size,
6775 				   enum bpf_access_type atype,
6776 				   int value_regno)
6777 {
6778 	struct bpf_reg_state *reg = regs + regno;
6779 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6780 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6781 	const char *field_name = NULL;
6782 	enum bpf_type_flag flag = 0;
6783 	u32 btf_id = 0;
6784 	bool mask;
6785 	int ret;
6786 
6787 	if (!env->allow_ptr_leaks) {
6788 		verbose(env,
6789 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6790 			tname);
6791 		return -EPERM;
6792 	}
6793 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6794 		verbose(env,
6795 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6796 			tname);
6797 		return -EINVAL;
6798 	}
6799 	if (off < 0) {
6800 		verbose(env,
6801 			"R%d is ptr_%s invalid negative access: off=%d\n",
6802 			regno, tname, off);
6803 		return -EACCES;
6804 	}
6805 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6806 		char tn_buf[48];
6807 
6808 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6809 		verbose(env,
6810 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6811 			regno, tname, off, tn_buf);
6812 		return -EACCES;
6813 	}
6814 
6815 	if (reg->type & MEM_USER) {
6816 		verbose(env,
6817 			"R%d is ptr_%s access user memory: off=%d\n",
6818 			regno, tname, off);
6819 		return -EACCES;
6820 	}
6821 
6822 	if (reg->type & MEM_PERCPU) {
6823 		verbose(env,
6824 			"R%d is ptr_%s access percpu memory: off=%d\n",
6825 			regno, tname, off);
6826 		return -EACCES;
6827 	}
6828 
6829 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6830 		if (!btf_is_kernel(reg->btf)) {
6831 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6832 			return -EFAULT;
6833 		}
6834 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6835 	} else {
6836 		/* Writes are permitted with default btf_struct_access for
6837 		 * program allocated objects (which always have ref_obj_id > 0),
6838 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6839 		 */
6840 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6841 			verbose(env, "only read is supported\n");
6842 			return -EACCES;
6843 		}
6844 
6845 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6846 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
6847 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6848 			return -EFAULT;
6849 		}
6850 
6851 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6852 	}
6853 
6854 	if (ret < 0)
6855 		return ret;
6856 	/* For raw_tp progs, we allow dereference of PTR_MAYBE_NULL
6857 	 * trusted PTR_TO_BTF_ID, these are the ones that are possibly
6858 	 * arguments to the raw_tp. Since internal checks in for trusted
6859 	 * reg in check_ptr_to_btf_access would consider PTR_MAYBE_NULL
6860 	 * modifier as problematic, mask it out temporarily for the
6861 	 * check. Don't apply this to pointers with ref_obj_id > 0, as
6862 	 * those won't be raw_tp args.
6863 	 *
6864 	 * We may end up applying this relaxation to other trusted
6865 	 * PTR_TO_BTF_ID with maybe null flag, since we cannot
6866 	 * distinguish PTR_MAYBE_NULL tagged for arguments vs normal
6867 	 * tagging, but that should expand allowed behavior, and not
6868 	 * cause regression for existing behavior.
6869 	 */
6870 	mask = mask_raw_tp_reg(env, reg);
6871 	if (ret != PTR_TO_BTF_ID) {
6872 		/* just mark; */
6873 
6874 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6875 		/* If this is an untrusted pointer, all pointers formed by walking it
6876 		 * also inherit the untrusted flag.
6877 		 */
6878 		flag = PTR_UNTRUSTED;
6879 
6880 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6881 		/* By default any pointer obtained from walking a trusted pointer is no
6882 		 * longer trusted, unless the field being accessed has explicitly been
6883 		 * marked as inheriting its parent's state of trust (either full or RCU).
6884 		 * For example:
6885 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6886 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6887 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6888 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6889 		 *
6890 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6891 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6892 		 */
6893 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6894 			flag |= PTR_TRUSTED;
6895 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
6896 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
6897 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6898 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6899 				/* ignore __rcu tag and mark it MEM_RCU */
6900 				flag |= MEM_RCU;
6901 			} else if (flag & MEM_RCU ||
6902 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6903 				/* __rcu tagged pointers can be NULL */
6904 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6905 
6906 				/* We always trust them */
6907 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6908 				    flag & PTR_UNTRUSTED)
6909 					flag &= ~PTR_UNTRUSTED;
6910 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6911 				/* keep as-is */
6912 			} else {
6913 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6914 				clear_trusted_flags(&flag);
6915 			}
6916 		} else {
6917 			/*
6918 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6919 			 * aggressively mark as untrusted otherwise such
6920 			 * pointers will be plain PTR_TO_BTF_ID without flags
6921 			 * and will be allowed to be passed into helpers for
6922 			 * compat reasons.
6923 			 */
6924 			flag = PTR_UNTRUSTED;
6925 		}
6926 	} else {
6927 		/* Old compat. Deprecated */
6928 		clear_trusted_flags(&flag);
6929 	}
6930 
6931 	if (atype == BPF_READ && value_regno >= 0) {
6932 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6933 		/* We've assigned a new type to regno, so don't undo masking. */
6934 		if (regno == value_regno)
6935 			mask = false;
6936 	}
6937 	unmask_raw_tp_reg(reg, mask);
6938 
6939 	return 0;
6940 }
6941 
6942 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6943 				   struct bpf_reg_state *regs,
6944 				   int regno, int off, int size,
6945 				   enum bpf_access_type atype,
6946 				   int value_regno)
6947 {
6948 	struct bpf_reg_state *reg = regs + regno;
6949 	struct bpf_map *map = reg->map_ptr;
6950 	struct bpf_reg_state map_reg;
6951 	enum bpf_type_flag flag = 0;
6952 	const struct btf_type *t;
6953 	const char *tname;
6954 	u32 btf_id;
6955 	int ret;
6956 
6957 	if (!btf_vmlinux) {
6958 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6959 		return -ENOTSUPP;
6960 	}
6961 
6962 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6963 		verbose(env, "map_ptr access not supported for map type %d\n",
6964 			map->map_type);
6965 		return -ENOTSUPP;
6966 	}
6967 
6968 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6969 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6970 
6971 	if (!env->allow_ptr_leaks) {
6972 		verbose(env,
6973 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6974 			tname);
6975 		return -EPERM;
6976 	}
6977 
6978 	if (off < 0) {
6979 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6980 			regno, tname, off);
6981 		return -EACCES;
6982 	}
6983 
6984 	if (atype != BPF_READ) {
6985 		verbose(env, "only read from %s is supported\n", tname);
6986 		return -EACCES;
6987 	}
6988 
6989 	/* Simulate access to a PTR_TO_BTF_ID */
6990 	memset(&map_reg, 0, sizeof(map_reg));
6991 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6992 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6993 	if (ret < 0)
6994 		return ret;
6995 
6996 	if (value_regno >= 0)
6997 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6998 
6999 	return 0;
7000 }
7001 
7002 /* Check that the stack access at the given offset is within bounds. The
7003  * maximum valid offset is -1.
7004  *
7005  * The minimum valid offset is -MAX_BPF_STACK for writes, and
7006  * -state->allocated_stack for reads.
7007  */
7008 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
7009                                           s64 off,
7010                                           struct bpf_func_state *state,
7011                                           enum bpf_access_type t)
7012 {
7013 	int min_valid_off;
7014 
7015 	if (t == BPF_WRITE || env->allow_uninit_stack)
7016 		min_valid_off = -MAX_BPF_STACK;
7017 	else
7018 		min_valid_off = -state->allocated_stack;
7019 
7020 	if (off < min_valid_off || off > -1)
7021 		return -EACCES;
7022 	return 0;
7023 }
7024 
7025 /* Check that the stack access at 'regno + off' falls within the maximum stack
7026  * bounds.
7027  *
7028  * 'off' includes `regno->offset`, but not its dynamic part (if any).
7029  */
7030 static int check_stack_access_within_bounds(
7031 		struct bpf_verifier_env *env,
7032 		int regno, int off, int access_size,
7033 		enum bpf_access_src src, enum bpf_access_type type)
7034 {
7035 	struct bpf_reg_state *regs = cur_regs(env);
7036 	struct bpf_reg_state *reg = regs + regno;
7037 	struct bpf_func_state *state = func(env, reg);
7038 	s64 min_off, max_off;
7039 	int err;
7040 	char *err_extra;
7041 
7042 	if (src == ACCESS_HELPER)
7043 		/* We don't know if helpers are reading or writing (or both). */
7044 		err_extra = " indirect access to";
7045 	else if (type == BPF_READ)
7046 		err_extra = " read from";
7047 	else
7048 		err_extra = " write to";
7049 
7050 	if (tnum_is_const(reg->var_off)) {
7051 		min_off = (s64)reg->var_off.value + off;
7052 		max_off = min_off + access_size;
7053 	} else {
7054 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
7055 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
7056 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
7057 				err_extra, regno);
7058 			return -EACCES;
7059 		}
7060 		min_off = reg->smin_value + off;
7061 		max_off = reg->smax_value + off + access_size;
7062 	}
7063 
7064 	err = check_stack_slot_within_bounds(env, min_off, state, type);
7065 	if (!err && max_off > 0)
7066 		err = -EINVAL; /* out of stack access into non-negative offsets */
7067 	if (!err && access_size < 0)
7068 		/* access_size should not be negative (or overflow an int); others checks
7069 		 * along the way should have prevented such an access.
7070 		 */
7071 		err = -EFAULT; /* invalid negative access size; integer overflow? */
7072 
7073 	if (err) {
7074 		if (tnum_is_const(reg->var_off)) {
7075 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
7076 				err_extra, regno, off, access_size);
7077 		} else {
7078 			char tn_buf[48];
7079 
7080 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7081 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
7082 				err_extra, regno, tn_buf, off, access_size);
7083 		}
7084 		return err;
7085 	}
7086 
7087 	/* Note that there is no stack access with offset zero, so the needed stack
7088 	 * size is -min_off, not -min_off+1.
7089 	 */
7090 	return grow_stack_state(env, state, -min_off /* size */);
7091 }
7092 
7093 static bool get_func_retval_range(struct bpf_prog *prog,
7094 				  struct bpf_retval_range *range)
7095 {
7096 	if (prog->type == BPF_PROG_TYPE_LSM &&
7097 		prog->expected_attach_type == BPF_LSM_MAC &&
7098 		!bpf_lsm_get_retval_range(prog, range)) {
7099 		return true;
7100 	}
7101 	return false;
7102 }
7103 
7104 /* check whether memory at (regno + off) is accessible for t = (read | write)
7105  * if t==write, value_regno is a register which value is stored into memory
7106  * if t==read, value_regno is a register which will receive the value from memory
7107  * if t==write && value_regno==-1, some unknown value is stored into memory
7108  * if t==read && value_regno==-1, don't care what we read from memory
7109  */
7110 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
7111 			    int off, int bpf_size, enum bpf_access_type t,
7112 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
7113 {
7114 	struct bpf_reg_state *regs = cur_regs(env);
7115 	struct bpf_reg_state *reg = regs + regno;
7116 	int size, err = 0;
7117 
7118 	size = bpf_size_to_bytes(bpf_size);
7119 	if (size < 0)
7120 		return size;
7121 
7122 	/* alignment checks will add in reg->off themselves */
7123 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
7124 	if (err)
7125 		return err;
7126 
7127 	/* for access checks, reg->off is just part of off */
7128 	off += reg->off;
7129 
7130 	if (reg->type == PTR_TO_MAP_KEY) {
7131 		if (t == BPF_WRITE) {
7132 			verbose(env, "write to change key R%d not allowed\n", regno);
7133 			return -EACCES;
7134 		}
7135 
7136 		err = check_mem_region_access(env, regno, off, size,
7137 					      reg->map_ptr->key_size, false);
7138 		if (err)
7139 			return err;
7140 		if (value_regno >= 0)
7141 			mark_reg_unknown(env, regs, value_regno);
7142 	} else if (reg->type == PTR_TO_MAP_VALUE) {
7143 		struct btf_field *kptr_field = NULL;
7144 
7145 		if (t == BPF_WRITE && value_regno >= 0 &&
7146 		    is_pointer_value(env, value_regno)) {
7147 			verbose(env, "R%d leaks addr into map\n", value_regno);
7148 			return -EACCES;
7149 		}
7150 		err = check_map_access_type(env, regno, off, size, t);
7151 		if (err)
7152 			return err;
7153 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
7154 		if (err)
7155 			return err;
7156 		if (tnum_is_const(reg->var_off))
7157 			kptr_field = btf_record_find(reg->map_ptr->record,
7158 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
7159 		if (kptr_field) {
7160 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
7161 		} else if (t == BPF_READ && value_regno >= 0) {
7162 			struct bpf_map *map = reg->map_ptr;
7163 
7164 			/* if map is read-only, track its contents as scalars */
7165 			if (tnum_is_const(reg->var_off) &&
7166 			    bpf_map_is_rdonly(map) &&
7167 			    map->ops->map_direct_value_addr) {
7168 				int map_off = off + reg->var_off.value;
7169 				u64 val = 0;
7170 
7171 				err = bpf_map_direct_read(map, map_off, size,
7172 							  &val, is_ldsx);
7173 				if (err)
7174 					return err;
7175 
7176 				regs[value_regno].type = SCALAR_VALUE;
7177 				__mark_reg_known(&regs[value_regno], val);
7178 			} else {
7179 				mark_reg_unknown(env, regs, value_regno);
7180 			}
7181 		}
7182 	} else if (base_type(reg->type) == PTR_TO_MEM) {
7183 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7184 
7185 		if (type_may_be_null(reg->type)) {
7186 			verbose(env, "R%d invalid mem access '%s'\n", regno,
7187 				reg_type_str(env, reg->type));
7188 			return -EACCES;
7189 		}
7190 
7191 		if (t == BPF_WRITE && rdonly_mem) {
7192 			verbose(env, "R%d cannot write into %s\n",
7193 				regno, reg_type_str(env, reg->type));
7194 			return -EACCES;
7195 		}
7196 
7197 		if (t == BPF_WRITE && value_regno >= 0 &&
7198 		    is_pointer_value(env, value_regno)) {
7199 			verbose(env, "R%d leaks addr into mem\n", value_regno);
7200 			return -EACCES;
7201 		}
7202 
7203 		err = check_mem_region_access(env, regno, off, size,
7204 					      reg->mem_size, false);
7205 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7206 			mark_reg_unknown(env, regs, value_regno);
7207 	} else if (reg->type == PTR_TO_CTX) {
7208 		bool is_retval = false;
7209 		struct bpf_retval_range range;
7210 		enum bpf_reg_type reg_type = SCALAR_VALUE;
7211 		struct btf *btf = NULL;
7212 		u32 btf_id = 0;
7213 
7214 		if (t == BPF_WRITE && value_regno >= 0 &&
7215 		    is_pointer_value(env, value_regno)) {
7216 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
7217 			return -EACCES;
7218 		}
7219 
7220 		err = check_ptr_off_reg(env, reg, regno);
7221 		if (err < 0)
7222 			return err;
7223 
7224 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
7225 				       &btf_id, &is_retval, is_ldsx);
7226 		if (err)
7227 			verbose_linfo(env, insn_idx, "; ");
7228 		if (!err && t == BPF_READ && value_regno >= 0) {
7229 			/* ctx access returns either a scalar, or a
7230 			 * PTR_TO_PACKET[_META,_END]. In the latter
7231 			 * case, we know the offset is zero.
7232 			 */
7233 			if (reg_type == SCALAR_VALUE) {
7234 				if (is_retval && get_func_retval_range(env->prog, &range)) {
7235 					err = __mark_reg_s32_range(env, regs, value_regno,
7236 								   range.minval, range.maxval);
7237 					if (err)
7238 						return err;
7239 				} else {
7240 					mark_reg_unknown(env, regs, value_regno);
7241 				}
7242 			} else {
7243 				mark_reg_known_zero(env, regs,
7244 						    value_regno);
7245 				if (type_may_be_null(reg_type))
7246 					regs[value_regno].id = ++env->id_gen;
7247 				/* A load of ctx field could have different
7248 				 * actual load size with the one encoded in the
7249 				 * insn. When the dst is PTR, it is for sure not
7250 				 * a sub-register.
7251 				 */
7252 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
7253 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
7254 					regs[value_regno].btf = btf;
7255 					regs[value_regno].btf_id = btf_id;
7256 				}
7257 			}
7258 			regs[value_regno].type = reg_type;
7259 		}
7260 
7261 	} else if (reg->type == PTR_TO_STACK) {
7262 		/* Basic bounds checks. */
7263 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
7264 		if (err)
7265 			return err;
7266 
7267 		if (t == BPF_READ)
7268 			err = check_stack_read(env, regno, off, size,
7269 					       value_regno);
7270 		else
7271 			err = check_stack_write(env, regno, off, size,
7272 						value_regno, insn_idx);
7273 	} else if (reg_is_pkt_pointer(reg)) {
7274 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7275 			verbose(env, "cannot write into packet\n");
7276 			return -EACCES;
7277 		}
7278 		if (t == BPF_WRITE && value_regno >= 0 &&
7279 		    is_pointer_value(env, value_regno)) {
7280 			verbose(env, "R%d leaks addr into packet\n",
7281 				value_regno);
7282 			return -EACCES;
7283 		}
7284 		err = check_packet_access(env, regno, off, size, false);
7285 		if (!err && t == BPF_READ && value_regno >= 0)
7286 			mark_reg_unknown(env, regs, value_regno);
7287 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
7288 		if (t == BPF_WRITE && value_regno >= 0 &&
7289 		    is_pointer_value(env, value_regno)) {
7290 			verbose(env, "R%d leaks addr into flow keys\n",
7291 				value_regno);
7292 			return -EACCES;
7293 		}
7294 
7295 		err = check_flow_keys_access(env, off, size);
7296 		if (!err && t == BPF_READ && value_regno >= 0)
7297 			mark_reg_unknown(env, regs, value_regno);
7298 	} else if (type_is_sk_pointer(reg->type)) {
7299 		if (t == BPF_WRITE) {
7300 			verbose(env, "R%d cannot write into %s\n",
7301 				regno, reg_type_str(env, reg->type));
7302 			return -EACCES;
7303 		}
7304 		err = check_sock_access(env, insn_idx, regno, off, size, t);
7305 		if (!err && value_regno >= 0)
7306 			mark_reg_unknown(env, regs, value_regno);
7307 	} else if (reg->type == PTR_TO_TP_BUFFER) {
7308 		err = check_tp_buffer_access(env, reg, regno, off, size);
7309 		if (!err && t == BPF_READ && value_regno >= 0)
7310 			mark_reg_unknown(env, regs, value_regno);
7311 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7312 		   (mask_raw_tp_reg_cond(env, reg) || !type_may_be_null(reg->type))) {
7313 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
7314 					      value_regno);
7315 	} else if (reg->type == CONST_PTR_TO_MAP) {
7316 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7317 					      value_regno);
7318 	} else if (base_type(reg->type) == PTR_TO_BUF) {
7319 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7320 		u32 *max_access;
7321 
7322 		if (rdonly_mem) {
7323 			if (t == BPF_WRITE) {
7324 				verbose(env, "R%d cannot write into %s\n",
7325 					regno, reg_type_str(env, reg->type));
7326 				return -EACCES;
7327 			}
7328 			max_access = &env->prog->aux->max_rdonly_access;
7329 		} else {
7330 			max_access = &env->prog->aux->max_rdwr_access;
7331 		}
7332 
7333 		err = check_buffer_access(env, reg, regno, off, size, false,
7334 					  max_access);
7335 
7336 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7337 			mark_reg_unknown(env, regs, value_regno);
7338 	} else if (reg->type == PTR_TO_ARENA) {
7339 		if (t == BPF_READ && value_regno >= 0)
7340 			mark_reg_unknown(env, regs, value_regno);
7341 	} else {
7342 		verbose(env, "R%d invalid mem access '%s'\n", regno,
7343 			reg_type_str(env, reg->type));
7344 		return -EACCES;
7345 	}
7346 
7347 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7348 	    regs[value_regno].type == SCALAR_VALUE) {
7349 		if (!is_ldsx)
7350 			/* b/h/w load zero-extends, mark upper bits as known 0 */
7351 			coerce_reg_to_size(&regs[value_regno], size);
7352 		else
7353 			coerce_reg_to_size_sx(&regs[value_regno], size);
7354 	}
7355 	return err;
7356 }
7357 
7358 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7359 			     bool allow_trust_mismatch);
7360 
7361 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
7362 {
7363 	int load_reg;
7364 	int err;
7365 
7366 	switch (insn->imm) {
7367 	case BPF_ADD:
7368 	case BPF_ADD | BPF_FETCH:
7369 	case BPF_AND:
7370 	case BPF_AND | BPF_FETCH:
7371 	case BPF_OR:
7372 	case BPF_OR | BPF_FETCH:
7373 	case BPF_XOR:
7374 	case BPF_XOR | BPF_FETCH:
7375 	case BPF_XCHG:
7376 	case BPF_CMPXCHG:
7377 		break;
7378 	default:
7379 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
7380 		return -EINVAL;
7381 	}
7382 
7383 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7384 		verbose(env, "invalid atomic operand size\n");
7385 		return -EINVAL;
7386 	}
7387 
7388 	/* check src1 operand */
7389 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7390 	if (err)
7391 		return err;
7392 
7393 	/* check src2 operand */
7394 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7395 	if (err)
7396 		return err;
7397 
7398 	if (insn->imm == BPF_CMPXCHG) {
7399 		/* Check comparison of R0 with memory location */
7400 		const u32 aux_reg = BPF_REG_0;
7401 
7402 		err = check_reg_arg(env, aux_reg, SRC_OP);
7403 		if (err)
7404 			return err;
7405 
7406 		if (is_pointer_value(env, aux_reg)) {
7407 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7408 			return -EACCES;
7409 		}
7410 	}
7411 
7412 	if (is_pointer_value(env, insn->src_reg)) {
7413 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7414 		return -EACCES;
7415 	}
7416 
7417 	if (is_ctx_reg(env, insn->dst_reg) ||
7418 	    is_pkt_reg(env, insn->dst_reg) ||
7419 	    is_flow_key_reg(env, insn->dst_reg) ||
7420 	    is_sk_reg(env, insn->dst_reg) ||
7421 	    (is_arena_reg(env, insn->dst_reg) && !bpf_jit_supports_insn(insn, true))) {
7422 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7423 			insn->dst_reg,
7424 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7425 		return -EACCES;
7426 	}
7427 
7428 	if (insn->imm & BPF_FETCH) {
7429 		if (insn->imm == BPF_CMPXCHG)
7430 			load_reg = BPF_REG_0;
7431 		else
7432 			load_reg = insn->src_reg;
7433 
7434 		/* check and record load of old value */
7435 		err = check_reg_arg(env, load_reg, DST_OP);
7436 		if (err)
7437 			return err;
7438 	} else {
7439 		/* This instruction accesses a memory location but doesn't
7440 		 * actually load it into a register.
7441 		 */
7442 		load_reg = -1;
7443 	}
7444 
7445 	/* Check whether we can read the memory, with second call for fetch
7446 	 * case to simulate the register fill.
7447 	 */
7448 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7449 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7450 	if (!err && load_reg >= 0)
7451 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7452 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
7453 				       true, false);
7454 	if (err)
7455 		return err;
7456 
7457 	if (is_arena_reg(env, insn->dst_reg)) {
7458 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
7459 		if (err)
7460 			return err;
7461 	}
7462 	/* Check whether we can write into the same memory. */
7463 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7464 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7465 	if (err)
7466 		return err;
7467 	return 0;
7468 }
7469 
7470 /* When register 'regno' is used to read the stack (either directly or through
7471  * a helper function) make sure that it's within stack boundary and, depending
7472  * on the access type and privileges, that all elements of the stack are
7473  * initialized.
7474  *
7475  * 'off' includes 'regno->off', but not its dynamic part (if any).
7476  *
7477  * All registers that have been spilled on the stack in the slots within the
7478  * read offsets are marked as read.
7479  */
7480 static int check_stack_range_initialized(
7481 		struct bpf_verifier_env *env, int regno, int off,
7482 		int access_size, bool zero_size_allowed,
7483 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7484 {
7485 	struct bpf_reg_state *reg = reg_state(env, regno);
7486 	struct bpf_func_state *state = func(env, reg);
7487 	int err, min_off, max_off, i, j, slot, spi;
7488 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7489 	enum bpf_access_type bounds_check_type;
7490 	/* Some accesses can write anything into the stack, others are
7491 	 * read-only.
7492 	 */
7493 	bool clobber = false;
7494 
7495 	if (access_size == 0 && !zero_size_allowed) {
7496 		verbose(env, "invalid zero-sized read\n");
7497 		return -EACCES;
7498 	}
7499 
7500 	if (type == ACCESS_HELPER) {
7501 		/* The bounds checks for writes are more permissive than for
7502 		 * reads. However, if raw_mode is not set, we'll do extra
7503 		 * checks below.
7504 		 */
7505 		bounds_check_type = BPF_WRITE;
7506 		clobber = true;
7507 	} else {
7508 		bounds_check_type = BPF_READ;
7509 	}
7510 	err = check_stack_access_within_bounds(env, regno, off, access_size,
7511 					       type, bounds_check_type);
7512 	if (err)
7513 		return err;
7514 
7515 
7516 	if (tnum_is_const(reg->var_off)) {
7517 		min_off = max_off = reg->var_off.value + off;
7518 	} else {
7519 		/* Variable offset is prohibited for unprivileged mode for
7520 		 * simplicity since it requires corresponding support in
7521 		 * Spectre masking for stack ALU.
7522 		 * See also retrieve_ptr_limit().
7523 		 */
7524 		if (!env->bypass_spec_v1) {
7525 			char tn_buf[48];
7526 
7527 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7528 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7529 				regno, err_extra, tn_buf);
7530 			return -EACCES;
7531 		}
7532 		/* Only initialized buffer on stack is allowed to be accessed
7533 		 * with variable offset. With uninitialized buffer it's hard to
7534 		 * guarantee that whole memory is marked as initialized on
7535 		 * helper return since specific bounds are unknown what may
7536 		 * cause uninitialized stack leaking.
7537 		 */
7538 		if (meta && meta->raw_mode)
7539 			meta = NULL;
7540 
7541 		min_off = reg->smin_value + off;
7542 		max_off = reg->smax_value + off;
7543 	}
7544 
7545 	if (meta && meta->raw_mode) {
7546 		/* Ensure we won't be overwriting dynptrs when simulating byte
7547 		 * by byte access in check_helper_call using meta.access_size.
7548 		 * This would be a problem if we have a helper in the future
7549 		 * which takes:
7550 		 *
7551 		 *	helper(uninit_mem, len, dynptr)
7552 		 *
7553 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7554 		 * may end up writing to dynptr itself when touching memory from
7555 		 * arg 1. This can be relaxed on a case by case basis for known
7556 		 * safe cases, but reject due to the possibilitiy of aliasing by
7557 		 * default.
7558 		 */
7559 		for (i = min_off; i < max_off + access_size; i++) {
7560 			int stack_off = -i - 1;
7561 
7562 			spi = __get_spi(i);
7563 			/* raw_mode may write past allocated_stack */
7564 			if (state->allocated_stack <= stack_off)
7565 				continue;
7566 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7567 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7568 				return -EACCES;
7569 			}
7570 		}
7571 		meta->access_size = access_size;
7572 		meta->regno = regno;
7573 		return 0;
7574 	}
7575 
7576 	for (i = min_off; i < max_off + access_size; i++) {
7577 		u8 *stype;
7578 
7579 		slot = -i - 1;
7580 		spi = slot / BPF_REG_SIZE;
7581 		if (state->allocated_stack <= slot) {
7582 			verbose(env, "verifier bug: allocated_stack too small");
7583 			return -EFAULT;
7584 		}
7585 
7586 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7587 		if (*stype == STACK_MISC)
7588 			goto mark;
7589 		if ((*stype == STACK_ZERO) ||
7590 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7591 			if (clobber) {
7592 				/* helper can write anything into the stack */
7593 				*stype = STACK_MISC;
7594 			}
7595 			goto mark;
7596 		}
7597 
7598 		if (is_spilled_reg(&state->stack[spi]) &&
7599 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7600 		     env->allow_ptr_leaks)) {
7601 			if (clobber) {
7602 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7603 				for (j = 0; j < BPF_REG_SIZE; j++)
7604 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7605 			}
7606 			goto mark;
7607 		}
7608 
7609 		if (tnum_is_const(reg->var_off)) {
7610 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7611 				err_extra, regno, min_off, i - min_off, access_size);
7612 		} else {
7613 			char tn_buf[48];
7614 
7615 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7616 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7617 				err_extra, regno, tn_buf, i - min_off, access_size);
7618 		}
7619 		return -EACCES;
7620 mark:
7621 		/* reading any byte out of 8-byte 'spill_slot' will cause
7622 		 * the whole slot to be marked as 'read'
7623 		 */
7624 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7625 			      state->stack[spi].spilled_ptr.parent,
7626 			      REG_LIVE_READ64);
7627 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7628 		 * be sure that whether stack slot is written to or not. Hence,
7629 		 * we must still conservatively propagate reads upwards even if
7630 		 * helper may write to the entire memory range.
7631 		 */
7632 	}
7633 	return 0;
7634 }
7635 
7636 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7637 				   int access_size, enum bpf_access_type access_type,
7638 				   bool zero_size_allowed,
7639 				   struct bpf_call_arg_meta *meta)
7640 {
7641 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7642 	u32 *max_access;
7643 
7644 	switch (base_type(reg->type)) {
7645 	case PTR_TO_PACKET:
7646 	case PTR_TO_PACKET_META:
7647 		return check_packet_access(env, regno, reg->off, access_size,
7648 					   zero_size_allowed);
7649 	case PTR_TO_MAP_KEY:
7650 		if (access_type == BPF_WRITE) {
7651 			verbose(env, "R%d cannot write into %s\n", regno,
7652 				reg_type_str(env, reg->type));
7653 			return -EACCES;
7654 		}
7655 		return check_mem_region_access(env, regno, reg->off, access_size,
7656 					       reg->map_ptr->key_size, false);
7657 	case PTR_TO_MAP_VALUE:
7658 		if (check_map_access_type(env, regno, reg->off, access_size, access_type))
7659 			return -EACCES;
7660 		return check_map_access(env, regno, reg->off, access_size,
7661 					zero_size_allowed, ACCESS_HELPER);
7662 	case PTR_TO_MEM:
7663 		if (type_is_rdonly_mem(reg->type)) {
7664 			if (access_type == BPF_WRITE) {
7665 				verbose(env, "R%d cannot write into %s\n", regno,
7666 					reg_type_str(env, reg->type));
7667 				return -EACCES;
7668 			}
7669 		}
7670 		return check_mem_region_access(env, regno, reg->off,
7671 					       access_size, reg->mem_size,
7672 					       zero_size_allowed);
7673 	case PTR_TO_BUF:
7674 		if (type_is_rdonly_mem(reg->type)) {
7675 			if (access_type == BPF_WRITE) {
7676 				verbose(env, "R%d cannot write into %s\n", regno,
7677 					reg_type_str(env, reg->type));
7678 				return -EACCES;
7679 			}
7680 
7681 			max_access = &env->prog->aux->max_rdonly_access;
7682 		} else {
7683 			max_access = &env->prog->aux->max_rdwr_access;
7684 		}
7685 		return check_buffer_access(env, reg, regno, reg->off,
7686 					   access_size, zero_size_allowed,
7687 					   max_access);
7688 	case PTR_TO_STACK:
7689 		return check_stack_range_initialized(
7690 				env,
7691 				regno, reg->off, access_size,
7692 				zero_size_allowed, ACCESS_HELPER, meta);
7693 	case PTR_TO_BTF_ID:
7694 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7695 					       access_size, BPF_READ, -1);
7696 	case PTR_TO_CTX:
7697 		/* in case the function doesn't know how to access the context,
7698 		 * (because we are in a program of type SYSCALL for example), we
7699 		 * can not statically check its size.
7700 		 * Dynamically check it now.
7701 		 */
7702 		if (!env->ops->convert_ctx_access) {
7703 			int offset = access_size - 1;
7704 
7705 			/* Allow zero-byte read from PTR_TO_CTX */
7706 			if (access_size == 0)
7707 				return zero_size_allowed ? 0 : -EACCES;
7708 
7709 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7710 						access_type, -1, false, false);
7711 		}
7712 
7713 		fallthrough;
7714 	default: /* scalar_value or invalid ptr */
7715 		/* Allow zero-byte read from NULL, regardless of pointer type */
7716 		if (zero_size_allowed && access_size == 0 &&
7717 		    register_is_null(reg))
7718 			return 0;
7719 
7720 		verbose(env, "R%d type=%s ", regno,
7721 			reg_type_str(env, reg->type));
7722 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7723 		return -EACCES;
7724 	}
7725 }
7726 
7727 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7728  * size.
7729  *
7730  * @regno is the register containing the access size. regno-1 is the register
7731  * containing the pointer.
7732  */
7733 static int check_mem_size_reg(struct bpf_verifier_env *env,
7734 			      struct bpf_reg_state *reg, u32 regno,
7735 			      enum bpf_access_type access_type,
7736 			      bool zero_size_allowed,
7737 			      struct bpf_call_arg_meta *meta)
7738 {
7739 	int err;
7740 
7741 	/* This is used to refine r0 return value bounds for helpers
7742 	 * that enforce this value as an upper bound on return values.
7743 	 * See do_refine_retval_range() for helpers that can refine
7744 	 * the return value. C type of helper is u32 so we pull register
7745 	 * bound from umax_value however, if negative verifier errors
7746 	 * out. Only upper bounds can be learned because retval is an
7747 	 * int type and negative retvals are allowed.
7748 	 */
7749 	meta->msize_max_value = reg->umax_value;
7750 
7751 	/* The register is SCALAR_VALUE; the access check happens using
7752 	 * its boundaries. For unprivileged variable accesses, disable
7753 	 * raw mode so that the program is required to initialize all
7754 	 * the memory that the helper could just partially fill up.
7755 	 */
7756 	if (!tnum_is_const(reg->var_off))
7757 		meta = NULL;
7758 
7759 	if (reg->smin_value < 0) {
7760 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7761 			regno);
7762 		return -EACCES;
7763 	}
7764 
7765 	if (reg->umin_value == 0 && !zero_size_allowed) {
7766 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7767 			regno, reg->umin_value, reg->umax_value);
7768 		return -EACCES;
7769 	}
7770 
7771 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7772 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7773 			regno);
7774 		return -EACCES;
7775 	}
7776 	err = check_helper_mem_access(env, regno - 1, reg->umax_value,
7777 				      access_type, zero_size_allowed, meta);
7778 	if (!err)
7779 		err = mark_chain_precision(env, regno);
7780 	return err;
7781 }
7782 
7783 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7784 			 u32 regno, u32 mem_size)
7785 {
7786 	bool may_be_null = type_may_be_null(reg->type);
7787 	struct bpf_reg_state saved_reg;
7788 	int err;
7789 
7790 	if (register_is_null(reg))
7791 		return 0;
7792 
7793 	/* Assuming that the register contains a value check if the memory
7794 	 * access is safe. Temporarily save and restore the register's state as
7795 	 * the conversion shouldn't be visible to a caller.
7796 	 */
7797 	if (may_be_null) {
7798 		saved_reg = *reg;
7799 		mark_ptr_not_null_reg(reg);
7800 	}
7801 
7802 	err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL);
7803 	err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL);
7804 
7805 	if (may_be_null)
7806 		*reg = saved_reg;
7807 
7808 	return err;
7809 }
7810 
7811 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7812 				    u32 regno)
7813 {
7814 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7815 	bool may_be_null = type_may_be_null(mem_reg->type);
7816 	struct bpf_reg_state saved_reg;
7817 	struct bpf_call_arg_meta meta;
7818 	int err;
7819 
7820 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7821 
7822 	memset(&meta, 0, sizeof(meta));
7823 
7824 	if (may_be_null) {
7825 		saved_reg = *mem_reg;
7826 		mark_ptr_not_null_reg(mem_reg);
7827 	}
7828 
7829 	err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta);
7830 	err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta);
7831 
7832 	if (may_be_null)
7833 		*mem_reg = saved_reg;
7834 
7835 	return err;
7836 }
7837 
7838 /* Implementation details:
7839  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7840  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7841  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7842  * Two separate bpf_obj_new will also have different reg->id.
7843  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7844  * clears reg->id after value_or_null->value transition, since the verifier only
7845  * cares about the range of access to valid map value pointer and doesn't care
7846  * about actual address of the map element.
7847  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7848  * reg->id > 0 after value_or_null->value transition. By doing so
7849  * two bpf_map_lookups will be considered two different pointers that
7850  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7851  * returned from bpf_obj_new.
7852  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7853  * dead-locks.
7854  * Since only one bpf_spin_lock is allowed the checks are simpler than
7855  * reg_is_refcounted() logic. The verifier needs to remember only
7856  * one spin_lock instead of array of acquired_refs.
7857  * cur_func(env)->active_locks remembers which map value element or allocated
7858  * object got locked and clears it after bpf_spin_unlock.
7859  */
7860 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7861 			     bool is_lock)
7862 {
7863 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7864 	bool is_const = tnum_is_const(reg->var_off);
7865 	struct bpf_func_state *cur = cur_func(env);
7866 	u64 val = reg->var_off.value;
7867 	struct bpf_map *map = NULL;
7868 	struct btf *btf = NULL;
7869 	struct btf_record *rec;
7870 	int err;
7871 
7872 	if (!is_const) {
7873 		verbose(env,
7874 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7875 			regno);
7876 		return -EINVAL;
7877 	}
7878 	if (reg->type == PTR_TO_MAP_VALUE) {
7879 		map = reg->map_ptr;
7880 		if (!map->btf) {
7881 			verbose(env,
7882 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7883 				map->name);
7884 			return -EINVAL;
7885 		}
7886 	} else {
7887 		btf = reg->btf;
7888 	}
7889 
7890 	rec = reg_btf_record(reg);
7891 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7892 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7893 			map ? map->name : "kptr");
7894 		return -EINVAL;
7895 	}
7896 	if (rec->spin_lock_off != val + reg->off) {
7897 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7898 			val + reg->off, rec->spin_lock_off);
7899 		return -EINVAL;
7900 	}
7901 	if (is_lock) {
7902 		void *ptr;
7903 
7904 		if (map)
7905 			ptr = map;
7906 		else
7907 			ptr = btf;
7908 
7909 		if (cur->active_locks) {
7910 			verbose(env,
7911 				"Locking two bpf_spin_locks are not allowed\n");
7912 			return -EINVAL;
7913 		}
7914 		err = acquire_lock_state(env, env->insn_idx, REF_TYPE_LOCK, reg->id, ptr);
7915 		if (err < 0) {
7916 			verbose(env, "Failed to acquire lock state\n");
7917 			return err;
7918 		}
7919 	} else {
7920 		void *ptr;
7921 
7922 		if (map)
7923 			ptr = map;
7924 		else
7925 			ptr = btf;
7926 
7927 		if (!cur->active_locks) {
7928 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7929 			return -EINVAL;
7930 		}
7931 
7932 		if (release_lock_state(cur_func(env), REF_TYPE_LOCK, reg->id, ptr)) {
7933 			verbose(env, "bpf_spin_unlock of different lock\n");
7934 			return -EINVAL;
7935 		}
7936 
7937 		invalidate_non_owning_refs(env);
7938 	}
7939 	return 0;
7940 }
7941 
7942 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7943 			      struct bpf_call_arg_meta *meta)
7944 {
7945 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7946 	bool is_const = tnum_is_const(reg->var_off);
7947 	struct bpf_map *map = reg->map_ptr;
7948 	u64 val = reg->var_off.value;
7949 
7950 	if (!is_const) {
7951 		verbose(env,
7952 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7953 			regno);
7954 		return -EINVAL;
7955 	}
7956 	if (!map->btf) {
7957 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7958 			map->name);
7959 		return -EINVAL;
7960 	}
7961 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7962 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7963 		return -EINVAL;
7964 	}
7965 	if (map->record->timer_off != val + reg->off) {
7966 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7967 			val + reg->off, map->record->timer_off);
7968 		return -EINVAL;
7969 	}
7970 	if (meta->map_ptr) {
7971 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7972 		return -EFAULT;
7973 	}
7974 	meta->map_uid = reg->map_uid;
7975 	meta->map_ptr = map;
7976 	return 0;
7977 }
7978 
7979 static int process_wq_func(struct bpf_verifier_env *env, int regno,
7980 			   struct bpf_kfunc_call_arg_meta *meta)
7981 {
7982 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7983 	struct bpf_map *map = reg->map_ptr;
7984 	u64 val = reg->var_off.value;
7985 
7986 	if (map->record->wq_off != val + reg->off) {
7987 		verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n",
7988 			val + reg->off, map->record->wq_off);
7989 		return -EINVAL;
7990 	}
7991 	meta->map.uid = reg->map_uid;
7992 	meta->map.ptr = map;
7993 	return 0;
7994 }
7995 
7996 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7997 			     struct bpf_call_arg_meta *meta)
7998 {
7999 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8000 	struct btf_field *kptr_field;
8001 	struct bpf_map *map_ptr;
8002 	struct btf_record *rec;
8003 	u32 kptr_off;
8004 
8005 	if (type_is_ptr_alloc_obj(reg->type)) {
8006 		rec = reg_btf_record(reg);
8007 	} else { /* PTR_TO_MAP_VALUE */
8008 		map_ptr = reg->map_ptr;
8009 		if (!map_ptr->btf) {
8010 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
8011 				map_ptr->name);
8012 			return -EINVAL;
8013 		}
8014 		rec = map_ptr->record;
8015 		meta->map_ptr = map_ptr;
8016 	}
8017 
8018 	if (!tnum_is_const(reg->var_off)) {
8019 		verbose(env,
8020 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
8021 			regno);
8022 		return -EINVAL;
8023 	}
8024 
8025 	if (!btf_record_has_field(rec, BPF_KPTR)) {
8026 		verbose(env, "R%d has no valid kptr\n", regno);
8027 		return -EINVAL;
8028 	}
8029 
8030 	kptr_off = reg->off + reg->var_off.value;
8031 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
8032 	if (!kptr_field) {
8033 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
8034 		return -EACCES;
8035 	}
8036 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
8037 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
8038 		return -EACCES;
8039 	}
8040 	meta->kptr_field = kptr_field;
8041 	return 0;
8042 }
8043 
8044 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
8045  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
8046  *
8047  * In both cases we deal with the first 8 bytes, but need to mark the next 8
8048  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
8049  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
8050  *
8051  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
8052  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
8053  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
8054  * mutate the view of the dynptr and also possibly destroy it. In the latter
8055  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
8056  * memory that dynptr points to.
8057  *
8058  * The verifier will keep track both levels of mutation (bpf_dynptr's in
8059  * reg->type and the memory's in reg->dynptr.type), but there is no support for
8060  * readonly dynptr view yet, hence only the first case is tracked and checked.
8061  *
8062  * This is consistent with how C applies the const modifier to a struct object,
8063  * where the pointer itself inside bpf_dynptr becomes const but not what it
8064  * points to.
8065  *
8066  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
8067  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
8068  */
8069 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
8070 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
8071 {
8072 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8073 	int err;
8074 
8075 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
8076 		verbose(env,
8077 			"arg#%d expected pointer to stack or const struct bpf_dynptr\n",
8078 			regno - 1);
8079 		return -EINVAL;
8080 	}
8081 
8082 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
8083 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
8084 	 */
8085 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
8086 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
8087 		return -EFAULT;
8088 	}
8089 
8090 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
8091 	 *		 constructing a mutable bpf_dynptr object.
8092 	 *
8093 	 *		 Currently, this is only possible with PTR_TO_STACK
8094 	 *		 pointing to a region of at least 16 bytes which doesn't
8095 	 *		 contain an existing bpf_dynptr.
8096 	 *
8097 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
8098 	 *		 mutated or destroyed. However, the memory it points to
8099 	 *		 may be mutated.
8100 	 *
8101 	 *  None       - Points to a initialized dynptr that can be mutated and
8102 	 *		 destroyed, including mutation of the memory it points
8103 	 *		 to.
8104 	 */
8105 	if (arg_type & MEM_UNINIT) {
8106 		int i;
8107 
8108 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
8109 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
8110 			return -EINVAL;
8111 		}
8112 
8113 		/* we write BPF_DW bits (8 bytes) at a time */
8114 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8115 			err = check_mem_access(env, insn_idx, regno,
8116 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8117 			if (err)
8118 				return err;
8119 		}
8120 
8121 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
8122 	} else /* MEM_RDONLY and None case from above */ {
8123 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
8124 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
8125 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
8126 			return -EINVAL;
8127 		}
8128 
8129 		if (!is_dynptr_reg_valid_init(env, reg)) {
8130 			verbose(env,
8131 				"Expected an initialized dynptr as arg #%d\n",
8132 				regno - 1);
8133 			return -EINVAL;
8134 		}
8135 
8136 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
8137 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
8138 			verbose(env,
8139 				"Expected a dynptr of type %s as arg #%d\n",
8140 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1);
8141 			return -EINVAL;
8142 		}
8143 
8144 		err = mark_dynptr_read(env, reg);
8145 	}
8146 	return err;
8147 }
8148 
8149 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
8150 {
8151 	struct bpf_func_state *state = func(env, reg);
8152 
8153 	return state->stack[spi].spilled_ptr.ref_obj_id;
8154 }
8155 
8156 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8157 {
8158 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8159 }
8160 
8161 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8162 {
8163 	return meta->kfunc_flags & KF_ITER_NEW;
8164 }
8165 
8166 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8167 {
8168 	return meta->kfunc_flags & KF_ITER_NEXT;
8169 }
8170 
8171 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8172 {
8173 	return meta->kfunc_flags & KF_ITER_DESTROY;
8174 }
8175 
8176 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
8177 			      const struct btf_param *arg)
8178 {
8179 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
8180 	 * kfunc is iter state pointer
8181 	 */
8182 	if (is_iter_kfunc(meta))
8183 		return arg_idx == 0;
8184 
8185 	/* iter passed as an argument to a generic kfunc */
8186 	return btf_param_match_suffix(meta->btf, arg, "__iter");
8187 }
8188 
8189 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
8190 			    struct bpf_kfunc_call_arg_meta *meta)
8191 {
8192 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8193 	const struct btf_type *t;
8194 	int spi, err, i, nr_slots, btf_id;
8195 
8196 	if (reg->type != PTR_TO_STACK) {
8197 		verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1);
8198 		return -EINVAL;
8199 	}
8200 
8201 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8202 	 * ensures struct convention, so we wouldn't need to do any BTF
8203 	 * validation here. But given iter state can be passed as a parameter
8204 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8205 	 * conservative here.
8206 	 */
8207 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1);
8208 	if (btf_id < 0) {
8209 		verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1);
8210 		return -EINVAL;
8211 	}
8212 	t = btf_type_by_id(meta->btf, btf_id);
8213 	nr_slots = t->size / BPF_REG_SIZE;
8214 
8215 	if (is_iter_new_kfunc(meta)) {
8216 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
8217 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8218 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
8219 				iter_type_str(meta->btf, btf_id), regno - 1);
8220 			return -EINVAL;
8221 		}
8222 
8223 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8224 			err = check_mem_access(env, insn_idx, regno,
8225 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8226 			if (err)
8227 				return err;
8228 		}
8229 
8230 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8231 		if (err)
8232 			return err;
8233 	} else {
8234 		/* iter_next() or iter_destroy(), as well as any kfunc
8235 		 * accepting iter argument, expect initialized iter state
8236 		 */
8237 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8238 		switch (err) {
8239 		case 0:
8240 			break;
8241 		case -EINVAL:
8242 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
8243 				iter_type_str(meta->btf, btf_id), regno - 1);
8244 			return err;
8245 		case -EPROTO:
8246 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8247 			return err;
8248 		default:
8249 			return err;
8250 		}
8251 
8252 		spi = iter_get_spi(env, reg, nr_slots);
8253 		if (spi < 0)
8254 			return spi;
8255 
8256 		err = mark_iter_read(env, reg, spi, nr_slots);
8257 		if (err)
8258 			return err;
8259 
8260 		/* remember meta->iter info for process_iter_next_call() */
8261 		meta->iter.spi = spi;
8262 		meta->iter.frameno = reg->frameno;
8263 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
8264 
8265 		if (is_iter_destroy_kfunc(meta)) {
8266 			err = unmark_stack_slots_iter(env, reg, nr_slots);
8267 			if (err)
8268 				return err;
8269 		}
8270 	}
8271 
8272 	return 0;
8273 }
8274 
8275 /* Look for a previous loop entry at insn_idx: nearest parent state
8276  * stopped at insn_idx with callsites matching those in cur->frame.
8277  */
8278 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
8279 						  struct bpf_verifier_state *cur,
8280 						  int insn_idx)
8281 {
8282 	struct bpf_verifier_state_list *sl;
8283 	struct bpf_verifier_state *st;
8284 
8285 	/* Explored states are pushed in stack order, most recent states come first */
8286 	sl = *explored_state(env, insn_idx);
8287 	for (; sl; sl = sl->next) {
8288 		/* If st->branches != 0 state is a part of current DFS verification path,
8289 		 * hence cur & st for a loop.
8290 		 */
8291 		st = &sl->state;
8292 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
8293 		    st->dfs_depth < cur->dfs_depth)
8294 			return st;
8295 	}
8296 
8297 	return NULL;
8298 }
8299 
8300 static void reset_idmap_scratch(struct bpf_verifier_env *env);
8301 static bool regs_exact(const struct bpf_reg_state *rold,
8302 		       const struct bpf_reg_state *rcur,
8303 		       struct bpf_idmap *idmap);
8304 
8305 static void maybe_widen_reg(struct bpf_verifier_env *env,
8306 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8307 			    struct bpf_idmap *idmap)
8308 {
8309 	if (rold->type != SCALAR_VALUE)
8310 		return;
8311 	if (rold->type != rcur->type)
8312 		return;
8313 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
8314 		return;
8315 	__mark_reg_unknown(env, rcur);
8316 }
8317 
8318 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
8319 				   struct bpf_verifier_state *old,
8320 				   struct bpf_verifier_state *cur)
8321 {
8322 	struct bpf_func_state *fold, *fcur;
8323 	int i, fr;
8324 
8325 	reset_idmap_scratch(env);
8326 	for (fr = old->curframe; fr >= 0; fr--) {
8327 		fold = old->frame[fr];
8328 		fcur = cur->frame[fr];
8329 
8330 		for (i = 0; i < MAX_BPF_REG; i++)
8331 			maybe_widen_reg(env,
8332 					&fold->regs[i],
8333 					&fcur->regs[i],
8334 					&env->idmap_scratch);
8335 
8336 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
8337 			if (!is_spilled_reg(&fold->stack[i]) ||
8338 			    !is_spilled_reg(&fcur->stack[i]))
8339 				continue;
8340 
8341 			maybe_widen_reg(env,
8342 					&fold->stack[i].spilled_ptr,
8343 					&fcur->stack[i].spilled_ptr,
8344 					&env->idmap_scratch);
8345 		}
8346 	}
8347 	return 0;
8348 }
8349 
8350 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
8351 						 struct bpf_kfunc_call_arg_meta *meta)
8352 {
8353 	int iter_frameno = meta->iter.frameno;
8354 	int iter_spi = meta->iter.spi;
8355 
8356 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8357 }
8358 
8359 /* process_iter_next_call() is called when verifier gets to iterator's next
8360  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
8361  * to it as just "iter_next()" in comments below.
8362  *
8363  * BPF verifier relies on a crucial contract for any iter_next()
8364  * implementation: it should *eventually* return NULL, and once that happens
8365  * it should keep returning NULL. That is, once iterator exhausts elements to
8366  * iterate, it should never reset or spuriously return new elements.
8367  *
8368  * With the assumption of such contract, process_iter_next_call() simulates
8369  * a fork in the verifier state to validate loop logic correctness and safety
8370  * without having to simulate infinite amount of iterations.
8371  *
8372  * In current state, we first assume that iter_next() returned NULL and
8373  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
8374  * conditions we should not form an infinite loop and should eventually reach
8375  * exit.
8376  *
8377  * Besides that, we also fork current state and enqueue it for later
8378  * verification. In a forked state we keep iterator state as ACTIVE
8379  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
8380  * also bump iteration depth to prevent erroneous infinite loop detection
8381  * later on (see iter_active_depths_differ() comment for details). In this
8382  * state we assume that we'll eventually loop back to another iter_next()
8383  * calls (it could be in exactly same location or in some other instruction,
8384  * it doesn't matter, we don't make any unnecessary assumptions about this,
8385  * everything revolves around iterator state in a stack slot, not which
8386  * instruction is calling iter_next()). When that happens, we either will come
8387  * to iter_next() with equivalent state and can conclude that next iteration
8388  * will proceed in exactly the same way as we just verified, so it's safe to
8389  * assume that loop converges. If not, we'll go on another iteration
8390  * simulation with a different input state, until all possible starting states
8391  * are validated or we reach maximum number of instructions limit.
8392  *
8393  * This way, we will either exhaustively discover all possible input states
8394  * that iterator loop can start with and eventually will converge, or we'll
8395  * effectively regress into bounded loop simulation logic and either reach
8396  * maximum number of instructions if loop is not provably convergent, or there
8397  * is some statically known limit on number of iterations (e.g., if there is
8398  * an explicit `if n > 100 then break;` statement somewhere in the loop).
8399  *
8400  * Iteration convergence logic in is_state_visited() relies on exact
8401  * states comparison, which ignores read and precision marks.
8402  * This is necessary because read and precision marks are not finalized
8403  * while in the loop. Exact comparison might preclude convergence for
8404  * simple programs like below:
8405  *
8406  *     i = 0;
8407  *     while(iter_next(&it))
8408  *       i++;
8409  *
8410  * At each iteration step i++ would produce a new distinct state and
8411  * eventually instruction processing limit would be reached.
8412  *
8413  * To avoid such behavior speculatively forget (widen) range for
8414  * imprecise scalar registers, if those registers were not precise at the
8415  * end of the previous iteration and do not match exactly.
8416  *
8417  * This is a conservative heuristic that allows to verify wide range of programs,
8418  * however it precludes verification of programs that conjure an
8419  * imprecise value on the first loop iteration and use it as precise on a second.
8420  * For example, the following safe program would fail to verify:
8421  *
8422  *     struct bpf_num_iter it;
8423  *     int arr[10];
8424  *     int i = 0, a = 0;
8425  *     bpf_iter_num_new(&it, 0, 10);
8426  *     while (bpf_iter_num_next(&it)) {
8427  *       if (a == 0) {
8428  *         a = 1;
8429  *         i = 7; // Because i changed verifier would forget
8430  *                // it's range on second loop entry.
8431  *       } else {
8432  *         arr[i] = 42; // This would fail to verify.
8433  *       }
8434  *     }
8435  *     bpf_iter_num_destroy(&it);
8436  */
8437 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8438 				  struct bpf_kfunc_call_arg_meta *meta)
8439 {
8440 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
8441 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8442 	struct bpf_reg_state *cur_iter, *queued_iter;
8443 
8444 	BTF_TYPE_EMIT(struct bpf_iter);
8445 
8446 	cur_iter = get_iter_from_state(cur_st, meta);
8447 
8448 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8449 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8450 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
8451 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8452 		return -EFAULT;
8453 	}
8454 
8455 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
8456 		/* Because iter_next() call is a checkpoint is_state_visitied()
8457 		 * should guarantee parent state with same call sites and insn_idx.
8458 		 */
8459 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8460 		    !same_callsites(cur_st->parent, cur_st)) {
8461 			verbose(env, "bug: bad parent state for iter next call");
8462 			return -EFAULT;
8463 		}
8464 		/* Note cur_st->parent in the call below, it is necessary to skip
8465 		 * checkpoint created for cur_st by is_state_visited()
8466 		 * right at this instruction.
8467 		 */
8468 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
8469 		/* branch out active iter state */
8470 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
8471 		if (!queued_st)
8472 			return -ENOMEM;
8473 
8474 		queued_iter = get_iter_from_state(queued_st, meta);
8475 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
8476 		queued_iter->iter.depth++;
8477 		if (prev_st)
8478 			widen_imprecise_scalars(env, prev_st, queued_st);
8479 
8480 		queued_fr = queued_st->frame[queued_st->curframe];
8481 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
8482 	}
8483 
8484 	/* switch to DRAINED state, but keep the depth unchanged */
8485 	/* mark current iter state as drained and assume returned NULL */
8486 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8487 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
8488 
8489 	return 0;
8490 }
8491 
8492 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8493 {
8494 	return type == ARG_CONST_SIZE ||
8495 	       type == ARG_CONST_SIZE_OR_ZERO;
8496 }
8497 
8498 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
8499 {
8500 	return base_type(type) == ARG_PTR_TO_MEM &&
8501 	       type & MEM_UNINIT;
8502 }
8503 
8504 static bool arg_type_is_release(enum bpf_arg_type type)
8505 {
8506 	return type & OBJ_RELEASE;
8507 }
8508 
8509 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8510 {
8511 	return base_type(type) == ARG_PTR_TO_DYNPTR;
8512 }
8513 
8514 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8515 				 const struct bpf_call_arg_meta *meta,
8516 				 enum bpf_arg_type *arg_type)
8517 {
8518 	if (!meta->map_ptr) {
8519 		/* kernel subsystem misconfigured verifier */
8520 		verbose(env, "invalid map_ptr to access map->type\n");
8521 		return -EACCES;
8522 	}
8523 
8524 	switch (meta->map_ptr->map_type) {
8525 	case BPF_MAP_TYPE_SOCKMAP:
8526 	case BPF_MAP_TYPE_SOCKHASH:
8527 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8528 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8529 		} else {
8530 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8531 			return -EINVAL;
8532 		}
8533 		break;
8534 	case BPF_MAP_TYPE_BLOOM_FILTER:
8535 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8536 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8537 		break;
8538 	default:
8539 		break;
8540 	}
8541 	return 0;
8542 }
8543 
8544 struct bpf_reg_types {
8545 	const enum bpf_reg_type types[10];
8546 	u32 *btf_id;
8547 };
8548 
8549 static const struct bpf_reg_types sock_types = {
8550 	.types = {
8551 		PTR_TO_SOCK_COMMON,
8552 		PTR_TO_SOCKET,
8553 		PTR_TO_TCP_SOCK,
8554 		PTR_TO_XDP_SOCK,
8555 	},
8556 };
8557 
8558 #ifdef CONFIG_NET
8559 static const struct bpf_reg_types btf_id_sock_common_types = {
8560 	.types = {
8561 		PTR_TO_SOCK_COMMON,
8562 		PTR_TO_SOCKET,
8563 		PTR_TO_TCP_SOCK,
8564 		PTR_TO_XDP_SOCK,
8565 		PTR_TO_BTF_ID,
8566 		PTR_TO_BTF_ID | PTR_TRUSTED,
8567 	},
8568 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8569 };
8570 #endif
8571 
8572 static const struct bpf_reg_types mem_types = {
8573 	.types = {
8574 		PTR_TO_STACK,
8575 		PTR_TO_PACKET,
8576 		PTR_TO_PACKET_META,
8577 		PTR_TO_MAP_KEY,
8578 		PTR_TO_MAP_VALUE,
8579 		PTR_TO_MEM,
8580 		PTR_TO_MEM | MEM_RINGBUF,
8581 		PTR_TO_BUF,
8582 		PTR_TO_BTF_ID | PTR_TRUSTED,
8583 	},
8584 };
8585 
8586 static const struct bpf_reg_types spin_lock_types = {
8587 	.types = {
8588 		PTR_TO_MAP_VALUE,
8589 		PTR_TO_BTF_ID | MEM_ALLOC,
8590 	}
8591 };
8592 
8593 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8594 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8595 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8596 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8597 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8598 static const struct bpf_reg_types btf_ptr_types = {
8599 	.types = {
8600 		PTR_TO_BTF_ID,
8601 		PTR_TO_BTF_ID | PTR_TRUSTED,
8602 		PTR_TO_BTF_ID | MEM_RCU,
8603 	},
8604 };
8605 static const struct bpf_reg_types percpu_btf_ptr_types = {
8606 	.types = {
8607 		PTR_TO_BTF_ID | MEM_PERCPU,
8608 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8609 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8610 	}
8611 };
8612 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8613 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8614 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8615 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8616 static const struct bpf_reg_types kptr_xchg_dest_types = {
8617 	.types = {
8618 		PTR_TO_MAP_VALUE,
8619 		PTR_TO_BTF_ID | MEM_ALLOC
8620 	}
8621 };
8622 static const struct bpf_reg_types dynptr_types = {
8623 	.types = {
8624 		PTR_TO_STACK,
8625 		CONST_PTR_TO_DYNPTR,
8626 	}
8627 };
8628 
8629 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8630 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8631 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8632 	[ARG_CONST_SIZE]		= &scalar_types,
8633 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8634 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8635 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8636 	[ARG_PTR_TO_CTX]		= &context_types,
8637 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8638 #ifdef CONFIG_NET
8639 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8640 #endif
8641 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8642 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8643 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8644 	[ARG_PTR_TO_MEM]		= &mem_types,
8645 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8646 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8647 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8648 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8649 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8650 	[ARG_PTR_TO_TIMER]		= &timer_types,
8651 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
8652 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8653 };
8654 
8655 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8656 			  enum bpf_arg_type arg_type,
8657 			  const u32 *arg_btf_id,
8658 			  struct bpf_call_arg_meta *meta)
8659 {
8660 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8661 	enum bpf_reg_type expected, type = reg->type;
8662 	const struct bpf_reg_types *compatible;
8663 	int i, j;
8664 
8665 	compatible = compatible_reg_types[base_type(arg_type)];
8666 	if (!compatible) {
8667 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8668 		return -EFAULT;
8669 	}
8670 
8671 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8672 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8673 	 *
8674 	 * Same for MAYBE_NULL:
8675 	 *
8676 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8677 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8678 	 *
8679 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8680 	 *
8681 	 * Therefore we fold these flags depending on the arg_type before comparison.
8682 	 */
8683 	if (arg_type & MEM_RDONLY)
8684 		type &= ~MEM_RDONLY;
8685 	if (arg_type & PTR_MAYBE_NULL)
8686 		type &= ~PTR_MAYBE_NULL;
8687 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8688 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8689 
8690 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
8691 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) {
8692 		type &= ~MEM_ALLOC;
8693 		type &= ~MEM_PERCPU;
8694 	}
8695 
8696 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8697 		expected = compatible->types[i];
8698 		if (expected == NOT_INIT)
8699 			break;
8700 
8701 		if (type == expected)
8702 			goto found;
8703 	}
8704 
8705 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8706 	for (j = 0; j + 1 < i; j++)
8707 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8708 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8709 	return -EACCES;
8710 
8711 found:
8712 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8713 		return 0;
8714 
8715 	if (compatible == &mem_types) {
8716 		if (!(arg_type & MEM_RDONLY)) {
8717 			verbose(env,
8718 				"%s() may write into memory pointed by R%d type=%s\n",
8719 				func_id_name(meta->func_id),
8720 				regno, reg_type_str(env, reg->type));
8721 			return -EACCES;
8722 		}
8723 		return 0;
8724 	}
8725 
8726 	switch ((int)reg->type) {
8727 	case PTR_TO_BTF_ID:
8728 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8729 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
8730 	case PTR_TO_BTF_ID | MEM_RCU:
8731 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8732 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8733 	{
8734 		/* For bpf_sk_release, it needs to match against first member
8735 		 * 'struct sock_common', hence make an exception for it. This
8736 		 * allows bpf_sk_release to work for multiple socket types.
8737 		 */
8738 		bool strict_type_match = arg_type_is_release(arg_type) &&
8739 					 meta->func_id != BPF_FUNC_sk_release;
8740 
8741 		if (type_may_be_null(reg->type) &&
8742 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8743 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8744 			return -EACCES;
8745 		}
8746 
8747 		if (!arg_btf_id) {
8748 			if (!compatible->btf_id) {
8749 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8750 				return -EFAULT;
8751 			}
8752 			arg_btf_id = compatible->btf_id;
8753 		}
8754 
8755 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8756 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8757 				return -EACCES;
8758 		} else {
8759 			if (arg_btf_id == BPF_PTR_POISON) {
8760 				verbose(env, "verifier internal error:");
8761 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8762 					regno);
8763 				return -EACCES;
8764 			}
8765 
8766 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8767 						  btf_vmlinux, *arg_btf_id,
8768 						  strict_type_match)) {
8769 				verbose(env, "R%d is of type %s but %s is expected\n",
8770 					regno, btf_type_name(reg->btf, reg->btf_id),
8771 					btf_type_name(btf_vmlinux, *arg_btf_id));
8772 				return -EACCES;
8773 			}
8774 		}
8775 		break;
8776 	}
8777 	case PTR_TO_BTF_ID | MEM_ALLOC:
8778 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8779 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8780 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8781 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8782 			return -EFAULT;
8783 		}
8784 		/* Check if local kptr in src arg matches kptr in dst arg */
8785 		if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) {
8786 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8787 				return -EACCES;
8788 		}
8789 		break;
8790 	case PTR_TO_BTF_ID | MEM_PERCPU:
8791 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8792 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8793 		/* Handled by helper specific checks */
8794 		break;
8795 	default:
8796 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8797 		return -EFAULT;
8798 	}
8799 	return 0;
8800 }
8801 
8802 static struct btf_field *
8803 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8804 {
8805 	struct btf_field *field;
8806 	struct btf_record *rec;
8807 
8808 	rec = reg_btf_record(reg);
8809 	if (!rec)
8810 		return NULL;
8811 
8812 	field = btf_record_find(rec, off, fields);
8813 	if (!field)
8814 		return NULL;
8815 
8816 	return field;
8817 }
8818 
8819 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8820 				  const struct bpf_reg_state *reg, int regno,
8821 				  enum bpf_arg_type arg_type)
8822 {
8823 	u32 type = reg->type;
8824 
8825 	/* When referenced register is passed to release function, its fixed
8826 	 * offset must be 0.
8827 	 *
8828 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8829 	 * meta->release_regno.
8830 	 */
8831 	if (arg_type_is_release(arg_type)) {
8832 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8833 		 * may not directly point to the object being released, but to
8834 		 * dynptr pointing to such object, which might be at some offset
8835 		 * on the stack. In that case, we simply to fallback to the
8836 		 * default handling.
8837 		 */
8838 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8839 			return 0;
8840 
8841 		/* Doing check_ptr_off_reg check for the offset will catch this
8842 		 * because fixed_off_ok is false, but checking here allows us
8843 		 * to give the user a better error message.
8844 		 */
8845 		if (reg->off) {
8846 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8847 				regno);
8848 			return -EINVAL;
8849 		}
8850 		return __check_ptr_off_reg(env, reg, regno, false);
8851 	}
8852 
8853 	switch (type) {
8854 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8855 	case PTR_TO_STACK:
8856 	case PTR_TO_PACKET:
8857 	case PTR_TO_PACKET_META:
8858 	case PTR_TO_MAP_KEY:
8859 	case PTR_TO_MAP_VALUE:
8860 	case PTR_TO_MEM:
8861 	case PTR_TO_MEM | MEM_RDONLY:
8862 	case PTR_TO_MEM | MEM_RINGBUF:
8863 	case PTR_TO_BUF:
8864 	case PTR_TO_BUF | MEM_RDONLY:
8865 	case PTR_TO_ARENA:
8866 	case SCALAR_VALUE:
8867 		return 0;
8868 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8869 	 * fixed offset.
8870 	 */
8871 	case PTR_TO_BTF_ID:
8872 	case PTR_TO_BTF_ID | MEM_ALLOC:
8873 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8874 	case PTR_TO_BTF_ID | MEM_RCU:
8875 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8876 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8877 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8878 		 * its fixed offset must be 0. In the other cases, fixed offset
8879 		 * can be non-zero. This was already checked above. So pass
8880 		 * fixed_off_ok as true to allow fixed offset for all other
8881 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8882 		 * still need to do checks instead of returning.
8883 		 */
8884 		return __check_ptr_off_reg(env, reg, regno, true);
8885 	default:
8886 		return __check_ptr_off_reg(env, reg, regno, false);
8887 	}
8888 }
8889 
8890 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8891 						const struct bpf_func_proto *fn,
8892 						struct bpf_reg_state *regs)
8893 {
8894 	struct bpf_reg_state *state = NULL;
8895 	int i;
8896 
8897 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8898 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8899 			if (state) {
8900 				verbose(env, "verifier internal error: multiple dynptr args\n");
8901 				return NULL;
8902 			}
8903 			state = &regs[BPF_REG_1 + i];
8904 		}
8905 
8906 	if (!state)
8907 		verbose(env, "verifier internal error: no dynptr arg found\n");
8908 
8909 	return state;
8910 }
8911 
8912 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8913 {
8914 	struct bpf_func_state *state = func(env, reg);
8915 	int spi;
8916 
8917 	if (reg->type == CONST_PTR_TO_DYNPTR)
8918 		return reg->id;
8919 	spi = dynptr_get_spi(env, reg);
8920 	if (spi < 0)
8921 		return spi;
8922 	return state->stack[spi].spilled_ptr.id;
8923 }
8924 
8925 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8926 {
8927 	struct bpf_func_state *state = func(env, reg);
8928 	int spi;
8929 
8930 	if (reg->type == CONST_PTR_TO_DYNPTR)
8931 		return reg->ref_obj_id;
8932 	spi = dynptr_get_spi(env, reg);
8933 	if (spi < 0)
8934 		return spi;
8935 	return state->stack[spi].spilled_ptr.ref_obj_id;
8936 }
8937 
8938 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8939 					    struct bpf_reg_state *reg)
8940 {
8941 	struct bpf_func_state *state = func(env, reg);
8942 	int spi;
8943 
8944 	if (reg->type == CONST_PTR_TO_DYNPTR)
8945 		return reg->dynptr.type;
8946 
8947 	spi = __get_spi(reg->off);
8948 	if (spi < 0) {
8949 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8950 		return BPF_DYNPTR_TYPE_INVALID;
8951 	}
8952 
8953 	return state->stack[spi].spilled_ptr.dynptr.type;
8954 }
8955 
8956 static int check_reg_const_str(struct bpf_verifier_env *env,
8957 			       struct bpf_reg_state *reg, u32 regno)
8958 {
8959 	struct bpf_map *map = reg->map_ptr;
8960 	int err;
8961 	int map_off;
8962 	u64 map_addr;
8963 	char *str_ptr;
8964 
8965 	if (reg->type != PTR_TO_MAP_VALUE)
8966 		return -EINVAL;
8967 
8968 	if (!bpf_map_is_rdonly(map)) {
8969 		verbose(env, "R%d does not point to a readonly map'\n", regno);
8970 		return -EACCES;
8971 	}
8972 
8973 	if (!tnum_is_const(reg->var_off)) {
8974 		verbose(env, "R%d is not a constant address'\n", regno);
8975 		return -EACCES;
8976 	}
8977 
8978 	if (!map->ops->map_direct_value_addr) {
8979 		verbose(env, "no direct value access support for this map type\n");
8980 		return -EACCES;
8981 	}
8982 
8983 	err = check_map_access(env, regno, reg->off,
8984 			       map->value_size - reg->off, false,
8985 			       ACCESS_HELPER);
8986 	if (err)
8987 		return err;
8988 
8989 	map_off = reg->off + reg->var_off.value;
8990 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8991 	if (err) {
8992 		verbose(env, "direct value access on string failed\n");
8993 		return err;
8994 	}
8995 
8996 	str_ptr = (char *)(long)(map_addr);
8997 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8998 		verbose(env, "string is not zero-terminated\n");
8999 		return -EINVAL;
9000 	}
9001 	return 0;
9002 }
9003 
9004 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
9005 			  struct bpf_call_arg_meta *meta,
9006 			  const struct bpf_func_proto *fn,
9007 			  int insn_idx)
9008 {
9009 	u32 regno = BPF_REG_1 + arg;
9010 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
9011 	enum bpf_arg_type arg_type = fn->arg_type[arg];
9012 	enum bpf_reg_type type = reg->type;
9013 	u32 *arg_btf_id = NULL;
9014 	int err = 0;
9015 	bool mask;
9016 
9017 	if (arg_type == ARG_DONTCARE)
9018 		return 0;
9019 
9020 	err = check_reg_arg(env, regno, SRC_OP);
9021 	if (err)
9022 		return err;
9023 
9024 	if (arg_type == ARG_ANYTHING) {
9025 		if (is_pointer_value(env, regno)) {
9026 			verbose(env, "R%d leaks addr into helper function\n",
9027 				regno);
9028 			return -EACCES;
9029 		}
9030 		return 0;
9031 	}
9032 
9033 	if (type_is_pkt_pointer(type) &&
9034 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
9035 		verbose(env, "helper access to the packet is not allowed\n");
9036 		return -EACCES;
9037 	}
9038 
9039 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
9040 		err = resolve_map_arg_type(env, meta, &arg_type);
9041 		if (err)
9042 			return err;
9043 	}
9044 
9045 	if (register_is_null(reg) && type_may_be_null(arg_type))
9046 		/* A NULL register has a SCALAR_VALUE type, so skip
9047 		 * type checking.
9048 		 */
9049 		goto skip_type_check;
9050 
9051 	/* arg_btf_id and arg_size are in a union. */
9052 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
9053 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
9054 		arg_btf_id = fn->arg_btf_id[arg];
9055 
9056 	mask = mask_raw_tp_reg(env, reg);
9057 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
9058 
9059 	err = err ?: check_func_arg_reg_off(env, reg, regno, arg_type);
9060 	unmask_raw_tp_reg(reg, mask);
9061 	if (err)
9062 		return err;
9063 
9064 skip_type_check:
9065 	if (arg_type_is_release(arg_type)) {
9066 		if (arg_type_is_dynptr(arg_type)) {
9067 			struct bpf_func_state *state = func(env, reg);
9068 			int spi;
9069 
9070 			/* Only dynptr created on stack can be released, thus
9071 			 * the get_spi and stack state checks for spilled_ptr
9072 			 * should only be done before process_dynptr_func for
9073 			 * PTR_TO_STACK.
9074 			 */
9075 			if (reg->type == PTR_TO_STACK) {
9076 				spi = dynptr_get_spi(env, reg);
9077 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
9078 					verbose(env, "arg %d is an unacquired reference\n", regno);
9079 					return -EINVAL;
9080 				}
9081 			} else {
9082 				verbose(env, "cannot release unowned const bpf_dynptr\n");
9083 				return -EINVAL;
9084 			}
9085 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
9086 			verbose(env, "R%d must be referenced when passed to release function\n",
9087 				regno);
9088 			return -EINVAL;
9089 		}
9090 		if (meta->release_regno) {
9091 			verbose(env, "verifier internal error: more than one release argument\n");
9092 			return -EFAULT;
9093 		}
9094 		meta->release_regno = regno;
9095 	}
9096 
9097 	if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) {
9098 		if (meta->ref_obj_id) {
9099 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
9100 				regno, reg->ref_obj_id,
9101 				meta->ref_obj_id);
9102 			return -EFAULT;
9103 		}
9104 		meta->ref_obj_id = reg->ref_obj_id;
9105 	}
9106 
9107 	switch (base_type(arg_type)) {
9108 	case ARG_CONST_MAP_PTR:
9109 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
9110 		if (meta->map_ptr) {
9111 			/* Use map_uid (which is unique id of inner map) to reject:
9112 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
9113 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
9114 			 * if (inner_map1 && inner_map2) {
9115 			 *     timer = bpf_map_lookup_elem(inner_map1);
9116 			 *     if (timer)
9117 			 *         // mismatch would have been allowed
9118 			 *         bpf_timer_init(timer, inner_map2);
9119 			 * }
9120 			 *
9121 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
9122 			 */
9123 			if (meta->map_ptr != reg->map_ptr ||
9124 			    meta->map_uid != reg->map_uid) {
9125 				verbose(env,
9126 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
9127 					meta->map_uid, reg->map_uid);
9128 				return -EINVAL;
9129 			}
9130 		}
9131 		meta->map_ptr = reg->map_ptr;
9132 		meta->map_uid = reg->map_uid;
9133 		break;
9134 	case ARG_PTR_TO_MAP_KEY:
9135 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
9136 		 * check that [key, key + map->key_size) are within
9137 		 * stack limits and initialized
9138 		 */
9139 		if (!meta->map_ptr) {
9140 			/* in function declaration map_ptr must come before
9141 			 * map_key, so that it's verified and known before
9142 			 * we have to check map_key here. Otherwise it means
9143 			 * that kernel subsystem misconfigured verifier
9144 			 */
9145 			verbose(env, "invalid map_ptr to access map->key\n");
9146 			return -EACCES;
9147 		}
9148 		err = check_helper_mem_access(env, regno, meta->map_ptr->key_size,
9149 					      BPF_READ, false, NULL);
9150 		break;
9151 	case ARG_PTR_TO_MAP_VALUE:
9152 		if (type_may_be_null(arg_type) && register_is_null(reg))
9153 			return 0;
9154 
9155 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
9156 		 * check [value, value + map->value_size) validity
9157 		 */
9158 		if (!meta->map_ptr) {
9159 			/* kernel subsystem misconfigured verifier */
9160 			verbose(env, "invalid map_ptr to access map->value\n");
9161 			return -EACCES;
9162 		}
9163 		meta->raw_mode = arg_type & MEM_UNINIT;
9164 		err = check_helper_mem_access(env, regno, meta->map_ptr->value_size,
9165 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9166 					      false, meta);
9167 		break;
9168 	case ARG_PTR_TO_PERCPU_BTF_ID:
9169 		if (!reg->btf_id) {
9170 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
9171 			return -EACCES;
9172 		}
9173 		meta->ret_btf = reg->btf;
9174 		meta->ret_btf_id = reg->btf_id;
9175 		break;
9176 	case ARG_PTR_TO_SPIN_LOCK:
9177 		if (in_rbtree_lock_required_cb(env)) {
9178 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
9179 			return -EACCES;
9180 		}
9181 		if (meta->func_id == BPF_FUNC_spin_lock) {
9182 			err = process_spin_lock(env, regno, true);
9183 			if (err)
9184 				return err;
9185 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
9186 			err = process_spin_lock(env, regno, false);
9187 			if (err)
9188 				return err;
9189 		} else {
9190 			verbose(env, "verifier internal error\n");
9191 			return -EFAULT;
9192 		}
9193 		break;
9194 	case ARG_PTR_TO_TIMER:
9195 		err = process_timer_func(env, regno, meta);
9196 		if (err)
9197 			return err;
9198 		break;
9199 	case ARG_PTR_TO_FUNC:
9200 		meta->subprogno = reg->subprogno;
9201 		break;
9202 	case ARG_PTR_TO_MEM:
9203 		/* The access to this pointer is only checked when we hit the
9204 		 * next is_mem_size argument below.
9205 		 */
9206 		meta->raw_mode = arg_type & MEM_UNINIT;
9207 		if (arg_type & MEM_FIXED_SIZE) {
9208 			err = check_helper_mem_access(env, regno, fn->arg_size[arg],
9209 						      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9210 						      false, meta);
9211 			if (err)
9212 				return err;
9213 			if (arg_type & MEM_ALIGNED)
9214 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
9215 		}
9216 		break;
9217 	case ARG_CONST_SIZE:
9218 		err = check_mem_size_reg(env, reg, regno,
9219 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9220 					 BPF_WRITE : BPF_READ,
9221 					 false, meta);
9222 		break;
9223 	case ARG_CONST_SIZE_OR_ZERO:
9224 		err = check_mem_size_reg(env, reg, regno,
9225 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9226 					 BPF_WRITE : BPF_READ,
9227 					 true, meta);
9228 		break;
9229 	case ARG_PTR_TO_DYNPTR:
9230 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
9231 		if (err)
9232 			return err;
9233 		break;
9234 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
9235 		if (!tnum_is_const(reg->var_off)) {
9236 			verbose(env, "R%d is not a known constant'\n",
9237 				regno);
9238 			return -EACCES;
9239 		}
9240 		meta->mem_size = reg->var_off.value;
9241 		err = mark_chain_precision(env, regno);
9242 		if (err)
9243 			return err;
9244 		break;
9245 	case ARG_PTR_TO_CONST_STR:
9246 	{
9247 		err = check_reg_const_str(env, reg, regno);
9248 		if (err)
9249 			return err;
9250 		break;
9251 	}
9252 	case ARG_KPTR_XCHG_DEST:
9253 		err = process_kptr_func(env, regno, meta);
9254 		if (err)
9255 			return err;
9256 		break;
9257 	}
9258 
9259 	return err;
9260 }
9261 
9262 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
9263 {
9264 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
9265 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9266 
9267 	if (func_id != BPF_FUNC_map_update_elem &&
9268 	    func_id != BPF_FUNC_map_delete_elem)
9269 		return false;
9270 
9271 	/* It's not possible to get access to a locked struct sock in these
9272 	 * contexts, so updating is safe.
9273 	 */
9274 	switch (type) {
9275 	case BPF_PROG_TYPE_TRACING:
9276 		if (eatype == BPF_TRACE_ITER)
9277 			return true;
9278 		break;
9279 	case BPF_PROG_TYPE_SOCK_OPS:
9280 		/* map_update allowed only via dedicated helpers with event type checks */
9281 		if (func_id == BPF_FUNC_map_delete_elem)
9282 			return true;
9283 		break;
9284 	case BPF_PROG_TYPE_SOCKET_FILTER:
9285 	case BPF_PROG_TYPE_SCHED_CLS:
9286 	case BPF_PROG_TYPE_SCHED_ACT:
9287 	case BPF_PROG_TYPE_XDP:
9288 	case BPF_PROG_TYPE_SK_REUSEPORT:
9289 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
9290 	case BPF_PROG_TYPE_SK_LOOKUP:
9291 		return true;
9292 	default:
9293 		break;
9294 	}
9295 
9296 	verbose(env, "cannot update sockmap in this context\n");
9297 	return false;
9298 }
9299 
9300 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
9301 {
9302 	return env->prog->jit_requested &&
9303 	       bpf_jit_supports_subprog_tailcalls();
9304 }
9305 
9306 static int check_map_func_compatibility(struct bpf_verifier_env *env,
9307 					struct bpf_map *map, int func_id)
9308 {
9309 	if (!map)
9310 		return 0;
9311 
9312 	/* We need a two way check, first is from map perspective ... */
9313 	switch (map->map_type) {
9314 	case BPF_MAP_TYPE_PROG_ARRAY:
9315 		if (func_id != BPF_FUNC_tail_call)
9316 			goto error;
9317 		break;
9318 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
9319 		if (func_id != BPF_FUNC_perf_event_read &&
9320 		    func_id != BPF_FUNC_perf_event_output &&
9321 		    func_id != BPF_FUNC_skb_output &&
9322 		    func_id != BPF_FUNC_perf_event_read_value &&
9323 		    func_id != BPF_FUNC_xdp_output)
9324 			goto error;
9325 		break;
9326 	case BPF_MAP_TYPE_RINGBUF:
9327 		if (func_id != BPF_FUNC_ringbuf_output &&
9328 		    func_id != BPF_FUNC_ringbuf_reserve &&
9329 		    func_id != BPF_FUNC_ringbuf_query &&
9330 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
9331 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
9332 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
9333 			goto error;
9334 		break;
9335 	case BPF_MAP_TYPE_USER_RINGBUF:
9336 		if (func_id != BPF_FUNC_user_ringbuf_drain)
9337 			goto error;
9338 		break;
9339 	case BPF_MAP_TYPE_STACK_TRACE:
9340 		if (func_id != BPF_FUNC_get_stackid)
9341 			goto error;
9342 		break;
9343 	case BPF_MAP_TYPE_CGROUP_ARRAY:
9344 		if (func_id != BPF_FUNC_skb_under_cgroup &&
9345 		    func_id != BPF_FUNC_current_task_under_cgroup)
9346 			goto error;
9347 		break;
9348 	case BPF_MAP_TYPE_CGROUP_STORAGE:
9349 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
9350 		if (func_id != BPF_FUNC_get_local_storage)
9351 			goto error;
9352 		break;
9353 	case BPF_MAP_TYPE_DEVMAP:
9354 	case BPF_MAP_TYPE_DEVMAP_HASH:
9355 		if (func_id != BPF_FUNC_redirect_map &&
9356 		    func_id != BPF_FUNC_map_lookup_elem)
9357 			goto error;
9358 		break;
9359 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
9360 	 * appear.
9361 	 */
9362 	case BPF_MAP_TYPE_CPUMAP:
9363 		if (func_id != BPF_FUNC_redirect_map)
9364 			goto error;
9365 		break;
9366 	case BPF_MAP_TYPE_XSKMAP:
9367 		if (func_id != BPF_FUNC_redirect_map &&
9368 		    func_id != BPF_FUNC_map_lookup_elem)
9369 			goto error;
9370 		break;
9371 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
9372 	case BPF_MAP_TYPE_HASH_OF_MAPS:
9373 		if (func_id != BPF_FUNC_map_lookup_elem)
9374 			goto error;
9375 		break;
9376 	case BPF_MAP_TYPE_SOCKMAP:
9377 		if (func_id != BPF_FUNC_sk_redirect_map &&
9378 		    func_id != BPF_FUNC_sock_map_update &&
9379 		    func_id != BPF_FUNC_msg_redirect_map &&
9380 		    func_id != BPF_FUNC_sk_select_reuseport &&
9381 		    func_id != BPF_FUNC_map_lookup_elem &&
9382 		    !may_update_sockmap(env, func_id))
9383 			goto error;
9384 		break;
9385 	case BPF_MAP_TYPE_SOCKHASH:
9386 		if (func_id != BPF_FUNC_sk_redirect_hash &&
9387 		    func_id != BPF_FUNC_sock_hash_update &&
9388 		    func_id != BPF_FUNC_msg_redirect_hash &&
9389 		    func_id != BPF_FUNC_sk_select_reuseport &&
9390 		    func_id != BPF_FUNC_map_lookup_elem &&
9391 		    !may_update_sockmap(env, func_id))
9392 			goto error;
9393 		break;
9394 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
9395 		if (func_id != BPF_FUNC_sk_select_reuseport)
9396 			goto error;
9397 		break;
9398 	case BPF_MAP_TYPE_QUEUE:
9399 	case BPF_MAP_TYPE_STACK:
9400 		if (func_id != BPF_FUNC_map_peek_elem &&
9401 		    func_id != BPF_FUNC_map_pop_elem &&
9402 		    func_id != BPF_FUNC_map_push_elem)
9403 			goto error;
9404 		break;
9405 	case BPF_MAP_TYPE_SK_STORAGE:
9406 		if (func_id != BPF_FUNC_sk_storage_get &&
9407 		    func_id != BPF_FUNC_sk_storage_delete &&
9408 		    func_id != BPF_FUNC_kptr_xchg)
9409 			goto error;
9410 		break;
9411 	case BPF_MAP_TYPE_INODE_STORAGE:
9412 		if (func_id != BPF_FUNC_inode_storage_get &&
9413 		    func_id != BPF_FUNC_inode_storage_delete &&
9414 		    func_id != BPF_FUNC_kptr_xchg)
9415 			goto error;
9416 		break;
9417 	case BPF_MAP_TYPE_TASK_STORAGE:
9418 		if (func_id != BPF_FUNC_task_storage_get &&
9419 		    func_id != BPF_FUNC_task_storage_delete &&
9420 		    func_id != BPF_FUNC_kptr_xchg)
9421 			goto error;
9422 		break;
9423 	case BPF_MAP_TYPE_CGRP_STORAGE:
9424 		if (func_id != BPF_FUNC_cgrp_storage_get &&
9425 		    func_id != BPF_FUNC_cgrp_storage_delete &&
9426 		    func_id != BPF_FUNC_kptr_xchg)
9427 			goto error;
9428 		break;
9429 	case BPF_MAP_TYPE_BLOOM_FILTER:
9430 		if (func_id != BPF_FUNC_map_peek_elem &&
9431 		    func_id != BPF_FUNC_map_push_elem)
9432 			goto error;
9433 		break;
9434 	default:
9435 		break;
9436 	}
9437 
9438 	/* ... and second from the function itself. */
9439 	switch (func_id) {
9440 	case BPF_FUNC_tail_call:
9441 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
9442 			goto error;
9443 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
9444 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
9445 			return -EINVAL;
9446 		}
9447 		break;
9448 	case BPF_FUNC_perf_event_read:
9449 	case BPF_FUNC_perf_event_output:
9450 	case BPF_FUNC_perf_event_read_value:
9451 	case BPF_FUNC_skb_output:
9452 	case BPF_FUNC_xdp_output:
9453 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
9454 			goto error;
9455 		break;
9456 	case BPF_FUNC_ringbuf_output:
9457 	case BPF_FUNC_ringbuf_reserve:
9458 	case BPF_FUNC_ringbuf_query:
9459 	case BPF_FUNC_ringbuf_reserve_dynptr:
9460 	case BPF_FUNC_ringbuf_submit_dynptr:
9461 	case BPF_FUNC_ringbuf_discard_dynptr:
9462 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
9463 			goto error;
9464 		break;
9465 	case BPF_FUNC_user_ringbuf_drain:
9466 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
9467 			goto error;
9468 		break;
9469 	case BPF_FUNC_get_stackid:
9470 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
9471 			goto error;
9472 		break;
9473 	case BPF_FUNC_current_task_under_cgroup:
9474 	case BPF_FUNC_skb_under_cgroup:
9475 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
9476 			goto error;
9477 		break;
9478 	case BPF_FUNC_redirect_map:
9479 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
9480 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
9481 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
9482 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
9483 			goto error;
9484 		break;
9485 	case BPF_FUNC_sk_redirect_map:
9486 	case BPF_FUNC_msg_redirect_map:
9487 	case BPF_FUNC_sock_map_update:
9488 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
9489 			goto error;
9490 		break;
9491 	case BPF_FUNC_sk_redirect_hash:
9492 	case BPF_FUNC_msg_redirect_hash:
9493 	case BPF_FUNC_sock_hash_update:
9494 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
9495 			goto error;
9496 		break;
9497 	case BPF_FUNC_get_local_storage:
9498 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
9499 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
9500 			goto error;
9501 		break;
9502 	case BPF_FUNC_sk_select_reuseport:
9503 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
9504 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
9505 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
9506 			goto error;
9507 		break;
9508 	case BPF_FUNC_map_pop_elem:
9509 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9510 		    map->map_type != BPF_MAP_TYPE_STACK)
9511 			goto error;
9512 		break;
9513 	case BPF_FUNC_map_peek_elem:
9514 	case BPF_FUNC_map_push_elem:
9515 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9516 		    map->map_type != BPF_MAP_TYPE_STACK &&
9517 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9518 			goto error;
9519 		break;
9520 	case BPF_FUNC_map_lookup_percpu_elem:
9521 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9522 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9523 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9524 			goto error;
9525 		break;
9526 	case BPF_FUNC_sk_storage_get:
9527 	case BPF_FUNC_sk_storage_delete:
9528 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9529 			goto error;
9530 		break;
9531 	case BPF_FUNC_inode_storage_get:
9532 	case BPF_FUNC_inode_storage_delete:
9533 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9534 			goto error;
9535 		break;
9536 	case BPF_FUNC_task_storage_get:
9537 	case BPF_FUNC_task_storage_delete:
9538 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9539 			goto error;
9540 		break;
9541 	case BPF_FUNC_cgrp_storage_get:
9542 	case BPF_FUNC_cgrp_storage_delete:
9543 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9544 			goto error;
9545 		break;
9546 	default:
9547 		break;
9548 	}
9549 
9550 	return 0;
9551 error:
9552 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9553 		map->map_type, func_id_name(func_id), func_id);
9554 	return -EINVAL;
9555 }
9556 
9557 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9558 {
9559 	int count = 0;
9560 
9561 	if (arg_type_is_raw_mem(fn->arg1_type))
9562 		count++;
9563 	if (arg_type_is_raw_mem(fn->arg2_type))
9564 		count++;
9565 	if (arg_type_is_raw_mem(fn->arg3_type))
9566 		count++;
9567 	if (arg_type_is_raw_mem(fn->arg4_type))
9568 		count++;
9569 	if (arg_type_is_raw_mem(fn->arg5_type))
9570 		count++;
9571 
9572 	/* We only support one arg being in raw mode at the moment,
9573 	 * which is sufficient for the helper functions we have
9574 	 * right now.
9575 	 */
9576 	return count <= 1;
9577 }
9578 
9579 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9580 {
9581 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9582 	bool has_size = fn->arg_size[arg] != 0;
9583 	bool is_next_size = false;
9584 
9585 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9586 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9587 
9588 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9589 		return is_next_size;
9590 
9591 	return has_size == is_next_size || is_next_size == is_fixed;
9592 }
9593 
9594 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9595 {
9596 	/* bpf_xxx(..., buf, len) call will access 'len'
9597 	 * bytes from memory 'buf'. Both arg types need
9598 	 * to be paired, so make sure there's no buggy
9599 	 * helper function specification.
9600 	 */
9601 	if (arg_type_is_mem_size(fn->arg1_type) ||
9602 	    check_args_pair_invalid(fn, 0) ||
9603 	    check_args_pair_invalid(fn, 1) ||
9604 	    check_args_pair_invalid(fn, 2) ||
9605 	    check_args_pair_invalid(fn, 3) ||
9606 	    check_args_pair_invalid(fn, 4))
9607 		return false;
9608 
9609 	return true;
9610 }
9611 
9612 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9613 {
9614 	int i;
9615 
9616 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9617 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9618 			return !!fn->arg_btf_id[i];
9619 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9620 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9621 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9622 		    /* arg_btf_id and arg_size are in a union. */
9623 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9624 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9625 			return false;
9626 	}
9627 
9628 	return true;
9629 }
9630 
9631 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9632 {
9633 	return check_raw_mode_ok(fn) &&
9634 	       check_arg_pair_ok(fn) &&
9635 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9636 }
9637 
9638 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9639  * are now invalid, so turn them into unknown SCALAR_VALUE.
9640  *
9641  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9642  * since these slices point to packet data.
9643  */
9644 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9645 {
9646 	struct bpf_func_state *state;
9647 	struct bpf_reg_state *reg;
9648 
9649 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9650 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9651 			mark_reg_invalid(env, reg);
9652 	}));
9653 }
9654 
9655 enum {
9656 	AT_PKT_END = -1,
9657 	BEYOND_PKT_END = -2,
9658 };
9659 
9660 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9661 {
9662 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9663 	struct bpf_reg_state *reg = &state->regs[regn];
9664 
9665 	if (reg->type != PTR_TO_PACKET)
9666 		/* PTR_TO_PACKET_META is not supported yet */
9667 		return;
9668 
9669 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9670 	 * How far beyond pkt_end it goes is unknown.
9671 	 * if (!range_open) it's the case of pkt >= pkt_end
9672 	 * if (range_open) it's the case of pkt > pkt_end
9673 	 * hence this pointer is at least 1 byte bigger than pkt_end
9674 	 */
9675 	if (range_open)
9676 		reg->range = BEYOND_PKT_END;
9677 	else
9678 		reg->range = AT_PKT_END;
9679 }
9680 
9681 /* The pointer with the specified id has released its reference to kernel
9682  * resources. Identify all copies of the same pointer and clear the reference.
9683  */
9684 static int release_reference(struct bpf_verifier_env *env,
9685 			     int ref_obj_id)
9686 {
9687 	struct bpf_func_state *state;
9688 	struct bpf_reg_state *reg;
9689 	int err;
9690 
9691 	err = release_reference_state(cur_func(env), ref_obj_id);
9692 	if (err)
9693 		return err;
9694 
9695 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9696 		if (reg->ref_obj_id == ref_obj_id)
9697 			mark_reg_invalid(env, reg);
9698 	}));
9699 
9700 	return 0;
9701 }
9702 
9703 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9704 {
9705 	struct bpf_func_state *unused;
9706 	struct bpf_reg_state *reg;
9707 
9708 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9709 		if (type_is_non_owning_ref(reg->type))
9710 			mark_reg_invalid(env, reg);
9711 	}));
9712 }
9713 
9714 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9715 				    struct bpf_reg_state *regs)
9716 {
9717 	int i;
9718 
9719 	/* after the call registers r0 - r5 were scratched */
9720 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9721 		mark_reg_not_init(env, regs, caller_saved[i]);
9722 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9723 	}
9724 }
9725 
9726 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9727 				   struct bpf_func_state *caller,
9728 				   struct bpf_func_state *callee,
9729 				   int insn_idx);
9730 
9731 static int set_callee_state(struct bpf_verifier_env *env,
9732 			    struct bpf_func_state *caller,
9733 			    struct bpf_func_state *callee, int insn_idx);
9734 
9735 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9736 			    set_callee_state_fn set_callee_state_cb,
9737 			    struct bpf_verifier_state *state)
9738 {
9739 	struct bpf_func_state *caller, *callee;
9740 	int err;
9741 
9742 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9743 		verbose(env, "the call stack of %d frames is too deep\n",
9744 			state->curframe + 2);
9745 		return -E2BIG;
9746 	}
9747 
9748 	if (state->frame[state->curframe + 1]) {
9749 		verbose(env, "verifier bug. Frame %d already allocated\n",
9750 			state->curframe + 1);
9751 		return -EFAULT;
9752 	}
9753 
9754 	caller = state->frame[state->curframe];
9755 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9756 	if (!callee)
9757 		return -ENOMEM;
9758 	state->frame[state->curframe + 1] = callee;
9759 
9760 	/* callee cannot access r0, r6 - r9 for reading and has to write
9761 	 * into its own stack before reading from it.
9762 	 * callee can read/write into caller's stack
9763 	 */
9764 	init_func_state(env, callee,
9765 			/* remember the callsite, it will be used by bpf_exit */
9766 			callsite,
9767 			state->curframe + 1 /* frameno within this callchain */,
9768 			subprog /* subprog number within this prog */);
9769 	/* Transfer references to the callee */
9770 	err = copy_reference_state(callee, caller);
9771 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9772 	if (err)
9773 		goto err_out;
9774 
9775 	/* only increment it after check_reg_arg() finished */
9776 	state->curframe++;
9777 
9778 	return 0;
9779 
9780 err_out:
9781 	free_func_state(callee);
9782 	state->frame[state->curframe + 1] = NULL;
9783 	return err;
9784 }
9785 
9786 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
9787 				    const struct btf *btf,
9788 				    struct bpf_reg_state *regs)
9789 {
9790 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
9791 	struct bpf_verifier_log *log = &env->log;
9792 	u32 i;
9793 	int ret;
9794 
9795 	ret = btf_prepare_func_args(env, subprog);
9796 	if (ret)
9797 		return ret;
9798 
9799 	/* check that BTF function arguments match actual types that the
9800 	 * verifier sees.
9801 	 */
9802 	for (i = 0; i < sub->arg_cnt; i++) {
9803 		u32 regno = i + 1;
9804 		struct bpf_reg_state *reg = &regs[regno];
9805 		struct bpf_subprog_arg_info *arg = &sub->args[i];
9806 
9807 		if (arg->arg_type == ARG_ANYTHING) {
9808 			if (reg->type != SCALAR_VALUE) {
9809 				bpf_log(log, "R%d is not a scalar\n", regno);
9810 				return -EINVAL;
9811 			}
9812 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
9813 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9814 			if (ret < 0)
9815 				return ret;
9816 			/* If function expects ctx type in BTF check that caller
9817 			 * is passing PTR_TO_CTX.
9818 			 */
9819 			if (reg->type != PTR_TO_CTX) {
9820 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
9821 				return -EINVAL;
9822 			}
9823 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
9824 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9825 			if (ret < 0)
9826 				return ret;
9827 			if (check_mem_reg(env, reg, regno, arg->mem_size))
9828 				return -EINVAL;
9829 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
9830 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
9831 				return -EINVAL;
9832 			}
9833 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
9834 			/*
9835 			 * Can pass any value and the kernel won't crash, but
9836 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
9837 			 * else is a bug in the bpf program. Point it out to
9838 			 * the user at the verification time instead of
9839 			 * run-time debug nightmare.
9840 			 */
9841 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
9842 				bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
9843 				return -EINVAL;
9844 			}
9845 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
9846 			ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
9847 			if (ret)
9848 				return ret;
9849 
9850 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
9851 			if (ret)
9852 				return ret;
9853 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
9854 			struct bpf_call_arg_meta meta;
9855 			bool mask;
9856 			int err;
9857 
9858 			if (register_is_null(reg) && type_may_be_null(arg->arg_type))
9859 				continue;
9860 
9861 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
9862 			mask = mask_raw_tp_reg(env, reg);
9863 			err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
9864 			err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
9865 			unmask_raw_tp_reg(reg, mask);
9866 			if (err)
9867 				return err;
9868 		} else {
9869 			bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n",
9870 				i, arg->arg_type);
9871 			return -EFAULT;
9872 		}
9873 	}
9874 
9875 	return 0;
9876 }
9877 
9878 /* Compare BTF of a function call with given bpf_reg_state.
9879  * Returns:
9880  * EFAULT - there is a verifier bug. Abort verification.
9881  * EINVAL - there is a type mismatch or BTF is not available.
9882  * 0 - BTF matches with what bpf_reg_state expects.
9883  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
9884  */
9885 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
9886 				  struct bpf_reg_state *regs)
9887 {
9888 	struct bpf_prog *prog = env->prog;
9889 	struct btf *btf = prog->aux->btf;
9890 	u32 btf_id;
9891 	int err;
9892 
9893 	if (!prog->aux->func_info)
9894 		return -EINVAL;
9895 
9896 	btf_id = prog->aux->func_info[subprog].type_id;
9897 	if (!btf_id)
9898 		return -EFAULT;
9899 
9900 	if (prog->aux->func_info_aux[subprog].unreliable)
9901 		return -EINVAL;
9902 
9903 	err = btf_check_func_arg_match(env, subprog, btf, regs);
9904 	/* Compiler optimizations can remove arguments from static functions
9905 	 * or mismatched type can be passed into a global function.
9906 	 * In such cases mark the function as unreliable from BTF point of view.
9907 	 */
9908 	if (err)
9909 		prog->aux->func_info_aux[subprog].unreliable = true;
9910 	return err;
9911 }
9912 
9913 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9914 			      int insn_idx, int subprog,
9915 			      set_callee_state_fn set_callee_state_cb)
9916 {
9917 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9918 	struct bpf_func_state *caller, *callee;
9919 	int err;
9920 
9921 	caller = state->frame[state->curframe];
9922 	err = btf_check_subprog_call(env, subprog, caller->regs);
9923 	if (err == -EFAULT)
9924 		return err;
9925 
9926 	/* set_callee_state is used for direct subprog calls, but we are
9927 	 * interested in validating only BPF helpers that can call subprogs as
9928 	 * callbacks
9929 	 */
9930 	env->subprog_info[subprog].is_cb = true;
9931 	if (bpf_pseudo_kfunc_call(insn) &&
9932 	    !is_callback_calling_kfunc(insn->imm)) {
9933 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9934 			func_id_name(insn->imm), insn->imm);
9935 		return -EFAULT;
9936 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9937 		   !is_callback_calling_function(insn->imm)) { /* helper */
9938 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9939 			func_id_name(insn->imm), insn->imm);
9940 		return -EFAULT;
9941 	}
9942 
9943 	if (is_async_callback_calling_insn(insn)) {
9944 		struct bpf_verifier_state *async_cb;
9945 
9946 		/* there is no real recursion here. timer and workqueue callbacks are async */
9947 		env->subprog_info[subprog].is_async_cb = true;
9948 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9949 					 insn_idx, subprog,
9950 					 is_bpf_wq_set_callback_impl_kfunc(insn->imm));
9951 		if (!async_cb)
9952 			return -EFAULT;
9953 		callee = async_cb->frame[0];
9954 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9955 
9956 		/* Convert bpf_timer_set_callback() args into timer callback args */
9957 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9958 		if (err)
9959 			return err;
9960 
9961 		return 0;
9962 	}
9963 
9964 	/* for callback functions enqueue entry to callback and
9965 	 * proceed with next instruction within current frame.
9966 	 */
9967 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9968 	if (!callback_state)
9969 		return -ENOMEM;
9970 
9971 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9972 			       callback_state);
9973 	if (err)
9974 		return err;
9975 
9976 	callback_state->callback_unroll_depth++;
9977 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9978 	caller->callback_depth = 0;
9979 	return 0;
9980 }
9981 
9982 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9983 			   int *insn_idx)
9984 {
9985 	struct bpf_verifier_state *state = env->cur_state;
9986 	struct bpf_func_state *caller;
9987 	int err, subprog, target_insn;
9988 
9989 	target_insn = *insn_idx + insn->imm + 1;
9990 	subprog = find_subprog(env, target_insn);
9991 	if (subprog < 0) {
9992 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9993 		return -EFAULT;
9994 	}
9995 
9996 	caller = state->frame[state->curframe];
9997 	err = btf_check_subprog_call(env, subprog, caller->regs);
9998 	if (err == -EFAULT)
9999 		return err;
10000 	if (subprog_is_global(env, subprog)) {
10001 		const char *sub_name = subprog_name(env, subprog);
10002 
10003 		/* Only global subprogs cannot be called with a lock held. */
10004 		if (cur_func(env)->active_locks) {
10005 			verbose(env, "global function calls are not allowed while holding a lock,\n"
10006 				     "use static function instead\n");
10007 			return -EINVAL;
10008 		}
10009 
10010 		/* Only global subprogs cannot be called with preemption disabled. */
10011 		if (env->cur_state->active_preempt_lock) {
10012 			verbose(env, "global function calls are not allowed with preemption disabled,\n"
10013 				     "use static function instead\n");
10014 			return -EINVAL;
10015 		}
10016 
10017 		if (err) {
10018 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
10019 				subprog, sub_name);
10020 			return err;
10021 		}
10022 
10023 		verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
10024 			subprog, sub_name);
10025 		/* mark global subprog for verifying after main prog */
10026 		subprog_aux(env, subprog)->called = true;
10027 		clear_caller_saved_regs(env, caller->regs);
10028 
10029 		/* All global functions return a 64-bit SCALAR_VALUE */
10030 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
10031 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10032 
10033 		/* continue with next insn after call */
10034 		return 0;
10035 	}
10036 
10037 	/* for regular function entry setup new frame and continue
10038 	 * from that frame.
10039 	 */
10040 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
10041 	if (err)
10042 		return err;
10043 
10044 	clear_caller_saved_regs(env, caller->regs);
10045 
10046 	/* and go analyze first insn of the callee */
10047 	*insn_idx = env->subprog_info[subprog].start - 1;
10048 
10049 	if (env->log.level & BPF_LOG_LEVEL) {
10050 		verbose(env, "caller:\n");
10051 		print_verifier_state(env, caller, true);
10052 		verbose(env, "callee:\n");
10053 		print_verifier_state(env, state->frame[state->curframe], true);
10054 	}
10055 
10056 	return 0;
10057 }
10058 
10059 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
10060 				   struct bpf_func_state *caller,
10061 				   struct bpf_func_state *callee)
10062 {
10063 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
10064 	 *      void *callback_ctx, u64 flags);
10065 	 * callback_fn(struct bpf_map *map, void *key, void *value,
10066 	 *      void *callback_ctx);
10067 	 */
10068 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10069 
10070 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10071 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10072 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10073 
10074 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10075 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10076 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10077 
10078 	/* pointer to stack or null */
10079 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
10080 
10081 	/* unused */
10082 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10083 	return 0;
10084 }
10085 
10086 static int set_callee_state(struct bpf_verifier_env *env,
10087 			    struct bpf_func_state *caller,
10088 			    struct bpf_func_state *callee, int insn_idx)
10089 {
10090 	int i;
10091 
10092 	/* copy r1 - r5 args that callee can access.  The copy includes parent
10093 	 * pointers, which connects us up to the liveness chain
10094 	 */
10095 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
10096 		callee->regs[i] = caller->regs[i];
10097 	return 0;
10098 }
10099 
10100 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
10101 				       struct bpf_func_state *caller,
10102 				       struct bpf_func_state *callee,
10103 				       int insn_idx)
10104 {
10105 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
10106 	struct bpf_map *map;
10107 	int err;
10108 
10109 	/* valid map_ptr and poison value does not matter */
10110 	map = insn_aux->map_ptr_state.map_ptr;
10111 	if (!map->ops->map_set_for_each_callback_args ||
10112 	    !map->ops->map_for_each_callback) {
10113 		verbose(env, "callback function not allowed for map\n");
10114 		return -ENOTSUPP;
10115 	}
10116 
10117 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
10118 	if (err)
10119 		return err;
10120 
10121 	callee->in_callback_fn = true;
10122 	callee->callback_ret_range = retval_range(0, 1);
10123 	return 0;
10124 }
10125 
10126 static int set_loop_callback_state(struct bpf_verifier_env *env,
10127 				   struct bpf_func_state *caller,
10128 				   struct bpf_func_state *callee,
10129 				   int insn_idx)
10130 {
10131 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
10132 	 *	    u64 flags);
10133 	 * callback_fn(u64 index, void *callback_ctx);
10134 	 */
10135 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
10136 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10137 
10138 	/* unused */
10139 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10140 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10141 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10142 
10143 	callee->in_callback_fn = true;
10144 	callee->callback_ret_range = retval_range(0, 1);
10145 	return 0;
10146 }
10147 
10148 static int set_timer_callback_state(struct bpf_verifier_env *env,
10149 				    struct bpf_func_state *caller,
10150 				    struct bpf_func_state *callee,
10151 				    int insn_idx)
10152 {
10153 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
10154 
10155 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
10156 	 * callback_fn(struct bpf_map *map, void *key, void *value);
10157 	 */
10158 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10159 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10160 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
10161 
10162 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10163 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10164 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
10165 
10166 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10167 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10168 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
10169 
10170 	/* unused */
10171 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10172 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10173 	callee->in_async_callback_fn = true;
10174 	callee->callback_ret_range = retval_range(0, 1);
10175 	return 0;
10176 }
10177 
10178 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
10179 				       struct bpf_func_state *caller,
10180 				       struct bpf_func_state *callee,
10181 				       int insn_idx)
10182 {
10183 	/* bpf_find_vma(struct task_struct *task, u64 addr,
10184 	 *               void *callback_fn, void *callback_ctx, u64 flags)
10185 	 * (callback_fn)(struct task_struct *task,
10186 	 *               struct vm_area_struct *vma, void *callback_ctx);
10187 	 */
10188 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10189 
10190 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
10191 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10192 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
10193 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
10194 
10195 	/* pointer to stack or null */
10196 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
10197 
10198 	/* unused */
10199 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10200 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10201 	callee->in_callback_fn = true;
10202 	callee->callback_ret_range = retval_range(0, 1);
10203 	return 0;
10204 }
10205 
10206 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
10207 					   struct bpf_func_state *caller,
10208 					   struct bpf_func_state *callee,
10209 					   int insn_idx)
10210 {
10211 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
10212 	 *			  callback_ctx, u64 flags);
10213 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
10214 	 */
10215 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
10216 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
10217 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10218 
10219 	/* unused */
10220 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10221 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10222 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10223 
10224 	callee->in_callback_fn = true;
10225 	callee->callback_ret_range = retval_range(0, 1);
10226 	return 0;
10227 }
10228 
10229 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
10230 					 struct bpf_func_state *caller,
10231 					 struct bpf_func_state *callee,
10232 					 int insn_idx)
10233 {
10234 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
10235 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
10236 	 *
10237 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
10238 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
10239 	 * by this point, so look at 'root'
10240 	 */
10241 	struct btf_field *field;
10242 
10243 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
10244 				      BPF_RB_ROOT);
10245 	if (!field || !field->graph_root.value_btf_id)
10246 		return -EFAULT;
10247 
10248 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
10249 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
10250 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
10251 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
10252 
10253 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10254 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10255 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10256 	callee->in_callback_fn = true;
10257 	callee->callback_ret_range = retval_range(0, 1);
10258 	return 0;
10259 }
10260 
10261 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
10262 
10263 /* Are we currently verifying the callback for a rbtree helper that must
10264  * be called with lock held? If so, no need to complain about unreleased
10265  * lock
10266  */
10267 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
10268 {
10269 	struct bpf_verifier_state *state = env->cur_state;
10270 	struct bpf_insn *insn = env->prog->insnsi;
10271 	struct bpf_func_state *callee;
10272 	int kfunc_btf_id;
10273 
10274 	if (!state->curframe)
10275 		return false;
10276 
10277 	callee = state->frame[state->curframe];
10278 
10279 	if (!callee->in_callback_fn)
10280 		return false;
10281 
10282 	kfunc_btf_id = insn[callee->callsite].imm;
10283 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
10284 }
10285 
10286 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg,
10287 				bool return_32bit)
10288 {
10289 	if (return_32bit)
10290 		return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval;
10291 	else
10292 		return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
10293 }
10294 
10295 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
10296 {
10297 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
10298 	struct bpf_func_state *caller, *callee;
10299 	struct bpf_reg_state *r0;
10300 	bool in_callback_fn;
10301 	int err;
10302 
10303 	callee = state->frame[state->curframe];
10304 	r0 = &callee->regs[BPF_REG_0];
10305 	if (r0->type == PTR_TO_STACK) {
10306 		/* technically it's ok to return caller's stack pointer
10307 		 * (or caller's caller's pointer) back to the caller,
10308 		 * since these pointers are valid. Only current stack
10309 		 * pointer will be invalid as soon as function exits,
10310 		 * but let's be conservative
10311 		 */
10312 		verbose(env, "cannot return stack pointer to the caller\n");
10313 		return -EINVAL;
10314 	}
10315 
10316 	caller = state->frame[state->curframe - 1];
10317 	if (callee->in_callback_fn) {
10318 		if (r0->type != SCALAR_VALUE) {
10319 			verbose(env, "R0 not a scalar value\n");
10320 			return -EACCES;
10321 		}
10322 
10323 		/* we are going to rely on register's precise value */
10324 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
10325 		err = err ?: mark_chain_precision(env, BPF_REG_0);
10326 		if (err)
10327 			return err;
10328 
10329 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
10330 		if (!retval_range_within(callee->callback_ret_range, r0, false)) {
10331 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
10332 					       "At callback return", "R0");
10333 			return -EINVAL;
10334 		}
10335 		if (!calls_callback(env, callee->callsite)) {
10336 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
10337 				*insn_idx, callee->callsite);
10338 			return -EFAULT;
10339 		}
10340 	} else {
10341 		/* return to the caller whatever r0 had in the callee */
10342 		caller->regs[BPF_REG_0] = *r0;
10343 	}
10344 
10345 	/* Transfer references to the caller */
10346 	err = copy_reference_state(caller, callee);
10347 	if (err)
10348 		return err;
10349 
10350 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
10351 	 * there function call logic would reschedule callback visit. If iteration
10352 	 * converges is_state_visited() would prune that visit eventually.
10353 	 */
10354 	in_callback_fn = callee->in_callback_fn;
10355 	if (in_callback_fn)
10356 		*insn_idx = callee->callsite;
10357 	else
10358 		*insn_idx = callee->callsite + 1;
10359 
10360 	if (env->log.level & BPF_LOG_LEVEL) {
10361 		verbose(env, "returning from callee:\n");
10362 		print_verifier_state(env, callee, true);
10363 		verbose(env, "to caller at %d:\n", *insn_idx);
10364 		print_verifier_state(env, caller, true);
10365 	}
10366 	/* clear everything in the callee. In case of exceptional exits using
10367 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
10368 	free_func_state(callee);
10369 	state->frame[state->curframe--] = NULL;
10370 
10371 	/* for callbacks widen imprecise scalars to make programs like below verify:
10372 	 *
10373 	 *   struct ctx { int i; }
10374 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
10375 	 *   ...
10376 	 *   struct ctx = { .i = 0; }
10377 	 *   bpf_loop(100, cb, &ctx, 0);
10378 	 *
10379 	 * This is similar to what is done in process_iter_next_call() for open
10380 	 * coded iterators.
10381 	 */
10382 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
10383 	if (prev_st) {
10384 		err = widen_imprecise_scalars(env, prev_st, state);
10385 		if (err)
10386 			return err;
10387 	}
10388 	return 0;
10389 }
10390 
10391 static int do_refine_retval_range(struct bpf_verifier_env *env,
10392 				  struct bpf_reg_state *regs, int ret_type,
10393 				  int func_id,
10394 				  struct bpf_call_arg_meta *meta)
10395 {
10396 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
10397 
10398 	if (ret_type != RET_INTEGER)
10399 		return 0;
10400 
10401 	switch (func_id) {
10402 	case BPF_FUNC_get_stack:
10403 	case BPF_FUNC_get_task_stack:
10404 	case BPF_FUNC_probe_read_str:
10405 	case BPF_FUNC_probe_read_kernel_str:
10406 	case BPF_FUNC_probe_read_user_str:
10407 		ret_reg->smax_value = meta->msize_max_value;
10408 		ret_reg->s32_max_value = meta->msize_max_value;
10409 		ret_reg->smin_value = -MAX_ERRNO;
10410 		ret_reg->s32_min_value = -MAX_ERRNO;
10411 		reg_bounds_sync(ret_reg);
10412 		break;
10413 	case BPF_FUNC_get_smp_processor_id:
10414 		ret_reg->umax_value = nr_cpu_ids - 1;
10415 		ret_reg->u32_max_value = nr_cpu_ids - 1;
10416 		ret_reg->smax_value = nr_cpu_ids - 1;
10417 		ret_reg->s32_max_value = nr_cpu_ids - 1;
10418 		ret_reg->umin_value = 0;
10419 		ret_reg->u32_min_value = 0;
10420 		ret_reg->smin_value = 0;
10421 		ret_reg->s32_min_value = 0;
10422 		reg_bounds_sync(ret_reg);
10423 		break;
10424 	}
10425 
10426 	return reg_bounds_sanity_check(env, ret_reg, "retval");
10427 }
10428 
10429 static int
10430 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10431 		int func_id, int insn_idx)
10432 {
10433 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10434 	struct bpf_map *map = meta->map_ptr;
10435 
10436 	if (func_id != BPF_FUNC_tail_call &&
10437 	    func_id != BPF_FUNC_map_lookup_elem &&
10438 	    func_id != BPF_FUNC_map_update_elem &&
10439 	    func_id != BPF_FUNC_map_delete_elem &&
10440 	    func_id != BPF_FUNC_map_push_elem &&
10441 	    func_id != BPF_FUNC_map_pop_elem &&
10442 	    func_id != BPF_FUNC_map_peek_elem &&
10443 	    func_id != BPF_FUNC_for_each_map_elem &&
10444 	    func_id != BPF_FUNC_redirect_map &&
10445 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
10446 		return 0;
10447 
10448 	if (map == NULL) {
10449 		verbose(env, "kernel subsystem misconfigured verifier\n");
10450 		return -EINVAL;
10451 	}
10452 
10453 	/* In case of read-only, some additional restrictions
10454 	 * need to be applied in order to prevent altering the
10455 	 * state of the map from program side.
10456 	 */
10457 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
10458 	    (func_id == BPF_FUNC_map_delete_elem ||
10459 	     func_id == BPF_FUNC_map_update_elem ||
10460 	     func_id == BPF_FUNC_map_push_elem ||
10461 	     func_id == BPF_FUNC_map_pop_elem)) {
10462 		verbose(env, "write into map forbidden\n");
10463 		return -EACCES;
10464 	}
10465 
10466 	if (!aux->map_ptr_state.map_ptr)
10467 		bpf_map_ptr_store(aux, meta->map_ptr,
10468 				  !meta->map_ptr->bypass_spec_v1, false);
10469 	else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
10470 		bpf_map_ptr_store(aux, meta->map_ptr,
10471 				  !meta->map_ptr->bypass_spec_v1, true);
10472 	return 0;
10473 }
10474 
10475 static int
10476 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10477 		int func_id, int insn_idx)
10478 {
10479 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10480 	struct bpf_reg_state *regs = cur_regs(env), *reg;
10481 	struct bpf_map *map = meta->map_ptr;
10482 	u64 val, max;
10483 	int err;
10484 
10485 	if (func_id != BPF_FUNC_tail_call)
10486 		return 0;
10487 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
10488 		verbose(env, "kernel subsystem misconfigured verifier\n");
10489 		return -EINVAL;
10490 	}
10491 
10492 	reg = &regs[BPF_REG_3];
10493 	val = reg->var_off.value;
10494 	max = map->max_entries;
10495 
10496 	if (!(is_reg_const(reg, false) && val < max)) {
10497 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10498 		return 0;
10499 	}
10500 
10501 	err = mark_chain_precision(env, BPF_REG_3);
10502 	if (err)
10503 		return err;
10504 	if (bpf_map_key_unseen(aux))
10505 		bpf_map_key_store(aux, val);
10506 	else if (!bpf_map_key_poisoned(aux) &&
10507 		  bpf_map_key_immediate(aux) != val)
10508 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10509 	return 0;
10510 }
10511 
10512 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
10513 {
10514 	struct bpf_func_state *state = cur_func(env);
10515 	bool refs_lingering = false;
10516 	int i;
10517 
10518 	if (!exception_exit && state->frameno)
10519 		return 0;
10520 
10521 	for (i = 0; i < state->acquired_refs; i++) {
10522 		if (state->refs[i].type != REF_TYPE_PTR)
10523 			continue;
10524 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
10525 			state->refs[i].id, state->refs[i].insn_idx);
10526 		refs_lingering = true;
10527 	}
10528 	return refs_lingering ? -EINVAL : 0;
10529 }
10530 
10531 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
10532 {
10533 	int err;
10534 
10535 	if (check_lock && cur_func(env)->active_locks) {
10536 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
10537 		return -EINVAL;
10538 	}
10539 
10540 	err = check_reference_leak(env, exception_exit);
10541 	if (err) {
10542 		verbose(env, "%s would lead to reference leak\n", prefix);
10543 		return err;
10544 	}
10545 
10546 	if (check_lock && env->cur_state->active_rcu_lock) {
10547 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
10548 		return -EINVAL;
10549 	}
10550 
10551 	if (check_lock && env->cur_state->active_preempt_lock) {
10552 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
10553 		return -EINVAL;
10554 	}
10555 
10556 	return 0;
10557 }
10558 
10559 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
10560 				   struct bpf_reg_state *regs)
10561 {
10562 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
10563 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
10564 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
10565 	struct bpf_bprintf_data data = {};
10566 	int err, fmt_map_off, num_args;
10567 	u64 fmt_addr;
10568 	char *fmt;
10569 
10570 	/* data must be an array of u64 */
10571 	if (data_len_reg->var_off.value % 8)
10572 		return -EINVAL;
10573 	num_args = data_len_reg->var_off.value / 8;
10574 
10575 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
10576 	 * and map_direct_value_addr is set.
10577 	 */
10578 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
10579 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
10580 						  fmt_map_off);
10581 	if (err) {
10582 		verbose(env, "verifier bug\n");
10583 		return -EFAULT;
10584 	}
10585 	fmt = (char *)(long)fmt_addr + fmt_map_off;
10586 
10587 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
10588 	 * can focus on validating the format specifiers.
10589 	 */
10590 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
10591 	if (err < 0)
10592 		verbose(env, "Invalid format string\n");
10593 
10594 	return err;
10595 }
10596 
10597 static int check_get_func_ip(struct bpf_verifier_env *env)
10598 {
10599 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10600 	int func_id = BPF_FUNC_get_func_ip;
10601 
10602 	if (type == BPF_PROG_TYPE_TRACING) {
10603 		if (!bpf_prog_has_trampoline(env->prog)) {
10604 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
10605 				func_id_name(func_id), func_id);
10606 			return -ENOTSUPP;
10607 		}
10608 		return 0;
10609 	} else if (type == BPF_PROG_TYPE_KPROBE) {
10610 		return 0;
10611 	}
10612 
10613 	verbose(env, "func %s#%d not supported for program type %d\n",
10614 		func_id_name(func_id), func_id, type);
10615 	return -ENOTSUPP;
10616 }
10617 
10618 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
10619 {
10620 	return &env->insn_aux_data[env->insn_idx];
10621 }
10622 
10623 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10624 {
10625 	struct bpf_reg_state *regs = cur_regs(env);
10626 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
10627 	bool reg_is_null = register_is_null(reg);
10628 
10629 	if (reg_is_null)
10630 		mark_chain_precision(env, BPF_REG_4);
10631 
10632 	return reg_is_null;
10633 }
10634 
10635 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10636 {
10637 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10638 
10639 	if (!state->initialized) {
10640 		state->initialized = 1;
10641 		state->fit_for_inline = loop_flag_is_zero(env);
10642 		state->callback_subprogno = subprogno;
10643 		return;
10644 	}
10645 
10646 	if (!state->fit_for_inline)
10647 		return;
10648 
10649 	state->fit_for_inline = (loop_flag_is_zero(env) &&
10650 				 state->callback_subprogno == subprogno);
10651 }
10652 
10653 static int get_helper_proto(struct bpf_verifier_env *env, int func_id,
10654 			    const struct bpf_func_proto **ptr)
10655 {
10656 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
10657 		return -ERANGE;
10658 
10659 	if (!env->ops->get_func_proto)
10660 		return -EINVAL;
10661 
10662 	*ptr = env->ops->get_func_proto(func_id, env->prog);
10663 	return *ptr ? 0 : -EINVAL;
10664 }
10665 
10666 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10667 			     int *insn_idx_p)
10668 {
10669 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10670 	bool returns_cpu_specific_alloc_ptr = false;
10671 	const struct bpf_func_proto *fn = NULL;
10672 	enum bpf_return_type ret_type;
10673 	enum bpf_type_flag ret_flag;
10674 	struct bpf_reg_state *regs;
10675 	struct bpf_call_arg_meta meta;
10676 	int insn_idx = *insn_idx_p;
10677 	bool changes_data;
10678 	int i, err, func_id;
10679 
10680 	/* find function prototype */
10681 	func_id = insn->imm;
10682 	err = get_helper_proto(env, insn->imm, &fn);
10683 	if (err == -ERANGE) {
10684 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
10685 		return -EINVAL;
10686 	}
10687 
10688 	if (err) {
10689 		verbose(env, "program of this type cannot use helper %s#%d\n",
10690 			func_id_name(func_id), func_id);
10691 		return err;
10692 	}
10693 
10694 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
10695 	if (!env->prog->gpl_compatible && fn->gpl_only) {
10696 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10697 		return -EINVAL;
10698 	}
10699 
10700 	if (fn->allowed && !fn->allowed(env->prog)) {
10701 		verbose(env, "helper call is not allowed in probe\n");
10702 		return -EINVAL;
10703 	}
10704 
10705 	if (!in_sleepable(env) && fn->might_sleep) {
10706 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
10707 		return -EINVAL;
10708 	}
10709 
10710 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
10711 	changes_data = bpf_helper_changes_pkt_data(fn->func);
10712 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10713 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10714 			func_id_name(func_id), func_id);
10715 		return -EINVAL;
10716 	}
10717 
10718 	memset(&meta, 0, sizeof(meta));
10719 	meta.pkt_access = fn->pkt_access;
10720 
10721 	err = check_func_proto(fn, func_id);
10722 	if (err) {
10723 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10724 			func_id_name(func_id), func_id);
10725 		return err;
10726 	}
10727 
10728 	if (env->cur_state->active_rcu_lock) {
10729 		if (fn->might_sleep) {
10730 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10731 				func_id_name(func_id), func_id);
10732 			return -EINVAL;
10733 		}
10734 
10735 		if (in_sleepable(env) && is_storage_get_function(func_id))
10736 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10737 	}
10738 
10739 	if (env->cur_state->active_preempt_lock) {
10740 		if (fn->might_sleep) {
10741 			verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
10742 				func_id_name(func_id), func_id);
10743 			return -EINVAL;
10744 		}
10745 
10746 		if (in_sleepable(env) && is_storage_get_function(func_id))
10747 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10748 	}
10749 
10750 	meta.func_id = func_id;
10751 	/* check args */
10752 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10753 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10754 		if (err)
10755 			return err;
10756 	}
10757 
10758 	err = record_func_map(env, &meta, func_id, insn_idx);
10759 	if (err)
10760 		return err;
10761 
10762 	err = record_func_key(env, &meta, func_id, insn_idx);
10763 	if (err)
10764 		return err;
10765 
10766 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10767 	 * is inferred from register state.
10768 	 */
10769 	for (i = 0; i < meta.access_size; i++) {
10770 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10771 				       BPF_WRITE, -1, false, false);
10772 		if (err)
10773 			return err;
10774 	}
10775 
10776 	regs = cur_regs(env);
10777 
10778 	if (meta.release_regno) {
10779 		err = -EINVAL;
10780 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10781 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10782 		 * is safe to do directly.
10783 		 */
10784 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10785 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10786 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10787 				return -EFAULT;
10788 			}
10789 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10790 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10791 			u32 ref_obj_id = meta.ref_obj_id;
10792 			bool in_rcu = in_rcu_cs(env);
10793 			struct bpf_func_state *state;
10794 			struct bpf_reg_state *reg;
10795 
10796 			err = release_reference_state(cur_func(env), ref_obj_id);
10797 			if (!err) {
10798 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10799 					if (reg->ref_obj_id == ref_obj_id) {
10800 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10801 							reg->ref_obj_id = 0;
10802 							reg->type &= ~MEM_ALLOC;
10803 							reg->type |= MEM_RCU;
10804 						} else {
10805 							mark_reg_invalid(env, reg);
10806 						}
10807 					}
10808 				}));
10809 			}
10810 		} else if (meta.ref_obj_id) {
10811 			err = release_reference(env, meta.ref_obj_id);
10812 		} else if (register_is_null(&regs[meta.release_regno])) {
10813 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10814 			 * released is NULL, which must be > R0.
10815 			 */
10816 			err = 0;
10817 		}
10818 		if (err) {
10819 			verbose(env, "func %s#%d reference has not been acquired before\n",
10820 				func_id_name(func_id), func_id);
10821 			return err;
10822 		}
10823 	}
10824 
10825 	switch (func_id) {
10826 	case BPF_FUNC_tail_call:
10827 		err = check_resource_leak(env, false, true, "tail_call");
10828 		if (err)
10829 			return err;
10830 		break;
10831 	case BPF_FUNC_get_local_storage:
10832 		/* check that flags argument in get_local_storage(map, flags) is 0,
10833 		 * this is required because get_local_storage() can't return an error.
10834 		 */
10835 		if (!register_is_null(&regs[BPF_REG_2])) {
10836 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10837 			return -EINVAL;
10838 		}
10839 		break;
10840 	case BPF_FUNC_for_each_map_elem:
10841 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10842 					 set_map_elem_callback_state);
10843 		break;
10844 	case BPF_FUNC_timer_set_callback:
10845 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10846 					 set_timer_callback_state);
10847 		break;
10848 	case BPF_FUNC_find_vma:
10849 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10850 					 set_find_vma_callback_state);
10851 		break;
10852 	case BPF_FUNC_snprintf:
10853 		err = check_bpf_snprintf_call(env, regs);
10854 		break;
10855 	case BPF_FUNC_loop:
10856 		update_loop_inline_state(env, meta.subprogno);
10857 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10858 		 * is finished, thus mark it precise.
10859 		 */
10860 		err = mark_chain_precision(env, BPF_REG_1);
10861 		if (err)
10862 			return err;
10863 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10864 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10865 						 set_loop_callback_state);
10866 		} else {
10867 			cur_func(env)->callback_depth = 0;
10868 			if (env->log.level & BPF_LOG_LEVEL2)
10869 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10870 					env->cur_state->curframe);
10871 		}
10872 		break;
10873 	case BPF_FUNC_dynptr_from_mem:
10874 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10875 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10876 				reg_type_str(env, regs[BPF_REG_1].type));
10877 			return -EACCES;
10878 		}
10879 		break;
10880 	case BPF_FUNC_set_retval:
10881 		if (prog_type == BPF_PROG_TYPE_LSM &&
10882 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10883 			if (!env->prog->aux->attach_func_proto->type) {
10884 				/* Make sure programs that attach to void
10885 				 * hooks don't try to modify return value.
10886 				 */
10887 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10888 				return -EINVAL;
10889 			}
10890 		}
10891 		break;
10892 	case BPF_FUNC_dynptr_data:
10893 	{
10894 		struct bpf_reg_state *reg;
10895 		int id, ref_obj_id;
10896 
10897 		reg = get_dynptr_arg_reg(env, fn, regs);
10898 		if (!reg)
10899 			return -EFAULT;
10900 
10901 
10902 		if (meta.dynptr_id) {
10903 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10904 			return -EFAULT;
10905 		}
10906 		if (meta.ref_obj_id) {
10907 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10908 			return -EFAULT;
10909 		}
10910 
10911 		id = dynptr_id(env, reg);
10912 		if (id < 0) {
10913 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10914 			return id;
10915 		}
10916 
10917 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10918 		if (ref_obj_id < 0) {
10919 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10920 			return ref_obj_id;
10921 		}
10922 
10923 		meta.dynptr_id = id;
10924 		meta.ref_obj_id = ref_obj_id;
10925 
10926 		break;
10927 	}
10928 	case BPF_FUNC_dynptr_write:
10929 	{
10930 		enum bpf_dynptr_type dynptr_type;
10931 		struct bpf_reg_state *reg;
10932 
10933 		reg = get_dynptr_arg_reg(env, fn, regs);
10934 		if (!reg)
10935 			return -EFAULT;
10936 
10937 		dynptr_type = dynptr_get_type(env, reg);
10938 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10939 			return -EFAULT;
10940 
10941 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10942 			/* this will trigger clear_all_pkt_pointers(), which will
10943 			 * invalidate all dynptr slices associated with the skb
10944 			 */
10945 			changes_data = true;
10946 
10947 		break;
10948 	}
10949 	case BPF_FUNC_per_cpu_ptr:
10950 	case BPF_FUNC_this_cpu_ptr:
10951 	{
10952 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
10953 		const struct btf_type *type;
10954 
10955 		if (reg->type & MEM_RCU) {
10956 			type = btf_type_by_id(reg->btf, reg->btf_id);
10957 			if (!type || !btf_type_is_struct(type)) {
10958 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
10959 				return -EFAULT;
10960 			}
10961 			returns_cpu_specific_alloc_ptr = true;
10962 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10963 		}
10964 		break;
10965 	}
10966 	case BPF_FUNC_user_ringbuf_drain:
10967 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10968 					 set_user_ringbuf_callback_state);
10969 		break;
10970 	}
10971 
10972 	if (err)
10973 		return err;
10974 
10975 	/* reset caller saved regs */
10976 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10977 		mark_reg_not_init(env, regs, caller_saved[i]);
10978 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10979 	}
10980 
10981 	/* helper call returns 64-bit value. */
10982 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10983 
10984 	/* update return register (already marked as written above) */
10985 	ret_type = fn->ret_type;
10986 	ret_flag = type_flag(ret_type);
10987 
10988 	switch (base_type(ret_type)) {
10989 	case RET_INTEGER:
10990 		/* sets type to SCALAR_VALUE */
10991 		mark_reg_unknown(env, regs, BPF_REG_0);
10992 		break;
10993 	case RET_VOID:
10994 		regs[BPF_REG_0].type = NOT_INIT;
10995 		break;
10996 	case RET_PTR_TO_MAP_VALUE:
10997 		/* There is no offset yet applied, variable or fixed */
10998 		mark_reg_known_zero(env, regs, BPF_REG_0);
10999 		/* remember map_ptr, so that check_map_access()
11000 		 * can check 'value_size' boundary of memory access
11001 		 * to map element returned from bpf_map_lookup_elem()
11002 		 */
11003 		if (meta.map_ptr == NULL) {
11004 			verbose(env,
11005 				"kernel subsystem misconfigured verifier\n");
11006 			return -EINVAL;
11007 		}
11008 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
11009 		regs[BPF_REG_0].map_uid = meta.map_uid;
11010 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
11011 		if (!type_may_be_null(ret_type) &&
11012 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
11013 			regs[BPF_REG_0].id = ++env->id_gen;
11014 		}
11015 		break;
11016 	case RET_PTR_TO_SOCKET:
11017 		mark_reg_known_zero(env, regs, BPF_REG_0);
11018 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
11019 		break;
11020 	case RET_PTR_TO_SOCK_COMMON:
11021 		mark_reg_known_zero(env, regs, BPF_REG_0);
11022 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
11023 		break;
11024 	case RET_PTR_TO_TCP_SOCK:
11025 		mark_reg_known_zero(env, regs, BPF_REG_0);
11026 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
11027 		break;
11028 	case RET_PTR_TO_MEM:
11029 		mark_reg_known_zero(env, regs, BPF_REG_0);
11030 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11031 		regs[BPF_REG_0].mem_size = meta.mem_size;
11032 		break;
11033 	case RET_PTR_TO_MEM_OR_BTF_ID:
11034 	{
11035 		const struct btf_type *t;
11036 
11037 		mark_reg_known_zero(env, regs, BPF_REG_0);
11038 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
11039 		if (!btf_type_is_struct(t)) {
11040 			u32 tsize;
11041 			const struct btf_type *ret;
11042 			const char *tname;
11043 
11044 			/* resolve the type size of ksym. */
11045 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
11046 			if (IS_ERR(ret)) {
11047 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
11048 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
11049 					tname, PTR_ERR(ret));
11050 				return -EINVAL;
11051 			}
11052 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11053 			regs[BPF_REG_0].mem_size = tsize;
11054 		} else {
11055 			if (returns_cpu_specific_alloc_ptr) {
11056 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
11057 			} else {
11058 				/* MEM_RDONLY may be carried from ret_flag, but it
11059 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
11060 				 * it will confuse the check of PTR_TO_BTF_ID in
11061 				 * check_mem_access().
11062 				 */
11063 				ret_flag &= ~MEM_RDONLY;
11064 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11065 			}
11066 
11067 			regs[BPF_REG_0].btf = meta.ret_btf;
11068 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11069 		}
11070 		break;
11071 	}
11072 	case RET_PTR_TO_BTF_ID:
11073 	{
11074 		struct btf *ret_btf;
11075 		int ret_btf_id;
11076 
11077 		mark_reg_known_zero(env, regs, BPF_REG_0);
11078 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11079 		if (func_id == BPF_FUNC_kptr_xchg) {
11080 			ret_btf = meta.kptr_field->kptr.btf;
11081 			ret_btf_id = meta.kptr_field->kptr.btf_id;
11082 			if (!btf_is_kernel(ret_btf)) {
11083 				regs[BPF_REG_0].type |= MEM_ALLOC;
11084 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
11085 					regs[BPF_REG_0].type |= MEM_PERCPU;
11086 			}
11087 		} else {
11088 			if (fn->ret_btf_id == BPF_PTR_POISON) {
11089 				verbose(env, "verifier internal error:");
11090 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
11091 					func_id_name(func_id));
11092 				return -EINVAL;
11093 			}
11094 			ret_btf = btf_vmlinux;
11095 			ret_btf_id = *fn->ret_btf_id;
11096 		}
11097 		if (ret_btf_id == 0) {
11098 			verbose(env, "invalid return type %u of func %s#%d\n",
11099 				base_type(ret_type), func_id_name(func_id),
11100 				func_id);
11101 			return -EINVAL;
11102 		}
11103 		regs[BPF_REG_0].btf = ret_btf;
11104 		regs[BPF_REG_0].btf_id = ret_btf_id;
11105 		break;
11106 	}
11107 	default:
11108 		verbose(env, "unknown return type %u of func %s#%d\n",
11109 			base_type(ret_type), func_id_name(func_id), func_id);
11110 		return -EINVAL;
11111 	}
11112 
11113 	if (type_may_be_null(regs[BPF_REG_0].type))
11114 		regs[BPF_REG_0].id = ++env->id_gen;
11115 
11116 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
11117 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
11118 			func_id_name(func_id), func_id);
11119 		return -EFAULT;
11120 	}
11121 
11122 	if (is_dynptr_ref_function(func_id))
11123 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
11124 
11125 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
11126 		/* For release_reference() */
11127 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11128 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
11129 		int id = acquire_reference_state(env, insn_idx);
11130 
11131 		if (id < 0)
11132 			return id;
11133 		/* For mark_ptr_or_null_reg() */
11134 		regs[BPF_REG_0].id = id;
11135 		/* For release_reference() */
11136 		regs[BPF_REG_0].ref_obj_id = id;
11137 	}
11138 
11139 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
11140 	if (err)
11141 		return err;
11142 
11143 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
11144 	if (err)
11145 		return err;
11146 
11147 	if ((func_id == BPF_FUNC_get_stack ||
11148 	     func_id == BPF_FUNC_get_task_stack) &&
11149 	    !env->prog->has_callchain_buf) {
11150 		const char *err_str;
11151 
11152 #ifdef CONFIG_PERF_EVENTS
11153 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
11154 		err_str = "cannot get callchain buffer for func %s#%d\n";
11155 #else
11156 		err = -ENOTSUPP;
11157 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
11158 #endif
11159 		if (err) {
11160 			verbose(env, err_str, func_id_name(func_id), func_id);
11161 			return err;
11162 		}
11163 
11164 		env->prog->has_callchain_buf = true;
11165 	}
11166 
11167 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
11168 		env->prog->call_get_stack = true;
11169 
11170 	if (func_id == BPF_FUNC_get_func_ip) {
11171 		if (check_get_func_ip(env))
11172 			return -ENOTSUPP;
11173 		env->prog->call_get_func_ip = true;
11174 	}
11175 
11176 	if (changes_data)
11177 		clear_all_pkt_pointers(env);
11178 	return 0;
11179 }
11180 
11181 /* mark_btf_func_reg_size() is used when the reg size is determined by
11182  * the BTF func_proto's return value size and argument.
11183  */
11184 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
11185 				   size_t reg_size)
11186 {
11187 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
11188 
11189 	if (regno == BPF_REG_0) {
11190 		/* Function return value */
11191 		reg->live |= REG_LIVE_WRITTEN;
11192 		reg->subreg_def = reg_size == sizeof(u64) ?
11193 			DEF_NOT_SUBREG : env->insn_idx + 1;
11194 	} else {
11195 		/* Function argument */
11196 		if (reg_size == sizeof(u64)) {
11197 			mark_insn_zext(env, reg);
11198 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
11199 		} else {
11200 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
11201 		}
11202 	}
11203 }
11204 
11205 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
11206 {
11207 	return meta->kfunc_flags & KF_ACQUIRE;
11208 }
11209 
11210 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
11211 {
11212 	return meta->kfunc_flags & KF_RELEASE;
11213 }
11214 
11215 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
11216 {
11217 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
11218 }
11219 
11220 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
11221 {
11222 	return meta->kfunc_flags & KF_SLEEPABLE;
11223 }
11224 
11225 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
11226 {
11227 	return meta->kfunc_flags & KF_DESTRUCTIVE;
11228 }
11229 
11230 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
11231 {
11232 	return meta->kfunc_flags & KF_RCU;
11233 }
11234 
11235 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
11236 {
11237 	return meta->kfunc_flags & KF_RCU_PROTECTED;
11238 }
11239 
11240 static bool is_kfunc_arg_mem_size(const struct btf *btf,
11241 				  const struct btf_param *arg,
11242 				  const struct bpf_reg_state *reg)
11243 {
11244 	const struct btf_type *t;
11245 
11246 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11247 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11248 		return false;
11249 
11250 	return btf_param_match_suffix(btf, arg, "__sz");
11251 }
11252 
11253 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
11254 					const struct btf_param *arg,
11255 					const struct bpf_reg_state *reg)
11256 {
11257 	const struct btf_type *t;
11258 
11259 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11260 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11261 		return false;
11262 
11263 	return btf_param_match_suffix(btf, arg, "__szk");
11264 }
11265 
11266 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
11267 {
11268 	return btf_param_match_suffix(btf, arg, "__opt");
11269 }
11270 
11271 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
11272 {
11273 	return btf_param_match_suffix(btf, arg, "__k");
11274 }
11275 
11276 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
11277 {
11278 	return btf_param_match_suffix(btf, arg, "__ign");
11279 }
11280 
11281 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
11282 {
11283 	return btf_param_match_suffix(btf, arg, "__map");
11284 }
11285 
11286 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
11287 {
11288 	return btf_param_match_suffix(btf, arg, "__alloc");
11289 }
11290 
11291 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
11292 {
11293 	return btf_param_match_suffix(btf, arg, "__uninit");
11294 }
11295 
11296 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
11297 {
11298 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
11299 }
11300 
11301 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
11302 {
11303 	return btf_param_match_suffix(btf, arg, "__nullable");
11304 }
11305 
11306 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
11307 {
11308 	return btf_param_match_suffix(btf, arg, "__str");
11309 }
11310 
11311 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
11312 					  const struct btf_param *arg,
11313 					  const char *name)
11314 {
11315 	int len, target_len = strlen(name);
11316 	const char *param_name;
11317 
11318 	param_name = btf_name_by_offset(btf, arg->name_off);
11319 	if (str_is_empty(param_name))
11320 		return false;
11321 	len = strlen(param_name);
11322 	if (len != target_len)
11323 		return false;
11324 	if (strcmp(param_name, name))
11325 		return false;
11326 
11327 	return true;
11328 }
11329 
11330 enum {
11331 	KF_ARG_DYNPTR_ID,
11332 	KF_ARG_LIST_HEAD_ID,
11333 	KF_ARG_LIST_NODE_ID,
11334 	KF_ARG_RB_ROOT_ID,
11335 	KF_ARG_RB_NODE_ID,
11336 	KF_ARG_WORKQUEUE_ID,
11337 };
11338 
11339 BTF_ID_LIST(kf_arg_btf_ids)
11340 BTF_ID(struct, bpf_dynptr)
11341 BTF_ID(struct, bpf_list_head)
11342 BTF_ID(struct, bpf_list_node)
11343 BTF_ID(struct, bpf_rb_root)
11344 BTF_ID(struct, bpf_rb_node)
11345 BTF_ID(struct, bpf_wq)
11346 
11347 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
11348 				    const struct btf_param *arg, int type)
11349 {
11350 	const struct btf_type *t;
11351 	u32 res_id;
11352 
11353 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11354 	if (!t)
11355 		return false;
11356 	if (!btf_type_is_ptr(t))
11357 		return false;
11358 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
11359 	if (!t)
11360 		return false;
11361 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
11362 }
11363 
11364 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
11365 {
11366 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
11367 }
11368 
11369 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
11370 {
11371 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
11372 }
11373 
11374 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
11375 {
11376 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
11377 }
11378 
11379 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
11380 {
11381 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
11382 }
11383 
11384 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
11385 {
11386 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
11387 }
11388 
11389 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
11390 {
11391 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
11392 }
11393 
11394 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
11395 				  const struct btf_param *arg)
11396 {
11397 	const struct btf_type *t;
11398 
11399 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
11400 	if (!t)
11401 		return false;
11402 
11403 	return true;
11404 }
11405 
11406 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
11407 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
11408 					const struct btf *btf,
11409 					const struct btf_type *t, int rec)
11410 {
11411 	const struct btf_type *member_type;
11412 	const struct btf_member *member;
11413 	u32 i;
11414 
11415 	if (!btf_type_is_struct(t))
11416 		return false;
11417 
11418 	for_each_member(i, t, member) {
11419 		const struct btf_array *array;
11420 
11421 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
11422 		if (btf_type_is_struct(member_type)) {
11423 			if (rec >= 3) {
11424 				verbose(env, "max struct nesting depth exceeded\n");
11425 				return false;
11426 			}
11427 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
11428 				return false;
11429 			continue;
11430 		}
11431 		if (btf_type_is_array(member_type)) {
11432 			array = btf_array(member_type);
11433 			if (!array->nelems)
11434 				return false;
11435 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
11436 			if (!btf_type_is_scalar(member_type))
11437 				return false;
11438 			continue;
11439 		}
11440 		if (!btf_type_is_scalar(member_type))
11441 			return false;
11442 	}
11443 	return true;
11444 }
11445 
11446 enum kfunc_ptr_arg_type {
11447 	KF_ARG_PTR_TO_CTX,
11448 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
11449 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
11450 	KF_ARG_PTR_TO_DYNPTR,
11451 	KF_ARG_PTR_TO_ITER,
11452 	KF_ARG_PTR_TO_LIST_HEAD,
11453 	KF_ARG_PTR_TO_LIST_NODE,
11454 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
11455 	KF_ARG_PTR_TO_MEM,
11456 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
11457 	KF_ARG_PTR_TO_CALLBACK,
11458 	KF_ARG_PTR_TO_RB_ROOT,
11459 	KF_ARG_PTR_TO_RB_NODE,
11460 	KF_ARG_PTR_TO_NULL,
11461 	KF_ARG_PTR_TO_CONST_STR,
11462 	KF_ARG_PTR_TO_MAP,
11463 	KF_ARG_PTR_TO_WORKQUEUE,
11464 };
11465 
11466 enum special_kfunc_type {
11467 	KF_bpf_obj_new_impl,
11468 	KF_bpf_obj_drop_impl,
11469 	KF_bpf_refcount_acquire_impl,
11470 	KF_bpf_list_push_front_impl,
11471 	KF_bpf_list_push_back_impl,
11472 	KF_bpf_list_pop_front,
11473 	KF_bpf_list_pop_back,
11474 	KF_bpf_cast_to_kern_ctx,
11475 	KF_bpf_rdonly_cast,
11476 	KF_bpf_rcu_read_lock,
11477 	KF_bpf_rcu_read_unlock,
11478 	KF_bpf_rbtree_remove,
11479 	KF_bpf_rbtree_add_impl,
11480 	KF_bpf_rbtree_first,
11481 	KF_bpf_dynptr_from_skb,
11482 	KF_bpf_dynptr_from_xdp,
11483 	KF_bpf_dynptr_slice,
11484 	KF_bpf_dynptr_slice_rdwr,
11485 	KF_bpf_dynptr_clone,
11486 	KF_bpf_percpu_obj_new_impl,
11487 	KF_bpf_percpu_obj_drop_impl,
11488 	KF_bpf_throw,
11489 	KF_bpf_wq_set_callback_impl,
11490 	KF_bpf_preempt_disable,
11491 	KF_bpf_preempt_enable,
11492 	KF_bpf_iter_css_task_new,
11493 	KF_bpf_session_cookie,
11494 	KF_bpf_get_kmem_cache,
11495 };
11496 
11497 BTF_SET_START(special_kfunc_set)
11498 BTF_ID(func, bpf_obj_new_impl)
11499 BTF_ID(func, bpf_obj_drop_impl)
11500 BTF_ID(func, bpf_refcount_acquire_impl)
11501 BTF_ID(func, bpf_list_push_front_impl)
11502 BTF_ID(func, bpf_list_push_back_impl)
11503 BTF_ID(func, bpf_list_pop_front)
11504 BTF_ID(func, bpf_list_pop_back)
11505 BTF_ID(func, bpf_cast_to_kern_ctx)
11506 BTF_ID(func, bpf_rdonly_cast)
11507 BTF_ID(func, bpf_rbtree_remove)
11508 BTF_ID(func, bpf_rbtree_add_impl)
11509 BTF_ID(func, bpf_rbtree_first)
11510 BTF_ID(func, bpf_dynptr_from_skb)
11511 BTF_ID(func, bpf_dynptr_from_xdp)
11512 BTF_ID(func, bpf_dynptr_slice)
11513 BTF_ID(func, bpf_dynptr_slice_rdwr)
11514 BTF_ID(func, bpf_dynptr_clone)
11515 BTF_ID(func, bpf_percpu_obj_new_impl)
11516 BTF_ID(func, bpf_percpu_obj_drop_impl)
11517 BTF_ID(func, bpf_throw)
11518 BTF_ID(func, bpf_wq_set_callback_impl)
11519 #ifdef CONFIG_CGROUPS
11520 BTF_ID(func, bpf_iter_css_task_new)
11521 #endif
11522 BTF_SET_END(special_kfunc_set)
11523 
11524 BTF_ID_LIST(special_kfunc_list)
11525 BTF_ID(func, bpf_obj_new_impl)
11526 BTF_ID(func, bpf_obj_drop_impl)
11527 BTF_ID(func, bpf_refcount_acquire_impl)
11528 BTF_ID(func, bpf_list_push_front_impl)
11529 BTF_ID(func, bpf_list_push_back_impl)
11530 BTF_ID(func, bpf_list_pop_front)
11531 BTF_ID(func, bpf_list_pop_back)
11532 BTF_ID(func, bpf_cast_to_kern_ctx)
11533 BTF_ID(func, bpf_rdonly_cast)
11534 BTF_ID(func, bpf_rcu_read_lock)
11535 BTF_ID(func, bpf_rcu_read_unlock)
11536 BTF_ID(func, bpf_rbtree_remove)
11537 BTF_ID(func, bpf_rbtree_add_impl)
11538 BTF_ID(func, bpf_rbtree_first)
11539 BTF_ID(func, bpf_dynptr_from_skb)
11540 BTF_ID(func, bpf_dynptr_from_xdp)
11541 BTF_ID(func, bpf_dynptr_slice)
11542 BTF_ID(func, bpf_dynptr_slice_rdwr)
11543 BTF_ID(func, bpf_dynptr_clone)
11544 BTF_ID(func, bpf_percpu_obj_new_impl)
11545 BTF_ID(func, bpf_percpu_obj_drop_impl)
11546 BTF_ID(func, bpf_throw)
11547 BTF_ID(func, bpf_wq_set_callback_impl)
11548 BTF_ID(func, bpf_preempt_disable)
11549 BTF_ID(func, bpf_preempt_enable)
11550 #ifdef CONFIG_CGROUPS
11551 BTF_ID(func, bpf_iter_css_task_new)
11552 #else
11553 BTF_ID_UNUSED
11554 #endif
11555 #ifdef CONFIG_BPF_EVENTS
11556 BTF_ID(func, bpf_session_cookie)
11557 #else
11558 BTF_ID_UNUSED
11559 #endif
11560 BTF_ID(func, bpf_get_kmem_cache)
11561 
11562 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
11563 {
11564 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
11565 	    meta->arg_owning_ref) {
11566 		return false;
11567 	}
11568 
11569 	return meta->kfunc_flags & KF_RET_NULL;
11570 }
11571 
11572 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
11573 {
11574 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
11575 }
11576 
11577 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
11578 {
11579 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
11580 }
11581 
11582 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
11583 {
11584 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
11585 }
11586 
11587 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
11588 {
11589 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
11590 }
11591 
11592 static enum kfunc_ptr_arg_type
11593 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
11594 		       struct bpf_kfunc_call_arg_meta *meta,
11595 		       const struct btf_type *t, const struct btf_type *ref_t,
11596 		       const char *ref_tname, const struct btf_param *args,
11597 		       int argno, int nargs)
11598 {
11599 	u32 regno = argno + 1;
11600 	struct bpf_reg_state *regs = cur_regs(env);
11601 	struct bpf_reg_state *reg = &regs[regno];
11602 	bool arg_mem_size = false;
11603 
11604 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
11605 		return KF_ARG_PTR_TO_CTX;
11606 
11607 	/* In this function, we verify the kfunc's BTF as per the argument type,
11608 	 * leaving the rest of the verification with respect to the register
11609 	 * type to our caller. When a set of conditions hold in the BTF type of
11610 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
11611 	 */
11612 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
11613 		return KF_ARG_PTR_TO_CTX;
11614 
11615 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
11616 		return KF_ARG_PTR_TO_NULL;
11617 
11618 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
11619 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
11620 
11621 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
11622 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
11623 
11624 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
11625 		return KF_ARG_PTR_TO_DYNPTR;
11626 
11627 	if (is_kfunc_arg_iter(meta, argno, &args[argno]))
11628 		return KF_ARG_PTR_TO_ITER;
11629 
11630 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
11631 		return KF_ARG_PTR_TO_LIST_HEAD;
11632 
11633 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
11634 		return KF_ARG_PTR_TO_LIST_NODE;
11635 
11636 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
11637 		return KF_ARG_PTR_TO_RB_ROOT;
11638 
11639 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
11640 		return KF_ARG_PTR_TO_RB_NODE;
11641 
11642 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
11643 		return KF_ARG_PTR_TO_CONST_STR;
11644 
11645 	if (is_kfunc_arg_map(meta->btf, &args[argno]))
11646 		return KF_ARG_PTR_TO_MAP;
11647 
11648 	if (is_kfunc_arg_wq(meta->btf, &args[argno]))
11649 		return KF_ARG_PTR_TO_WORKQUEUE;
11650 
11651 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11652 		if (!btf_type_is_struct(ref_t)) {
11653 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
11654 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
11655 			return -EINVAL;
11656 		}
11657 		return KF_ARG_PTR_TO_BTF_ID;
11658 	}
11659 
11660 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
11661 		return KF_ARG_PTR_TO_CALLBACK;
11662 
11663 	if (argno + 1 < nargs &&
11664 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
11665 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
11666 		arg_mem_size = true;
11667 
11668 	/* This is the catch all argument type of register types supported by
11669 	 * check_helper_mem_access. However, we only allow when argument type is
11670 	 * pointer to scalar, or struct composed (recursively) of scalars. When
11671 	 * arg_mem_size is true, the pointer can be void *.
11672 	 */
11673 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11674 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11675 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
11676 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11677 		return -EINVAL;
11678 	}
11679 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11680 }
11681 
11682 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11683 					struct bpf_reg_state *reg,
11684 					const struct btf_type *ref_t,
11685 					const char *ref_tname, u32 ref_id,
11686 					struct bpf_kfunc_call_arg_meta *meta,
11687 					int argno)
11688 {
11689 	const struct btf_type *reg_ref_t;
11690 	bool strict_type_match = false;
11691 	const struct btf *reg_btf;
11692 	const char *reg_ref_tname;
11693 	bool taking_projection;
11694 	bool struct_same;
11695 	u32 reg_ref_id;
11696 
11697 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
11698 		reg_btf = reg->btf;
11699 		reg_ref_id = reg->btf_id;
11700 	} else {
11701 		reg_btf = btf_vmlinux;
11702 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11703 	}
11704 
11705 	/* Enforce strict type matching for calls to kfuncs that are acquiring
11706 	 * or releasing a reference, or are no-cast aliases. We do _not_
11707 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
11708 	 * as we want to enable BPF programs to pass types that are bitwise
11709 	 * equivalent without forcing them to explicitly cast with something
11710 	 * like bpf_cast_to_kern_ctx().
11711 	 *
11712 	 * For example, say we had a type like the following:
11713 	 *
11714 	 * struct bpf_cpumask {
11715 	 *	cpumask_t cpumask;
11716 	 *	refcount_t usage;
11717 	 * };
11718 	 *
11719 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11720 	 * to a struct cpumask, so it would be safe to pass a struct
11721 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11722 	 *
11723 	 * The philosophy here is similar to how we allow scalars of different
11724 	 * types to be passed to kfuncs as long as the size is the same. The
11725 	 * only difference here is that we're simply allowing
11726 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
11727 	 * resolve types.
11728 	 */
11729 	if ((is_kfunc_release(meta) && reg->ref_obj_id) ||
11730 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11731 		strict_type_match = true;
11732 
11733 	WARN_ON_ONCE(is_kfunc_release(meta) &&
11734 		     (reg->off || !tnum_is_const(reg->var_off) ||
11735 		      reg->var_off.value));
11736 
11737 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
11738 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11739 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
11740 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
11741 	 * actually use it -- it must cast to the underlying type. So we allow
11742 	 * caller to pass in the underlying type.
11743 	 */
11744 	taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
11745 	if (!taking_projection && !struct_same) {
11746 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
11747 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
11748 			btf_type_str(reg_ref_t), reg_ref_tname);
11749 		return -EINVAL;
11750 	}
11751 	return 0;
11752 }
11753 
11754 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11755 {
11756 	struct btf_record *rec = reg_btf_record(reg);
11757 
11758 	if (!cur_func(env)->active_locks) {
11759 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
11760 		return -EFAULT;
11761 	}
11762 
11763 	if (type_flag(reg->type) & NON_OWN_REF) {
11764 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
11765 		return -EFAULT;
11766 	}
11767 
11768 	reg->type |= NON_OWN_REF;
11769 	if (rec->refcount_off >= 0)
11770 		reg->type |= MEM_RCU;
11771 
11772 	return 0;
11773 }
11774 
11775 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
11776 {
11777 	struct bpf_func_state *state, *unused;
11778 	struct bpf_reg_state *reg;
11779 	int i;
11780 
11781 	state = cur_func(env);
11782 
11783 	if (!ref_obj_id) {
11784 		verbose(env, "verifier internal error: ref_obj_id is zero for "
11785 			     "owning -> non-owning conversion\n");
11786 		return -EFAULT;
11787 	}
11788 
11789 	for (i = 0; i < state->acquired_refs; i++) {
11790 		if (state->refs[i].id != ref_obj_id)
11791 			continue;
11792 
11793 		/* Clear ref_obj_id here so release_reference doesn't clobber
11794 		 * the whole reg
11795 		 */
11796 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11797 			if (reg->ref_obj_id == ref_obj_id) {
11798 				reg->ref_obj_id = 0;
11799 				ref_set_non_owning(env, reg);
11800 			}
11801 		}));
11802 		return 0;
11803 	}
11804 
11805 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
11806 	return -EFAULT;
11807 }
11808 
11809 /* Implementation details:
11810  *
11811  * Each register points to some region of memory, which we define as an
11812  * allocation. Each allocation may embed a bpf_spin_lock which protects any
11813  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11814  * allocation. The lock and the data it protects are colocated in the same
11815  * memory region.
11816  *
11817  * Hence, everytime a register holds a pointer value pointing to such
11818  * allocation, the verifier preserves a unique reg->id for it.
11819  *
11820  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11821  * bpf_spin_lock is called.
11822  *
11823  * To enable this, lock state in the verifier captures two values:
11824  *	active_lock.ptr = Register's type specific pointer
11825  *	active_lock.id  = A unique ID for each register pointer value
11826  *
11827  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11828  * supported register types.
11829  *
11830  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11831  * allocated objects is the reg->btf pointer.
11832  *
11833  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11834  * can establish the provenance of the map value statically for each distinct
11835  * lookup into such maps. They always contain a single map value hence unique
11836  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11837  *
11838  * So, in case of global variables, they use array maps with max_entries = 1,
11839  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11840  * into the same map value as max_entries is 1, as described above).
11841  *
11842  * In case of inner map lookups, the inner map pointer has same map_ptr as the
11843  * outer map pointer (in verifier context), but each lookup into an inner map
11844  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11845  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11846  * will get different reg->id assigned to each lookup, hence different
11847  * active_lock.id.
11848  *
11849  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11850  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11851  * returned from bpf_obj_new. Each allocation receives a new reg->id.
11852  */
11853 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11854 {
11855 	struct bpf_reference_state *s;
11856 	void *ptr;
11857 	u32 id;
11858 
11859 	switch ((int)reg->type) {
11860 	case PTR_TO_MAP_VALUE:
11861 		ptr = reg->map_ptr;
11862 		break;
11863 	case PTR_TO_BTF_ID | MEM_ALLOC:
11864 		ptr = reg->btf;
11865 		break;
11866 	default:
11867 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11868 		return -EFAULT;
11869 	}
11870 	id = reg->id;
11871 
11872 	if (!cur_func(env)->active_locks)
11873 		return -EINVAL;
11874 	s = find_lock_state(env, REF_TYPE_LOCK, id, ptr);
11875 	if (!s) {
11876 		verbose(env, "held lock and object are not in the same allocation\n");
11877 		return -EINVAL;
11878 	}
11879 	return 0;
11880 }
11881 
11882 static bool is_bpf_list_api_kfunc(u32 btf_id)
11883 {
11884 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11885 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11886 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11887 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11888 }
11889 
11890 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11891 {
11892 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11893 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11894 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11895 }
11896 
11897 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11898 {
11899 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11900 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11901 }
11902 
11903 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11904 {
11905 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11906 }
11907 
11908 static bool is_async_callback_calling_kfunc(u32 btf_id)
11909 {
11910 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
11911 }
11912 
11913 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
11914 {
11915 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11916 	       insn->imm == special_kfunc_list[KF_bpf_throw];
11917 }
11918 
11919 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
11920 {
11921 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
11922 }
11923 
11924 static bool is_callback_calling_kfunc(u32 btf_id)
11925 {
11926 	return is_sync_callback_calling_kfunc(btf_id) ||
11927 	       is_async_callback_calling_kfunc(btf_id);
11928 }
11929 
11930 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11931 {
11932 	return is_bpf_rbtree_api_kfunc(btf_id);
11933 }
11934 
11935 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11936 					  enum btf_field_type head_field_type,
11937 					  u32 kfunc_btf_id)
11938 {
11939 	bool ret;
11940 
11941 	switch (head_field_type) {
11942 	case BPF_LIST_HEAD:
11943 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11944 		break;
11945 	case BPF_RB_ROOT:
11946 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11947 		break;
11948 	default:
11949 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11950 			btf_field_type_name(head_field_type));
11951 		return false;
11952 	}
11953 
11954 	if (!ret)
11955 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11956 			btf_field_type_name(head_field_type));
11957 	return ret;
11958 }
11959 
11960 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11961 					  enum btf_field_type node_field_type,
11962 					  u32 kfunc_btf_id)
11963 {
11964 	bool ret;
11965 
11966 	switch (node_field_type) {
11967 	case BPF_LIST_NODE:
11968 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11969 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11970 		break;
11971 	case BPF_RB_NODE:
11972 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11973 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11974 		break;
11975 	default:
11976 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11977 			btf_field_type_name(node_field_type));
11978 		return false;
11979 	}
11980 
11981 	if (!ret)
11982 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11983 			btf_field_type_name(node_field_type));
11984 	return ret;
11985 }
11986 
11987 static int
11988 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11989 				   struct bpf_reg_state *reg, u32 regno,
11990 				   struct bpf_kfunc_call_arg_meta *meta,
11991 				   enum btf_field_type head_field_type,
11992 				   struct btf_field **head_field)
11993 {
11994 	const char *head_type_name;
11995 	struct btf_field *field;
11996 	struct btf_record *rec;
11997 	u32 head_off;
11998 
11999 	if (meta->btf != btf_vmlinux) {
12000 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
12001 		return -EFAULT;
12002 	}
12003 
12004 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
12005 		return -EFAULT;
12006 
12007 	head_type_name = btf_field_type_name(head_field_type);
12008 	if (!tnum_is_const(reg->var_off)) {
12009 		verbose(env,
12010 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
12011 			regno, head_type_name);
12012 		return -EINVAL;
12013 	}
12014 
12015 	rec = reg_btf_record(reg);
12016 	head_off = reg->off + reg->var_off.value;
12017 	field = btf_record_find(rec, head_off, head_field_type);
12018 	if (!field) {
12019 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
12020 		return -EINVAL;
12021 	}
12022 
12023 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
12024 	if (check_reg_allocation_locked(env, reg)) {
12025 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
12026 			rec->spin_lock_off, head_type_name);
12027 		return -EINVAL;
12028 	}
12029 
12030 	if (*head_field) {
12031 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
12032 		return -EFAULT;
12033 	}
12034 	*head_field = field;
12035 	return 0;
12036 }
12037 
12038 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
12039 					   struct bpf_reg_state *reg, u32 regno,
12040 					   struct bpf_kfunc_call_arg_meta *meta)
12041 {
12042 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
12043 							  &meta->arg_list_head.field);
12044 }
12045 
12046 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
12047 					     struct bpf_reg_state *reg, u32 regno,
12048 					     struct bpf_kfunc_call_arg_meta *meta)
12049 {
12050 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
12051 							  &meta->arg_rbtree_root.field);
12052 }
12053 
12054 static int
12055 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
12056 				   struct bpf_reg_state *reg, u32 regno,
12057 				   struct bpf_kfunc_call_arg_meta *meta,
12058 				   enum btf_field_type head_field_type,
12059 				   enum btf_field_type node_field_type,
12060 				   struct btf_field **node_field)
12061 {
12062 	const char *node_type_name;
12063 	const struct btf_type *et, *t;
12064 	struct btf_field *field;
12065 	u32 node_off;
12066 
12067 	if (meta->btf != btf_vmlinux) {
12068 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
12069 		return -EFAULT;
12070 	}
12071 
12072 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
12073 		return -EFAULT;
12074 
12075 	node_type_name = btf_field_type_name(node_field_type);
12076 	if (!tnum_is_const(reg->var_off)) {
12077 		verbose(env,
12078 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
12079 			regno, node_type_name);
12080 		return -EINVAL;
12081 	}
12082 
12083 	node_off = reg->off + reg->var_off.value;
12084 	field = reg_find_field_offset(reg, node_off, node_field_type);
12085 	if (!field) {
12086 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
12087 		return -EINVAL;
12088 	}
12089 
12090 	field = *node_field;
12091 
12092 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
12093 	t = btf_type_by_id(reg->btf, reg->btf_id);
12094 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
12095 				  field->graph_root.value_btf_id, true)) {
12096 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
12097 			"in struct %s, but arg is at offset=%d in struct %s\n",
12098 			btf_field_type_name(head_field_type),
12099 			btf_field_type_name(node_field_type),
12100 			field->graph_root.node_offset,
12101 			btf_name_by_offset(field->graph_root.btf, et->name_off),
12102 			node_off, btf_name_by_offset(reg->btf, t->name_off));
12103 		return -EINVAL;
12104 	}
12105 	meta->arg_btf = reg->btf;
12106 	meta->arg_btf_id = reg->btf_id;
12107 
12108 	if (node_off != field->graph_root.node_offset) {
12109 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
12110 			node_off, btf_field_type_name(node_field_type),
12111 			field->graph_root.node_offset,
12112 			btf_name_by_offset(field->graph_root.btf, et->name_off));
12113 		return -EINVAL;
12114 	}
12115 
12116 	return 0;
12117 }
12118 
12119 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
12120 					   struct bpf_reg_state *reg, u32 regno,
12121 					   struct bpf_kfunc_call_arg_meta *meta)
12122 {
12123 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
12124 						  BPF_LIST_HEAD, BPF_LIST_NODE,
12125 						  &meta->arg_list_head.field);
12126 }
12127 
12128 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
12129 					     struct bpf_reg_state *reg, u32 regno,
12130 					     struct bpf_kfunc_call_arg_meta *meta)
12131 {
12132 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
12133 						  BPF_RB_ROOT, BPF_RB_NODE,
12134 						  &meta->arg_rbtree_root.field);
12135 }
12136 
12137 /*
12138  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
12139  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
12140  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
12141  * them can only be attached to some specific hook points.
12142  */
12143 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
12144 {
12145 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12146 
12147 	switch (prog_type) {
12148 	case BPF_PROG_TYPE_LSM:
12149 		return true;
12150 	case BPF_PROG_TYPE_TRACING:
12151 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
12152 			return true;
12153 		fallthrough;
12154 	default:
12155 		return in_sleepable(env);
12156 	}
12157 }
12158 
12159 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
12160 			    int insn_idx)
12161 {
12162 	const char *func_name = meta->func_name, *ref_tname;
12163 	const struct btf *btf = meta->btf;
12164 	const struct btf_param *args;
12165 	struct btf_record *rec;
12166 	u32 i, nargs;
12167 	int ret;
12168 
12169 	args = (const struct btf_param *)(meta->func_proto + 1);
12170 	nargs = btf_type_vlen(meta->func_proto);
12171 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
12172 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
12173 			MAX_BPF_FUNC_REG_ARGS);
12174 		return -EINVAL;
12175 	}
12176 
12177 	/* Check that BTF function arguments match actual types that the
12178 	 * verifier sees.
12179 	 */
12180 	for (i = 0; i < nargs; i++) {
12181 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
12182 		const struct btf_type *t, *ref_t, *resolve_ret;
12183 		enum bpf_arg_type arg_type = ARG_DONTCARE;
12184 		u32 regno = i + 1, ref_id, type_size;
12185 		bool is_ret_buf_sz = false;
12186 		bool mask = false;
12187 		int kf_arg_type;
12188 
12189 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
12190 
12191 		if (is_kfunc_arg_ignore(btf, &args[i]))
12192 			continue;
12193 
12194 		if (btf_type_is_scalar(t)) {
12195 			if (reg->type != SCALAR_VALUE) {
12196 				verbose(env, "R%d is not a scalar\n", regno);
12197 				return -EINVAL;
12198 			}
12199 
12200 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
12201 				if (meta->arg_constant.found) {
12202 					verbose(env, "verifier internal error: only one constant argument permitted\n");
12203 					return -EFAULT;
12204 				}
12205 				if (!tnum_is_const(reg->var_off)) {
12206 					verbose(env, "R%d must be a known constant\n", regno);
12207 					return -EINVAL;
12208 				}
12209 				ret = mark_chain_precision(env, regno);
12210 				if (ret < 0)
12211 					return ret;
12212 				meta->arg_constant.found = true;
12213 				meta->arg_constant.value = reg->var_off.value;
12214 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
12215 				meta->r0_rdonly = true;
12216 				is_ret_buf_sz = true;
12217 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
12218 				is_ret_buf_sz = true;
12219 			}
12220 
12221 			if (is_ret_buf_sz) {
12222 				if (meta->r0_size) {
12223 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
12224 					return -EINVAL;
12225 				}
12226 
12227 				if (!tnum_is_const(reg->var_off)) {
12228 					verbose(env, "R%d is not a const\n", regno);
12229 					return -EINVAL;
12230 				}
12231 
12232 				meta->r0_size = reg->var_off.value;
12233 				ret = mark_chain_precision(env, regno);
12234 				if (ret)
12235 					return ret;
12236 			}
12237 			continue;
12238 		}
12239 
12240 		if (!btf_type_is_ptr(t)) {
12241 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
12242 			return -EINVAL;
12243 		}
12244 
12245 		mask = mask_raw_tp_reg(env, reg);
12246 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
12247 		    (register_is_null(reg) || type_may_be_null(reg->type)) &&
12248 			!is_kfunc_arg_nullable(meta->btf, &args[i])) {
12249 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
12250 			unmask_raw_tp_reg(reg, mask);
12251 			return -EACCES;
12252 		}
12253 		unmask_raw_tp_reg(reg, mask);
12254 
12255 		if (reg->ref_obj_id) {
12256 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
12257 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
12258 					regno, reg->ref_obj_id,
12259 					meta->ref_obj_id);
12260 				return -EFAULT;
12261 			}
12262 			meta->ref_obj_id = reg->ref_obj_id;
12263 			if (is_kfunc_release(meta))
12264 				meta->release_regno = regno;
12265 		}
12266 
12267 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
12268 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12269 
12270 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
12271 		if (kf_arg_type < 0)
12272 			return kf_arg_type;
12273 
12274 		switch (kf_arg_type) {
12275 		case KF_ARG_PTR_TO_NULL:
12276 			continue;
12277 		case KF_ARG_PTR_TO_MAP:
12278 			if (!reg->map_ptr) {
12279 				verbose(env, "pointer in R%d isn't map pointer\n", regno);
12280 				return -EINVAL;
12281 			}
12282 			if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) {
12283 				/* Use map_uid (which is unique id of inner map) to reject:
12284 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
12285 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
12286 				 * if (inner_map1 && inner_map2) {
12287 				 *     wq = bpf_map_lookup_elem(inner_map1);
12288 				 *     if (wq)
12289 				 *         // mismatch would have been allowed
12290 				 *         bpf_wq_init(wq, inner_map2);
12291 				 * }
12292 				 *
12293 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
12294 				 */
12295 				if (meta->map.ptr != reg->map_ptr ||
12296 				    meta->map.uid != reg->map_uid) {
12297 					verbose(env,
12298 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
12299 						meta->map.uid, reg->map_uid);
12300 					return -EINVAL;
12301 				}
12302 			}
12303 			meta->map.ptr = reg->map_ptr;
12304 			meta->map.uid = reg->map_uid;
12305 			fallthrough;
12306 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
12307 		case KF_ARG_PTR_TO_BTF_ID:
12308 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
12309 				break;
12310 
12311 			/* Allow passing maybe NULL raw_tp arguments to
12312 			 * kfuncs for compatibility. Don't apply this to
12313 			 * arguments with ref_obj_id > 0.
12314 			 */
12315 			mask = mask_raw_tp_reg(env, reg);
12316 			if (!is_trusted_reg(reg)) {
12317 				if (!is_kfunc_rcu(meta)) {
12318 					verbose(env, "R%d must be referenced or trusted\n", regno);
12319 					unmask_raw_tp_reg(reg, mask);
12320 					return -EINVAL;
12321 				}
12322 				if (!is_rcu_reg(reg)) {
12323 					verbose(env, "R%d must be a rcu pointer\n", regno);
12324 					unmask_raw_tp_reg(reg, mask);
12325 					return -EINVAL;
12326 				}
12327 			}
12328 			unmask_raw_tp_reg(reg, mask);
12329 			fallthrough;
12330 		case KF_ARG_PTR_TO_CTX:
12331 		case KF_ARG_PTR_TO_DYNPTR:
12332 		case KF_ARG_PTR_TO_ITER:
12333 		case KF_ARG_PTR_TO_LIST_HEAD:
12334 		case KF_ARG_PTR_TO_LIST_NODE:
12335 		case KF_ARG_PTR_TO_RB_ROOT:
12336 		case KF_ARG_PTR_TO_RB_NODE:
12337 		case KF_ARG_PTR_TO_MEM:
12338 		case KF_ARG_PTR_TO_MEM_SIZE:
12339 		case KF_ARG_PTR_TO_CALLBACK:
12340 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12341 		case KF_ARG_PTR_TO_CONST_STR:
12342 		case KF_ARG_PTR_TO_WORKQUEUE:
12343 			break;
12344 		default:
12345 			WARN_ON_ONCE(1);
12346 			return -EFAULT;
12347 		}
12348 
12349 		if (is_kfunc_release(meta) && reg->ref_obj_id)
12350 			arg_type |= OBJ_RELEASE;
12351 		mask = mask_raw_tp_reg(env, reg);
12352 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
12353 		unmask_raw_tp_reg(reg, mask);
12354 		if (ret < 0)
12355 			return ret;
12356 
12357 		switch (kf_arg_type) {
12358 		case KF_ARG_PTR_TO_CTX:
12359 			if (reg->type != PTR_TO_CTX) {
12360 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n",
12361 					i, reg_type_str(env, reg->type));
12362 				return -EINVAL;
12363 			}
12364 
12365 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12366 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
12367 				if (ret < 0)
12368 					return -EINVAL;
12369 				meta->ret_btf_id  = ret;
12370 			}
12371 			break;
12372 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
12373 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
12374 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
12375 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
12376 					return -EINVAL;
12377 				}
12378 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
12379 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12380 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
12381 					return -EINVAL;
12382 				}
12383 			} else {
12384 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
12385 				return -EINVAL;
12386 			}
12387 			if (!reg->ref_obj_id) {
12388 				verbose(env, "allocated object must be referenced\n");
12389 				return -EINVAL;
12390 			}
12391 			if (meta->btf == btf_vmlinux) {
12392 				meta->arg_btf = reg->btf;
12393 				meta->arg_btf_id = reg->btf_id;
12394 			}
12395 			break;
12396 		case KF_ARG_PTR_TO_DYNPTR:
12397 		{
12398 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
12399 			int clone_ref_obj_id = 0;
12400 
12401 			if (reg->type == CONST_PTR_TO_DYNPTR)
12402 				dynptr_arg_type |= MEM_RDONLY;
12403 
12404 			if (is_kfunc_arg_uninit(btf, &args[i]))
12405 				dynptr_arg_type |= MEM_UNINIT;
12406 
12407 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
12408 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
12409 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
12410 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
12411 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
12412 				   (dynptr_arg_type & MEM_UNINIT)) {
12413 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
12414 
12415 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
12416 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
12417 					return -EFAULT;
12418 				}
12419 
12420 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
12421 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
12422 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
12423 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
12424 					return -EFAULT;
12425 				}
12426 			}
12427 
12428 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
12429 			if (ret < 0)
12430 				return ret;
12431 
12432 			if (!(dynptr_arg_type & MEM_UNINIT)) {
12433 				int id = dynptr_id(env, reg);
12434 
12435 				if (id < 0) {
12436 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
12437 					return id;
12438 				}
12439 				meta->initialized_dynptr.id = id;
12440 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
12441 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
12442 			}
12443 
12444 			break;
12445 		}
12446 		case KF_ARG_PTR_TO_ITER:
12447 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
12448 				if (!check_css_task_iter_allowlist(env)) {
12449 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
12450 					return -EINVAL;
12451 				}
12452 			}
12453 			ret = process_iter_arg(env, regno, insn_idx, meta);
12454 			if (ret < 0)
12455 				return ret;
12456 			break;
12457 		case KF_ARG_PTR_TO_LIST_HEAD:
12458 			if (reg->type != PTR_TO_MAP_VALUE &&
12459 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12460 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
12461 				return -EINVAL;
12462 			}
12463 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
12464 				verbose(env, "allocated object must be referenced\n");
12465 				return -EINVAL;
12466 			}
12467 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
12468 			if (ret < 0)
12469 				return ret;
12470 			break;
12471 		case KF_ARG_PTR_TO_RB_ROOT:
12472 			if (reg->type != PTR_TO_MAP_VALUE &&
12473 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12474 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
12475 				return -EINVAL;
12476 			}
12477 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
12478 				verbose(env, "allocated object must be referenced\n");
12479 				return -EINVAL;
12480 			}
12481 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
12482 			if (ret < 0)
12483 				return ret;
12484 			break;
12485 		case KF_ARG_PTR_TO_LIST_NODE:
12486 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12487 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
12488 				return -EINVAL;
12489 			}
12490 			if (!reg->ref_obj_id) {
12491 				verbose(env, "allocated object must be referenced\n");
12492 				return -EINVAL;
12493 			}
12494 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
12495 			if (ret < 0)
12496 				return ret;
12497 			break;
12498 		case KF_ARG_PTR_TO_RB_NODE:
12499 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
12500 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
12501 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
12502 					return -EINVAL;
12503 				}
12504 				if (in_rbtree_lock_required_cb(env)) {
12505 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
12506 					return -EINVAL;
12507 				}
12508 			} else {
12509 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12510 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
12511 					return -EINVAL;
12512 				}
12513 				if (!reg->ref_obj_id) {
12514 					verbose(env, "allocated object must be referenced\n");
12515 					return -EINVAL;
12516 				}
12517 			}
12518 
12519 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
12520 			if (ret < 0)
12521 				return ret;
12522 			break;
12523 		case KF_ARG_PTR_TO_MAP:
12524 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
12525 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
12526 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
12527 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12528 			fallthrough;
12529 		case KF_ARG_PTR_TO_BTF_ID:
12530 			mask = mask_raw_tp_reg(env, reg);
12531 			/* Only base_type is checked, further checks are done here */
12532 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
12533 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
12534 			    !reg2btf_ids[base_type(reg->type)]) {
12535 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
12536 				verbose(env, "expected %s or socket\n",
12537 					reg_type_str(env, base_type(reg->type) |
12538 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
12539 				unmask_raw_tp_reg(reg, mask);
12540 				return -EINVAL;
12541 			}
12542 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
12543 			unmask_raw_tp_reg(reg, mask);
12544 			if (ret < 0)
12545 				return ret;
12546 			break;
12547 		case KF_ARG_PTR_TO_MEM:
12548 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
12549 			if (IS_ERR(resolve_ret)) {
12550 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
12551 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
12552 				return -EINVAL;
12553 			}
12554 			ret = check_mem_reg(env, reg, regno, type_size);
12555 			if (ret < 0)
12556 				return ret;
12557 			break;
12558 		case KF_ARG_PTR_TO_MEM_SIZE:
12559 		{
12560 			struct bpf_reg_state *buff_reg = &regs[regno];
12561 			const struct btf_param *buff_arg = &args[i];
12562 			struct bpf_reg_state *size_reg = &regs[regno + 1];
12563 			const struct btf_param *size_arg = &args[i + 1];
12564 
12565 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
12566 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
12567 				if (ret < 0) {
12568 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
12569 					return ret;
12570 				}
12571 			}
12572 
12573 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
12574 				if (meta->arg_constant.found) {
12575 					verbose(env, "verifier internal error: only one constant argument permitted\n");
12576 					return -EFAULT;
12577 				}
12578 				if (!tnum_is_const(size_reg->var_off)) {
12579 					verbose(env, "R%d must be a known constant\n", regno + 1);
12580 					return -EINVAL;
12581 				}
12582 				meta->arg_constant.found = true;
12583 				meta->arg_constant.value = size_reg->var_off.value;
12584 			}
12585 
12586 			/* Skip next '__sz' or '__szk' argument */
12587 			i++;
12588 			break;
12589 		}
12590 		case KF_ARG_PTR_TO_CALLBACK:
12591 			if (reg->type != PTR_TO_FUNC) {
12592 				verbose(env, "arg%d expected pointer to func\n", i);
12593 				return -EINVAL;
12594 			}
12595 			meta->subprogno = reg->subprogno;
12596 			break;
12597 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12598 			if (!type_is_ptr_alloc_obj(reg->type)) {
12599 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
12600 				return -EINVAL;
12601 			}
12602 			if (!type_is_non_owning_ref(reg->type))
12603 				meta->arg_owning_ref = true;
12604 
12605 			rec = reg_btf_record(reg);
12606 			if (!rec) {
12607 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
12608 				return -EFAULT;
12609 			}
12610 
12611 			if (rec->refcount_off < 0) {
12612 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
12613 				return -EINVAL;
12614 			}
12615 
12616 			meta->arg_btf = reg->btf;
12617 			meta->arg_btf_id = reg->btf_id;
12618 			break;
12619 		case KF_ARG_PTR_TO_CONST_STR:
12620 			if (reg->type != PTR_TO_MAP_VALUE) {
12621 				verbose(env, "arg#%d doesn't point to a const string\n", i);
12622 				return -EINVAL;
12623 			}
12624 			ret = check_reg_const_str(env, reg, regno);
12625 			if (ret)
12626 				return ret;
12627 			break;
12628 		case KF_ARG_PTR_TO_WORKQUEUE:
12629 			if (reg->type != PTR_TO_MAP_VALUE) {
12630 				verbose(env, "arg#%d doesn't point to a map value\n", i);
12631 				return -EINVAL;
12632 			}
12633 			ret = process_wq_func(env, regno, meta);
12634 			if (ret < 0)
12635 				return ret;
12636 			break;
12637 		}
12638 	}
12639 
12640 	if (is_kfunc_release(meta) && !meta->release_regno) {
12641 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
12642 			func_name);
12643 		return -EINVAL;
12644 	}
12645 
12646 	return 0;
12647 }
12648 
12649 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
12650 			    struct bpf_insn *insn,
12651 			    struct bpf_kfunc_call_arg_meta *meta,
12652 			    const char **kfunc_name)
12653 {
12654 	const struct btf_type *func, *func_proto;
12655 	u32 func_id, *kfunc_flags;
12656 	const char *func_name;
12657 	struct btf *desc_btf;
12658 
12659 	if (kfunc_name)
12660 		*kfunc_name = NULL;
12661 
12662 	if (!insn->imm)
12663 		return -EINVAL;
12664 
12665 	desc_btf = find_kfunc_desc_btf(env, insn->off);
12666 	if (IS_ERR(desc_btf))
12667 		return PTR_ERR(desc_btf);
12668 
12669 	func_id = insn->imm;
12670 	func = btf_type_by_id(desc_btf, func_id);
12671 	func_name = btf_name_by_offset(desc_btf, func->name_off);
12672 	if (kfunc_name)
12673 		*kfunc_name = func_name;
12674 	func_proto = btf_type_by_id(desc_btf, func->type);
12675 
12676 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
12677 	if (!kfunc_flags) {
12678 		return -EACCES;
12679 	}
12680 
12681 	memset(meta, 0, sizeof(*meta));
12682 	meta->btf = desc_btf;
12683 	meta->func_id = func_id;
12684 	meta->kfunc_flags = *kfunc_flags;
12685 	meta->func_proto = func_proto;
12686 	meta->func_name = func_name;
12687 
12688 	return 0;
12689 }
12690 
12691 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
12692 
12693 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12694 			    int *insn_idx_p)
12695 {
12696 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
12697 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
12698 	struct bpf_reg_state *regs = cur_regs(env);
12699 	const char *func_name, *ptr_type_name;
12700 	const struct btf_type *t, *ptr_type;
12701 	struct bpf_kfunc_call_arg_meta meta;
12702 	struct bpf_insn_aux_data *insn_aux;
12703 	int err, insn_idx = *insn_idx_p;
12704 	const struct btf_param *args;
12705 	const struct btf_type *ret_t;
12706 	struct btf *desc_btf;
12707 
12708 	/* skip for now, but return error when we find this in fixup_kfunc_call */
12709 	if (!insn->imm)
12710 		return 0;
12711 
12712 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
12713 	if (err == -EACCES && func_name)
12714 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
12715 	if (err)
12716 		return err;
12717 	desc_btf = meta.btf;
12718 	insn_aux = &env->insn_aux_data[insn_idx];
12719 
12720 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
12721 
12722 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
12723 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
12724 		return -EACCES;
12725 	}
12726 
12727 	sleepable = is_kfunc_sleepable(&meta);
12728 	if (sleepable && !in_sleepable(env)) {
12729 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
12730 		return -EACCES;
12731 	}
12732 
12733 	/* Check the arguments */
12734 	err = check_kfunc_args(env, &meta, insn_idx);
12735 	if (err < 0)
12736 		return err;
12737 
12738 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12739 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12740 					 set_rbtree_add_callback_state);
12741 		if (err) {
12742 			verbose(env, "kfunc %s#%d failed callback verification\n",
12743 				func_name, meta.func_id);
12744 			return err;
12745 		}
12746 	}
12747 
12748 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
12749 		meta.r0_size = sizeof(u64);
12750 		meta.r0_rdonly = false;
12751 	}
12752 
12753 	if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
12754 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12755 					 set_timer_callback_state);
12756 		if (err) {
12757 			verbose(env, "kfunc %s#%d failed callback verification\n",
12758 				func_name, meta.func_id);
12759 			return err;
12760 		}
12761 	}
12762 
12763 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
12764 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
12765 
12766 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
12767 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
12768 
12769 	if (env->cur_state->active_rcu_lock) {
12770 		struct bpf_func_state *state;
12771 		struct bpf_reg_state *reg;
12772 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
12773 
12774 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
12775 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
12776 			return -EACCES;
12777 		}
12778 
12779 		if (rcu_lock) {
12780 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
12781 			return -EINVAL;
12782 		} else if (rcu_unlock) {
12783 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
12784 				if (reg->type & MEM_RCU) {
12785 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
12786 					reg->type |= PTR_UNTRUSTED;
12787 				}
12788 			}));
12789 			env->cur_state->active_rcu_lock = false;
12790 		} else if (sleepable) {
12791 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
12792 			return -EACCES;
12793 		}
12794 	} else if (rcu_lock) {
12795 		env->cur_state->active_rcu_lock = true;
12796 	} else if (rcu_unlock) {
12797 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
12798 		return -EINVAL;
12799 	}
12800 
12801 	if (env->cur_state->active_preempt_lock) {
12802 		if (preempt_disable) {
12803 			env->cur_state->active_preempt_lock++;
12804 		} else if (preempt_enable) {
12805 			env->cur_state->active_preempt_lock--;
12806 		} else if (sleepable) {
12807 			verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
12808 			return -EACCES;
12809 		}
12810 	} else if (preempt_disable) {
12811 		env->cur_state->active_preempt_lock++;
12812 	} else if (preempt_enable) {
12813 		verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
12814 		return -EINVAL;
12815 	}
12816 
12817 	/* In case of release function, we get register number of refcounted
12818 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
12819 	 */
12820 	if (meta.release_regno) {
12821 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
12822 		if (err) {
12823 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12824 				func_name, meta.func_id);
12825 			return err;
12826 		}
12827 	}
12828 
12829 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12830 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12831 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12832 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
12833 		insn_aux->insert_off = regs[BPF_REG_2].off;
12834 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
12835 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
12836 		if (err) {
12837 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
12838 				func_name, meta.func_id);
12839 			return err;
12840 		}
12841 
12842 		err = release_reference(env, release_ref_obj_id);
12843 		if (err) {
12844 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12845 				func_name, meta.func_id);
12846 			return err;
12847 		}
12848 	}
12849 
12850 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
12851 		if (!bpf_jit_supports_exceptions()) {
12852 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
12853 				func_name, meta.func_id);
12854 			return -ENOTSUPP;
12855 		}
12856 		env->seen_exception = true;
12857 
12858 		/* In the case of the default callback, the cookie value passed
12859 		 * to bpf_throw becomes the return value of the program.
12860 		 */
12861 		if (!env->exception_callback_subprog) {
12862 			err = check_return_code(env, BPF_REG_1, "R1");
12863 			if (err < 0)
12864 				return err;
12865 		}
12866 	}
12867 
12868 	for (i = 0; i < CALLER_SAVED_REGS; i++)
12869 		mark_reg_not_init(env, regs, caller_saved[i]);
12870 
12871 	/* Check return type */
12872 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
12873 
12874 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
12875 		/* Only exception is bpf_obj_new_impl */
12876 		if (meta.btf != btf_vmlinux ||
12877 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
12878 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
12879 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
12880 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
12881 			return -EINVAL;
12882 		}
12883 	}
12884 
12885 	if (btf_type_is_scalar(t)) {
12886 		mark_reg_unknown(env, regs, BPF_REG_0);
12887 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
12888 	} else if (btf_type_is_ptr(t)) {
12889 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
12890 
12891 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12892 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
12893 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12894 				struct btf_struct_meta *struct_meta;
12895 				struct btf *ret_btf;
12896 				u32 ret_btf_id;
12897 
12898 				if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
12899 					return -ENOMEM;
12900 
12901 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
12902 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12903 					return -EINVAL;
12904 				}
12905 
12906 				ret_btf = env->prog->aux->btf;
12907 				ret_btf_id = meta.arg_constant.value;
12908 
12909 				/* This may be NULL due to user not supplying a BTF */
12910 				if (!ret_btf) {
12911 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12912 					return -EINVAL;
12913 				}
12914 
12915 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12916 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
12917 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12918 					return -EINVAL;
12919 				}
12920 
12921 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12922 					if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
12923 						verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
12924 							ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
12925 						return -EINVAL;
12926 					}
12927 
12928 					if (!bpf_global_percpu_ma_set) {
12929 						mutex_lock(&bpf_percpu_ma_lock);
12930 						if (!bpf_global_percpu_ma_set) {
12931 							/* Charge memory allocated with bpf_global_percpu_ma to
12932 							 * root memcg. The obj_cgroup for root memcg is NULL.
12933 							 */
12934 							err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
12935 							if (!err)
12936 								bpf_global_percpu_ma_set = true;
12937 						}
12938 						mutex_unlock(&bpf_percpu_ma_lock);
12939 						if (err)
12940 							return err;
12941 					}
12942 
12943 					mutex_lock(&bpf_percpu_ma_lock);
12944 					err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
12945 					mutex_unlock(&bpf_percpu_ma_lock);
12946 					if (err)
12947 						return err;
12948 				}
12949 
12950 				struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12951 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12952 					if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12953 						verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12954 						return -EINVAL;
12955 					}
12956 
12957 					if (struct_meta) {
12958 						verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12959 						return -EINVAL;
12960 					}
12961 				}
12962 
12963 				mark_reg_known_zero(env, regs, BPF_REG_0);
12964 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12965 				regs[BPF_REG_0].btf = ret_btf;
12966 				regs[BPF_REG_0].btf_id = ret_btf_id;
12967 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12968 					regs[BPF_REG_0].type |= MEM_PERCPU;
12969 
12970 				insn_aux->obj_new_size = ret_t->size;
12971 				insn_aux->kptr_struct_meta = struct_meta;
12972 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12973 				mark_reg_known_zero(env, regs, BPF_REG_0);
12974 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12975 				regs[BPF_REG_0].btf = meta.arg_btf;
12976 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
12977 
12978 				insn_aux->kptr_struct_meta =
12979 					btf_find_struct_meta(meta.arg_btf,
12980 							     meta.arg_btf_id);
12981 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12982 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12983 				struct btf_field *field = meta.arg_list_head.field;
12984 
12985 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12986 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12987 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12988 				struct btf_field *field = meta.arg_rbtree_root.field;
12989 
12990 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12991 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12992 				mark_reg_known_zero(env, regs, BPF_REG_0);
12993 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12994 				regs[BPF_REG_0].btf = desc_btf;
12995 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12996 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12997 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12998 				if (!ret_t || !btf_type_is_struct(ret_t)) {
12999 					verbose(env,
13000 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
13001 					return -EINVAL;
13002 				}
13003 
13004 				mark_reg_known_zero(env, regs, BPF_REG_0);
13005 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
13006 				regs[BPF_REG_0].btf = desc_btf;
13007 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
13008 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
13009 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
13010 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
13011 
13012 				mark_reg_known_zero(env, regs, BPF_REG_0);
13013 
13014 				if (!meta.arg_constant.found) {
13015 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
13016 					return -EFAULT;
13017 				}
13018 
13019 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
13020 
13021 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
13022 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
13023 
13024 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
13025 					regs[BPF_REG_0].type |= MEM_RDONLY;
13026 				} else {
13027 					/* this will set env->seen_direct_write to true */
13028 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
13029 						verbose(env, "the prog does not allow writes to packet data\n");
13030 						return -EINVAL;
13031 					}
13032 				}
13033 
13034 				if (!meta.initialized_dynptr.id) {
13035 					verbose(env, "verifier internal error: no dynptr id\n");
13036 					return -EFAULT;
13037 				}
13038 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
13039 
13040 				/* we don't need to set BPF_REG_0's ref obj id
13041 				 * because packet slices are not refcounted (see
13042 				 * dynptr_type_refcounted)
13043 				 */
13044 			} else {
13045 				verbose(env, "kernel function %s unhandled dynamic return type\n",
13046 					meta.func_name);
13047 				return -EFAULT;
13048 			}
13049 		} else if (btf_type_is_void(ptr_type)) {
13050 			/* kfunc returning 'void *' is equivalent to returning scalar */
13051 			mark_reg_unknown(env, regs, BPF_REG_0);
13052 		} else if (!__btf_type_is_struct(ptr_type)) {
13053 			if (!meta.r0_size) {
13054 				__u32 sz;
13055 
13056 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
13057 					meta.r0_size = sz;
13058 					meta.r0_rdonly = true;
13059 				}
13060 			}
13061 			if (!meta.r0_size) {
13062 				ptr_type_name = btf_name_by_offset(desc_btf,
13063 								   ptr_type->name_off);
13064 				verbose(env,
13065 					"kernel function %s returns pointer type %s %s is not supported\n",
13066 					func_name,
13067 					btf_type_str(ptr_type),
13068 					ptr_type_name);
13069 				return -EINVAL;
13070 			}
13071 
13072 			mark_reg_known_zero(env, regs, BPF_REG_0);
13073 			regs[BPF_REG_0].type = PTR_TO_MEM;
13074 			regs[BPF_REG_0].mem_size = meta.r0_size;
13075 
13076 			if (meta.r0_rdonly)
13077 				regs[BPF_REG_0].type |= MEM_RDONLY;
13078 
13079 			/* Ensures we don't access the memory after a release_reference() */
13080 			if (meta.ref_obj_id)
13081 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
13082 		} else {
13083 			mark_reg_known_zero(env, regs, BPF_REG_0);
13084 			regs[BPF_REG_0].btf = desc_btf;
13085 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
13086 			regs[BPF_REG_0].btf_id = ptr_type_id;
13087 
13088 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
13089 				regs[BPF_REG_0].type |= PTR_UNTRUSTED;
13090 
13091 			if (is_iter_next_kfunc(&meta)) {
13092 				struct bpf_reg_state *cur_iter;
13093 
13094 				cur_iter = get_iter_from_state(env->cur_state, &meta);
13095 
13096 				if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
13097 					regs[BPF_REG_0].type |= MEM_RCU;
13098 				else
13099 					regs[BPF_REG_0].type |= PTR_TRUSTED;
13100 			}
13101 		}
13102 
13103 		if (is_kfunc_ret_null(&meta)) {
13104 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
13105 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
13106 			regs[BPF_REG_0].id = ++env->id_gen;
13107 		}
13108 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
13109 		if (is_kfunc_acquire(&meta)) {
13110 			int id = acquire_reference_state(env, insn_idx);
13111 
13112 			if (id < 0)
13113 				return id;
13114 			if (is_kfunc_ret_null(&meta))
13115 				regs[BPF_REG_0].id = id;
13116 			regs[BPF_REG_0].ref_obj_id = id;
13117 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
13118 			ref_set_non_owning(env, &regs[BPF_REG_0]);
13119 		}
13120 
13121 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
13122 			regs[BPF_REG_0].id = ++env->id_gen;
13123 	} else if (btf_type_is_void(t)) {
13124 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
13125 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
13126 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
13127 				insn_aux->kptr_struct_meta =
13128 					btf_find_struct_meta(meta.arg_btf,
13129 							     meta.arg_btf_id);
13130 			}
13131 		}
13132 	}
13133 
13134 	nargs = btf_type_vlen(meta.func_proto);
13135 	args = (const struct btf_param *)(meta.func_proto + 1);
13136 	for (i = 0; i < nargs; i++) {
13137 		u32 regno = i + 1;
13138 
13139 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
13140 		if (btf_type_is_ptr(t))
13141 			mark_btf_func_reg_size(env, regno, sizeof(void *));
13142 		else
13143 			/* scalar. ensured by btf_check_kfunc_arg_match() */
13144 			mark_btf_func_reg_size(env, regno, t->size);
13145 	}
13146 
13147 	if (is_iter_next_kfunc(&meta)) {
13148 		err = process_iter_next_call(env, insn_idx, &meta);
13149 		if (err)
13150 			return err;
13151 	}
13152 
13153 	return 0;
13154 }
13155 
13156 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
13157 				  const struct bpf_reg_state *reg,
13158 				  enum bpf_reg_type type)
13159 {
13160 	bool known = tnum_is_const(reg->var_off);
13161 	s64 val = reg->var_off.value;
13162 	s64 smin = reg->smin_value;
13163 
13164 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
13165 		verbose(env, "math between %s pointer and %lld is not allowed\n",
13166 			reg_type_str(env, type), val);
13167 		return false;
13168 	}
13169 
13170 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
13171 		verbose(env, "%s pointer offset %d is not allowed\n",
13172 			reg_type_str(env, type), reg->off);
13173 		return false;
13174 	}
13175 
13176 	if (smin == S64_MIN) {
13177 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
13178 			reg_type_str(env, type));
13179 		return false;
13180 	}
13181 
13182 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
13183 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
13184 			smin, reg_type_str(env, type));
13185 		return false;
13186 	}
13187 
13188 	return true;
13189 }
13190 
13191 enum {
13192 	REASON_BOUNDS	= -1,
13193 	REASON_TYPE	= -2,
13194 	REASON_PATHS	= -3,
13195 	REASON_LIMIT	= -4,
13196 	REASON_STACK	= -5,
13197 };
13198 
13199 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
13200 			      u32 *alu_limit, bool mask_to_left)
13201 {
13202 	u32 max = 0, ptr_limit = 0;
13203 
13204 	switch (ptr_reg->type) {
13205 	case PTR_TO_STACK:
13206 		/* Offset 0 is out-of-bounds, but acceptable start for the
13207 		 * left direction, see BPF_REG_FP. Also, unknown scalar
13208 		 * offset where we would need to deal with min/max bounds is
13209 		 * currently prohibited for unprivileged.
13210 		 */
13211 		max = MAX_BPF_STACK + mask_to_left;
13212 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
13213 		break;
13214 	case PTR_TO_MAP_VALUE:
13215 		max = ptr_reg->map_ptr->value_size;
13216 		ptr_limit = (mask_to_left ?
13217 			     ptr_reg->smin_value :
13218 			     ptr_reg->umax_value) + ptr_reg->off;
13219 		break;
13220 	default:
13221 		return REASON_TYPE;
13222 	}
13223 
13224 	if (ptr_limit >= max)
13225 		return REASON_LIMIT;
13226 	*alu_limit = ptr_limit;
13227 	return 0;
13228 }
13229 
13230 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
13231 				    const struct bpf_insn *insn)
13232 {
13233 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
13234 }
13235 
13236 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
13237 				       u32 alu_state, u32 alu_limit)
13238 {
13239 	/* If we arrived here from different branches with different
13240 	 * state or limits to sanitize, then this won't work.
13241 	 */
13242 	if (aux->alu_state &&
13243 	    (aux->alu_state != alu_state ||
13244 	     aux->alu_limit != alu_limit))
13245 		return REASON_PATHS;
13246 
13247 	/* Corresponding fixup done in do_misc_fixups(). */
13248 	aux->alu_state = alu_state;
13249 	aux->alu_limit = alu_limit;
13250 	return 0;
13251 }
13252 
13253 static int sanitize_val_alu(struct bpf_verifier_env *env,
13254 			    struct bpf_insn *insn)
13255 {
13256 	struct bpf_insn_aux_data *aux = cur_aux(env);
13257 
13258 	if (can_skip_alu_sanitation(env, insn))
13259 		return 0;
13260 
13261 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
13262 }
13263 
13264 static bool sanitize_needed(u8 opcode)
13265 {
13266 	return opcode == BPF_ADD || opcode == BPF_SUB;
13267 }
13268 
13269 struct bpf_sanitize_info {
13270 	struct bpf_insn_aux_data aux;
13271 	bool mask_to_left;
13272 };
13273 
13274 static struct bpf_verifier_state *
13275 sanitize_speculative_path(struct bpf_verifier_env *env,
13276 			  const struct bpf_insn *insn,
13277 			  u32 next_idx, u32 curr_idx)
13278 {
13279 	struct bpf_verifier_state *branch;
13280 	struct bpf_reg_state *regs;
13281 
13282 	branch = push_stack(env, next_idx, curr_idx, true);
13283 	if (branch && insn) {
13284 		regs = branch->frame[branch->curframe]->regs;
13285 		if (BPF_SRC(insn->code) == BPF_K) {
13286 			mark_reg_unknown(env, regs, insn->dst_reg);
13287 		} else if (BPF_SRC(insn->code) == BPF_X) {
13288 			mark_reg_unknown(env, regs, insn->dst_reg);
13289 			mark_reg_unknown(env, regs, insn->src_reg);
13290 		}
13291 	}
13292 	return branch;
13293 }
13294 
13295 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
13296 			    struct bpf_insn *insn,
13297 			    const struct bpf_reg_state *ptr_reg,
13298 			    const struct bpf_reg_state *off_reg,
13299 			    struct bpf_reg_state *dst_reg,
13300 			    struct bpf_sanitize_info *info,
13301 			    const bool commit_window)
13302 {
13303 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
13304 	struct bpf_verifier_state *vstate = env->cur_state;
13305 	bool off_is_imm = tnum_is_const(off_reg->var_off);
13306 	bool off_is_neg = off_reg->smin_value < 0;
13307 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
13308 	u8 opcode = BPF_OP(insn->code);
13309 	u32 alu_state, alu_limit;
13310 	struct bpf_reg_state tmp;
13311 	bool ret;
13312 	int err;
13313 
13314 	if (can_skip_alu_sanitation(env, insn))
13315 		return 0;
13316 
13317 	/* We already marked aux for masking from non-speculative
13318 	 * paths, thus we got here in the first place. We only care
13319 	 * to explore bad access from here.
13320 	 */
13321 	if (vstate->speculative)
13322 		goto do_sim;
13323 
13324 	if (!commit_window) {
13325 		if (!tnum_is_const(off_reg->var_off) &&
13326 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
13327 			return REASON_BOUNDS;
13328 
13329 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
13330 				     (opcode == BPF_SUB && !off_is_neg);
13331 	}
13332 
13333 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
13334 	if (err < 0)
13335 		return err;
13336 
13337 	if (commit_window) {
13338 		/* In commit phase we narrow the masking window based on
13339 		 * the observed pointer move after the simulated operation.
13340 		 */
13341 		alu_state = info->aux.alu_state;
13342 		alu_limit = abs(info->aux.alu_limit - alu_limit);
13343 	} else {
13344 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
13345 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
13346 		alu_state |= ptr_is_dst_reg ?
13347 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
13348 
13349 		/* Limit pruning on unknown scalars to enable deep search for
13350 		 * potential masking differences from other program paths.
13351 		 */
13352 		if (!off_is_imm)
13353 			env->explore_alu_limits = true;
13354 	}
13355 
13356 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
13357 	if (err < 0)
13358 		return err;
13359 do_sim:
13360 	/* If we're in commit phase, we're done here given we already
13361 	 * pushed the truncated dst_reg into the speculative verification
13362 	 * stack.
13363 	 *
13364 	 * Also, when register is a known constant, we rewrite register-based
13365 	 * operation to immediate-based, and thus do not need masking (and as
13366 	 * a consequence, do not need to simulate the zero-truncation either).
13367 	 */
13368 	if (commit_window || off_is_imm)
13369 		return 0;
13370 
13371 	/* Simulate and find potential out-of-bounds access under
13372 	 * speculative execution from truncation as a result of
13373 	 * masking when off was not within expected range. If off
13374 	 * sits in dst, then we temporarily need to move ptr there
13375 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
13376 	 * for cases where we use K-based arithmetic in one direction
13377 	 * and truncated reg-based in the other in order to explore
13378 	 * bad access.
13379 	 */
13380 	if (!ptr_is_dst_reg) {
13381 		tmp = *dst_reg;
13382 		copy_register_state(dst_reg, ptr_reg);
13383 	}
13384 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
13385 					env->insn_idx);
13386 	if (!ptr_is_dst_reg && ret)
13387 		*dst_reg = tmp;
13388 	return !ret ? REASON_STACK : 0;
13389 }
13390 
13391 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
13392 {
13393 	struct bpf_verifier_state *vstate = env->cur_state;
13394 
13395 	/* If we simulate paths under speculation, we don't update the
13396 	 * insn as 'seen' such that when we verify unreachable paths in
13397 	 * the non-speculative domain, sanitize_dead_code() can still
13398 	 * rewrite/sanitize them.
13399 	 */
13400 	if (!vstate->speculative)
13401 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
13402 }
13403 
13404 static int sanitize_err(struct bpf_verifier_env *env,
13405 			const struct bpf_insn *insn, int reason,
13406 			const struct bpf_reg_state *off_reg,
13407 			const struct bpf_reg_state *dst_reg)
13408 {
13409 	static const char *err = "pointer arithmetic with it prohibited for !root";
13410 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
13411 	u32 dst = insn->dst_reg, src = insn->src_reg;
13412 
13413 	switch (reason) {
13414 	case REASON_BOUNDS:
13415 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
13416 			off_reg == dst_reg ? dst : src, err);
13417 		break;
13418 	case REASON_TYPE:
13419 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
13420 			off_reg == dst_reg ? src : dst, err);
13421 		break;
13422 	case REASON_PATHS:
13423 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
13424 			dst, op, err);
13425 		break;
13426 	case REASON_LIMIT:
13427 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
13428 			dst, op, err);
13429 		break;
13430 	case REASON_STACK:
13431 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
13432 			dst, err);
13433 		break;
13434 	default:
13435 		verbose(env, "verifier internal error: unknown reason (%d)\n",
13436 			reason);
13437 		break;
13438 	}
13439 
13440 	return -EACCES;
13441 }
13442 
13443 /* check that stack access falls within stack limits and that 'reg' doesn't
13444  * have a variable offset.
13445  *
13446  * Variable offset is prohibited for unprivileged mode for simplicity since it
13447  * requires corresponding support in Spectre masking for stack ALU.  See also
13448  * retrieve_ptr_limit().
13449  *
13450  *
13451  * 'off' includes 'reg->off'.
13452  */
13453 static int check_stack_access_for_ptr_arithmetic(
13454 				struct bpf_verifier_env *env,
13455 				int regno,
13456 				const struct bpf_reg_state *reg,
13457 				int off)
13458 {
13459 	if (!tnum_is_const(reg->var_off)) {
13460 		char tn_buf[48];
13461 
13462 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
13463 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
13464 			regno, tn_buf, off);
13465 		return -EACCES;
13466 	}
13467 
13468 	if (off >= 0 || off < -MAX_BPF_STACK) {
13469 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
13470 			"prohibited for !root; off=%d\n", regno, off);
13471 		return -EACCES;
13472 	}
13473 
13474 	return 0;
13475 }
13476 
13477 static int sanitize_check_bounds(struct bpf_verifier_env *env,
13478 				 const struct bpf_insn *insn,
13479 				 const struct bpf_reg_state *dst_reg)
13480 {
13481 	u32 dst = insn->dst_reg;
13482 
13483 	/* For unprivileged we require that resulting offset must be in bounds
13484 	 * in order to be able to sanitize access later on.
13485 	 */
13486 	if (env->bypass_spec_v1)
13487 		return 0;
13488 
13489 	switch (dst_reg->type) {
13490 	case PTR_TO_STACK:
13491 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
13492 					dst_reg->off + dst_reg->var_off.value))
13493 			return -EACCES;
13494 		break;
13495 	case PTR_TO_MAP_VALUE:
13496 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
13497 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
13498 				"prohibited for !root\n", dst);
13499 			return -EACCES;
13500 		}
13501 		break;
13502 	default:
13503 		break;
13504 	}
13505 
13506 	return 0;
13507 }
13508 
13509 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
13510  * Caller should also handle BPF_MOV case separately.
13511  * If we return -EACCES, caller may want to try again treating pointer as a
13512  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
13513  */
13514 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
13515 				   struct bpf_insn *insn,
13516 				   struct bpf_reg_state *ptr_reg,
13517 				   const struct bpf_reg_state *off_reg)
13518 {
13519 	struct bpf_verifier_state *vstate = env->cur_state;
13520 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13521 	struct bpf_reg_state *regs = state->regs, *dst_reg;
13522 	bool known = tnum_is_const(off_reg->var_off);
13523 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
13524 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
13525 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
13526 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
13527 	struct bpf_sanitize_info info = {};
13528 	u8 opcode = BPF_OP(insn->code);
13529 	u32 dst = insn->dst_reg;
13530 	bool mask;
13531 	int ret;
13532 
13533 	dst_reg = &regs[dst];
13534 
13535 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
13536 	    smin_val > smax_val || umin_val > umax_val) {
13537 		/* Taint dst register if offset had invalid bounds derived from
13538 		 * e.g. dead branches.
13539 		 */
13540 		__mark_reg_unknown(env, dst_reg);
13541 		return 0;
13542 	}
13543 
13544 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
13545 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
13546 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13547 			__mark_reg_unknown(env, dst_reg);
13548 			return 0;
13549 		}
13550 
13551 		verbose(env,
13552 			"R%d 32-bit pointer arithmetic prohibited\n",
13553 			dst);
13554 		return -EACCES;
13555 	}
13556 
13557 	mask = mask_raw_tp_reg(env, ptr_reg);
13558 	if (ptr_reg->type & PTR_MAYBE_NULL) {
13559 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
13560 			dst, reg_type_str(env, ptr_reg->type));
13561 		unmask_raw_tp_reg(ptr_reg, mask);
13562 		return -EACCES;
13563 	}
13564 	unmask_raw_tp_reg(ptr_reg, mask);
13565 
13566 	switch (base_type(ptr_reg->type)) {
13567 	case PTR_TO_CTX:
13568 	case PTR_TO_MAP_VALUE:
13569 	case PTR_TO_MAP_KEY:
13570 	case PTR_TO_STACK:
13571 	case PTR_TO_PACKET_META:
13572 	case PTR_TO_PACKET:
13573 	case PTR_TO_TP_BUFFER:
13574 	case PTR_TO_BTF_ID:
13575 	case PTR_TO_MEM:
13576 	case PTR_TO_BUF:
13577 	case PTR_TO_FUNC:
13578 	case CONST_PTR_TO_DYNPTR:
13579 		break;
13580 	case PTR_TO_FLOW_KEYS:
13581 		if (known)
13582 			break;
13583 		fallthrough;
13584 	case CONST_PTR_TO_MAP:
13585 		/* smin_val represents the known value */
13586 		if (known && smin_val == 0 && opcode == BPF_ADD)
13587 			break;
13588 		fallthrough;
13589 	default:
13590 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
13591 			dst, reg_type_str(env, ptr_reg->type));
13592 		return -EACCES;
13593 	}
13594 
13595 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
13596 	 * The id may be overwritten later if we create a new variable offset.
13597 	 */
13598 	dst_reg->type = ptr_reg->type;
13599 	dst_reg->id = ptr_reg->id;
13600 
13601 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
13602 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
13603 		return -EINVAL;
13604 
13605 	/* pointer types do not carry 32-bit bounds at the moment. */
13606 	__mark_reg32_unbounded(dst_reg);
13607 
13608 	if (sanitize_needed(opcode)) {
13609 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
13610 				       &info, false);
13611 		if (ret < 0)
13612 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13613 	}
13614 
13615 	switch (opcode) {
13616 	case BPF_ADD:
13617 		/* We can take a fixed offset as long as it doesn't overflow
13618 		 * the s32 'off' field
13619 		 */
13620 		if (known && (ptr_reg->off + smin_val ==
13621 			      (s64)(s32)(ptr_reg->off + smin_val))) {
13622 			/* pointer += K.  Accumulate it into fixed offset */
13623 			dst_reg->smin_value = smin_ptr;
13624 			dst_reg->smax_value = smax_ptr;
13625 			dst_reg->umin_value = umin_ptr;
13626 			dst_reg->umax_value = umax_ptr;
13627 			dst_reg->var_off = ptr_reg->var_off;
13628 			dst_reg->off = ptr_reg->off + smin_val;
13629 			dst_reg->raw = ptr_reg->raw;
13630 			break;
13631 		}
13632 		/* A new variable offset is created.  Note that off_reg->off
13633 		 * == 0, since it's a scalar.
13634 		 * dst_reg gets the pointer type and since some positive
13635 		 * integer value was added to the pointer, give it a new 'id'
13636 		 * if it's a PTR_TO_PACKET.
13637 		 * this creates a new 'base' pointer, off_reg (variable) gets
13638 		 * added into the variable offset, and we copy the fixed offset
13639 		 * from ptr_reg.
13640 		 */
13641 		if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
13642 		    check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
13643 			dst_reg->smin_value = S64_MIN;
13644 			dst_reg->smax_value = S64_MAX;
13645 		}
13646 		if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
13647 		    check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
13648 			dst_reg->umin_value = 0;
13649 			dst_reg->umax_value = U64_MAX;
13650 		}
13651 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
13652 		dst_reg->off = ptr_reg->off;
13653 		dst_reg->raw = ptr_reg->raw;
13654 		if (reg_is_pkt_pointer(ptr_reg)) {
13655 			dst_reg->id = ++env->id_gen;
13656 			/* something was added to pkt_ptr, set range to zero */
13657 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13658 		}
13659 		break;
13660 	case BPF_SUB:
13661 		if (dst_reg == off_reg) {
13662 			/* scalar -= pointer.  Creates an unknown scalar */
13663 			verbose(env, "R%d tried to subtract pointer from scalar\n",
13664 				dst);
13665 			return -EACCES;
13666 		}
13667 		/* We don't allow subtraction from FP, because (according to
13668 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
13669 		 * be able to deal with it.
13670 		 */
13671 		if (ptr_reg->type == PTR_TO_STACK) {
13672 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
13673 				dst);
13674 			return -EACCES;
13675 		}
13676 		if (known && (ptr_reg->off - smin_val ==
13677 			      (s64)(s32)(ptr_reg->off - smin_val))) {
13678 			/* pointer -= K.  Subtract it from fixed offset */
13679 			dst_reg->smin_value = smin_ptr;
13680 			dst_reg->smax_value = smax_ptr;
13681 			dst_reg->umin_value = umin_ptr;
13682 			dst_reg->umax_value = umax_ptr;
13683 			dst_reg->var_off = ptr_reg->var_off;
13684 			dst_reg->id = ptr_reg->id;
13685 			dst_reg->off = ptr_reg->off - smin_val;
13686 			dst_reg->raw = ptr_reg->raw;
13687 			break;
13688 		}
13689 		/* A new variable offset is created.  If the subtrahend is known
13690 		 * nonnegative, then any reg->range we had before is still good.
13691 		 */
13692 		if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
13693 		    check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
13694 			/* Overflow possible, we know nothing */
13695 			dst_reg->smin_value = S64_MIN;
13696 			dst_reg->smax_value = S64_MAX;
13697 		}
13698 		if (umin_ptr < umax_val) {
13699 			/* Overflow possible, we know nothing */
13700 			dst_reg->umin_value = 0;
13701 			dst_reg->umax_value = U64_MAX;
13702 		} else {
13703 			/* Cannot overflow (as long as bounds are consistent) */
13704 			dst_reg->umin_value = umin_ptr - umax_val;
13705 			dst_reg->umax_value = umax_ptr - umin_val;
13706 		}
13707 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
13708 		dst_reg->off = ptr_reg->off;
13709 		dst_reg->raw = ptr_reg->raw;
13710 		if (reg_is_pkt_pointer(ptr_reg)) {
13711 			dst_reg->id = ++env->id_gen;
13712 			/* something was added to pkt_ptr, set range to zero */
13713 			if (smin_val < 0)
13714 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13715 		}
13716 		break;
13717 	case BPF_AND:
13718 	case BPF_OR:
13719 	case BPF_XOR:
13720 		/* bitwise ops on pointers are troublesome, prohibit. */
13721 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
13722 			dst, bpf_alu_string[opcode >> 4]);
13723 		return -EACCES;
13724 	default:
13725 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
13726 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
13727 			dst, bpf_alu_string[opcode >> 4]);
13728 		return -EACCES;
13729 	}
13730 
13731 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
13732 		return -EINVAL;
13733 	reg_bounds_sync(dst_reg);
13734 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
13735 		return -EACCES;
13736 	if (sanitize_needed(opcode)) {
13737 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
13738 				       &info, true);
13739 		if (ret < 0)
13740 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13741 	}
13742 
13743 	return 0;
13744 }
13745 
13746 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
13747 				 struct bpf_reg_state *src_reg)
13748 {
13749 	s32 *dst_smin = &dst_reg->s32_min_value;
13750 	s32 *dst_smax = &dst_reg->s32_max_value;
13751 	u32 *dst_umin = &dst_reg->u32_min_value;
13752 	u32 *dst_umax = &dst_reg->u32_max_value;
13753 
13754 	if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
13755 	    check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
13756 		*dst_smin = S32_MIN;
13757 		*dst_smax = S32_MAX;
13758 	}
13759 	if (check_add_overflow(*dst_umin, src_reg->u32_min_value, dst_umin) ||
13760 	    check_add_overflow(*dst_umax, src_reg->u32_max_value, dst_umax)) {
13761 		*dst_umin = 0;
13762 		*dst_umax = U32_MAX;
13763 	}
13764 }
13765 
13766 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
13767 			       struct bpf_reg_state *src_reg)
13768 {
13769 	s64 *dst_smin = &dst_reg->smin_value;
13770 	s64 *dst_smax = &dst_reg->smax_value;
13771 	u64 *dst_umin = &dst_reg->umin_value;
13772 	u64 *dst_umax = &dst_reg->umax_value;
13773 
13774 	if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
13775 	    check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
13776 		*dst_smin = S64_MIN;
13777 		*dst_smax = S64_MAX;
13778 	}
13779 	if (check_add_overflow(*dst_umin, src_reg->umin_value, dst_umin) ||
13780 	    check_add_overflow(*dst_umax, src_reg->umax_value, dst_umax)) {
13781 		*dst_umin = 0;
13782 		*dst_umax = U64_MAX;
13783 	}
13784 }
13785 
13786 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
13787 				 struct bpf_reg_state *src_reg)
13788 {
13789 	s32 *dst_smin = &dst_reg->s32_min_value;
13790 	s32 *dst_smax = &dst_reg->s32_max_value;
13791 	u32 umin_val = src_reg->u32_min_value;
13792 	u32 umax_val = src_reg->u32_max_value;
13793 
13794 	if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
13795 	    check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
13796 		/* Overflow possible, we know nothing */
13797 		*dst_smin = S32_MIN;
13798 		*dst_smax = S32_MAX;
13799 	}
13800 	if (dst_reg->u32_min_value < umax_val) {
13801 		/* Overflow possible, we know nothing */
13802 		dst_reg->u32_min_value = 0;
13803 		dst_reg->u32_max_value = U32_MAX;
13804 	} else {
13805 		/* Cannot overflow (as long as bounds are consistent) */
13806 		dst_reg->u32_min_value -= umax_val;
13807 		dst_reg->u32_max_value -= umin_val;
13808 	}
13809 }
13810 
13811 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
13812 			       struct bpf_reg_state *src_reg)
13813 {
13814 	s64 *dst_smin = &dst_reg->smin_value;
13815 	s64 *dst_smax = &dst_reg->smax_value;
13816 	u64 umin_val = src_reg->umin_value;
13817 	u64 umax_val = src_reg->umax_value;
13818 
13819 	if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
13820 	    check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
13821 		/* Overflow possible, we know nothing */
13822 		*dst_smin = S64_MIN;
13823 		*dst_smax = S64_MAX;
13824 	}
13825 	if (dst_reg->umin_value < umax_val) {
13826 		/* Overflow possible, we know nothing */
13827 		dst_reg->umin_value = 0;
13828 		dst_reg->umax_value = U64_MAX;
13829 	} else {
13830 		/* Cannot overflow (as long as bounds are consistent) */
13831 		dst_reg->umin_value -= umax_val;
13832 		dst_reg->umax_value -= umin_val;
13833 	}
13834 }
13835 
13836 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13837 				 struct bpf_reg_state *src_reg)
13838 {
13839 	s32 smin_val = src_reg->s32_min_value;
13840 	u32 umin_val = src_reg->u32_min_value;
13841 	u32 umax_val = src_reg->u32_max_value;
13842 
13843 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
13844 		/* Ain't nobody got time to multiply that sign */
13845 		__mark_reg32_unbounded(dst_reg);
13846 		return;
13847 	}
13848 	/* Both values are positive, so we can work with unsigned and
13849 	 * copy the result to signed (unless it exceeds S32_MAX).
13850 	 */
13851 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
13852 		/* Potential overflow, we know nothing */
13853 		__mark_reg32_unbounded(dst_reg);
13854 		return;
13855 	}
13856 	dst_reg->u32_min_value *= umin_val;
13857 	dst_reg->u32_max_value *= umax_val;
13858 	if (dst_reg->u32_max_value > S32_MAX) {
13859 		/* Overflow possible, we know nothing */
13860 		dst_reg->s32_min_value = S32_MIN;
13861 		dst_reg->s32_max_value = S32_MAX;
13862 	} else {
13863 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13864 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13865 	}
13866 }
13867 
13868 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13869 			       struct bpf_reg_state *src_reg)
13870 {
13871 	s64 smin_val = src_reg->smin_value;
13872 	u64 umin_val = src_reg->umin_value;
13873 	u64 umax_val = src_reg->umax_value;
13874 
13875 	if (smin_val < 0 || dst_reg->smin_value < 0) {
13876 		/* Ain't nobody got time to multiply that sign */
13877 		__mark_reg64_unbounded(dst_reg);
13878 		return;
13879 	}
13880 	/* Both values are positive, so we can work with unsigned and
13881 	 * copy the result to signed (unless it exceeds S64_MAX).
13882 	 */
13883 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
13884 		/* Potential overflow, we know nothing */
13885 		__mark_reg64_unbounded(dst_reg);
13886 		return;
13887 	}
13888 	dst_reg->umin_value *= umin_val;
13889 	dst_reg->umax_value *= umax_val;
13890 	if (dst_reg->umax_value > S64_MAX) {
13891 		/* Overflow possible, we know nothing */
13892 		dst_reg->smin_value = S64_MIN;
13893 		dst_reg->smax_value = S64_MAX;
13894 	} else {
13895 		dst_reg->smin_value = dst_reg->umin_value;
13896 		dst_reg->smax_value = dst_reg->umax_value;
13897 	}
13898 }
13899 
13900 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13901 				 struct bpf_reg_state *src_reg)
13902 {
13903 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13904 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13905 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13906 	u32 umax_val = src_reg->u32_max_value;
13907 
13908 	if (src_known && dst_known) {
13909 		__mark_reg32_known(dst_reg, var32_off.value);
13910 		return;
13911 	}
13912 
13913 	/* We get our minimum from the var_off, since that's inherently
13914 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13915 	 */
13916 	dst_reg->u32_min_value = var32_off.value;
13917 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13918 
13919 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
13920 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
13921 	 */
13922 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
13923 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13924 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13925 	} else {
13926 		dst_reg->s32_min_value = S32_MIN;
13927 		dst_reg->s32_max_value = S32_MAX;
13928 	}
13929 }
13930 
13931 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
13932 			       struct bpf_reg_state *src_reg)
13933 {
13934 	bool src_known = tnum_is_const(src_reg->var_off);
13935 	bool dst_known = tnum_is_const(dst_reg->var_off);
13936 	u64 umax_val = src_reg->umax_value;
13937 
13938 	if (src_known && dst_known) {
13939 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13940 		return;
13941 	}
13942 
13943 	/* We get our minimum from the var_off, since that's inherently
13944 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13945 	 */
13946 	dst_reg->umin_value = dst_reg->var_off.value;
13947 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13948 
13949 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
13950 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
13951 	 */
13952 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
13953 		dst_reg->smin_value = dst_reg->umin_value;
13954 		dst_reg->smax_value = dst_reg->umax_value;
13955 	} else {
13956 		dst_reg->smin_value = S64_MIN;
13957 		dst_reg->smax_value = S64_MAX;
13958 	}
13959 	/* We may learn something more from the var_off */
13960 	__update_reg_bounds(dst_reg);
13961 }
13962 
13963 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13964 				struct bpf_reg_state *src_reg)
13965 {
13966 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13967 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13968 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13969 	u32 umin_val = src_reg->u32_min_value;
13970 
13971 	if (src_known && dst_known) {
13972 		__mark_reg32_known(dst_reg, var32_off.value);
13973 		return;
13974 	}
13975 
13976 	/* We get our maximum from the var_off, and our minimum is the
13977 	 * maximum of the operands' minima
13978 	 */
13979 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13980 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13981 
13982 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
13983 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
13984 	 */
13985 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
13986 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13987 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13988 	} else {
13989 		dst_reg->s32_min_value = S32_MIN;
13990 		dst_reg->s32_max_value = S32_MAX;
13991 	}
13992 }
13993 
13994 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13995 			      struct bpf_reg_state *src_reg)
13996 {
13997 	bool src_known = tnum_is_const(src_reg->var_off);
13998 	bool dst_known = tnum_is_const(dst_reg->var_off);
13999 	u64 umin_val = src_reg->umin_value;
14000 
14001 	if (src_known && dst_known) {
14002 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14003 		return;
14004 	}
14005 
14006 	/* We get our maximum from the var_off, and our minimum is the
14007 	 * maximum of the operands' minima
14008 	 */
14009 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
14010 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
14011 
14012 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
14013 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
14014 	 */
14015 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
14016 		dst_reg->smin_value = dst_reg->umin_value;
14017 		dst_reg->smax_value = dst_reg->umax_value;
14018 	} else {
14019 		dst_reg->smin_value = S64_MIN;
14020 		dst_reg->smax_value = S64_MAX;
14021 	}
14022 	/* We may learn something more from the var_off */
14023 	__update_reg_bounds(dst_reg);
14024 }
14025 
14026 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
14027 				 struct bpf_reg_state *src_reg)
14028 {
14029 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14030 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14031 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14032 
14033 	if (src_known && dst_known) {
14034 		__mark_reg32_known(dst_reg, var32_off.value);
14035 		return;
14036 	}
14037 
14038 	/* We get both minimum and maximum from the var32_off. */
14039 	dst_reg->u32_min_value = var32_off.value;
14040 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
14041 
14042 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
14043 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
14044 	 */
14045 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
14046 		dst_reg->s32_min_value = dst_reg->u32_min_value;
14047 		dst_reg->s32_max_value = dst_reg->u32_max_value;
14048 	} else {
14049 		dst_reg->s32_min_value = S32_MIN;
14050 		dst_reg->s32_max_value = S32_MAX;
14051 	}
14052 }
14053 
14054 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
14055 			       struct bpf_reg_state *src_reg)
14056 {
14057 	bool src_known = tnum_is_const(src_reg->var_off);
14058 	bool dst_known = tnum_is_const(dst_reg->var_off);
14059 
14060 	if (src_known && dst_known) {
14061 		/* dst_reg->var_off.value has been updated earlier */
14062 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14063 		return;
14064 	}
14065 
14066 	/* We get both minimum and maximum from the var_off. */
14067 	dst_reg->umin_value = dst_reg->var_off.value;
14068 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
14069 
14070 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
14071 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
14072 	 */
14073 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
14074 		dst_reg->smin_value = dst_reg->umin_value;
14075 		dst_reg->smax_value = dst_reg->umax_value;
14076 	} else {
14077 		dst_reg->smin_value = S64_MIN;
14078 		dst_reg->smax_value = S64_MAX;
14079 	}
14080 
14081 	__update_reg_bounds(dst_reg);
14082 }
14083 
14084 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
14085 				   u64 umin_val, u64 umax_val)
14086 {
14087 	/* We lose all sign bit information (except what we can pick
14088 	 * up from var_off)
14089 	 */
14090 	dst_reg->s32_min_value = S32_MIN;
14091 	dst_reg->s32_max_value = S32_MAX;
14092 	/* If we might shift our top bit out, then we know nothing */
14093 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
14094 		dst_reg->u32_min_value = 0;
14095 		dst_reg->u32_max_value = U32_MAX;
14096 	} else {
14097 		dst_reg->u32_min_value <<= umin_val;
14098 		dst_reg->u32_max_value <<= umax_val;
14099 	}
14100 }
14101 
14102 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
14103 				 struct bpf_reg_state *src_reg)
14104 {
14105 	u32 umax_val = src_reg->u32_max_value;
14106 	u32 umin_val = src_reg->u32_min_value;
14107 	/* u32 alu operation will zext upper bits */
14108 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
14109 
14110 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
14111 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
14112 	/* Not required but being careful mark reg64 bounds as unknown so
14113 	 * that we are forced to pick them up from tnum and zext later and
14114 	 * if some path skips this step we are still safe.
14115 	 */
14116 	__mark_reg64_unbounded(dst_reg);
14117 	__update_reg32_bounds(dst_reg);
14118 }
14119 
14120 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
14121 				   u64 umin_val, u64 umax_val)
14122 {
14123 	/* Special case <<32 because it is a common compiler pattern to sign
14124 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
14125 	 * positive we know this shift will also be positive so we can track
14126 	 * bounds correctly. Otherwise we lose all sign bit information except
14127 	 * what we can pick up from var_off. Perhaps we can generalize this
14128 	 * later to shifts of any length.
14129 	 */
14130 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
14131 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
14132 	else
14133 		dst_reg->smax_value = S64_MAX;
14134 
14135 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
14136 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
14137 	else
14138 		dst_reg->smin_value = S64_MIN;
14139 
14140 	/* If we might shift our top bit out, then we know nothing */
14141 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
14142 		dst_reg->umin_value = 0;
14143 		dst_reg->umax_value = U64_MAX;
14144 	} else {
14145 		dst_reg->umin_value <<= umin_val;
14146 		dst_reg->umax_value <<= umax_val;
14147 	}
14148 }
14149 
14150 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
14151 			       struct bpf_reg_state *src_reg)
14152 {
14153 	u64 umax_val = src_reg->umax_value;
14154 	u64 umin_val = src_reg->umin_value;
14155 
14156 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
14157 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
14158 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
14159 
14160 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
14161 	/* We may learn something more from the var_off */
14162 	__update_reg_bounds(dst_reg);
14163 }
14164 
14165 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
14166 				 struct bpf_reg_state *src_reg)
14167 {
14168 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
14169 	u32 umax_val = src_reg->u32_max_value;
14170 	u32 umin_val = src_reg->u32_min_value;
14171 
14172 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
14173 	 * be negative, then either:
14174 	 * 1) src_reg might be zero, so the sign bit of the result is
14175 	 *    unknown, so we lose our signed bounds
14176 	 * 2) it's known negative, thus the unsigned bounds capture the
14177 	 *    signed bounds
14178 	 * 3) the signed bounds cross zero, so they tell us nothing
14179 	 *    about the result
14180 	 * If the value in dst_reg is known nonnegative, then again the
14181 	 * unsigned bounds capture the signed bounds.
14182 	 * Thus, in all cases it suffices to blow away our signed bounds
14183 	 * and rely on inferring new ones from the unsigned bounds and
14184 	 * var_off of the result.
14185 	 */
14186 	dst_reg->s32_min_value = S32_MIN;
14187 	dst_reg->s32_max_value = S32_MAX;
14188 
14189 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
14190 	dst_reg->u32_min_value >>= umax_val;
14191 	dst_reg->u32_max_value >>= umin_val;
14192 
14193 	__mark_reg64_unbounded(dst_reg);
14194 	__update_reg32_bounds(dst_reg);
14195 }
14196 
14197 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
14198 			       struct bpf_reg_state *src_reg)
14199 {
14200 	u64 umax_val = src_reg->umax_value;
14201 	u64 umin_val = src_reg->umin_value;
14202 
14203 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
14204 	 * be negative, then either:
14205 	 * 1) src_reg might be zero, so the sign bit of the result is
14206 	 *    unknown, so we lose our signed bounds
14207 	 * 2) it's known negative, thus the unsigned bounds capture the
14208 	 *    signed bounds
14209 	 * 3) the signed bounds cross zero, so they tell us nothing
14210 	 *    about the result
14211 	 * If the value in dst_reg is known nonnegative, then again the
14212 	 * unsigned bounds capture the signed bounds.
14213 	 * Thus, in all cases it suffices to blow away our signed bounds
14214 	 * and rely on inferring new ones from the unsigned bounds and
14215 	 * var_off of the result.
14216 	 */
14217 	dst_reg->smin_value = S64_MIN;
14218 	dst_reg->smax_value = S64_MAX;
14219 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
14220 	dst_reg->umin_value >>= umax_val;
14221 	dst_reg->umax_value >>= umin_val;
14222 
14223 	/* Its not easy to operate on alu32 bounds here because it depends
14224 	 * on bits being shifted in. Take easy way out and mark unbounded
14225 	 * so we can recalculate later from tnum.
14226 	 */
14227 	__mark_reg32_unbounded(dst_reg);
14228 	__update_reg_bounds(dst_reg);
14229 }
14230 
14231 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
14232 				  struct bpf_reg_state *src_reg)
14233 {
14234 	u64 umin_val = src_reg->u32_min_value;
14235 
14236 	/* Upon reaching here, src_known is true and
14237 	 * umax_val is equal to umin_val.
14238 	 */
14239 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
14240 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
14241 
14242 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
14243 
14244 	/* blow away the dst_reg umin_value/umax_value and rely on
14245 	 * dst_reg var_off to refine the result.
14246 	 */
14247 	dst_reg->u32_min_value = 0;
14248 	dst_reg->u32_max_value = U32_MAX;
14249 
14250 	__mark_reg64_unbounded(dst_reg);
14251 	__update_reg32_bounds(dst_reg);
14252 }
14253 
14254 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
14255 				struct bpf_reg_state *src_reg)
14256 {
14257 	u64 umin_val = src_reg->umin_value;
14258 
14259 	/* Upon reaching here, src_known is true and umax_val is equal
14260 	 * to umin_val.
14261 	 */
14262 	dst_reg->smin_value >>= umin_val;
14263 	dst_reg->smax_value >>= umin_val;
14264 
14265 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
14266 
14267 	/* blow away the dst_reg umin_value/umax_value and rely on
14268 	 * dst_reg var_off to refine the result.
14269 	 */
14270 	dst_reg->umin_value = 0;
14271 	dst_reg->umax_value = U64_MAX;
14272 
14273 	/* Its not easy to operate on alu32 bounds here because it depends
14274 	 * on bits being shifted in from upper 32-bits. Take easy way out
14275 	 * and mark unbounded so we can recalculate later from tnum.
14276 	 */
14277 	__mark_reg32_unbounded(dst_reg);
14278 	__update_reg_bounds(dst_reg);
14279 }
14280 
14281 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
14282 					     const struct bpf_reg_state *src_reg)
14283 {
14284 	bool src_is_const = false;
14285 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
14286 
14287 	if (insn_bitness == 32) {
14288 		if (tnum_subreg_is_const(src_reg->var_off)
14289 		    && src_reg->s32_min_value == src_reg->s32_max_value
14290 		    && src_reg->u32_min_value == src_reg->u32_max_value)
14291 			src_is_const = true;
14292 	} else {
14293 		if (tnum_is_const(src_reg->var_off)
14294 		    && src_reg->smin_value == src_reg->smax_value
14295 		    && src_reg->umin_value == src_reg->umax_value)
14296 			src_is_const = true;
14297 	}
14298 
14299 	switch (BPF_OP(insn->code)) {
14300 	case BPF_ADD:
14301 	case BPF_SUB:
14302 	case BPF_AND:
14303 	case BPF_XOR:
14304 	case BPF_OR:
14305 	case BPF_MUL:
14306 		return true;
14307 
14308 	/* Shift operators range is only computable if shift dimension operand
14309 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
14310 	 * includes shifts by a negative number.
14311 	 */
14312 	case BPF_LSH:
14313 	case BPF_RSH:
14314 	case BPF_ARSH:
14315 		return (src_is_const && src_reg->umax_value < insn_bitness);
14316 	default:
14317 		return false;
14318 	}
14319 }
14320 
14321 /* WARNING: This function does calculations on 64-bit values, but the actual
14322  * execution may occur on 32-bit values. Therefore, things like bitshifts
14323  * need extra checks in the 32-bit case.
14324  */
14325 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
14326 				      struct bpf_insn *insn,
14327 				      struct bpf_reg_state *dst_reg,
14328 				      struct bpf_reg_state src_reg)
14329 {
14330 	u8 opcode = BPF_OP(insn->code);
14331 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
14332 	int ret;
14333 
14334 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
14335 		__mark_reg_unknown(env, dst_reg);
14336 		return 0;
14337 	}
14338 
14339 	if (sanitize_needed(opcode)) {
14340 		ret = sanitize_val_alu(env, insn);
14341 		if (ret < 0)
14342 			return sanitize_err(env, insn, ret, NULL, NULL);
14343 	}
14344 
14345 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
14346 	 * There are two classes of instructions: The first class we track both
14347 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
14348 	 * greatest amount of precision when alu operations are mixed with jmp32
14349 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
14350 	 * and BPF_OR. This is possible because these ops have fairly easy to
14351 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
14352 	 * See alu32 verifier tests for examples. The second class of
14353 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
14354 	 * with regards to tracking sign/unsigned bounds because the bits may
14355 	 * cross subreg boundaries in the alu64 case. When this happens we mark
14356 	 * the reg unbounded in the subreg bound space and use the resulting
14357 	 * tnum to calculate an approximation of the sign/unsigned bounds.
14358 	 */
14359 	switch (opcode) {
14360 	case BPF_ADD:
14361 		scalar32_min_max_add(dst_reg, &src_reg);
14362 		scalar_min_max_add(dst_reg, &src_reg);
14363 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
14364 		break;
14365 	case BPF_SUB:
14366 		scalar32_min_max_sub(dst_reg, &src_reg);
14367 		scalar_min_max_sub(dst_reg, &src_reg);
14368 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
14369 		break;
14370 	case BPF_MUL:
14371 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
14372 		scalar32_min_max_mul(dst_reg, &src_reg);
14373 		scalar_min_max_mul(dst_reg, &src_reg);
14374 		break;
14375 	case BPF_AND:
14376 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
14377 		scalar32_min_max_and(dst_reg, &src_reg);
14378 		scalar_min_max_and(dst_reg, &src_reg);
14379 		break;
14380 	case BPF_OR:
14381 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
14382 		scalar32_min_max_or(dst_reg, &src_reg);
14383 		scalar_min_max_or(dst_reg, &src_reg);
14384 		break;
14385 	case BPF_XOR:
14386 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
14387 		scalar32_min_max_xor(dst_reg, &src_reg);
14388 		scalar_min_max_xor(dst_reg, &src_reg);
14389 		break;
14390 	case BPF_LSH:
14391 		if (alu32)
14392 			scalar32_min_max_lsh(dst_reg, &src_reg);
14393 		else
14394 			scalar_min_max_lsh(dst_reg, &src_reg);
14395 		break;
14396 	case BPF_RSH:
14397 		if (alu32)
14398 			scalar32_min_max_rsh(dst_reg, &src_reg);
14399 		else
14400 			scalar_min_max_rsh(dst_reg, &src_reg);
14401 		break;
14402 	case BPF_ARSH:
14403 		if (alu32)
14404 			scalar32_min_max_arsh(dst_reg, &src_reg);
14405 		else
14406 			scalar_min_max_arsh(dst_reg, &src_reg);
14407 		break;
14408 	default:
14409 		break;
14410 	}
14411 
14412 	/* ALU32 ops are zero extended into 64bit register */
14413 	if (alu32)
14414 		zext_32_to_64(dst_reg);
14415 	reg_bounds_sync(dst_reg);
14416 	return 0;
14417 }
14418 
14419 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
14420  * and var_off.
14421  */
14422 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
14423 				   struct bpf_insn *insn)
14424 {
14425 	struct bpf_verifier_state *vstate = env->cur_state;
14426 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14427 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
14428 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
14429 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
14430 	u8 opcode = BPF_OP(insn->code);
14431 	int err;
14432 
14433 	dst_reg = &regs[insn->dst_reg];
14434 	src_reg = NULL;
14435 
14436 	if (dst_reg->type == PTR_TO_ARENA) {
14437 		struct bpf_insn_aux_data *aux = cur_aux(env);
14438 
14439 		if (BPF_CLASS(insn->code) == BPF_ALU64)
14440 			/*
14441 			 * 32-bit operations zero upper bits automatically.
14442 			 * 64-bit operations need to be converted to 32.
14443 			 */
14444 			aux->needs_zext = true;
14445 
14446 		/* Any arithmetic operations are allowed on arena pointers */
14447 		return 0;
14448 	}
14449 
14450 	if (dst_reg->type != SCALAR_VALUE)
14451 		ptr_reg = dst_reg;
14452 
14453 	if (BPF_SRC(insn->code) == BPF_X) {
14454 		src_reg = &regs[insn->src_reg];
14455 		if (src_reg->type != SCALAR_VALUE) {
14456 			if (dst_reg->type != SCALAR_VALUE) {
14457 				/* Combining two pointers by any ALU op yields
14458 				 * an arbitrary scalar. Disallow all math except
14459 				 * pointer subtraction
14460 				 */
14461 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14462 					mark_reg_unknown(env, regs, insn->dst_reg);
14463 					return 0;
14464 				}
14465 				verbose(env, "R%d pointer %s pointer prohibited\n",
14466 					insn->dst_reg,
14467 					bpf_alu_string[opcode >> 4]);
14468 				return -EACCES;
14469 			} else {
14470 				/* scalar += pointer
14471 				 * This is legal, but we have to reverse our
14472 				 * src/dest handling in computing the range
14473 				 */
14474 				err = mark_chain_precision(env, insn->dst_reg);
14475 				if (err)
14476 					return err;
14477 				return adjust_ptr_min_max_vals(env, insn,
14478 							       src_reg, dst_reg);
14479 			}
14480 		} else if (ptr_reg) {
14481 			/* pointer += scalar */
14482 			err = mark_chain_precision(env, insn->src_reg);
14483 			if (err)
14484 				return err;
14485 			return adjust_ptr_min_max_vals(env, insn,
14486 						       dst_reg, src_reg);
14487 		} else if (dst_reg->precise) {
14488 			/* if dst_reg is precise, src_reg should be precise as well */
14489 			err = mark_chain_precision(env, insn->src_reg);
14490 			if (err)
14491 				return err;
14492 		}
14493 	} else {
14494 		/* Pretend the src is a reg with a known value, since we only
14495 		 * need to be able to read from this state.
14496 		 */
14497 		off_reg.type = SCALAR_VALUE;
14498 		__mark_reg_known(&off_reg, insn->imm);
14499 		src_reg = &off_reg;
14500 		if (ptr_reg) /* pointer += K */
14501 			return adjust_ptr_min_max_vals(env, insn,
14502 						       ptr_reg, src_reg);
14503 	}
14504 
14505 	/* Got here implies adding two SCALAR_VALUEs */
14506 	if (WARN_ON_ONCE(ptr_reg)) {
14507 		print_verifier_state(env, state, true);
14508 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
14509 		return -EINVAL;
14510 	}
14511 	if (WARN_ON(!src_reg)) {
14512 		print_verifier_state(env, state, true);
14513 		verbose(env, "verifier internal error: no src_reg\n");
14514 		return -EINVAL;
14515 	}
14516 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
14517 	if (err)
14518 		return err;
14519 	/*
14520 	 * Compilers can generate the code
14521 	 * r1 = r2
14522 	 * r1 += 0x1
14523 	 * if r2 < 1000 goto ...
14524 	 * use r1 in memory access
14525 	 * So for 64-bit alu remember constant delta between r2 and r1 and
14526 	 * update r1 after 'if' condition.
14527 	 */
14528 	if (env->bpf_capable &&
14529 	    BPF_OP(insn->code) == BPF_ADD && !alu32 &&
14530 	    dst_reg->id && is_reg_const(src_reg, false)) {
14531 		u64 val = reg_const_value(src_reg, false);
14532 
14533 		if ((dst_reg->id & BPF_ADD_CONST) ||
14534 		    /* prevent overflow in sync_linked_regs() later */
14535 		    val > (u32)S32_MAX) {
14536 			/*
14537 			 * If the register already went through rX += val
14538 			 * we cannot accumulate another val into rx->off.
14539 			 */
14540 			dst_reg->off = 0;
14541 			dst_reg->id = 0;
14542 		} else {
14543 			dst_reg->id |= BPF_ADD_CONST;
14544 			dst_reg->off = val;
14545 		}
14546 	} else {
14547 		/*
14548 		 * Make sure ID is cleared otherwise dst_reg min/max could be
14549 		 * incorrectly propagated into other registers by sync_linked_regs()
14550 		 */
14551 		dst_reg->id = 0;
14552 	}
14553 	return 0;
14554 }
14555 
14556 /* check validity of 32-bit and 64-bit arithmetic operations */
14557 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
14558 {
14559 	struct bpf_reg_state *regs = cur_regs(env);
14560 	u8 opcode = BPF_OP(insn->code);
14561 	int err;
14562 
14563 	if (opcode == BPF_END || opcode == BPF_NEG) {
14564 		if (opcode == BPF_NEG) {
14565 			if (BPF_SRC(insn->code) != BPF_K ||
14566 			    insn->src_reg != BPF_REG_0 ||
14567 			    insn->off != 0 || insn->imm != 0) {
14568 				verbose(env, "BPF_NEG uses reserved fields\n");
14569 				return -EINVAL;
14570 			}
14571 		} else {
14572 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
14573 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
14574 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
14575 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
14576 				verbose(env, "BPF_END uses reserved fields\n");
14577 				return -EINVAL;
14578 			}
14579 		}
14580 
14581 		/* check src operand */
14582 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14583 		if (err)
14584 			return err;
14585 
14586 		if (is_pointer_value(env, insn->dst_reg)) {
14587 			verbose(env, "R%d pointer arithmetic prohibited\n",
14588 				insn->dst_reg);
14589 			return -EACCES;
14590 		}
14591 
14592 		/* check dest operand */
14593 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
14594 		if (err)
14595 			return err;
14596 
14597 	} else if (opcode == BPF_MOV) {
14598 
14599 		if (BPF_SRC(insn->code) == BPF_X) {
14600 			if (BPF_CLASS(insn->code) == BPF_ALU) {
14601 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
14602 				    insn->imm) {
14603 					verbose(env, "BPF_MOV uses reserved fields\n");
14604 					return -EINVAL;
14605 				}
14606 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
14607 				if (insn->imm != 1 && insn->imm != 1u << 16) {
14608 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
14609 					return -EINVAL;
14610 				}
14611 				if (!env->prog->aux->arena) {
14612 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
14613 					return -EINVAL;
14614 				}
14615 			} else {
14616 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
14617 				     insn->off != 32) || insn->imm) {
14618 					verbose(env, "BPF_MOV uses reserved fields\n");
14619 					return -EINVAL;
14620 				}
14621 			}
14622 
14623 			/* check src operand */
14624 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14625 			if (err)
14626 				return err;
14627 		} else {
14628 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
14629 				verbose(env, "BPF_MOV uses reserved fields\n");
14630 				return -EINVAL;
14631 			}
14632 		}
14633 
14634 		/* check dest operand, mark as required later */
14635 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14636 		if (err)
14637 			return err;
14638 
14639 		if (BPF_SRC(insn->code) == BPF_X) {
14640 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
14641 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
14642 
14643 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
14644 				if (insn->imm) {
14645 					/* off == BPF_ADDR_SPACE_CAST */
14646 					mark_reg_unknown(env, regs, insn->dst_reg);
14647 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
14648 						dst_reg->type = PTR_TO_ARENA;
14649 						/* PTR_TO_ARENA is 32-bit */
14650 						dst_reg->subreg_def = env->insn_idx + 1;
14651 					}
14652 				} else if (insn->off == 0) {
14653 					/* case: R1 = R2
14654 					 * copy register state to dest reg
14655 					 */
14656 					assign_scalar_id_before_mov(env, src_reg);
14657 					copy_register_state(dst_reg, src_reg);
14658 					dst_reg->live |= REG_LIVE_WRITTEN;
14659 					dst_reg->subreg_def = DEF_NOT_SUBREG;
14660 				} else {
14661 					/* case: R1 = (s8, s16 s32)R2 */
14662 					if (is_pointer_value(env, insn->src_reg)) {
14663 						verbose(env,
14664 							"R%d sign-extension part of pointer\n",
14665 							insn->src_reg);
14666 						return -EACCES;
14667 					} else if (src_reg->type == SCALAR_VALUE) {
14668 						bool no_sext;
14669 
14670 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14671 						if (no_sext)
14672 							assign_scalar_id_before_mov(env, src_reg);
14673 						copy_register_state(dst_reg, src_reg);
14674 						if (!no_sext)
14675 							dst_reg->id = 0;
14676 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
14677 						dst_reg->live |= REG_LIVE_WRITTEN;
14678 						dst_reg->subreg_def = DEF_NOT_SUBREG;
14679 					} else {
14680 						mark_reg_unknown(env, regs, insn->dst_reg);
14681 					}
14682 				}
14683 			} else {
14684 				/* R1 = (u32) R2 */
14685 				if (is_pointer_value(env, insn->src_reg)) {
14686 					verbose(env,
14687 						"R%d partial copy of pointer\n",
14688 						insn->src_reg);
14689 					return -EACCES;
14690 				} else if (src_reg->type == SCALAR_VALUE) {
14691 					if (insn->off == 0) {
14692 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
14693 
14694 						if (is_src_reg_u32)
14695 							assign_scalar_id_before_mov(env, src_reg);
14696 						copy_register_state(dst_reg, src_reg);
14697 						/* Make sure ID is cleared if src_reg is not in u32
14698 						 * range otherwise dst_reg min/max could be incorrectly
14699 						 * propagated into src_reg by sync_linked_regs()
14700 						 */
14701 						if (!is_src_reg_u32)
14702 							dst_reg->id = 0;
14703 						dst_reg->live |= REG_LIVE_WRITTEN;
14704 						dst_reg->subreg_def = env->insn_idx + 1;
14705 					} else {
14706 						/* case: W1 = (s8, s16)W2 */
14707 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14708 
14709 						if (no_sext)
14710 							assign_scalar_id_before_mov(env, src_reg);
14711 						copy_register_state(dst_reg, src_reg);
14712 						if (!no_sext)
14713 							dst_reg->id = 0;
14714 						dst_reg->live |= REG_LIVE_WRITTEN;
14715 						dst_reg->subreg_def = env->insn_idx + 1;
14716 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
14717 					}
14718 				} else {
14719 					mark_reg_unknown(env, regs,
14720 							 insn->dst_reg);
14721 				}
14722 				zext_32_to_64(dst_reg);
14723 				reg_bounds_sync(dst_reg);
14724 			}
14725 		} else {
14726 			/* case: R = imm
14727 			 * remember the value we stored into this reg
14728 			 */
14729 			/* clear any state __mark_reg_known doesn't set */
14730 			mark_reg_unknown(env, regs, insn->dst_reg);
14731 			regs[insn->dst_reg].type = SCALAR_VALUE;
14732 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
14733 				__mark_reg_known(regs + insn->dst_reg,
14734 						 insn->imm);
14735 			} else {
14736 				__mark_reg_known(regs + insn->dst_reg,
14737 						 (u32)insn->imm);
14738 			}
14739 		}
14740 
14741 	} else if (opcode > BPF_END) {
14742 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
14743 		return -EINVAL;
14744 
14745 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
14746 
14747 		if (BPF_SRC(insn->code) == BPF_X) {
14748 			if (insn->imm != 0 || insn->off > 1 ||
14749 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14750 				verbose(env, "BPF_ALU uses reserved fields\n");
14751 				return -EINVAL;
14752 			}
14753 			/* check src1 operand */
14754 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14755 			if (err)
14756 				return err;
14757 		} else {
14758 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
14759 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14760 				verbose(env, "BPF_ALU uses reserved fields\n");
14761 				return -EINVAL;
14762 			}
14763 		}
14764 
14765 		/* check src2 operand */
14766 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14767 		if (err)
14768 			return err;
14769 
14770 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
14771 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
14772 			verbose(env, "div by zero\n");
14773 			return -EINVAL;
14774 		}
14775 
14776 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
14777 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
14778 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
14779 
14780 			if (insn->imm < 0 || insn->imm >= size) {
14781 				verbose(env, "invalid shift %d\n", insn->imm);
14782 				return -EINVAL;
14783 			}
14784 		}
14785 
14786 		/* check dest operand */
14787 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14788 		err = err ?: adjust_reg_min_max_vals(env, insn);
14789 		if (err)
14790 			return err;
14791 	}
14792 
14793 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
14794 }
14795 
14796 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
14797 				   struct bpf_reg_state *dst_reg,
14798 				   enum bpf_reg_type type,
14799 				   bool range_right_open)
14800 {
14801 	struct bpf_func_state *state;
14802 	struct bpf_reg_state *reg;
14803 	int new_range;
14804 
14805 	if (dst_reg->off < 0 ||
14806 	    (dst_reg->off == 0 && range_right_open))
14807 		/* This doesn't give us any range */
14808 		return;
14809 
14810 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
14811 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
14812 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
14813 		 * than pkt_end, but that's because it's also less than pkt.
14814 		 */
14815 		return;
14816 
14817 	new_range = dst_reg->off;
14818 	if (range_right_open)
14819 		new_range++;
14820 
14821 	/* Examples for register markings:
14822 	 *
14823 	 * pkt_data in dst register:
14824 	 *
14825 	 *   r2 = r3;
14826 	 *   r2 += 8;
14827 	 *   if (r2 > pkt_end) goto <handle exception>
14828 	 *   <access okay>
14829 	 *
14830 	 *   r2 = r3;
14831 	 *   r2 += 8;
14832 	 *   if (r2 < pkt_end) goto <access okay>
14833 	 *   <handle exception>
14834 	 *
14835 	 *   Where:
14836 	 *     r2 == dst_reg, pkt_end == src_reg
14837 	 *     r2=pkt(id=n,off=8,r=0)
14838 	 *     r3=pkt(id=n,off=0,r=0)
14839 	 *
14840 	 * pkt_data in src register:
14841 	 *
14842 	 *   r2 = r3;
14843 	 *   r2 += 8;
14844 	 *   if (pkt_end >= r2) goto <access okay>
14845 	 *   <handle exception>
14846 	 *
14847 	 *   r2 = r3;
14848 	 *   r2 += 8;
14849 	 *   if (pkt_end <= r2) goto <handle exception>
14850 	 *   <access okay>
14851 	 *
14852 	 *   Where:
14853 	 *     pkt_end == dst_reg, r2 == src_reg
14854 	 *     r2=pkt(id=n,off=8,r=0)
14855 	 *     r3=pkt(id=n,off=0,r=0)
14856 	 *
14857 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
14858 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
14859 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
14860 	 * the check.
14861 	 */
14862 
14863 	/* If our ids match, then we must have the same max_value.  And we
14864 	 * don't care about the other reg's fixed offset, since if it's too big
14865 	 * the range won't allow anything.
14866 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
14867 	 */
14868 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14869 		if (reg->type == type && reg->id == dst_reg->id)
14870 			/* keep the maximum range already checked */
14871 			reg->range = max(reg->range, new_range);
14872 	}));
14873 }
14874 
14875 /*
14876  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
14877  */
14878 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14879 				  u8 opcode, bool is_jmp32)
14880 {
14881 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
14882 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
14883 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
14884 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
14885 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
14886 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
14887 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
14888 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
14889 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
14890 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
14891 
14892 	switch (opcode) {
14893 	case BPF_JEQ:
14894 		/* constants, umin/umax and smin/smax checks would be
14895 		 * redundant in this case because they all should match
14896 		 */
14897 		if (tnum_is_const(t1) && tnum_is_const(t2))
14898 			return t1.value == t2.value;
14899 		/* non-overlapping ranges */
14900 		if (umin1 > umax2 || umax1 < umin2)
14901 			return 0;
14902 		if (smin1 > smax2 || smax1 < smin2)
14903 			return 0;
14904 		if (!is_jmp32) {
14905 			/* if 64-bit ranges are inconclusive, see if we can
14906 			 * utilize 32-bit subrange knowledge to eliminate
14907 			 * branches that can't be taken a priori
14908 			 */
14909 			if (reg1->u32_min_value > reg2->u32_max_value ||
14910 			    reg1->u32_max_value < reg2->u32_min_value)
14911 				return 0;
14912 			if (reg1->s32_min_value > reg2->s32_max_value ||
14913 			    reg1->s32_max_value < reg2->s32_min_value)
14914 				return 0;
14915 		}
14916 		break;
14917 	case BPF_JNE:
14918 		/* constants, umin/umax and smin/smax checks would be
14919 		 * redundant in this case because they all should match
14920 		 */
14921 		if (tnum_is_const(t1) && tnum_is_const(t2))
14922 			return t1.value != t2.value;
14923 		/* non-overlapping ranges */
14924 		if (umin1 > umax2 || umax1 < umin2)
14925 			return 1;
14926 		if (smin1 > smax2 || smax1 < smin2)
14927 			return 1;
14928 		if (!is_jmp32) {
14929 			/* if 64-bit ranges are inconclusive, see if we can
14930 			 * utilize 32-bit subrange knowledge to eliminate
14931 			 * branches that can't be taken a priori
14932 			 */
14933 			if (reg1->u32_min_value > reg2->u32_max_value ||
14934 			    reg1->u32_max_value < reg2->u32_min_value)
14935 				return 1;
14936 			if (reg1->s32_min_value > reg2->s32_max_value ||
14937 			    reg1->s32_max_value < reg2->s32_min_value)
14938 				return 1;
14939 		}
14940 		break;
14941 	case BPF_JSET:
14942 		if (!is_reg_const(reg2, is_jmp32)) {
14943 			swap(reg1, reg2);
14944 			swap(t1, t2);
14945 		}
14946 		if (!is_reg_const(reg2, is_jmp32))
14947 			return -1;
14948 		if ((~t1.mask & t1.value) & t2.value)
14949 			return 1;
14950 		if (!((t1.mask | t1.value) & t2.value))
14951 			return 0;
14952 		break;
14953 	case BPF_JGT:
14954 		if (umin1 > umax2)
14955 			return 1;
14956 		else if (umax1 <= umin2)
14957 			return 0;
14958 		break;
14959 	case BPF_JSGT:
14960 		if (smin1 > smax2)
14961 			return 1;
14962 		else if (smax1 <= smin2)
14963 			return 0;
14964 		break;
14965 	case BPF_JLT:
14966 		if (umax1 < umin2)
14967 			return 1;
14968 		else if (umin1 >= umax2)
14969 			return 0;
14970 		break;
14971 	case BPF_JSLT:
14972 		if (smax1 < smin2)
14973 			return 1;
14974 		else if (smin1 >= smax2)
14975 			return 0;
14976 		break;
14977 	case BPF_JGE:
14978 		if (umin1 >= umax2)
14979 			return 1;
14980 		else if (umax1 < umin2)
14981 			return 0;
14982 		break;
14983 	case BPF_JSGE:
14984 		if (smin1 >= smax2)
14985 			return 1;
14986 		else if (smax1 < smin2)
14987 			return 0;
14988 		break;
14989 	case BPF_JLE:
14990 		if (umax1 <= umin2)
14991 			return 1;
14992 		else if (umin1 > umax2)
14993 			return 0;
14994 		break;
14995 	case BPF_JSLE:
14996 		if (smax1 <= smin2)
14997 			return 1;
14998 		else if (smin1 > smax2)
14999 			return 0;
15000 		break;
15001 	}
15002 
15003 	return -1;
15004 }
15005 
15006 static int flip_opcode(u32 opcode)
15007 {
15008 	/* How can we transform "a <op> b" into "b <op> a"? */
15009 	static const u8 opcode_flip[16] = {
15010 		/* these stay the same */
15011 		[BPF_JEQ  >> 4] = BPF_JEQ,
15012 		[BPF_JNE  >> 4] = BPF_JNE,
15013 		[BPF_JSET >> 4] = BPF_JSET,
15014 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
15015 		[BPF_JGE  >> 4] = BPF_JLE,
15016 		[BPF_JGT  >> 4] = BPF_JLT,
15017 		[BPF_JLE  >> 4] = BPF_JGE,
15018 		[BPF_JLT  >> 4] = BPF_JGT,
15019 		[BPF_JSGE >> 4] = BPF_JSLE,
15020 		[BPF_JSGT >> 4] = BPF_JSLT,
15021 		[BPF_JSLE >> 4] = BPF_JSGE,
15022 		[BPF_JSLT >> 4] = BPF_JSGT
15023 	};
15024 	return opcode_flip[opcode >> 4];
15025 }
15026 
15027 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
15028 				   struct bpf_reg_state *src_reg,
15029 				   u8 opcode)
15030 {
15031 	struct bpf_reg_state *pkt;
15032 
15033 	if (src_reg->type == PTR_TO_PACKET_END) {
15034 		pkt = dst_reg;
15035 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
15036 		pkt = src_reg;
15037 		opcode = flip_opcode(opcode);
15038 	} else {
15039 		return -1;
15040 	}
15041 
15042 	if (pkt->range >= 0)
15043 		return -1;
15044 
15045 	switch (opcode) {
15046 	case BPF_JLE:
15047 		/* pkt <= pkt_end */
15048 		fallthrough;
15049 	case BPF_JGT:
15050 		/* pkt > pkt_end */
15051 		if (pkt->range == BEYOND_PKT_END)
15052 			/* pkt has at last one extra byte beyond pkt_end */
15053 			return opcode == BPF_JGT;
15054 		break;
15055 	case BPF_JLT:
15056 		/* pkt < pkt_end */
15057 		fallthrough;
15058 	case BPF_JGE:
15059 		/* pkt >= pkt_end */
15060 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
15061 			return opcode == BPF_JGE;
15062 		break;
15063 	}
15064 	return -1;
15065 }
15066 
15067 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
15068  * and return:
15069  *  1 - branch will be taken and "goto target" will be executed
15070  *  0 - branch will not be taken and fall-through to next insn
15071  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
15072  *      range [0,10]
15073  */
15074 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15075 			   u8 opcode, bool is_jmp32)
15076 {
15077 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
15078 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
15079 
15080 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
15081 		u64 val;
15082 
15083 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
15084 		if (!is_reg_const(reg2, is_jmp32)) {
15085 			opcode = flip_opcode(opcode);
15086 			swap(reg1, reg2);
15087 		}
15088 		/* and ensure that reg2 is a constant */
15089 		if (!is_reg_const(reg2, is_jmp32))
15090 			return -1;
15091 
15092 		if (!reg_not_null(reg1))
15093 			return -1;
15094 
15095 		/* If pointer is valid tests against zero will fail so we can
15096 		 * use this to direct branch taken.
15097 		 */
15098 		val = reg_const_value(reg2, is_jmp32);
15099 		if (val != 0)
15100 			return -1;
15101 
15102 		switch (opcode) {
15103 		case BPF_JEQ:
15104 			return 0;
15105 		case BPF_JNE:
15106 			return 1;
15107 		default:
15108 			return -1;
15109 		}
15110 	}
15111 
15112 	/* now deal with two scalars, but not necessarily constants */
15113 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
15114 }
15115 
15116 /* Opcode that corresponds to a *false* branch condition.
15117  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
15118  */
15119 static u8 rev_opcode(u8 opcode)
15120 {
15121 	switch (opcode) {
15122 	case BPF_JEQ:		return BPF_JNE;
15123 	case BPF_JNE:		return BPF_JEQ;
15124 	/* JSET doesn't have it's reverse opcode in BPF, so add
15125 	 * BPF_X flag to denote the reverse of that operation
15126 	 */
15127 	case BPF_JSET:		return BPF_JSET | BPF_X;
15128 	case BPF_JSET | BPF_X:	return BPF_JSET;
15129 	case BPF_JGE:		return BPF_JLT;
15130 	case BPF_JGT:		return BPF_JLE;
15131 	case BPF_JLE:		return BPF_JGT;
15132 	case BPF_JLT:		return BPF_JGE;
15133 	case BPF_JSGE:		return BPF_JSLT;
15134 	case BPF_JSGT:		return BPF_JSLE;
15135 	case BPF_JSLE:		return BPF_JSGT;
15136 	case BPF_JSLT:		return BPF_JSGE;
15137 	default:		return 0;
15138 	}
15139 }
15140 
15141 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
15142 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15143 				u8 opcode, bool is_jmp32)
15144 {
15145 	struct tnum t;
15146 	u64 val;
15147 
15148 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
15149 	switch (opcode) {
15150 	case BPF_JGE:
15151 	case BPF_JGT:
15152 	case BPF_JSGE:
15153 	case BPF_JSGT:
15154 		opcode = flip_opcode(opcode);
15155 		swap(reg1, reg2);
15156 		break;
15157 	default:
15158 		break;
15159 	}
15160 
15161 	switch (opcode) {
15162 	case BPF_JEQ:
15163 		if (is_jmp32) {
15164 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
15165 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
15166 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
15167 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
15168 			reg2->u32_min_value = reg1->u32_min_value;
15169 			reg2->u32_max_value = reg1->u32_max_value;
15170 			reg2->s32_min_value = reg1->s32_min_value;
15171 			reg2->s32_max_value = reg1->s32_max_value;
15172 
15173 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
15174 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
15175 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
15176 		} else {
15177 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
15178 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
15179 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
15180 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
15181 			reg2->umin_value = reg1->umin_value;
15182 			reg2->umax_value = reg1->umax_value;
15183 			reg2->smin_value = reg1->smin_value;
15184 			reg2->smax_value = reg1->smax_value;
15185 
15186 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
15187 			reg2->var_off = reg1->var_off;
15188 		}
15189 		break;
15190 	case BPF_JNE:
15191 		if (!is_reg_const(reg2, is_jmp32))
15192 			swap(reg1, reg2);
15193 		if (!is_reg_const(reg2, is_jmp32))
15194 			break;
15195 
15196 		/* try to recompute the bound of reg1 if reg2 is a const and
15197 		 * is exactly the edge of reg1.
15198 		 */
15199 		val = reg_const_value(reg2, is_jmp32);
15200 		if (is_jmp32) {
15201 			/* u32_min_value is not equal to 0xffffffff at this point,
15202 			 * because otherwise u32_max_value is 0xffffffff as well,
15203 			 * in such a case both reg1 and reg2 would be constants,
15204 			 * jump would be predicted and reg_set_min_max() won't
15205 			 * be called.
15206 			 *
15207 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
15208 			 * below.
15209 			 */
15210 			if (reg1->u32_min_value == (u32)val)
15211 				reg1->u32_min_value++;
15212 			if (reg1->u32_max_value == (u32)val)
15213 				reg1->u32_max_value--;
15214 			if (reg1->s32_min_value == (s32)val)
15215 				reg1->s32_min_value++;
15216 			if (reg1->s32_max_value == (s32)val)
15217 				reg1->s32_max_value--;
15218 		} else {
15219 			if (reg1->umin_value == (u64)val)
15220 				reg1->umin_value++;
15221 			if (reg1->umax_value == (u64)val)
15222 				reg1->umax_value--;
15223 			if (reg1->smin_value == (s64)val)
15224 				reg1->smin_value++;
15225 			if (reg1->smax_value == (s64)val)
15226 				reg1->smax_value--;
15227 		}
15228 		break;
15229 	case BPF_JSET:
15230 		if (!is_reg_const(reg2, is_jmp32))
15231 			swap(reg1, reg2);
15232 		if (!is_reg_const(reg2, is_jmp32))
15233 			break;
15234 		val = reg_const_value(reg2, is_jmp32);
15235 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
15236 		 * requires single bit to learn something useful. E.g., if we
15237 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
15238 		 * are actually set? We can learn something definite only if
15239 		 * it's a single-bit value to begin with.
15240 		 *
15241 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
15242 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
15243 		 * bit 1 is set, which we can readily use in adjustments.
15244 		 */
15245 		if (!is_power_of_2(val))
15246 			break;
15247 		if (is_jmp32) {
15248 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
15249 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
15250 		} else {
15251 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
15252 		}
15253 		break;
15254 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
15255 		if (!is_reg_const(reg2, is_jmp32))
15256 			swap(reg1, reg2);
15257 		if (!is_reg_const(reg2, is_jmp32))
15258 			break;
15259 		val = reg_const_value(reg2, is_jmp32);
15260 		if (is_jmp32) {
15261 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
15262 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
15263 		} else {
15264 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
15265 		}
15266 		break;
15267 	case BPF_JLE:
15268 		if (is_jmp32) {
15269 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
15270 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
15271 		} else {
15272 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
15273 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
15274 		}
15275 		break;
15276 	case BPF_JLT:
15277 		if (is_jmp32) {
15278 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
15279 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
15280 		} else {
15281 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
15282 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
15283 		}
15284 		break;
15285 	case BPF_JSLE:
15286 		if (is_jmp32) {
15287 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
15288 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
15289 		} else {
15290 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
15291 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
15292 		}
15293 		break;
15294 	case BPF_JSLT:
15295 		if (is_jmp32) {
15296 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
15297 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
15298 		} else {
15299 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
15300 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
15301 		}
15302 		break;
15303 	default:
15304 		return;
15305 	}
15306 }
15307 
15308 /* Adjusts the register min/max values in the case that the dst_reg and
15309  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
15310  * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
15311  * Technically we can do similar adjustments for pointers to the same object,
15312  * but we don't support that right now.
15313  */
15314 static int reg_set_min_max(struct bpf_verifier_env *env,
15315 			   struct bpf_reg_state *true_reg1,
15316 			   struct bpf_reg_state *true_reg2,
15317 			   struct bpf_reg_state *false_reg1,
15318 			   struct bpf_reg_state *false_reg2,
15319 			   u8 opcode, bool is_jmp32)
15320 {
15321 	int err;
15322 
15323 	/* If either register is a pointer, we can't learn anything about its
15324 	 * variable offset from the compare (unless they were a pointer into
15325 	 * the same object, but we don't bother with that).
15326 	 */
15327 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
15328 		return 0;
15329 
15330 	/* fallthrough (FALSE) branch */
15331 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
15332 	reg_bounds_sync(false_reg1);
15333 	reg_bounds_sync(false_reg2);
15334 
15335 	/* jump (TRUE) branch */
15336 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
15337 	reg_bounds_sync(true_reg1);
15338 	reg_bounds_sync(true_reg2);
15339 
15340 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
15341 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
15342 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
15343 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
15344 	return err;
15345 }
15346 
15347 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
15348 				 struct bpf_reg_state *reg, u32 id,
15349 				 bool is_null)
15350 {
15351 	if (type_may_be_null(reg->type) && reg->id == id &&
15352 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
15353 		/* Old offset (both fixed and variable parts) should have been
15354 		 * known-zero, because we don't allow pointer arithmetic on
15355 		 * pointers that might be NULL. If we see this happening, don't
15356 		 * convert the register.
15357 		 *
15358 		 * But in some cases, some helpers that return local kptrs
15359 		 * advance offset for the returned pointer. In those cases, it
15360 		 * is fine to expect to see reg->off.
15361 		 */
15362 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
15363 			return;
15364 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
15365 		    WARN_ON_ONCE(reg->off))
15366 			return;
15367 
15368 		if (is_null) {
15369 			reg->type = SCALAR_VALUE;
15370 			/* We don't need id and ref_obj_id from this point
15371 			 * onwards anymore, thus we should better reset it,
15372 			 * so that state pruning has chances to take effect.
15373 			 */
15374 			reg->id = 0;
15375 			reg->ref_obj_id = 0;
15376 
15377 			return;
15378 		}
15379 
15380 		mark_ptr_not_null_reg(reg);
15381 
15382 		if (!reg_may_point_to_spin_lock(reg)) {
15383 			/* For not-NULL ptr, reg->ref_obj_id will be reset
15384 			 * in release_reference().
15385 			 *
15386 			 * reg->id is still used by spin_lock ptr. Other
15387 			 * than spin_lock ptr type, reg->id can be reset.
15388 			 */
15389 			reg->id = 0;
15390 		}
15391 	}
15392 }
15393 
15394 /* The logic is similar to find_good_pkt_pointers(), both could eventually
15395  * be folded together at some point.
15396  */
15397 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
15398 				  bool is_null)
15399 {
15400 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
15401 	struct bpf_reg_state *regs = state->regs, *reg;
15402 	u32 ref_obj_id = regs[regno].ref_obj_id;
15403 	u32 id = regs[regno].id;
15404 
15405 	if (ref_obj_id && ref_obj_id == id && is_null)
15406 		/* regs[regno] is in the " == NULL" branch.
15407 		 * No one could have freed the reference state before
15408 		 * doing the NULL check.
15409 		 */
15410 		WARN_ON_ONCE(release_reference_state(state, id));
15411 
15412 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15413 		mark_ptr_or_null_reg(state, reg, id, is_null);
15414 	}));
15415 }
15416 
15417 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
15418 				   struct bpf_reg_state *dst_reg,
15419 				   struct bpf_reg_state *src_reg,
15420 				   struct bpf_verifier_state *this_branch,
15421 				   struct bpf_verifier_state *other_branch)
15422 {
15423 	if (BPF_SRC(insn->code) != BPF_X)
15424 		return false;
15425 
15426 	/* Pointers are always 64-bit. */
15427 	if (BPF_CLASS(insn->code) == BPF_JMP32)
15428 		return false;
15429 
15430 	switch (BPF_OP(insn->code)) {
15431 	case BPF_JGT:
15432 		if ((dst_reg->type == PTR_TO_PACKET &&
15433 		     src_reg->type == PTR_TO_PACKET_END) ||
15434 		    (dst_reg->type == PTR_TO_PACKET_META &&
15435 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15436 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
15437 			find_good_pkt_pointers(this_branch, dst_reg,
15438 					       dst_reg->type, false);
15439 			mark_pkt_end(other_branch, insn->dst_reg, true);
15440 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15441 			    src_reg->type == PTR_TO_PACKET) ||
15442 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15443 			    src_reg->type == PTR_TO_PACKET_META)) {
15444 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
15445 			find_good_pkt_pointers(other_branch, src_reg,
15446 					       src_reg->type, true);
15447 			mark_pkt_end(this_branch, insn->src_reg, false);
15448 		} else {
15449 			return false;
15450 		}
15451 		break;
15452 	case BPF_JLT:
15453 		if ((dst_reg->type == PTR_TO_PACKET &&
15454 		     src_reg->type == PTR_TO_PACKET_END) ||
15455 		    (dst_reg->type == PTR_TO_PACKET_META &&
15456 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15457 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
15458 			find_good_pkt_pointers(other_branch, dst_reg,
15459 					       dst_reg->type, true);
15460 			mark_pkt_end(this_branch, insn->dst_reg, false);
15461 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15462 			    src_reg->type == PTR_TO_PACKET) ||
15463 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15464 			    src_reg->type == PTR_TO_PACKET_META)) {
15465 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
15466 			find_good_pkt_pointers(this_branch, src_reg,
15467 					       src_reg->type, false);
15468 			mark_pkt_end(other_branch, insn->src_reg, true);
15469 		} else {
15470 			return false;
15471 		}
15472 		break;
15473 	case BPF_JGE:
15474 		if ((dst_reg->type == PTR_TO_PACKET &&
15475 		     src_reg->type == PTR_TO_PACKET_END) ||
15476 		    (dst_reg->type == PTR_TO_PACKET_META &&
15477 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15478 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
15479 			find_good_pkt_pointers(this_branch, dst_reg,
15480 					       dst_reg->type, true);
15481 			mark_pkt_end(other_branch, insn->dst_reg, false);
15482 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15483 			    src_reg->type == PTR_TO_PACKET) ||
15484 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15485 			    src_reg->type == PTR_TO_PACKET_META)) {
15486 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
15487 			find_good_pkt_pointers(other_branch, src_reg,
15488 					       src_reg->type, false);
15489 			mark_pkt_end(this_branch, insn->src_reg, true);
15490 		} else {
15491 			return false;
15492 		}
15493 		break;
15494 	case BPF_JLE:
15495 		if ((dst_reg->type == PTR_TO_PACKET &&
15496 		     src_reg->type == PTR_TO_PACKET_END) ||
15497 		    (dst_reg->type == PTR_TO_PACKET_META &&
15498 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15499 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
15500 			find_good_pkt_pointers(other_branch, dst_reg,
15501 					       dst_reg->type, false);
15502 			mark_pkt_end(this_branch, insn->dst_reg, true);
15503 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15504 			    src_reg->type == PTR_TO_PACKET) ||
15505 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15506 			    src_reg->type == PTR_TO_PACKET_META)) {
15507 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
15508 			find_good_pkt_pointers(this_branch, src_reg,
15509 					       src_reg->type, true);
15510 			mark_pkt_end(other_branch, insn->src_reg, false);
15511 		} else {
15512 			return false;
15513 		}
15514 		break;
15515 	default:
15516 		return false;
15517 	}
15518 
15519 	return true;
15520 }
15521 
15522 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
15523 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
15524 {
15525 	struct linked_reg *e;
15526 
15527 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
15528 		return;
15529 
15530 	e = linked_regs_push(reg_set);
15531 	if (e) {
15532 		e->frameno = frameno;
15533 		e->is_reg = is_reg;
15534 		e->regno = spi_or_reg;
15535 	} else {
15536 		reg->id = 0;
15537 	}
15538 }
15539 
15540 /* For all R being scalar registers or spilled scalar registers
15541  * in verifier state, save R in linked_regs if R->id == id.
15542  * If there are too many Rs sharing same id, reset id for leftover Rs.
15543  */
15544 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id,
15545 				struct linked_regs *linked_regs)
15546 {
15547 	struct bpf_func_state *func;
15548 	struct bpf_reg_state *reg;
15549 	int i, j;
15550 
15551 	id = id & ~BPF_ADD_CONST;
15552 	for (i = vstate->curframe; i >= 0; i--) {
15553 		func = vstate->frame[i];
15554 		for (j = 0; j < BPF_REG_FP; j++) {
15555 			reg = &func->regs[j];
15556 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
15557 		}
15558 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
15559 			if (!is_spilled_reg(&func->stack[j]))
15560 				continue;
15561 			reg = &func->stack[j].spilled_ptr;
15562 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
15563 		}
15564 	}
15565 }
15566 
15567 /* For all R in linked_regs, copy known_reg range into R
15568  * if R->id == known_reg->id.
15569  */
15570 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg,
15571 			     struct linked_regs *linked_regs)
15572 {
15573 	struct bpf_reg_state fake_reg;
15574 	struct bpf_reg_state *reg;
15575 	struct linked_reg *e;
15576 	int i;
15577 
15578 	for (i = 0; i < linked_regs->cnt; ++i) {
15579 		e = &linked_regs->entries[i];
15580 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
15581 				: &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
15582 		if (reg->type != SCALAR_VALUE || reg == known_reg)
15583 			continue;
15584 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
15585 			continue;
15586 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
15587 		    reg->off == known_reg->off) {
15588 			s32 saved_subreg_def = reg->subreg_def;
15589 
15590 			copy_register_state(reg, known_reg);
15591 			reg->subreg_def = saved_subreg_def;
15592 		} else {
15593 			s32 saved_subreg_def = reg->subreg_def;
15594 			s32 saved_off = reg->off;
15595 
15596 			fake_reg.type = SCALAR_VALUE;
15597 			__mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off);
15598 
15599 			/* reg = known_reg; reg += delta */
15600 			copy_register_state(reg, known_reg);
15601 			/*
15602 			 * Must preserve off, id and add_const flag,
15603 			 * otherwise another sync_linked_regs() will be incorrect.
15604 			 */
15605 			reg->off = saved_off;
15606 			reg->subreg_def = saved_subreg_def;
15607 
15608 			scalar32_min_max_add(reg, &fake_reg);
15609 			scalar_min_max_add(reg, &fake_reg);
15610 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
15611 		}
15612 	}
15613 }
15614 
15615 static int check_cond_jmp_op(struct bpf_verifier_env *env,
15616 			     struct bpf_insn *insn, int *insn_idx)
15617 {
15618 	struct bpf_verifier_state *this_branch = env->cur_state;
15619 	struct bpf_verifier_state *other_branch;
15620 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
15621 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
15622 	struct bpf_reg_state *eq_branch_regs;
15623 	struct linked_regs linked_regs = {};
15624 	u8 opcode = BPF_OP(insn->code);
15625 	bool is_jmp32;
15626 	int pred = -1;
15627 	int err;
15628 
15629 	/* Only conditional jumps are expected to reach here. */
15630 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
15631 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
15632 		return -EINVAL;
15633 	}
15634 
15635 	if (opcode == BPF_JCOND) {
15636 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
15637 		int idx = *insn_idx;
15638 
15639 		if (insn->code != (BPF_JMP | BPF_JCOND) ||
15640 		    insn->src_reg != BPF_MAY_GOTO ||
15641 		    insn->dst_reg || insn->imm || insn->off == 0) {
15642 			verbose(env, "invalid may_goto off %d imm %d\n",
15643 				insn->off, insn->imm);
15644 			return -EINVAL;
15645 		}
15646 		prev_st = find_prev_entry(env, cur_st->parent, idx);
15647 
15648 		/* branch out 'fallthrough' insn as a new state to explore */
15649 		queued_st = push_stack(env, idx + 1, idx, false);
15650 		if (!queued_st)
15651 			return -ENOMEM;
15652 
15653 		queued_st->may_goto_depth++;
15654 		if (prev_st)
15655 			widen_imprecise_scalars(env, prev_st, queued_st);
15656 		*insn_idx += insn->off;
15657 		return 0;
15658 	}
15659 
15660 	/* check src2 operand */
15661 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15662 	if (err)
15663 		return err;
15664 
15665 	dst_reg = &regs[insn->dst_reg];
15666 	if (BPF_SRC(insn->code) == BPF_X) {
15667 		if (insn->imm != 0) {
15668 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
15669 			return -EINVAL;
15670 		}
15671 
15672 		/* check src1 operand */
15673 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
15674 		if (err)
15675 			return err;
15676 
15677 		src_reg = &regs[insn->src_reg];
15678 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
15679 		    is_pointer_value(env, insn->src_reg)) {
15680 			verbose(env, "R%d pointer comparison prohibited\n",
15681 				insn->src_reg);
15682 			return -EACCES;
15683 		}
15684 	} else {
15685 		if (insn->src_reg != BPF_REG_0) {
15686 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
15687 			return -EINVAL;
15688 		}
15689 		src_reg = &env->fake_reg[0];
15690 		memset(src_reg, 0, sizeof(*src_reg));
15691 		src_reg->type = SCALAR_VALUE;
15692 		__mark_reg_known(src_reg, insn->imm);
15693 	}
15694 
15695 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
15696 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
15697 	if (pred >= 0) {
15698 		/* If we get here with a dst_reg pointer type it is because
15699 		 * above is_branch_taken() special cased the 0 comparison.
15700 		 */
15701 		if (!__is_pointer_value(false, dst_reg))
15702 			err = mark_chain_precision(env, insn->dst_reg);
15703 		if (BPF_SRC(insn->code) == BPF_X && !err &&
15704 		    !__is_pointer_value(false, src_reg))
15705 			err = mark_chain_precision(env, insn->src_reg);
15706 		if (err)
15707 			return err;
15708 	}
15709 
15710 	if (pred == 1) {
15711 		/* Only follow the goto, ignore fall-through. If needed, push
15712 		 * the fall-through branch for simulation under speculative
15713 		 * execution.
15714 		 */
15715 		if (!env->bypass_spec_v1 &&
15716 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
15717 					       *insn_idx))
15718 			return -EFAULT;
15719 		if (env->log.level & BPF_LOG_LEVEL)
15720 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
15721 		*insn_idx += insn->off;
15722 		return 0;
15723 	} else if (pred == 0) {
15724 		/* Only follow the fall-through branch, since that's where the
15725 		 * program will go. If needed, push the goto branch for
15726 		 * simulation under speculative execution.
15727 		 */
15728 		if (!env->bypass_spec_v1 &&
15729 		    !sanitize_speculative_path(env, insn,
15730 					       *insn_idx + insn->off + 1,
15731 					       *insn_idx))
15732 			return -EFAULT;
15733 		if (env->log.level & BPF_LOG_LEVEL)
15734 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
15735 		return 0;
15736 	}
15737 
15738 	/* Push scalar registers sharing same ID to jump history,
15739 	 * do this before creating 'other_branch', so that both
15740 	 * 'this_branch' and 'other_branch' share this history
15741 	 * if parent state is created.
15742 	 */
15743 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
15744 		collect_linked_regs(this_branch, src_reg->id, &linked_regs);
15745 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
15746 		collect_linked_regs(this_branch, dst_reg->id, &linked_regs);
15747 	if (linked_regs.cnt > 1) {
15748 		err = push_insn_history(env, this_branch, 0, linked_regs_pack(&linked_regs));
15749 		if (err)
15750 			return err;
15751 	}
15752 
15753 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
15754 				  false);
15755 	if (!other_branch)
15756 		return -EFAULT;
15757 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
15758 
15759 	if (BPF_SRC(insn->code) == BPF_X) {
15760 		err = reg_set_min_max(env,
15761 				      &other_branch_regs[insn->dst_reg],
15762 				      &other_branch_regs[insn->src_reg],
15763 				      dst_reg, src_reg, opcode, is_jmp32);
15764 	} else /* BPF_SRC(insn->code) == BPF_K */ {
15765 		/* reg_set_min_max() can mangle the fake_reg. Make a copy
15766 		 * so that these are two different memory locations. The
15767 		 * src_reg is not used beyond here in context of K.
15768 		 */
15769 		memcpy(&env->fake_reg[1], &env->fake_reg[0],
15770 		       sizeof(env->fake_reg[0]));
15771 		err = reg_set_min_max(env,
15772 				      &other_branch_regs[insn->dst_reg],
15773 				      &env->fake_reg[0],
15774 				      dst_reg, &env->fake_reg[1],
15775 				      opcode, is_jmp32);
15776 	}
15777 	if (err)
15778 		return err;
15779 
15780 	if (BPF_SRC(insn->code) == BPF_X &&
15781 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
15782 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
15783 		sync_linked_regs(this_branch, src_reg, &linked_regs);
15784 		sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs);
15785 	}
15786 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
15787 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
15788 		sync_linked_regs(this_branch, dst_reg, &linked_regs);
15789 		sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs);
15790 	}
15791 
15792 	/* if one pointer register is compared to another pointer
15793 	 * register check if PTR_MAYBE_NULL could be lifted.
15794 	 * E.g. register A - maybe null
15795 	 *      register B - not null
15796 	 * for JNE A, B, ... - A is not null in the false branch;
15797 	 * for JEQ A, B, ... - A is not null in the true branch.
15798 	 *
15799 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
15800 	 * not need to be null checked by the BPF program, i.e.,
15801 	 * could be null even without PTR_MAYBE_NULL marking, so
15802 	 * only propagate nullness when neither reg is that type.
15803 	 */
15804 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
15805 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
15806 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
15807 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
15808 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
15809 		eq_branch_regs = NULL;
15810 		switch (opcode) {
15811 		case BPF_JEQ:
15812 			eq_branch_regs = other_branch_regs;
15813 			break;
15814 		case BPF_JNE:
15815 			eq_branch_regs = regs;
15816 			break;
15817 		default:
15818 			/* do nothing */
15819 			break;
15820 		}
15821 		if (eq_branch_regs) {
15822 			if (type_may_be_null(src_reg->type))
15823 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
15824 			else
15825 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
15826 		}
15827 	}
15828 
15829 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
15830 	 * NOTE: these optimizations below are related with pointer comparison
15831 	 *       which will never be JMP32.
15832 	 */
15833 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
15834 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
15835 	    type_may_be_null(dst_reg->type)) {
15836 		/* Mark all identical registers in each branch as either
15837 		 * safe or unknown depending R == 0 or R != 0 conditional.
15838 		 */
15839 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
15840 				      opcode == BPF_JNE);
15841 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
15842 				      opcode == BPF_JEQ);
15843 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
15844 					   this_branch, other_branch) &&
15845 		   is_pointer_value(env, insn->dst_reg)) {
15846 		verbose(env, "R%d pointer comparison prohibited\n",
15847 			insn->dst_reg);
15848 		return -EACCES;
15849 	}
15850 	if (env->log.level & BPF_LOG_LEVEL)
15851 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
15852 	return 0;
15853 }
15854 
15855 /* verify BPF_LD_IMM64 instruction */
15856 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
15857 {
15858 	struct bpf_insn_aux_data *aux = cur_aux(env);
15859 	struct bpf_reg_state *regs = cur_regs(env);
15860 	struct bpf_reg_state *dst_reg;
15861 	struct bpf_map *map;
15862 	int err;
15863 
15864 	if (BPF_SIZE(insn->code) != BPF_DW) {
15865 		verbose(env, "invalid BPF_LD_IMM insn\n");
15866 		return -EINVAL;
15867 	}
15868 	if (insn->off != 0) {
15869 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
15870 		return -EINVAL;
15871 	}
15872 
15873 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
15874 	if (err)
15875 		return err;
15876 
15877 	dst_reg = &regs[insn->dst_reg];
15878 	if (insn->src_reg == 0) {
15879 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
15880 
15881 		dst_reg->type = SCALAR_VALUE;
15882 		__mark_reg_known(&regs[insn->dst_reg], imm);
15883 		return 0;
15884 	}
15885 
15886 	/* All special src_reg cases are listed below. From this point onwards
15887 	 * we either succeed and assign a corresponding dst_reg->type after
15888 	 * zeroing the offset, or fail and reject the program.
15889 	 */
15890 	mark_reg_known_zero(env, regs, insn->dst_reg);
15891 
15892 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
15893 		dst_reg->type = aux->btf_var.reg_type;
15894 		switch (base_type(dst_reg->type)) {
15895 		case PTR_TO_MEM:
15896 			dst_reg->mem_size = aux->btf_var.mem_size;
15897 			break;
15898 		case PTR_TO_BTF_ID:
15899 			dst_reg->btf = aux->btf_var.btf;
15900 			dst_reg->btf_id = aux->btf_var.btf_id;
15901 			break;
15902 		default:
15903 			verbose(env, "bpf verifier is misconfigured\n");
15904 			return -EFAULT;
15905 		}
15906 		return 0;
15907 	}
15908 
15909 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
15910 		struct bpf_prog_aux *aux = env->prog->aux;
15911 		u32 subprogno = find_subprog(env,
15912 					     env->insn_idx + insn->imm + 1);
15913 
15914 		if (!aux->func_info) {
15915 			verbose(env, "missing btf func_info\n");
15916 			return -EINVAL;
15917 		}
15918 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
15919 			verbose(env, "callback function not static\n");
15920 			return -EINVAL;
15921 		}
15922 
15923 		dst_reg->type = PTR_TO_FUNC;
15924 		dst_reg->subprogno = subprogno;
15925 		return 0;
15926 	}
15927 
15928 	map = env->used_maps[aux->map_index];
15929 	dst_reg->map_ptr = map;
15930 
15931 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
15932 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
15933 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
15934 			__mark_reg_unknown(env, dst_reg);
15935 			return 0;
15936 		}
15937 		dst_reg->type = PTR_TO_MAP_VALUE;
15938 		dst_reg->off = aux->map_off;
15939 		WARN_ON_ONCE(map->max_entries != 1);
15940 		/* We want reg->id to be same (0) as map_value is not distinct */
15941 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
15942 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
15943 		dst_reg->type = CONST_PTR_TO_MAP;
15944 	} else {
15945 		verbose(env, "bpf verifier is misconfigured\n");
15946 		return -EINVAL;
15947 	}
15948 
15949 	return 0;
15950 }
15951 
15952 static bool may_access_skb(enum bpf_prog_type type)
15953 {
15954 	switch (type) {
15955 	case BPF_PROG_TYPE_SOCKET_FILTER:
15956 	case BPF_PROG_TYPE_SCHED_CLS:
15957 	case BPF_PROG_TYPE_SCHED_ACT:
15958 		return true;
15959 	default:
15960 		return false;
15961 	}
15962 }
15963 
15964 /* verify safety of LD_ABS|LD_IND instructions:
15965  * - they can only appear in the programs where ctx == skb
15966  * - since they are wrappers of function calls, they scratch R1-R5 registers,
15967  *   preserve R6-R9, and store return value into R0
15968  *
15969  * Implicit input:
15970  *   ctx == skb == R6 == CTX
15971  *
15972  * Explicit input:
15973  *   SRC == any register
15974  *   IMM == 32-bit immediate
15975  *
15976  * Output:
15977  *   R0 - 8/16/32-bit skb data converted to cpu endianness
15978  */
15979 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
15980 {
15981 	struct bpf_reg_state *regs = cur_regs(env);
15982 	static const int ctx_reg = BPF_REG_6;
15983 	u8 mode = BPF_MODE(insn->code);
15984 	int i, err;
15985 
15986 	if (!may_access_skb(resolve_prog_type(env->prog))) {
15987 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
15988 		return -EINVAL;
15989 	}
15990 
15991 	if (!env->ops->gen_ld_abs) {
15992 		verbose(env, "bpf verifier is misconfigured\n");
15993 		return -EINVAL;
15994 	}
15995 
15996 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
15997 	    BPF_SIZE(insn->code) == BPF_DW ||
15998 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
15999 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
16000 		return -EINVAL;
16001 	}
16002 
16003 	/* check whether implicit source operand (register R6) is readable */
16004 	err = check_reg_arg(env, ctx_reg, SRC_OP);
16005 	if (err)
16006 		return err;
16007 
16008 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
16009 	 * gen_ld_abs() may terminate the program at runtime, leading to
16010 	 * reference leak.
16011 	 */
16012 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
16013 	if (err)
16014 		return err;
16015 
16016 	if (regs[ctx_reg].type != PTR_TO_CTX) {
16017 		verbose(env,
16018 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
16019 		return -EINVAL;
16020 	}
16021 
16022 	if (mode == BPF_IND) {
16023 		/* check explicit source operand */
16024 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
16025 		if (err)
16026 			return err;
16027 	}
16028 
16029 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
16030 	if (err < 0)
16031 		return err;
16032 
16033 	/* reset caller saved regs to unreadable */
16034 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
16035 		mark_reg_not_init(env, regs, caller_saved[i]);
16036 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
16037 	}
16038 
16039 	/* mark destination R0 register as readable, since it contains
16040 	 * the value fetched from the packet.
16041 	 * Already marked as written above.
16042 	 */
16043 	mark_reg_unknown(env, regs, BPF_REG_0);
16044 	/* ld_abs load up to 32-bit skb data. */
16045 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
16046 	return 0;
16047 }
16048 
16049 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
16050 {
16051 	const char *exit_ctx = "At program exit";
16052 	struct tnum enforce_attach_type_range = tnum_unknown;
16053 	const struct bpf_prog *prog = env->prog;
16054 	struct bpf_reg_state *reg;
16055 	struct bpf_retval_range range = retval_range(0, 1);
16056 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
16057 	int err;
16058 	struct bpf_func_state *frame = env->cur_state->frame[0];
16059 	const bool is_subprog = frame->subprogno;
16060 	bool return_32bit = false;
16061 
16062 	/* LSM and struct_ops func-ptr's return type could be "void" */
16063 	if (!is_subprog || frame->in_exception_callback_fn) {
16064 		switch (prog_type) {
16065 		case BPF_PROG_TYPE_LSM:
16066 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
16067 				/* See below, can be 0 or 0-1 depending on hook. */
16068 				break;
16069 			fallthrough;
16070 		case BPF_PROG_TYPE_STRUCT_OPS:
16071 			if (!prog->aux->attach_func_proto->type)
16072 				return 0;
16073 			break;
16074 		default:
16075 			break;
16076 		}
16077 	}
16078 
16079 	/* eBPF calling convention is such that R0 is used
16080 	 * to return the value from eBPF program.
16081 	 * Make sure that it's readable at this time
16082 	 * of bpf_exit, which means that program wrote
16083 	 * something into it earlier
16084 	 */
16085 	err = check_reg_arg(env, regno, SRC_OP);
16086 	if (err)
16087 		return err;
16088 
16089 	if (is_pointer_value(env, regno)) {
16090 		verbose(env, "R%d leaks addr as return value\n", regno);
16091 		return -EACCES;
16092 	}
16093 
16094 	reg = cur_regs(env) + regno;
16095 
16096 	if (frame->in_async_callback_fn) {
16097 		/* enforce return zero from async callbacks like timer */
16098 		exit_ctx = "At async callback return";
16099 		range = retval_range(0, 0);
16100 		goto enforce_retval;
16101 	}
16102 
16103 	if (is_subprog && !frame->in_exception_callback_fn) {
16104 		if (reg->type != SCALAR_VALUE) {
16105 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
16106 				regno, reg_type_str(env, reg->type));
16107 			return -EINVAL;
16108 		}
16109 		return 0;
16110 	}
16111 
16112 	switch (prog_type) {
16113 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
16114 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
16115 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
16116 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
16117 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
16118 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
16119 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
16120 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
16121 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
16122 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
16123 			range = retval_range(1, 1);
16124 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
16125 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
16126 			range = retval_range(0, 3);
16127 		break;
16128 	case BPF_PROG_TYPE_CGROUP_SKB:
16129 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
16130 			range = retval_range(0, 3);
16131 			enforce_attach_type_range = tnum_range(2, 3);
16132 		}
16133 		break;
16134 	case BPF_PROG_TYPE_CGROUP_SOCK:
16135 	case BPF_PROG_TYPE_SOCK_OPS:
16136 	case BPF_PROG_TYPE_CGROUP_DEVICE:
16137 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
16138 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
16139 		break;
16140 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
16141 		if (!env->prog->aux->attach_btf_id)
16142 			return 0;
16143 		range = retval_range(0, 0);
16144 		break;
16145 	case BPF_PROG_TYPE_TRACING:
16146 		switch (env->prog->expected_attach_type) {
16147 		case BPF_TRACE_FENTRY:
16148 		case BPF_TRACE_FEXIT:
16149 			range = retval_range(0, 0);
16150 			break;
16151 		case BPF_TRACE_RAW_TP:
16152 		case BPF_MODIFY_RETURN:
16153 			return 0;
16154 		case BPF_TRACE_ITER:
16155 			break;
16156 		default:
16157 			return -ENOTSUPP;
16158 		}
16159 		break;
16160 	case BPF_PROG_TYPE_KPROBE:
16161 		switch (env->prog->expected_attach_type) {
16162 		case BPF_TRACE_KPROBE_SESSION:
16163 		case BPF_TRACE_UPROBE_SESSION:
16164 			range = retval_range(0, 1);
16165 			break;
16166 		default:
16167 			return 0;
16168 		}
16169 		break;
16170 	case BPF_PROG_TYPE_SK_LOOKUP:
16171 		range = retval_range(SK_DROP, SK_PASS);
16172 		break;
16173 
16174 	case BPF_PROG_TYPE_LSM:
16175 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
16176 			/* no range found, any return value is allowed */
16177 			if (!get_func_retval_range(env->prog, &range))
16178 				return 0;
16179 			/* no restricted range, any return value is allowed */
16180 			if (range.minval == S32_MIN && range.maxval == S32_MAX)
16181 				return 0;
16182 			return_32bit = true;
16183 		} else if (!env->prog->aux->attach_func_proto->type) {
16184 			/* Make sure programs that attach to void
16185 			 * hooks don't try to modify return value.
16186 			 */
16187 			range = retval_range(1, 1);
16188 		}
16189 		break;
16190 
16191 	case BPF_PROG_TYPE_NETFILTER:
16192 		range = retval_range(NF_DROP, NF_ACCEPT);
16193 		break;
16194 	case BPF_PROG_TYPE_EXT:
16195 		/* freplace program can return anything as its return value
16196 		 * depends on the to-be-replaced kernel func or bpf program.
16197 		 */
16198 	default:
16199 		return 0;
16200 	}
16201 
16202 enforce_retval:
16203 	if (reg->type != SCALAR_VALUE) {
16204 		verbose(env, "%s the register R%d is not a known value (%s)\n",
16205 			exit_ctx, regno, reg_type_str(env, reg->type));
16206 		return -EINVAL;
16207 	}
16208 
16209 	err = mark_chain_precision(env, regno);
16210 	if (err)
16211 		return err;
16212 
16213 	if (!retval_range_within(range, reg, return_32bit)) {
16214 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
16215 		if (!is_subprog &&
16216 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
16217 		    prog_type == BPF_PROG_TYPE_LSM &&
16218 		    !prog->aux->attach_func_proto->type)
16219 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
16220 		return -EINVAL;
16221 	}
16222 
16223 	if (!tnum_is_unknown(enforce_attach_type_range) &&
16224 	    tnum_in(enforce_attach_type_range, reg->var_off))
16225 		env->prog->enforce_expected_attach_type = 1;
16226 	return 0;
16227 }
16228 
16229 /* non-recursive DFS pseudo code
16230  * 1  procedure DFS-iterative(G,v):
16231  * 2      label v as discovered
16232  * 3      let S be a stack
16233  * 4      S.push(v)
16234  * 5      while S is not empty
16235  * 6            t <- S.peek()
16236  * 7            if t is what we're looking for:
16237  * 8                return t
16238  * 9            for all edges e in G.adjacentEdges(t) do
16239  * 10               if edge e is already labelled
16240  * 11                   continue with the next edge
16241  * 12               w <- G.adjacentVertex(t,e)
16242  * 13               if vertex w is not discovered and not explored
16243  * 14                   label e as tree-edge
16244  * 15                   label w as discovered
16245  * 16                   S.push(w)
16246  * 17                   continue at 5
16247  * 18               else if vertex w is discovered
16248  * 19                   label e as back-edge
16249  * 20               else
16250  * 21                   // vertex w is explored
16251  * 22                   label e as forward- or cross-edge
16252  * 23           label t as explored
16253  * 24           S.pop()
16254  *
16255  * convention:
16256  * 0x10 - discovered
16257  * 0x11 - discovered and fall-through edge labelled
16258  * 0x12 - discovered and fall-through and branch edges labelled
16259  * 0x20 - explored
16260  */
16261 
16262 enum {
16263 	DISCOVERED = 0x10,
16264 	EXPLORED = 0x20,
16265 	FALLTHROUGH = 1,
16266 	BRANCH = 2,
16267 };
16268 
16269 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
16270 {
16271 	env->insn_aux_data[idx].prune_point = true;
16272 }
16273 
16274 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
16275 {
16276 	return env->insn_aux_data[insn_idx].prune_point;
16277 }
16278 
16279 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
16280 {
16281 	env->insn_aux_data[idx].force_checkpoint = true;
16282 }
16283 
16284 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
16285 {
16286 	return env->insn_aux_data[insn_idx].force_checkpoint;
16287 }
16288 
16289 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
16290 {
16291 	env->insn_aux_data[idx].calls_callback = true;
16292 }
16293 
16294 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
16295 {
16296 	return env->insn_aux_data[insn_idx].calls_callback;
16297 }
16298 
16299 enum {
16300 	DONE_EXPLORING = 0,
16301 	KEEP_EXPLORING = 1,
16302 };
16303 
16304 /* t, w, e - match pseudo-code above:
16305  * t - index of current instruction
16306  * w - next instruction
16307  * e - edge
16308  */
16309 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
16310 {
16311 	int *insn_stack = env->cfg.insn_stack;
16312 	int *insn_state = env->cfg.insn_state;
16313 
16314 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
16315 		return DONE_EXPLORING;
16316 
16317 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
16318 		return DONE_EXPLORING;
16319 
16320 	if (w < 0 || w >= env->prog->len) {
16321 		verbose_linfo(env, t, "%d: ", t);
16322 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
16323 		return -EINVAL;
16324 	}
16325 
16326 	if (e == BRANCH) {
16327 		/* mark branch target for state pruning */
16328 		mark_prune_point(env, w);
16329 		mark_jmp_point(env, w);
16330 	}
16331 
16332 	if (insn_state[w] == 0) {
16333 		/* tree-edge */
16334 		insn_state[t] = DISCOVERED | e;
16335 		insn_state[w] = DISCOVERED;
16336 		if (env->cfg.cur_stack >= env->prog->len)
16337 			return -E2BIG;
16338 		insn_stack[env->cfg.cur_stack++] = w;
16339 		return KEEP_EXPLORING;
16340 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
16341 		if (env->bpf_capable)
16342 			return DONE_EXPLORING;
16343 		verbose_linfo(env, t, "%d: ", t);
16344 		verbose_linfo(env, w, "%d: ", w);
16345 		verbose(env, "back-edge from insn %d to %d\n", t, w);
16346 		return -EINVAL;
16347 	} else if (insn_state[w] == EXPLORED) {
16348 		/* forward- or cross-edge */
16349 		insn_state[t] = DISCOVERED | e;
16350 	} else {
16351 		verbose(env, "insn state internal bug\n");
16352 		return -EFAULT;
16353 	}
16354 	return DONE_EXPLORING;
16355 }
16356 
16357 static int visit_func_call_insn(int t, struct bpf_insn *insns,
16358 				struct bpf_verifier_env *env,
16359 				bool visit_callee)
16360 {
16361 	int ret, insn_sz;
16362 
16363 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
16364 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
16365 	if (ret)
16366 		return ret;
16367 
16368 	mark_prune_point(env, t + insn_sz);
16369 	/* when we exit from subprog, we need to record non-linear history */
16370 	mark_jmp_point(env, t + insn_sz);
16371 
16372 	if (visit_callee) {
16373 		mark_prune_point(env, t);
16374 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
16375 	}
16376 	return ret;
16377 }
16378 
16379 /* Bitmask with 1s for all caller saved registers */
16380 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
16381 
16382 /* Return a bitmask specifying which caller saved registers are
16383  * clobbered by a call to a helper *as if* this helper follows
16384  * bpf_fastcall contract:
16385  * - includes R0 if function is non-void;
16386  * - includes R1-R5 if corresponding parameter has is described
16387  *   in the function prototype.
16388  */
16389 static u32 helper_fastcall_clobber_mask(const struct bpf_func_proto *fn)
16390 {
16391 	u32 mask;
16392 	int i;
16393 
16394 	mask = 0;
16395 	if (fn->ret_type != RET_VOID)
16396 		mask |= BIT(BPF_REG_0);
16397 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i)
16398 		if (fn->arg_type[i] != ARG_DONTCARE)
16399 			mask |= BIT(BPF_REG_1 + i);
16400 	return mask;
16401 }
16402 
16403 /* True if do_misc_fixups() replaces calls to helper number 'imm',
16404  * replacement patch is presumed to follow bpf_fastcall contract
16405  * (see mark_fastcall_pattern_for_call() below).
16406  */
16407 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
16408 {
16409 	switch (imm) {
16410 #ifdef CONFIG_X86_64
16411 	case BPF_FUNC_get_smp_processor_id:
16412 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
16413 #endif
16414 	default:
16415 		return false;
16416 	}
16417 }
16418 
16419 /* Same as helper_fastcall_clobber_mask() but for kfuncs, see comment above */
16420 static u32 kfunc_fastcall_clobber_mask(struct bpf_kfunc_call_arg_meta *meta)
16421 {
16422 	u32 vlen, i, mask;
16423 
16424 	vlen = btf_type_vlen(meta->func_proto);
16425 	mask = 0;
16426 	if (!btf_type_is_void(btf_type_by_id(meta->btf, meta->func_proto->type)))
16427 		mask |= BIT(BPF_REG_0);
16428 	for (i = 0; i < vlen; ++i)
16429 		mask |= BIT(BPF_REG_1 + i);
16430 	return mask;
16431 }
16432 
16433 /* Same as verifier_inlines_helper_call() but for kfuncs, see comment above */
16434 static bool is_fastcall_kfunc_call(struct bpf_kfunc_call_arg_meta *meta)
16435 {
16436 	return meta->kfunc_flags & KF_FASTCALL;
16437 }
16438 
16439 /* LLVM define a bpf_fastcall function attribute.
16440  * This attribute means that function scratches only some of
16441  * the caller saved registers defined by ABI.
16442  * For BPF the set of such registers could be defined as follows:
16443  * - R0 is scratched only if function is non-void;
16444  * - R1-R5 are scratched only if corresponding parameter type is defined
16445  *   in the function prototype.
16446  *
16447  * The contract between kernel and clang allows to simultaneously use
16448  * such functions and maintain backwards compatibility with old
16449  * kernels that don't understand bpf_fastcall calls:
16450  *
16451  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
16452  *   registers are not scratched by the call;
16453  *
16454  * - as a post-processing step, clang visits each bpf_fastcall call and adds
16455  *   spill/fill for every live r0-r5;
16456  *
16457  * - stack offsets used for the spill/fill are allocated as lowest
16458  *   stack offsets in whole function and are not used for any other
16459  *   purposes;
16460  *
16461  * - when kernel loads a program, it looks for such patterns
16462  *   (bpf_fastcall function surrounded by spills/fills) and checks if
16463  *   spill/fill stack offsets are used exclusively in fastcall patterns;
16464  *
16465  * - if so, and if verifier or current JIT inlines the call to the
16466  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
16467  *   spill/fill pairs;
16468  *
16469  * - when old kernel loads a program, presence of spill/fill pairs
16470  *   keeps BPF program valid, albeit slightly less efficient.
16471  *
16472  * For example:
16473  *
16474  *   r1 = 1;
16475  *   r2 = 2;
16476  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
16477  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
16478  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
16479  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
16480  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
16481  *   r0 = r1;                            exit;
16482  *   r0 += r2;
16483  *   exit;
16484  *
16485  * The purpose of mark_fastcall_pattern_for_call is to:
16486  * - look for such patterns;
16487  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
16488  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
16489  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
16490  *   at which bpf_fastcall spill/fill stack slots start;
16491  * - update env->subprog_info[*]->keep_fastcall_stack.
16492  *
16493  * The .fastcall_pattern and .fastcall_stack_off are used by
16494  * check_fastcall_stack_contract() to check if every stack access to
16495  * fastcall spill/fill stack slot originates from spill/fill
16496  * instructions, members of fastcall patterns.
16497  *
16498  * If such condition holds true for a subprogram, fastcall patterns could
16499  * be rewritten by remove_fastcall_spills_fills().
16500  * Otherwise bpf_fastcall patterns are not changed in the subprogram
16501  * (code, presumably, generated by an older clang version).
16502  *
16503  * For example, it is *not* safe to remove spill/fill below:
16504  *
16505  *   r1 = 1;
16506  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
16507  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
16508  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
16509  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
16510  *   r0 += r1;                           exit;
16511  *   exit;
16512  */
16513 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
16514 					   struct bpf_subprog_info *subprog,
16515 					   int insn_idx, s16 lowest_off)
16516 {
16517 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
16518 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
16519 	const struct bpf_func_proto *fn;
16520 	u32 clobbered_regs_mask = ALL_CALLER_SAVED_REGS;
16521 	u32 expected_regs_mask;
16522 	bool can_be_inlined = false;
16523 	s16 off;
16524 	int i;
16525 
16526 	if (bpf_helper_call(call)) {
16527 		if (get_helper_proto(env, call->imm, &fn) < 0)
16528 			/* error would be reported later */
16529 			return;
16530 		clobbered_regs_mask = helper_fastcall_clobber_mask(fn);
16531 		can_be_inlined = fn->allow_fastcall &&
16532 				 (verifier_inlines_helper_call(env, call->imm) ||
16533 				  bpf_jit_inlines_helper_call(call->imm));
16534 	}
16535 
16536 	if (bpf_pseudo_kfunc_call(call)) {
16537 		struct bpf_kfunc_call_arg_meta meta;
16538 		int err;
16539 
16540 		err = fetch_kfunc_meta(env, call, &meta, NULL);
16541 		if (err < 0)
16542 			/* error would be reported later */
16543 			return;
16544 
16545 		clobbered_regs_mask = kfunc_fastcall_clobber_mask(&meta);
16546 		can_be_inlined = is_fastcall_kfunc_call(&meta);
16547 	}
16548 
16549 	if (clobbered_regs_mask == ALL_CALLER_SAVED_REGS)
16550 		return;
16551 
16552 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
16553 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
16554 
16555 	/* match pairs of form:
16556 	 *
16557 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
16558 	 * ...
16559 	 * call %[to_be_inlined]
16560 	 * ...
16561 	 * rX = *(u64 *)(r10 - Y)
16562 	 */
16563 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
16564 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
16565 			break;
16566 		stx = &insns[insn_idx - i];
16567 		ldx = &insns[insn_idx + i];
16568 		/* must be a stack spill/fill pair */
16569 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
16570 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
16571 		    stx->dst_reg != BPF_REG_10 ||
16572 		    ldx->src_reg != BPF_REG_10)
16573 			break;
16574 		/* must be a spill/fill for the same reg */
16575 		if (stx->src_reg != ldx->dst_reg)
16576 			break;
16577 		/* must be one of the previously unseen registers */
16578 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
16579 			break;
16580 		/* must be a spill/fill for the same expected offset,
16581 		 * no need to check offset alignment, BPF_DW stack access
16582 		 * is always 8-byte aligned.
16583 		 */
16584 		if (stx->off != off || ldx->off != off)
16585 			break;
16586 		expected_regs_mask &= ~BIT(stx->src_reg);
16587 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
16588 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
16589 	}
16590 	if (i == 1)
16591 		return;
16592 
16593 	/* Conditionally set 'fastcall_spills_num' to allow forward
16594 	 * compatibility when more helper functions are marked as
16595 	 * bpf_fastcall at compile time than current kernel supports, e.g:
16596 	 *
16597 	 *   1: *(u64 *)(r10 - 8) = r1
16598 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
16599 	 *   3: r1 = *(u64 *)(r10 - 8)
16600 	 *   4: *(u64 *)(r10 - 8) = r1
16601 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
16602 	 *   6: r1 = *(u64 *)(r10 - 8)
16603 	 *
16604 	 * There is no need to block bpf_fastcall rewrite for such program.
16605 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
16606 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
16607 	 * does not remove spill/fill pair {4,6}.
16608 	 */
16609 	if (can_be_inlined)
16610 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
16611 	else
16612 		subprog->keep_fastcall_stack = 1;
16613 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
16614 }
16615 
16616 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
16617 {
16618 	struct bpf_subprog_info *subprog = env->subprog_info;
16619 	struct bpf_insn *insn;
16620 	s16 lowest_off;
16621 	int s, i;
16622 
16623 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
16624 		/* find lowest stack spill offset used in this subprog */
16625 		lowest_off = 0;
16626 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
16627 			insn = env->prog->insnsi + i;
16628 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
16629 			    insn->dst_reg != BPF_REG_10)
16630 				continue;
16631 			lowest_off = min(lowest_off, insn->off);
16632 		}
16633 		/* use this offset to find fastcall patterns */
16634 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
16635 			insn = env->prog->insnsi + i;
16636 			if (insn->code != (BPF_JMP | BPF_CALL))
16637 				continue;
16638 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
16639 		}
16640 	}
16641 	return 0;
16642 }
16643 
16644 /* Visits the instruction at index t and returns one of the following:
16645  *  < 0 - an error occurred
16646  *  DONE_EXPLORING - the instruction was fully explored
16647  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
16648  */
16649 static int visit_insn(int t, struct bpf_verifier_env *env)
16650 {
16651 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
16652 	int ret, off, insn_sz;
16653 
16654 	if (bpf_pseudo_func(insn))
16655 		return visit_func_call_insn(t, insns, env, true);
16656 
16657 	/* All non-branch instructions have a single fall-through edge. */
16658 	if (BPF_CLASS(insn->code) != BPF_JMP &&
16659 	    BPF_CLASS(insn->code) != BPF_JMP32) {
16660 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
16661 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
16662 	}
16663 
16664 	switch (BPF_OP(insn->code)) {
16665 	case BPF_EXIT:
16666 		return DONE_EXPLORING;
16667 
16668 	case BPF_CALL:
16669 		if (is_async_callback_calling_insn(insn))
16670 			/* Mark this call insn as a prune point to trigger
16671 			 * is_state_visited() check before call itself is
16672 			 * processed by __check_func_call(). Otherwise new
16673 			 * async state will be pushed for further exploration.
16674 			 */
16675 			mark_prune_point(env, t);
16676 		/* For functions that invoke callbacks it is not known how many times
16677 		 * callback would be called. Verifier models callback calling functions
16678 		 * by repeatedly visiting callback bodies and returning to origin call
16679 		 * instruction.
16680 		 * In order to stop such iteration verifier needs to identify when a
16681 		 * state identical some state from a previous iteration is reached.
16682 		 * Check below forces creation of checkpoint before callback calling
16683 		 * instruction to allow search for such identical states.
16684 		 */
16685 		if (is_sync_callback_calling_insn(insn)) {
16686 			mark_calls_callback(env, t);
16687 			mark_force_checkpoint(env, t);
16688 			mark_prune_point(env, t);
16689 			mark_jmp_point(env, t);
16690 		}
16691 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
16692 			struct bpf_kfunc_call_arg_meta meta;
16693 
16694 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
16695 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
16696 				mark_prune_point(env, t);
16697 				/* Checking and saving state checkpoints at iter_next() call
16698 				 * is crucial for fast convergence of open-coded iterator loop
16699 				 * logic, so we need to force it. If we don't do that,
16700 				 * is_state_visited() might skip saving a checkpoint, causing
16701 				 * unnecessarily long sequence of not checkpointed
16702 				 * instructions and jumps, leading to exhaustion of jump
16703 				 * history buffer, and potentially other undesired outcomes.
16704 				 * It is expected that with correct open-coded iterators
16705 				 * convergence will happen quickly, so we don't run a risk of
16706 				 * exhausting memory.
16707 				 */
16708 				mark_force_checkpoint(env, t);
16709 			}
16710 		}
16711 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
16712 
16713 	case BPF_JA:
16714 		if (BPF_SRC(insn->code) != BPF_K)
16715 			return -EINVAL;
16716 
16717 		if (BPF_CLASS(insn->code) == BPF_JMP)
16718 			off = insn->off;
16719 		else
16720 			off = insn->imm;
16721 
16722 		/* unconditional jump with single edge */
16723 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
16724 		if (ret)
16725 			return ret;
16726 
16727 		mark_prune_point(env, t + off + 1);
16728 		mark_jmp_point(env, t + off + 1);
16729 
16730 		return ret;
16731 
16732 	default:
16733 		/* conditional jump with two edges */
16734 		mark_prune_point(env, t);
16735 		if (is_may_goto_insn(insn))
16736 			mark_force_checkpoint(env, t);
16737 
16738 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
16739 		if (ret)
16740 			return ret;
16741 
16742 		return push_insn(t, t + insn->off + 1, BRANCH, env);
16743 	}
16744 }
16745 
16746 /* non-recursive depth-first-search to detect loops in BPF program
16747  * loop == back-edge in directed graph
16748  */
16749 static int check_cfg(struct bpf_verifier_env *env)
16750 {
16751 	int insn_cnt = env->prog->len;
16752 	int *insn_stack, *insn_state;
16753 	int ex_insn_beg, i, ret = 0;
16754 	bool ex_done = false;
16755 
16756 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
16757 	if (!insn_state)
16758 		return -ENOMEM;
16759 
16760 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
16761 	if (!insn_stack) {
16762 		kvfree(insn_state);
16763 		return -ENOMEM;
16764 	}
16765 
16766 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
16767 	insn_stack[0] = 0; /* 0 is the first instruction */
16768 	env->cfg.cur_stack = 1;
16769 
16770 walk_cfg:
16771 	while (env->cfg.cur_stack > 0) {
16772 		int t = insn_stack[env->cfg.cur_stack - 1];
16773 
16774 		ret = visit_insn(t, env);
16775 		switch (ret) {
16776 		case DONE_EXPLORING:
16777 			insn_state[t] = EXPLORED;
16778 			env->cfg.cur_stack--;
16779 			break;
16780 		case KEEP_EXPLORING:
16781 			break;
16782 		default:
16783 			if (ret > 0) {
16784 				verbose(env, "visit_insn internal bug\n");
16785 				ret = -EFAULT;
16786 			}
16787 			goto err_free;
16788 		}
16789 	}
16790 
16791 	if (env->cfg.cur_stack < 0) {
16792 		verbose(env, "pop stack internal bug\n");
16793 		ret = -EFAULT;
16794 		goto err_free;
16795 	}
16796 
16797 	if (env->exception_callback_subprog && !ex_done) {
16798 		ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
16799 
16800 		insn_state[ex_insn_beg] = DISCOVERED;
16801 		insn_stack[0] = ex_insn_beg;
16802 		env->cfg.cur_stack = 1;
16803 		ex_done = true;
16804 		goto walk_cfg;
16805 	}
16806 
16807 	for (i = 0; i < insn_cnt; i++) {
16808 		struct bpf_insn *insn = &env->prog->insnsi[i];
16809 
16810 		if (insn_state[i] != EXPLORED) {
16811 			verbose(env, "unreachable insn %d\n", i);
16812 			ret = -EINVAL;
16813 			goto err_free;
16814 		}
16815 		if (bpf_is_ldimm64(insn)) {
16816 			if (insn_state[i + 1] != 0) {
16817 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
16818 				ret = -EINVAL;
16819 				goto err_free;
16820 			}
16821 			i++; /* skip second half of ldimm64 */
16822 		}
16823 	}
16824 	ret = 0; /* cfg looks good */
16825 
16826 err_free:
16827 	kvfree(insn_state);
16828 	kvfree(insn_stack);
16829 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
16830 	return ret;
16831 }
16832 
16833 static int check_abnormal_return(struct bpf_verifier_env *env)
16834 {
16835 	int i;
16836 
16837 	for (i = 1; i < env->subprog_cnt; i++) {
16838 		if (env->subprog_info[i].has_ld_abs) {
16839 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
16840 			return -EINVAL;
16841 		}
16842 		if (env->subprog_info[i].has_tail_call) {
16843 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
16844 			return -EINVAL;
16845 		}
16846 	}
16847 	return 0;
16848 }
16849 
16850 /* The minimum supported BTF func info size */
16851 #define MIN_BPF_FUNCINFO_SIZE	8
16852 #define MAX_FUNCINFO_REC_SIZE	252
16853 
16854 static int check_btf_func_early(struct bpf_verifier_env *env,
16855 				const union bpf_attr *attr,
16856 				bpfptr_t uattr)
16857 {
16858 	u32 krec_size = sizeof(struct bpf_func_info);
16859 	const struct btf_type *type, *func_proto;
16860 	u32 i, nfuncs, urec_size, min_size;
16861 	struct bpf_func_info *krecord;
16862 	struct bpf_prog *prog;
16863 	const struct btf *btf;
16864 	u32 prev_offset = 0;
16865 	bpfptr_t urecord;
16866 	int ret = -ENOMEM;
16867 
16868 	nfuncs = attr->func_info_cnt;
16869 	if (!nfuncs) {
16870 		if (check_abnormal_return(env))
16871 			return -EINVAL;
16872 		return 0;
16873 	}
16874 
16875 	urec_size = attr->func_info_rec_size;
16876 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
16877 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
16878 	    urec_size % sizeof(u32)) {
16879 		verbose(env, "invalid func info rec size %u\n", urec_size);
16880 		return -EINVAL;
16881 	}
16882 
16883 	prog = env->prog;
16884 	btf = prog->aux->btf;
16885 
16886 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
16887 	min_size = min_t(u32, krec_size, urec_size);
16888 
16889 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
16890 	if (!krecord)
16891 		return -ENOMEM;
16892 
16893 	for (i = 0; i < nfuncs; i++) {
16894 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
16895 		if (ret) {
16896 			if (ret == -E2BIG) {
16897 				verbose(env, "nonzero tailing record in func info");
16898 				/* set the size kernel expects so loader can zero
16899 				 * out the rest of the record.
16900 				 */
16901 				if (copy_to_bpfptr_offset(uattr,
16902 							  offsetof(union bpf_attr, func_info_rec_size),
16903 							  &min_size, sizeof(min_size)))
16904 					ret = -EFAULT;
16905 			}
16906 			goto err_free;
16907 		}
16908 
16909 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
16910 			ret = -EFAULT;
16911 			goto err_free;
16912 		}
16913 
16914 		/* check insn_off */
16915 		ret = -EINVAL;
16916 		if (i == 0) {
16917 			if (krecord[i].insn_off) {
16918 				verbose(env,
16919 					"nonzero insn_off %u for the first func info record",
16920 					krecord[i].insn_off);
16921 				goto err_free;
16922 			}
16923 		} else if (krecord[i].insn_off <= prev_offset) {
16924 			verbose(env,
16925 				"same or smaller insn offset (%u) than previous func info record (%u)",
16926 				krecord[i].insn_off, prev_offset);
16927 			goto err_free;
16928 		}
16929 
16930 		/* check type_id */
16931 		type = btf_type_by_id(btf, krecord[i].type_id);
16932 		if (!type || !btf_type_is_func(type)) {
16933 			verbose(env, "invalid type id %d in func info",
16934 				krecord[i].type_id);
16935 			goto err_free;
16936 		}
16937 
16938 		func_proto = btf_type_by_id(btf, type->type);
16939 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
16940 			/* btf_func_check() already verified it during BTF load */
16941 			goto err_free;
16942 
16943 		prev_offset = krecord[i].insn_off;
16944 		bpfptr_add(&urecord, urec_size);
16945 	}
16946 
16947 	prog->aux->func_info = krecord;
16948 	prog->aux->func_info_cnt = nfuncs;
16949 	return 0;
16950 
16951 err_free:
16952 	kvfree(krecord);
16953 	return ret;
16954 }
16955 
16956 static int check_btf_func(struct bpf_verifier_env *env,
16957 			  const union bpf_attr *attr,
16958 			  bpfptr_t uattr)
16959 {
16960 	const struct btf_type *type, *func_proto, *ret_type;
16961 	u32 i, nfuncs, urec_size;
16962 	struct bpf_func_info *krecord;
16963 	struct bpf_func_info_aux *info_aux = NULL;
16964 	struct bpf_prog *prog;
16965 	const struct btf *btf;
16966 	bpfptr_t urecord;
16967 	bool scalar_return;
16968 	int ret = -ENOMEM;
16969 
16970 	nfuncs = attr->func_info_cnt;
16971 	if (!nfuncs) {
16972 		if (check_abnormal_return(env))
16973 			return -EINVAL;
16974 		return 0;
16975 	}
16976 	if (nfuncs != env->subprog_cnt) {
16977 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
16978 		return -EINVAL;
16979 	}
16980 
16981 	urec_size = attr->func_info_rec_size;
16982 
16983 	prog = env->prog;
16984 	btf = prog->aux->btf;
16985 
16986 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
16987 
16988 	krecord = prog->aux->func_info;
16989 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
16990 	if (!info_aux)
16991 		return -ENOMEM;
16992 
16993 	for (i = 0; i < nfuncs; i++) {
16994 		/* check insn_off */
16995 		ret = -EINVAL;
16996 
16997 		if (env->subprog_info[i].start != krecord[i].insn_off) {
16998 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
16999 			goto err_free;
17000 		}
17001 
17002 		/* Already checked type_id */
17003 		type = btf_type_by_id(btf, krecord[i].type_id);
17004 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
17005 		/* Already checked func_proto */
17006 		func_proto = btf_type_by_id(btf, type->type);
17007 
17008 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
17009 		scalar_return =
17010 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
17011 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
17012 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
17013 			goto err_free;
17014 		}
17015 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
17016 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
17017 			goto err_free;
17018 		}
17019 
17020 		bpfptr_add(&urecord, urec_size);
17021 	}
17022 
17023 	prog->aux->func_info_aux = info_aux;
17024 	return 0;
17025 
17026 err_free:
17027 	kfree(info_aux);
17028 	return ret;
17029 }
17030 
17031 static void adjust_btf_func(struct bpf_verifier_env *env)
17032 {
17033 	struct bpf_prog_aux *aux = env->prog->aux;
17034 	int i;
17035 
17036 	if (!aux->func_info)
17037 		return;
17038 
17039 	/* func_info is not available for hidden subprogs */
17040 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
17041 		aux->func_info[i].insn_off = env->subprog_info[i].start;
17042 }
17043 
17044 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
17045 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
17046 
17047 static int check_btf_line(struct bpf_verifier_env *env,
17048 			  const union bpf_attr *attr,
17049 			  bpfptr_t uattr)
17050 {
17051 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
17052 	struct bpf_subprog_info *sub;
17053 	struct bpf_line_info *linfo;
17054 	struct bpf_prog *prog;
17055 	const struct btf *btf;
17056 	bpfptr_t ulinfo;
17057 	int err;
17058 
17059 	nr_linfo = attr->line_info_cnt;
17060 	if (!nr_linfo)
17061 		return 0;
17062 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
17063 		return -EINVAL;
17064 
17065 	rec_size = attr->line_info_rec_size;
17066 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
17067 	    rec_size > MAX_LINEINFO_REC_SIZE ||
17068 	    rec_size & (sizeof(u32) - 1))
17069 		return -EINVAL;
17070 
17071 	/* Need to zero it in case the userspace may
17072 	 * pass in a smaller bpf_line_info object.
17073 	 */
17074 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
17075 			 GFP_KERNEL | __GFP_NOWARN);
17076 	if (!linfo)
17077 		return -ENOMEM;
17078 
17079 	prog = env->prog;
17080 	btf = prog->aux->btf;
17081 
17082 	s = 0;
17083 	sub = env->subprog_info;
17084 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
17085 	expected_size = sizeof(struct bpf_line_info);
17086 	ncopy = min_t(u32, expected_size, rec_size);
17087 	for (i = 0; i < nr_linfo; i++) {
17088 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
17089 		if (err) {
17090 			if (err == -E2BIG) {
17091 				verbose(env, "nonzero tailing record in line_info");
17092 				if (copy_to_bpfptr_offset(uattr,
17093 							  offsetof(union bpf_attr, line_info_rec_size),
17094 							  &expected_size, sizeof(expected_size)))
17095 					err = -EFAULT;
17096 			}
17097 			goto err_free;
17098 		}
17099 
17100 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
17101 			err = -EFAULT;
17102 			goto err_free;
17103 		}
17104 
17105 		/*
17106 		 * Check insn_off to ensure
17107 		 * 1) strictly increasing AND
17108 		 * 2) bounded by prog->len
17109 		 *
17110 		 * The linfo[0].insn_off == 0 check logically falls into
17111 		 * the later "missing bpf_line_info for func..." case
17112 		 * because the first linfo[0].insn_off must be the
17113 		 * first sub also and the first sub must have
17114 		 * subprog_info[0].start == 0.
17115 		 */
17116 		if ((i && linfo[i].insn_off <= prev_offset) ||
17117 		    linfo[i].insn_off >= prog->len) {
17118 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
17119 				i, linfo[i].insn_off, prev_offset,
17120 				prog->len);
17121 			err = -EINVAL;
17122 			goto err_free;
17123 		}
17124 
17125 		if (!prog->insnsi[linfo[i].insn_off].code) {
17126 			verbose(env,
17127 				"Invalid insn code at line_info[%u].insn_off\n",
17128 				i);
17129 			err = -EINVAL;
17130 			goto err_free;
17131 		}
17132 
17133 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
17134 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
17135 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
17136 			err = -EINVAL;
17137 			goto err_free;
17138 		}
17139 
17140 		if (s != env->subprog_cnt) {
17141 			if (linfo[i].insn_off == sub[s].start) {
17142 				sub[s].linfo_idx = i;
17143 				s++;
17144 			} else if (sub[s].start < linfo[i].insn_off) {
17145 				verbose(env, "missing bpf_line_info for func#%u\n", s);
17146 				err = -EINVAL;
17147 				goto err_free;
17148 			}
17149 		}
17150 
17151 		prev_offset = linfo[i].insn_off;
17152 		bpfptr_add(&ulinfo, rec_size);
17153 	}
17154 
17155 	if (s != env->subprog_cnt) {
17156 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
17157 			env->subprog_cnt - s, s);
17158 		err = -EINVAL;
17159 		goto err_free;
17160 	}
17161 
17162 	prog->aux->linfo = linfo;
17163 	prog->aux->nr_linfo = nr_linfo;
17164 
17165 	return 0;
17166 
17167 err_free:
17168 	kvfree(linfo);
17169 	return err;
17170 }
17171 
17172 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
17173 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
17174 
17175 static int check_core_relo(struct bpf_verifier_env *env,
17176 			   const union bpf_attr *attr,
17177 			   bpfptr_t uattr)
17178 {
17179 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
17180 	struct bpf_core_relo core_relo = {};
17181 	struct bpf_prog *prog = env->prog;
17182 	const struct btf *btf = prog->aux->btf;
17183 	struct bpf_core_ctx ctx = {
17184 		.log = &env->log,
17185 		.btf = btf,
17186 	};
17187 	bpfptr_t u_core_relo;
17188 	int err;
17189 
17190 	nr_core_relo = attr->core_relo_cnt;
17191 	if (!nr_core_relo)
17192 		return 0;
17193 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
17194 		return -EINVAL;
17195 
17196 	rec_size = attr->core_relo_rec_size;
17197 	if (rec_size < MIN_CORE_RELO_SIZE ||
17198 	    rec_size > MAX_CORE_RELO_SIZE ||
17199 	    rec_size % sizeof(u32))
17200 		return -EINVAL;
17201 
17202 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
17203 	expected_size = sizeof(struct bpf_core_relo);
17204 	ncopy = min_t(u32, expected_size, rec_size);
17205 
17206 	/* Unlike func_info and line_info, copy and apply each CO-RE
17207 	 * relocation record one at a time.
17208 	 */
17209 	for (i = 0; i < nr_core_relo; i++) {
17210 		/* future proofing when sizeof(bpf_core_relo) changes */
17211 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
17212 		if (err) {
17213 			if (err == -E2BIG) {
17214 				verbose(env, "nonzero tailing record in core_relo");
17215 				if (copy_to_bpfptr_offset(uattr,
17216 							  offsetof(union bpf_attr, core_relo_rec_size),
17217 							  &expected_size, sizeof(expected_size)))
17218 					err = -EFAULT;
17219 			}
17220 			break;
17221 		}
17222 
17223 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
17224 			err = -EFAULT;
17225 			break;
17226 		}
17227 
17228 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
17229 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
17230 				i, core_relo.insn_off, prog->len);
17231 			err = -EINVAL;
17232 			break;
17233 		}
17234 
17235 		err = bpf_core_apply(&ctx, &core_relo, i,
17236 				     &prog->insnsi[core_relo.insn_off / 8]);
17237 		if (err)
17238 			break;
17239 		bpfptr_add(&u_core_relo, rec_size);
17240 	}
17241 	return err;
17242 }
17243 
17244 static int check_btf_info_early(struct bpf_verifier_env *env,
17245 				const union bpf_attr *attr,
17246 				bpfptr_t uattr)
17247 {
17248 	struct btf *btf;
17249 	int err;
17250 
17251 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
17252 		if (check_abnormal_return(env))
17253 			return -EINVAL;
17254 		return 0;
17255 	}
17256 
17257 	btf = btf_get_by_fd(attr->prog_btf_fd);
17258 	if (IS_ERR(btf))
17259 		return PTR_ERR(btf);
17260 	if (btf_is_kernel(btf)) {
17261 		btf_put(btf);
17262 		return -EACCES;
17263 	}
17264 	env->prog->aux->btf = btf;
17265 
17266 	err = check_btf_func_early(env, attr, uattr);
17267 	if (err)
17268 		return err;
17269 	return 0;
17270 }
17271 
17272 static int check_btf_info(struct bpf_verifier_env *env,
17273 			  const union bpf_attr *attr,
17274 			  bpfptr_t uattr)
17275 {
17276 	int err;
17277 
17278 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
17279 		if (check_abnormal_return(env))
17280 			return -EINVAL;
17281 		return 0;
17282 	}
17283 
17284 	err = check_btf_func(env, attr, uattr);
17285 	if (err)
17286 		return err;
17287 
17288 	err = check_btf_line(env, attr, uattr);
17289 	if (err)
17290 		return err;
17291 
17292 	err = check_core_relo(env, attr, uattr);
17293 	if (err)
17294 		return err;
17295 
17296 	return 0;
17297 }
17298 
17299 /* check %cur's range satisfies %old's */
17300 static bool range_within(const struct bpf_reg_state *old,
17301 			 const struct bpf_reg_state *cur)
17302 {
17303 	return old->umin_value <= cur->umin_value &&
17304 	       old->umax_value >= cur->umax_value &&
17305 	       old->smin_value <= cur->smin_value &&
17306 	       old->smax_value >= cur->smax_value &&
17307 	       old->u32_min_value <= cur->u32_min_value &&
17308 	       old->u32_max_value >= cur->u32_max_value &&
17309 	       old->s32_min_value <= cur->s32_min_value &&
17310 	       old->s32_max_value >= cur->s32_max_value;
17311 }
17312 
17313 /* If in the old state two registers had the same id, then they need to have
17314  * the same id in the new state as well.  But that id could be different from
17315  * the old state, so we need to track the mapping from old to new ids.
17316  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
17317  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
17318  * regs with a different old id could still have new id 9, we don't care about
17319  * that.
17320  * So we look through our idmap to see if this old id has been seen before.  If
17321  * so, we require the new id to match; otherwise, we add the id pair to the map.
17322  */
17323 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
17324 {
17325 	struct bpf_id_pair *map = idmap->map;
17326 	unsigned int i;
17327 
17328 	/* either both IDs should be set or both should be zero */
17329 	if (!!old_id != !!cur_id)
17330 		return false;
17331 
17332 	if (old_id == 0) /* cur_id == 0 as well */
17333 		return true;
17334 
17335 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
17336 		if (!map[i].old) {
17337 			/* Reached an empty slot; haven't seen this id before */
17338 			map[i].old = old_id;
17339 			map[i].cur = cur_id;
17340 			return true;
17341 		}
17342 		if (map[i].old == old_id)
17343 			return map[i].cur == cur_id;
17344 		if (map[i].cur == cur_id)
17345 			return false;
17346 	}
17347 	/* We ran out of idmap slots, which should be impossible */
17348 	WARN_ON_ONCE(1);
17349 	return false;
17350 }
17351 
17352 /* Similar to check_ids(), but allocate a unique temporary ID
17353  * for 'old_id' or 'cur_id' of zero.
17354  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
17355  */
17356 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
17357 {
17358 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
17359 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
17360 
17361 	return check_ids(old_id, cur_id, idmap);
17362 }
17363 
17364 static void clean_func_state(struct bpf_verifier_env *env,
17365 			     struct bpf_func_state *st)
17366 {
17367 	enum bpf_reg_liveness live;
17368 	int i, j;
17369 
17370 	for (i = 0; i < BPF_REG_FP; i++) {
17371 		live = st->regs[i].live;
17372 		/* liveness must not touch this register anymore */
17373 		st->regs[i].live |= REG_LIVE_DONE;
17374 		if (!(live & REG_LIVE_READ))
17375 			/* since the register is unused, clear its state
17376 			 * to make further comparison simpler
17377 			 */
17378 			__mark_reg_not_init(env, &st->regs[i]);
17379 	}
17380 
17381 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
17382 		live = st->stack[i].spilled_ptr.live;
17383 		/* liveness must not touch this stack slot anymore */
17384 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
17385 		if (!(live & REG_LIVE_READ)) {
17386 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
17387 			for (j = 0; j < BPF_REG_SIZE; j++)
17388 				st->stack[i].slot_type[j] = STACK_INVALID;
17389 		}
17390 	}
17391 }
17392 
17393 static void clean_verifier_state(struct bpf_verifier_env *env,
17394 				 struct bpf_verifier_state *st)
17395 {
17396 	int i;
17397 
17398 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
17399 		/* all regs in this state in all frames were already marked */
17400 		return;
17401 
17402 	for (i = 0; i <= st->curframe; i++)
17403 		clean_func_state(env, st->frame[i]);
17404 }
17405 
17406 /* the parentage chains form a tree.
17407  * the verifier states are added to state lists at given insn and
17408  * pushed into state stack for future exploration.
17409  * when the verifier reaches bpf_exit insn some of the verifer states
17410  * stored in the state lists have their final liveness state already,
17411  * but a lot of states will get revised from liveness point of view when
17412  * the verifier explores other branches.
17413  * Example:
17414  * 1: r0 = 1
17415  * 2: if r1 == 100 goto pc+1
17416  * 3: r0 = 2
17417  * 4: exit
17418  * when the verifier reaches exit insn the register r0 in the state list of
17419  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
17420  * of insn 2 and goes exploring further. At the insn 4 it will walk the
17421  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
17422  *
17423  * Since the verifier pushes the branch states as it sees them while exploring
17424  * the program the condition of walking the branch instruction for the second
17425  * time means that all states below this branch were already explored and
17426  * their final liveness marks are already propagated.
17427  * Hence when the verifier completes the search of state list in is_state_visited()
17428  * we can call this clean_live_states() function to mark all liveness states
17429  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
17430  * will not be used.
17431  * This function also clears the registers and stack for states that !READ
17432  * to simplify state merging.
17433  *
17434  * Important note here that walking the same branch instruction in the callee
17435  * doesn't meant that the states are DONE. The verifier has to compare
17436  * the callsites
17437  */
17438 static void clean_live_states(struct bpf_verifier_env *env, int insn,
17439 			      struct bpf_verifier_state *cur)
17440 {
17441 	struct bpf_verifier_state_list *sl;
17442 
17443 	sl = *explored_state(env, insn);
17444 	while (sl) {
17445 		if (sl->state.branches)
17446 			goto next;
17447 		if (sl->state.insn_idx != insn ||
17448 		    !same_callsites(&sl->state, cur))
17449 			goto next;
17450 		clean_verifier_state(env, &sl->state);
17451 next:
17452 		sl = sl->next;
17453 	}
17454 }
17455 
17456 static bool regs_exact(const struct bpf_reg_state *rold,
17457 		       const struct bpf_reg_state *rcur,
17458 		       struct bpf_idmap *idmap)
17459 {
17460 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
17461 	       check_ids(rold->id, rcur->id, idmap) &&
17462 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
17463 }
17464 
17465 enum exact_level {
17466 	NOT_EXACT,
17467 	EXACT,
17468 	RANGE_WITHIN
17469 };
17470 
17471 /* Returns true if (rold safe implies rcur safe) */
17472 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
17473 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
17474 		    enum exact_level exact)
17475 {
17476 	if (exact == EXACT)
17477 		return regs_exact(rold, rcur, idmap);
17478 
17479 	if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT)
17480 		/* explored state didn't use this */
17481 		return true;
17482 	if (rold->type == NOT_INIT) {
17483 		if (exact == NOT_EXACT || rcur->type == NOT_INIT)
17484 			/* explored state can't have used this */
17485 			return true;
17486 	}
17487 
17488 	/* Enforce that register types have to match exactly, including their
17489 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
17490 	 * rule.
17491 	 *
17492 	 * One can make a point that using a pointer register as unbounded
17493 	 * SCALAR would be technically acceptable, but this could lead to
17494 	 * pointer leaks because scalars are allowed to leak while pointers
17495 	 * are not. We could make this safe in special cases if root is
17496 	 * calling us, but it's probably not worth the hassle.
17497 	 *
17498 	 * Also, register types that are *not* MAYBE_NULL could technically be
17499 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
17500 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
17501 	 * to the same map).
17502 	 * However, if the old MAYBE_NULL register then got NULL checked,
17503 	 * doing so could have affected others with the same id, and we can't
17504 	 * check for that because we lost the id when we converted to
17505 	 * a non-MAYBE_NULL variant.
17506 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
17507 	 * non-MAYBE_NULL registers as well.
17508 	 */
17509 	if (rold->type != rcur->type)
17510 		return false;
17511 
17512 	switch (base_type(rold->type)) {
17513 	case SCALAR_VALUE:
17514 		if (env->explore_alu_limits) {
17515 			/* explore_alu_limits disables tnum_in() and range_within()
17516 			 * logic and requires everything to be strict
17517 			 */
17518 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
17519 			       check_scalar_ids(rold->id, rcur->id, idmap);
17520 		}
17521 		if (!rold->precise && exact == NOT_EXACT)
17522 			return true;
17523 		if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
17524 			return false;
17525 		if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off))
17526 			return false;
17527 		/* Why check_ids() for scalar registers?
17528 		 *
17529 		 * Consider the following BPF code:
17530 		 *   1: r6 = ... unbound scalar, ID=a ...
17531 		 *   2: r7 = ... unbound scalar, ID=b ...
17532 		 *   3: if (r6 > r7) goto +1
17533 		 *   4: r6 = r7
17534 		 *   5: if (r6 > X) goto ...
17535 		 *   6: ... memory operation using r7 ...
17536 		 *
17537 		 * First verification path is [1-6]:
17538 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
17539 		 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
17540 		 *   r7 <= X, because r6 and r7 share same id.
17541 		 * Next verification path is [1-4, 6].
17542 		 *
17543 		 * Instruction (6) would be reached in two states:
17544 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
17545 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
17546 		 *
17547 		 * Use check_ids() to distinguish these states.
17548 		 * ---
17549 		 * Also verify that new value satisfies old value range knowledge.
17550 		 */
17551 		return range_within(rold, rcur) &&
17552 		       tnum_in(rold->var_off, rcur->var_off) &&
17553 		       check_scalar_ids(rold->id, rcur->id, idmap);
17554 	case PTR_TO_MAP_KEY:
17555 	case PTR_TO_MAP_VALUE:
17556 	case PTR_TO_MEM:
17557 	case PTR_TO_BUF:
17558 	case PTR_TO_TP_BUFFER:
17559 		/* If the new min/max/var_off satisfy the old ones and
17560 		 * everything else matches, we are OK.
17561 		 */
17562 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
17563 		       range_within(rold, rcur) &&
17564 		       tnum_in(rold->var_off, rcur->var_off) &&
17565 		       check_ids(rold->id, rcur->id, idmap) &&
17566 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
17567 	case PTR_TO_PACKET_META:
17568 	case PTR_TO_PACKET:
17569 		/* We must have at least as much range as the old ptr
17570 		 * did, so that any accesses which were safe before are
17571 		 * still safe.  This is true even if old range < old off,
17572 		 * since someone could have accessed through (ptr - k), or
17573 		 * even done ptr -= k in a register, to get a safe access.
17574 		 */
17575 		if (rold->range > rcur->range)
17576 			return false;
17577 		/* If the offsets don't match, we can't trust our alignment;
17578 		 * nor can we be sure that we won't fall out of range.
17579 		 */
17580 		if (rold->off != rcur->off)
17581 			return false;
17582 		/* id relations must be preserved */
17583 		if (!check_ids(rold->id, rcur->id, idmap))
17584 			return false;
17585 		/* new val must satisfy old val knowledge */
17586 		return range_within(rold, rcur) &&
17587 		       tnum_in(rold->var_off, rcur->var_off);
17588 	case PTR_TO_STACK:
17589 		/* two stack pointers are equal only if they're pointing to
17590 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
17591 		 */
17592 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
17593 	case PTR_TO_ARENA:
17594 		return true;
17595 	default:
17596 		return regs_exact(rold, rcur, idmap);
17597 	}
17598 }
17599 
17600 static struct bpf_reg_state unbound_reg;
17601 
17602 static __init int unbound_reg_init(void)
17603 {
17604 	__mark_reg_unknown_imprecise(&unbound_reg);
17605 	unbound_reg.live |= REG_LIVE_READ;
17606 	return 0;
17607 }
17608 late_initcall(unbound_reg_init);
17609 
17610 static bool is_stack_all_misc(struct bpf_verifier_env *env,
17611 			      struct bpf_stack_state *stack)
17612 {
17613 	u32 i;
17614 
17615 	for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
17616 		if ((stack->slot_type[i] == STACK_MISC) ||
17617 		    (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
17618 			continue;
17619 		return false;
17620 	}
17621 
17622 	return true;
17623 }
17624 
17625 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
17626 						  struct bpf_stack_state *stack)
17627 {
17628 	if (is_spilled_scalar_reg64(stack))
17629 		return &stack->spilled_ptr;
17630 
17631 	if (is_stack_all_misc(env, stack))
17632 		return &unbound_reg;
17633 
17634 	return NULL;
17635 }
17636 
17637 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
17638 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
17639 		      enum exact_level exact)
17640 {
17641 	int i, spi;
17642 
17643 	/* walk slots of the explored stack and ignore any additional
17644 	 * slots in the current stack, since explored(safe) state
17645 	 * didn't use them
17646 	 */
17647 	for (i = 0; i < old->allocated_stack; i++) {
17648 		struct bpf_reg_state *old_reg, *cur_reg;
17649 
17650 		spi = i / BPF_REG_SIZE;
17651 
17652 		if (exact != NOT_EXACT &&
17653 		    (i >= cur->allocated_stack ||
17654 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
17655 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
17656 			return false;
17657 
17658 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)
17659 		    && exact == NOT_EXACT) {
17660 			i += BPF_REG_SIZE - 1;
17661 			/* explored state didn't use this */
17662 			continue;
17663 		}
17664 
17665 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
17666 			continue;
17667 
17668 		if (env->allow_uninit_stack &&
17669 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
17670 			continue;
17671 
17672 		/* explored stack has more populated slots than current stack
17673 		 * and these slots were used
17674 		 */
17675 		if (i >= cur->allocated_stack)
17676 			return false;
17677 
17678 		/* 64-bit scalar spill vs all slots MISC and vice versa.
17679 		 * Load from all slots MISC produces unbound scalar.
17680 		 * Construct a fake register for such stack and call
17681 		 * regsafe() to ensure scalar ids are compared.
17682 		 */
17683 		old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
17684 		cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
17685 		if (old_reg && cur_reg) {
17686 			if (!regsafe(env, old_reg, cur_reg, idmap, exact))
17687 				return false;
17688 			i += BPF_REG_SIZE - 1;
17689 			continue;
17690 		}
17691 
17692 		/* if old state was safe with misc data in the stack
17693 		 * it will be safe with zero-initialized stack.
17694 		 * The opposite is not true
17695 		 */
17696 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
17697 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
17698 			continue;
17699 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
17700 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
17701 			/* Ex: old explored (safe) state has STACK_SPILL in
17702 			 * this stack slot, but current has STACK_MISC ->
17703 			 * this verifier states are not equivalent,
17704 			 * return false to continue verification of this path
17705 			 */
17706 			return false;
17707 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
17708 			continue;
17709 		/* Both old and cur are having same slot_type */
17710 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
17711 		case STACK_SPILL:
17712 			/* when explored and current stack slot are both storing
17713 			 * spilled registers, check that stored pointers types
17714 			 * are the same as well.
17715 			 * Ex: explored safe path could have stored
17716 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
17717 			 * but current path has stored:
17718 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
17719 			 * such verifier states are not equivalent.
17720 			 * return false to continue verification of this path
17721 			 */
17722 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
17723 				     &cur->stack[spi].spilled_ptr, idmap, exact))
17724 				return false;
17725 			break;
17726 		case STACK_DYNPTR:
17727 			old_reg = &old->stack[spi].spilled_ptr;
17728 			cur_reg = &cur->stack[spi].spilled_ptr;
17729 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
17730 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
17731 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
17732 				return false;
17733 			break;
17734 		case STACK_ITER:
17735 			old_reg = &old->stack[spi].spilled_ptr;
17736 			cur_reg = &cur->stack[spi].spilled_ptr;
17737 			/* iter.depth is not compared between states as it
17738 			 * doesn't matter for correctness and would otherwise
17739 			 * prevent convergence; we maintain it only to prevent
17740 			 * infinite loop check triggering, see
17741 			 * iter_active_depths_differ()
17742 			 */
17743 			if (old_reg->iter.btf != cur_reg->iter.btf ||
17744 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
17745 			    old_reg->iter.state != cur_reg->iter.state ||
17746 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
17747 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
17748 				return false;
17749 			break;
17750 		case STACK_MISC:
17751 		case STACK_ZERO:
17752 		case STACK_INVALID:
17753 			continue;
17754 		/* Ensure that new unhandled slot types return false by default */
17755 		default:
17756 			return false;
17757 		}
17758 	}
17759 	return true;
17760 }
17761 
17762 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
17763 		    struct bpf_idmap *idmap)
17764 {
17765 	int i;
17766 
17767 	if (old->acquired_refs != cur->acquired_refs)
17768 		return false;
17769 
17770 	for (i = 0; i < old->acquired_refs; i++) {
17771 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) ||
17772 		    old->refs[i].type != cur->refs[i].type)
17773 			return false;
17774 		switch (old->refs[i].type) {
17775 		case REF_TYPE_PTR:
17776 			break;
17777 		case REF_TYPE_LOCK:
17778 			if (old->refs[i].ptr != cur->refs[i].ptr)
17779 				return false;
17780 			break;
17781 		default:
17782 			WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type);
17783 			return false;
17784 		}
17785 	}
17786 
17787 	return true;
17788 }
17789 
17790 /* compare two verifier states
17791  *
17792  * all states stored in state_list are known to be valid, since
17793  * verifier reached 'bpf_exit' instruction through them
17794  *
17795  * this function is called when verifier exploring different branches of
17796  * execution popped from the state stack. If it sees an old state that has
17797  * more strict register state and more strict stack state then this execution
17798  * branch doesn't need to be explored further, since verifier already
17799  * concluded that more strict state leads to valid finish.
17800  *
17801  * Therefore two states are equivalent if register state is more conservative
17802  * and explored stack state is more conservative than the current one.
17803  * Example:
17804  *       explored                   current
17805  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
17806  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
17807  *
17808  * In other words if current stack state (one being explored) has more
17809  * valid slots than old one that already passed validation, it means
17810  * the verifier can stop exploring and conclude that current state is valid too
17811  *
17812  * Similarly with registers. If explored state has register type as invalid
17813  * whereas register type in current state is meaningful, it means that
17814  * the current state will reach 'bpf_exit' instruction safely
17815  */
17816 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
17817 			      struct bpf_func_state *cur, enum exact_level exact)
17818 {
17819 	int i;
17820 
17821 	if (old->callback_depth > cur->callback_depth)
17822 		return false;
17823 
17824 	for (i = 0; i < MAX_BPF_REG; i++)
17825 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
17826 			     &env->idmap_scratch, exact))
17827 			return false;
17828 
17829 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
17830 		return false;
17831 
17832 	if (!refsafe(old, cur, &env->idmap_scratch))
17833 		return false;
17834 
17835 	return true;
17836 }
17837 
17838 static void reset_idmap_scratch(struct bpf_verifier_env *env)
17839 {
17840 	env->idmap_scratch.tmp_id_gen = env->id_gen;
17841 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
17842 }
17843 
17844 static bool states_equal(struct bpf_verifier_env *env,
17845 			 struct bpf_verifier_state *old,
17846 			 struct bpf_verifier_state *cur,
17847 			 enum exact_level exact)
17848 {
17849 	int i;
17850 
17851 	if (old->curframe != cur->curframe)
17852 		return false;
17853 
17854 	reset_idmap_scratch(env);
17855 
17856 	/* Verification state from speculative execution simulation
17857 	 * must never prune a non-speculative execution one.
17858 	 */
17859 	if (old->speculative && !cur->speculative)
17860 		return false;
17861 
17862 	if (old->active_rcu_lock != cur->active_rcu_lock)
17863 		return false;
17864 
17865 	if (old->active_preempt_lock != cur->active_preempt_lock)
17866 		return false;
17867 
17868 	if (old->in_sleepable != cur->in_sleepable)
17869 		return false;
17870 
17871 	/* for states to be equal callsites have to be the same
17872 	 * and all frame states need to be equivalent
17873 	 */
17874 	for (i = 0; i <= old->curframe; i++) {
17875 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
17876 			return false;
17877 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
17878 			return false;
17879 	}
17880 	return true;
17881 }
17882 
17883 /* Return 0 if no propagation happened. Return negative error code if error
17884  * happened. Otherwise, return the propagated bit.
17885  */
17886 static int propagate_liveness_reg(struct bpf_verifier_env *env,
17887 				  struct bpf_reg_state *reg,
17888 				  struct bpf_reg_state *parent_reg)
17889 {
17890 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
17891 	u8 flag = reg->live & REG_LIVE_READ;
17892 	int err;
17893 
17894 	/* When comes here, read flags of PARENT_REG or REG could be any of
17895 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
17896 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
17897 	 */
17898 	if (parent_flag == REG_LIVE_READ64 ||
17899 	    /* Or if there is no read flag from REG. */
17900 	    !flag ||
17901 	    /* Or if the read flag from REG is the same as PARENT_REG. */
17902 	    parent_flag == flag)
17903 		return 0;
17904 
17905 	err = mark_reg_read(env, reg, parent_reg, flag);
17906 	if (err)
17907 		return err;
17908 
17909 	return flag;
17910 }
17911 
17912 /* A write screens off any subsequent reads; but write marks come from the
17913  * straight-line code between a state and its parent.  When we arrive at an
17914  * equivalent state (jump target or such) we didn't arrive by the straight-line
17915  * code, so read marks in the state must propagate to the parent regardless
17916  * of the state's write marks. That's what 'parent == state->parent' comparison
17917  * in mark_reg_read() is for.
17918  */
17919 static int propagate_liveness(struct bpf_verifier_env *env,
17920 			      const struct bpf_verifier_state *vstate,
17921 			      struct bpf_verifier_state *vparent)
17922 {
17923 	struct bpf_reg_state *state_reg, *parent_reg;
17924 	struct bpf_func_state *state, *parent;
17925 	int i, frame, err = 0;
17926 
17927 	if (vparent->curframe != vstate->curframe) {
17928 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
17929 		     vparent->curframe, vstate->curframe);
17930 		return -EFAULT;
17931 	}
17932 	/* Propagate read liveness of registers... */
17933 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
17934 	for (frame = 0; frame <= vstate->curframe; frame++) {
17935 		parent = vparent->frame[frame];
17936 		state = vstate->frame[frame];
17937 		parent_reg = parent->regs;
17938 		state_reg = state->regs;
17939 		/* We don't need to worry about FP liveness, it's read-only */
17940 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
17941 			err = propagate_liveness_reg(env, &state_reg[i],
17942 						     &parent_reg[i]);
17943 			if (err < 0)
17944 				return err;
17945 			if (err == REG_LIVE_READ64)
17946 				mark_insn_zext(env, &parent_reg[i]);
17947 		}
17948 
17949 		/* Propagate stack slots. */
17950 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
17951 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
17952 			parent_reg = &parent->stack[i].spilled_ptr;
17953 			state_reg = &state->stack[i].spilled_ptr;
17954 			err = propagate_liveness_reg(env, state_reg,
17955 						     parent_reg);
17956 			if (err < 0)
17957 				return err;
17958 		}
17959 	}
17960 	return 0;
17961 }
17962 
17963 /* find precise scalars in the previous equivalent state and
17964  * propagate them into the current state
17965  */
17966 static int propagate_precision(struct bpf_verifier_env *env,
17967 			       const struct bpf_verifier_state *old)
17968 {
17969 	struct bpf_reg_state *state_reg;
17970 	struct bpf_func_state *state;
17971 	int i, err = 0, fr;
17972 	bool first;
17973 
17974 	for (fr = old->curframe; fr >= 0; fr--) {
17975 		state = old->frame[fr];
17976 		state_reg = state->regs;
17977 		first = true;
17978 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
17979 			if (state_reg->type != SCALAR_VALUE ||
17980 			    !state_reg->precise ||
17981 			    !(state_reg->live & REG_LIVE_READ))
17982 				continue;
17983 			if (env->log.level & BPF_LOG_LEVEL2) {
17984 				if (first)
17985 					verbose(env, "frame %d: propagating r%d", fr, i);
17986 				else
17987 					verbose(env, ",r%d", i);
17988 			}
17989 			bt_set_frame_reg(&env->bt, fr, i);
17990 			first = false;
17991 		}
17992 
17993 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17994 			if (!is_spilled_reg(&state->stack[i]))
17995 				continue;
17996 			state_reg = &state->stack[i].spilled_ptr;
17997 			if (state_reg->type != SCALAR_VALUE ||
17998 			    !state_reg->precise ||
17999 			    !(state_reg->live & REG_LIVE_READ))
18000 				continue;
18001 			if (env->log.level & BPF_LOG_LEVEL2) {
18002 				if (first)
18003 					verbose(env, "frame %d: propagating fp%d",
18004 						fr, (-i - 1) * BPF_REG_SIZE);
18005 				else
18006 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
18007 			}
18008 			bt_set_frame_slot(&env->bt, fr, i);
18009 			first = false;
18010 		}
18011 		if (!first)
18012 			verbose(env, "\n");
18013 	}
18014 
18015 	err = mark_chain_precision_batch(env);
18016 	if (err < 0)
18017 		return err;
18018 
18019 	return 0;
18020 }
18021 
18022 static bool states_maybe_looping(struct bpf_verifier_state *old,
18023 				 struct bpf_verifier_state *cur)
18024 {
18025 	struct bpf_func_state *fold, *fcur;
18026 	int i, fr = cur->curframe;
18027 
18028 	if (old->curframe != fr)
18029 		return false;
18030 
18031 	fold = old->frame[fr];
18032 	fcur = cur->frame[fr];
18033 	for (i = 0; i < MAX_BPF_REG; i++)
18034 		if (memcmp(&fold->regs[i], &fcur->regs[i],
18035 			   offsetof(struct bpf_reg_state, parent)))
18036 			return false;
18037 	return true;
18038 }
18039 
18040 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
18041 {
18042 	return env->insn_aux_data[insn_idx].is_iter_next;
18043 }
18044 
18045 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
18046  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
18047  * states to match, which otherwise would look like an infinite loop. So while
18048  * iter_next() calls are taken care of, we still need to be careful and
18049  * prevent erroneous and too eager declaration of "ininite loop", when
18050  * iterators are involved.
18051  *
18052  * Here's a situation in pseudo-BPF assembly form:
18053  *
18054  *   0: again:                          ; set up iter_next() call args
18055  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
18056  *   2:   call bpf_iter_num_next        ; this is iter_next() call
18057  *   3:   if r0 == 0 goto done
18058  *   4:   ... something useful here ...
18059  *   5:   goto again                    ; another iteration
18060  *   6: done:
18061  *   7:   r1 = &it
18062  *   8:   call bpf_iter_num_destroy     ; clean up iter state
18063  *   9:   exit
18064  *
18065  * This is a typical loop. Let's assume that we have a prune point at 1:,
18066  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
18067  * again`, assuming other heuristics don't get in a way).
18068  *
18069  * When we first time come to 1:, let's say we have some state X. We proceed
18070  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
18071  * Now we come back to validate that forked ACTIVE state. We proceed through
18072  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
18073  * are converging. But the problem is that we don't know that yet, as this
18074  * convergence has to happen at iter_next() call site only. So if nothing is
18075  * done, at 1: verifier will use bounded loop logic and declare infinite
18076  * looping (and would be *technically* correct, if not for iterator's
18077  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
18078  * don't want that. So what we do in process_iter_next_call() when we go on
18079  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
18080  * a different iteration. So when we suspect an infinite loop, we additionally
18081  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
18082  * pretend we are not looping and wait for next iter_next() call.
18083  *
18084  * This only applies to ACTIVE state. In DRAINED state we don't expect to
18085  * loop, because that would actually mean infinite loop, as DRAINED state is
18086  * "sticky", and so we'll keep returning into the same instruction with the
18087  * same state (at least in one of possible code paths).
18088  *
18089  * This approach allows to keep infinite loop heuristic even in the face of
18090  * active iterator. E.g., C snippet below is and will be detected as
18091  * inifintely looping:
18092  *
18093  *   struct bpf_iter_num it;
18094  *   int *p, x;
18095  *
18096  *   bpf_iter_num_new(&it, 0, 10);
18097  *   while ((p = bpf_iter_num_next(&t))) {
18098  *       x = p;
18099  *       while (x--) {} // <<-- infinite loop here
18100  *   }
18101  *
18102  */
18103 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
18104 {
18105 	struct bpf_reg_state *slot, *cur_slot;
18106 	struct bpf_func_state *state;
18107 	int i, fr;
18108 
18109 	for (fr = old->curframe; fr >= 0; fr--) {
18110 		state = old->frame[fr];
18111 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
18112 			if (state->stack[i].slot_type[0] != STACK_ITER)
18113 				continue;
18114 
18115 			slot = &state->stack[i].spilled_ptr;
18116 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
18117 				continue;
18118 
18119 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
18120 			if (cur_slot->iter.depth != slot->iter.depth)
18121 				return true;
18122 		}
18123 	}
18124 	return false;
18125 }
18126 
18127 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
18128 {
18129 	struct bpf_verifier_state_list *new_sl;
18130 	struct bpf_verifier_state_list *sl, **pprev;
18131 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
18132 	int i, j, n, err, states_cnt = 0;
18133 	bool force_new_state, add_new_state, force_exact;
18134 
18135 	force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
18136 			  /* Avoid accumulating infinitely long jmp history */
18137 			  cur->insn_hist_end - cur->insn_hist_start > 40;
18138 
18139 	/* bpf progs typically have pruning point every 4 instructions
18140 	 * http://vger.kernel.org/bpfconf2019.html#session-1
18141 	 * Do not add new state for future pruning if the verifier hasn't seen
18142 	 * at least 2 jumps and at least 8 instructions.
18143 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
18144 	 * In tests that amounts to up to 50% reduction into total verifier
18145 	 * memory consumption and 20% verifier time speedup.
18146 	 */
18147 	add_new_state = force_new_state;
18148 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
18149 	    env->insn_processed - env->prev_insn_processed >= 8)
18150 		add_new_state = true;
18151 
18152 	pprev = explored_state(env, insn_idx);
18153 	sl = *pprev;
18154 
18155 	clean_live_states(env, insn_idx, cur);
18156 
18157 	while (sl) {
18158 		states_cnt++;
18159 		if (sl->state.insn_idx != insn_idx)
18160 			goto next;
18161 
18162 		if (sl->state.branches) {
18163 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
18164 
18165 			if (frame->in_async_callback_fn &&
18166 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
18167 				/* Different async_entry_cnt means that the verifier is
18168 				 * processing another entry into async callback.
18169 				 * Seeing the same state is not an indication of infinite
18170 				 * loop or infinite recursion.
18171 				 * But finding the same state doesn't mean that it's safe
18172 				 * to stop processing the current state. The previous state
18173 				 * hasn't yet reached bpf_exit, since state.branches > 0.
18174 				 * Checking in_async_callback_fn alone is not enough either.
18175 				 * Since the verifier still needs to catch infinite loops
18176 				 * inside async callbacks.
18177 				 */
18178 				goto skip_inf_loop_check;
18179 			}
18180 			/* BPF open-coded iterators loop detection is special.
18181 			 * states_maybe_looping() logic is too simplistic in detecting
18182 			 * states that *might* be equivalent, because it doesn't know
18183 			 * about ID remapping, so don't even perform it.
18184 			 * See process_iter_next_call() and iter_active_depths_differ()
18185 			 * for overview of the logic. When current and one of parent
18186 			 * states are detected as equivalent, it's a good thing: we prove
18187 			 * convergence and can stop simulating further iterations.
18188 			 * It's safe to assume that iterator loop will finish, taking into
18189 			 * account iter_next() contract of eventually returning
18190 			 * sticky NULL result.
18191 			 *
18192 			 * Note, that states have to be compared exactly in this case because
18193 			 * read and precision marks might not be finalized inside the loop.
18194 			 * E.g. as in the program below:
18195 			 *
18196 			 *     1. r7 = -16
18197 			 *     2. r6 = bpf_get_prandom_u32()
18198 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
18199 			 *     4.   if (r6 != 42) {
18200 			 *     5.     r7 = -32
18201 			 *     6.     r6 = bpf_get_prandom_u32()
18202 			 *     7.     continue
18203 			 *     8.   }
18204 			 *     9.   r0 = r10
18205 			 *    10.   r0 += r7
18206 			 *    11.   r8 = *(u64 *)(r0 + 0)
18207 			 *    12.   r6 = bpf_get_prandom_u32()
18208 			 *    13. }
18209 			 *
18210 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
18211 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
18212 			 * not have read or precision mark for r7 yet, thus inexact states
18213 			 * comparison would discard current state with r7=-32
18214 			 * => unsafe memory access at 11 would not be caught.
18215 			 */
18216 			if (is_iter_next_insn(env, insn_idx)) {
18217 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
18218 					struct bpf_func_state *cur_frame;
18219 					struct bpf_reg_state *iter_state, *iter_reg;
18220 					int spi;
18221 
18222 					cur_frame = cur->frame[cur->curframe];
18223 					/* btf_check_iter_kfuncs() enforces that
18224 					 * iter state pointer is always the first arg
18225 					 */
18226 					iter_reg = &cur_frame->regs[BPF_REG_1];
18227 					/* current state is valid due to states_equal(),
18228 					 * so we can assume valid iter and reg state,
18229 					 * no need for extra (re-)validations
18230 					 */
18231 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
18232 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
18233 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
18234 						update_loop_entry(cur, &sl->state);
18235 						goto hit;
18236 					}
18237 				}
18238 				goto skip_inf_loop_check;
18239 			}
18240 			if (is_may_goto_insn_at(env, insn_idx)) {
18241 				if (sl->state.may_goto_depth != cur->may_goto_depth &&
18242 				    states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
18243 					update_loop_entry(cur, &sl->state);
18244 					goto hit;
18245 				}
18246 			}
18247 			if (calls_callback(env, insn_idx)) {
18248 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
18249 					goto hit;
18250 				goto skip_inf_loop_check;
18251 			}
18252 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
18253 			if (states_maybe_looping(&sl->state, cur) &&
18254 			    states_equal(env, &sl->state, cur, EXACT) &&
18255 			    !iter_active_depths_differ(&sl->state, cur) &&
18256 			    sl->state.may_goto_depth == cur->may_goto_depth &&
18257 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
18258 				verbose_linfo(env, insn_idx, "; ");
18259 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
18260 				verbose(env, "cur state:");
18261 				print_verifier_state(env, cur->frame[cur->curframe], true);
18262 				verbose(env, "old state:");
18263 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
18264 				return -EINVAL;
18265 			}
18266 			/* if the verifier is processing a loop, avoid adding new state
18267 			 * too often, since different loop iterations have distinct
18268 			 * states and may not help future pruning.
18269 			 * This threshold shouldn't be too low to make sure that
18270 			 * a loop with large bound will be rejected quickly.
18271 			 * The most abusive loop will be:
18272 			 * r1 += 1
18273 			 * if r1 < 1000000 goto pc-2
18274 			 * 1M insn_procssed limit / 100 == 10k peak states.
18275 			 * This threshold shouldn't be too high either, since states
18276 			 * at the end of the loop are likely to be useful in pruning.
18277 			 */
18278 skip_inf_loop_check:
18279 			if (!force_new_state &&
18280 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
18281 			    env->insn_processed - env->prev_insn_processed < 100)
18282 				add_new_state = false;
18283 			goto miss;
18284 		}
18285 		/* If sl->state is a part of a loop and this loop's entry is a part of
18286 		 * current verification path then states have to be compared exactly.
18287 		 * 'force_exact' is needed to catch the following case:
18288 		 *
18289 		 *                initial     Here state 'succ' was processed first,
18290 		 *                  |         it was eventually tracked to produce a
18291 		 *                  V         state identical to 'hdr'.
18292 		 *     .---------> hdr        All branches from 'succ' had been explored
18293 		 *     |            |         and thus 'succ' has its .branches == 0.
18294 		 *     |            V
18295 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
18296 		 *     |    |       |         to the same instruction + callsites.
18297 		 *     |    V       V         In such case it is necessary to check
18298 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
18299 		 *     |    |       |         If 'succ' and 'cur' are a part of the
18300 		 *     |    V       V         same loop exact flag has to be set.
18301 		 *     |   succ <- cur        To check if that is the case, verify
18302 		 *     |    |                 if loop entry of 'succ' is in current
18303 		 *     |    V                 DFS path.
18304 		 *     |   ...
18305 		 *     |    |
18306 		 *     '----'
18307 		 *
18308 		 * Additional details are in the comment before get_loop_entry().
18309 		 */
18310 		loop_entry = get_loop_entry(&sl->state);
18311 		force_exact = loop_entry && loop_entry->branches > 0;
18312 		if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) {
18313 			if (force_exact)
18314 				update_loop_entry(cur, loop_entry);
18315 hit:
18316 			sl->hit_cnt++;
18317 			/* reached equivalent register/stack state,
18318 			 * prune the search.
18319 			 * Registers read by the continuation are read by us.
18320 			 * If we have any write marks in env->cur_state, they
18321 			 * will prevent corresponding reads in the continuation
18322 			 * from reaching our parent (an explored_state).  Our
18323 			 * own state will get the read marks recorded, but
18324 			 * they'll be immediately forgotten as we're pruning
18325 			 * this state and will pop a new one.
18326 			 */
18327 			err = propagate_liveness(env, &sl->state, cur);
18328 
18329 			/* if previous state reached the exit with precision and
18330 			 * current state is equivalent to it (except precision marks)
18331 			 * the precision needs to be propagated back in
18332 			 * the current state.
18333 			 */
18334 			if (is_jmp_point(env, env->insn_idx))
18335 				err = err ? : push_insn_history(env, cur, 0, 0);
18336 			err = err ? : propagate_precision(env, &sl->state);
18337 			if (err)
18338 				return err;
18339 			return 1;
18340 		}
18341 miss:
18342 		/* when new state is not going to be added do not increase miss count.
18343 		 * Otherwise several loop iterations will remove the state
18344 		 * recorded earlier. The goal of these heuristics is to have
18345 		 * states from some iterations of the loop (some in the beginning
18346 		 * and some at the end) to help pruning.
18347 		 */
18348 		if (add_new_state)
18349 			sl->miss_cnt++;
18350 		/* heuristic to determine whether this state is beneficial
18351 		 * to keep checking from state equivalence point of view.
18352 		 * Higher numbers increase max_states_per_insn and verification time,
18353 		 * but do not meaningfully decrease insn_processed.
18354 		 * 'n' controls how many times state could miss before eviction.
18355 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
18356 		 * too early would hinder iterator convergence.
18357 		 */
18358 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
18359 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
18360 			/* the state is unlikely to be useful. Remove it to
18361 			 * speed up verification
18362 			 */
18363 			*pprev = sl->next;
18364 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
18365 			    !sl->state.used_as_loop_entry) {
18366 				u32 br = sl->state.branches;
18367 
18368 				WARN_ONCE(br,
18369 					  "BUG live_done but branches_to_explore %d\n",
18370 					  br);
18371 				free_verifier_state(&sl->state, false);
18372 				kfree(sl);
18373 				env->peak_states--;
18374 			} else {
18375 				/* cannot free this state, since parentage chain may
18376 				 * walk it later. Add it for free_list instead to
18377 				 * be freed at the end of verification
18378 				 */
18379 				sl->next = env->free_list;
18380 				env->free_list = sl;
18381 			}
18382 			sl = *pprev;
18383 			continue;
18384 		}
18385 next:
18386 		pprev = &sl->next;
18387 		sl = *pprev;
18388 	}
18389 
18390 	if (env->max_states_per_insn < states_cnt)
18391 		env->max_states_per_insn = states_cnt;
18392 
18393 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
18394 		return 0;
18395 
18396 	if (!add_new_state)
18397 		return 0;
18398 
18399 	/* There were no equivalent states, remember the current one.
18400 	 * Technically the current state is not proven to be safe yet,
18401 	 * but it will either reach outer most bpf_exit (which means it's safe)
18402 	 * or it will be rejected. When there are no loops the verifier won't be
18403 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
18404 	 * again on the way to bpf_exit.
18405 	 * When looping the sl->state.branches will be > 0 and this state
18406 	 * will not be considered for equivalence until branches == 0.
18407 	 */
18408 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
18409 	if (!new_sl)
18410 		return -ENOMEM;
18411 	env->total_states++;
18412 	env->peak_states++;
18413 	env->prev_jmps_processed = env->jmps_processed;
18414 	env->prev_insn_processed = env->insn_processed;
18415 
18416 	/* forget precise markings we inherited, see __mark_chain_precision */
18417 	if (env->bpf_capable)
18418 		mark_all_scalars_imprecise(env, cur);
18419 
18420 	/* add new state to the head of linked list */
18421 	new = &new_sl->state;
18422 	err = copy_verifier_state(new, cur);
18423 	if (err) {
18424 		free_verifier_state(new, false);
18425 		kfree(new_sl);
18426 		return err;
18427 	}
18428 	new->insn_idx = insn_idx;
18429 	WARN_ONCE(new->branches != 1,
18430 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
18431 
18432 	cur->parent = new;
18433 	cur->first_insn_idx = insn_idx;
18434 	cur->insn_hist_start = cur->insn_hist_end;
18435 	cur->dfs_depth = new->dfs_depth + 1;
18436 	new_sl->next = *explored_state(env, insn_idx);
18437 	*explored_state(env, insn_idx) = new_sl;
18438 	/* connect new state to parentage chain. Current frame needs all
18439 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
18440 	 * to the stack implicitly by JITs) so in callers' frames connect just
18441 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
18442 	 * the state of the call instruction (with WRITTEN set), and r0 comes
18443 	 * from callee with its full parentage chain, anyway.
18444 	 */
18445 	/* clear write marks in current state: the writes we did are not writes
18446 	 * our child did, so they don't screen off its reads from us.
18447 	 * (There are no read marks in current state, because reads always mark
18448 	 * their parent and current state never has children yet.  Only
18449 	 * explored_states can get read marks.)
18450 	 */
18451 	for (j = 0; j <= cur->curframe; j++) {
18452 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
18453 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
18454 		for (i = 0; i < BPF_REG_FP; i++)
18455 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
18456 	}
18457 
18458 	/* all stack frames are accessible from callee, clear them all */
18459 	for (j = 0; j <= cur->curframe; j++) {
18460 		struct bpf_func_state *frame = cur->frame[j];
18461 		struct bpf_func_state *newframe = new->frame[j];
18462 
18463 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
18464 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
18465 			frame->stack[i].spilled_ptr.parent =
18466 						&newframe->stack[i].spilled_ptr;
18467 		}
18468 	}
18469 	return 0;
18470 }
18471 
18472 /* Return true if it's OK to have the same insn return a different type. */
18473 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
18474 {
18475 	switch (base_type(type)) {
18476 	case PTR_TO_CTX:
18477 	case PTR_TO_SOCKET:
18478 	case PTR_TO_SOCK_COMMON:
18479 	case PTR_TO_TCP_SOCK:
18480 	case PTR_TO_XDP_SOCK:
18481 	case PTR_TO_BTF_ID:
18482 	case PTR_TO_ARENA:
18483 		return false;
18484 	default:
18485 		return true;
18486 	}
18487 }
18488 
18489 /* If an instruction was previously used with particular pointer types, then we
18490  * need to be careful to avoid cases such as the below, where it may be ok
18491  * for one branch accessing the pointer, but not ok for the other branch:
18492  *
18493  * R1 = sock_ptr
18494  * goto X;
18495  * ...
18496  * R1 = some_other_valid_ptr;
18497  * goto X;
18498  * ...
18499  * R2 = *(u32 *)(R1 + 0);
18500  */
18501 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
18502 {
18503 	return src != prev && (!reg_type_mismatch_ok(src) ||
18504 			       !reg_type_mismatch_ok(prev));
18505 }
18506 
18507 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
18508 			     bool allow_trust_mismatch)
18509 {
18510 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
18511 
18512 	if (*prev_type == NOT_INIT) {
18513 		/* Saw a valid insn
18514 		 * dst_reg = *(u32 *)(src_reg + off)
18515 		 * save type to validate intersecting paths
18516 		 */
18517 		*prev_type = type;
18518 	} else if (reg_type_mismatch(type, *prev_type)) {
18519 		/* Abuser program is trying to use the same insn
18520 		 * dst_reg = *(u32*) (src_reg + off)
18521 		 * with different pointer types:
18522 		 * src_reg == ctx in one branch and
18523 		 * src_reg == stack|map in some other branch.
18524 		 * Reject it.
18525 		 */
18526 		if (allow_trust_mismatch &&
18527 		    base_type(type) == PTR_TO_BTF_ID &&
18528 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
18529 			/*
18530 			 * Have to support a use case when one path through
18531 			 * the program yields TRUSTED pointer while another
18532 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
18533 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
18534 			 */
18535 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
18536 		} else {
18537 			verbose(env, "same insn cannot be used with different pointers\n");
18538 			return -EINVAL;
18539 		}
18540 	}
18541 
18542 	return 0;
18543 }
18544 
18545 static int do_check(struct bpf_verifier_env *env)
18546 {
18547 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18548 	struct bpf_verifier_state *state = env->cur_state;
18549 	struct bpf_insn *insns = env->prog->insnsi;
18550 	struct bpf_reg_state *regs;
18551 	int insn_cnt = env->prog->len;
18552 	bool do_print_state = false;
18553 	int prev_insn_idx = -1;
18554 
18555 	for (;;) {
18556 		bool exception_exit = false;
18557 		struct bpf_insn *insn;
18558 		u8 class;
18559 		int err;
18560 
18561 		/* reset current history entry on each new instruction */
18562 		env->cur_hist_ent = NULL;
18563 
18564 		env->prev_insn_idx = prev_insn_idx;
18565 		if (env->insn_idx >= insn_cnt) {
18566 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
18567 				env->insn_idx, insn_cnt);
18568 			return -EFAULT;
18569 		}
18570 
18571 		insn = &insns[env->insn_idx];
18572 		class = BPF_CLASS(insn->code);
18573 
18574 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
18575 			verbose(env,
18576 				"BPF program is too large. Processed %d insn\n",
18577 				env->insn_processed);
18578 			return -E2BIG;
18579 		}
18580 
18581 		state->last_insn_idx = env->prev_insn_idx;
18582 
18583 		if (is_prune_point(env, env->insn_idx)) {
18584 			err = is_state_visited(env, env->insn_idx);
18585 			if (err < 0)
18586 				return err;
18587 			if (err == 1) {
18588 				/* found equivalent state, can prune the search */
18589 				if (env->log.level & BPF_LOG_LEVEL) {
18590 					if (do_print_state)
18591 						verbose(env, "\nfrom %d to %d%s: safe\n",
18592 							env->prev_insn_idx, env->insn_idx,
18593 							env->cur_state->speculative ?
18594 							" (speculative execution)" : "");
18595 					else
18596 						verbose(env, "%d: safe\n", env->insn_idx);
18597 				}
18598 				goto process_bpf_exit;
18599 			}
18600 		}
18601 
18602 		if (is_jmp_point(env, env->insn_idx)) {
18603 			err = push_insn_history(env, state, 0, 0);
18604 			if (err)
18605 				return err;
18606 		}
18607 
18608 		if (signal_pending(current))
18609 			return -EAGAIN;
18610 
18611 		if (need_resched())
18612 			cond_resched();
18613 
18614 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
18615 			verbose(env, "\nfrom %d to %d%s:",
18616 				env->prev_insn_idx, env->insn_idx,
18617 				env->cur_state->speculative ?
18618 				" (speculative execution)" : "");
18619 			print_verifier_state(env, state->frame[state->curframe], true);
18620 			do_print_state = false;
18621 		}
18622 
18623 		if (env->log.level & BPF_LOG_LEVEL) {
18624 			const struct bpf_insn_cbs cbs = {
18625 				.cb_call	= disasm_kfunc_name,
18626 				.cb_print	= verbose,
18627 				.private_data	= env,
18628 			};
18629 
18630 			if (verifier_state_scratched(env))
18631 				print_insn_state(env, state->frame[state->curframe]);
18632 
18633 			verbose_linfo(env, env->insn_idx, "; ");
18634 			env->prev_log_pos = env->log.end_pos;
18635 			verbose(env, "%d: ", env->insn_idx);
18636 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
18637 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
18638 			env->prev_log_pos = env->log.end_pos;
18639 		}
18640 
18641 		if (bpf_prog_is_offloaded(env->prog->aux)) {
18642 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
18643 							   env->prev_insn_idx);
18644 			if (err)
18645 				return err;
18646 		}
18647 
18648 		regs = cur_regs(env);
18649 		sanitize_mark_insn_seen(env);
18650 		prev_insn_idx = env->insn_idx;
18651 
18652 		if (class == BPF_ALU || class == BPF_ALU64) {
18653 			err = check_alu_op(env, insn);
18654 			if (err)
18655 				return err;
18656 
18657 		} else if (class == BPF_LDX) {
18658 			enum bpf_reg_type src_reg_type;
18659 
18660 			/* check for reserved fields is already done */
18661 
18662 			/* check src operand */
18663 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
18664 			if (err)
18665 				return err;
18666 
18667 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
18668 			if (err)
18669 				return err;
18670 
18671 			src_reg_type = regs[insn->src_reg].type;
18672 
18673 			/* check that memory (src_reg + off) is readable,
18674 			 * the state of dst_reg will be updated by this func
18675 			 */
18676 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
18677 					       insn->off, BPF_SIZE(insn->code),
18678 					       BPF_READ, insn->dst_reg, false,
18679 					       BPF_MODE(insn->code) == BPF_MEMSX);
18680 			err = err ?: save_aux_ptr_type(env, src_reg_type, true);
18681 			err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], "ldx");
18682 			if (err)
18683 				return err;
18684 		} else if (class == BPF_STX) {
18685 			enum bpf_reg_type dst_reg_type;
18686 
18687 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
18688 				err = check_atomic(env, env->insn_idx, insn);
18689 				if (err)
18690 					return err;
18691 				env->insn_idx++;
18692 				continue;
18693 			}
18694 
18695 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
18696 				verbose(env, "BPF_STX uses reserved fields\n");
18697 				return -EINVAL;
18698 			}
18699 
18700 			/* check src1 operand */
18701 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
18702 			if (err)
18703 				return err;
18704 			/* check src2 operand */
18705 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
18706 			if (err)
18707 				return err;
18708 
18709 			dst_reg_type = regs[insn->dst_reg].type;
18710 
18711 			/* check that memory (dst_reg + off) is writeable */
18712 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
18713 					       insn->off, BPF_SIZE(insn->code),
18714 					       BPF_WRITE, insn->src_reg, false, false);
18715 			if (err)
18716 				return err;
18717 
18718 			err = save_aux_ptr_type(env, dst_reg_type, false);
18719 			if (err)
18720 				return err;
18721 		} else if (class == BPF_ST) {
18722 			enum bpf_reg_type dst_reg_type;
18723 
18724 			if (BPF_MODE(insn->code) != BPF_MEM ||
18725 			    insn->src_reg != BPF_REG_0) {
18726 				verbose(env, "BPF_ST uses reserved fields\n");
18727 				return -EINVAL;
18728 			}
18729 			/* check src operand */
18730 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
18731 			if (err)
18732 				return err;
18733 
18734 			dst_reg_type = regs[insn->dst_reg].type;
18735 
18736 			/* check that memory (dst_reg + off) is writeable */
18737 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
18738 					       insn->off, BPF_SIZE(insn->code),
18739 					       BPF_WRITE, -1, false, false);
18740 			if (err)
18741 				return err;
18742 
18743 			err = save_aux_ptr_type(env, dst_reg_type, false);
18744 			if (err)
18745 				return err;
18746 		} else if (class == BPF_JMP || class == BPF_JMP32) {
18747 			u8 opcode = BPF_OP(insn->code);
18748 
18749 			env->jmps_processed++;
18750 			if (opcode == BPF_CALL) {
18751 				if (BPF_SRC(insn->code) != BPF_K ||
18752 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
18753 				     && insn->off != 0) ||
18754 				    (insn->src_reg != BPF_REG_0 &&
18755 				     insn->src_reg != BPF_PSEUDO_CALL &&
18756 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
18757 				    insn->dst_reg != BPF_REG_0 ||
18758 				    class == BPF_JMP32) {
18759 					verbose(env, "BPF_CALL uses reserved fields\n");
18760 					return -EINVAL;
18761 				}
18762 
18763 				if (cur_func(env)->active_locks) {
18764 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
18765 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
18766 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
18767 						verbose(env, "function calls are not allowed while holding a lock\n");
18768 						return -EINVAL;
18769 					}
18770 				}
18771 				if (insn->src_reg == BPF_PSEUDO_CALL) {
18772 					err = check_func_call(env, insn, &env->insn_idx);
18773 				} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18774 					err = check_kfunc_call(env, insn, &env->insn_idx);
18775 					if (!err && is_bpf_throw_kfunc(insn)) {
18776 						exception_exit = true;
18777 						goto process_bpf_exit_full;
18778 					}
18779 				} else {
18780 					err = check_helper_call(env, insn, &env->insn_idx);
18781 				}
18782 				if (err)
18783 					return err;
18784 
18785 				mark_reg_scratched(env, BPF_REG_0);
18786 			} else if (opcode == BPF_JA) {
18787 				if (BPF_SRC(insn->code) != BPF_K ||
18788 				    insn->src_reg != BPF_REG_0 ||
18789 				    insn->dst_reg != BPF_REG_0 ||
18790 				    (class == BPF_JMP && insn->imm != 0) ||
18791 				    (class == BPF_JMP32 && insn->off != 0)) {
18792 					verbose(env, "BPF_JA uses reserved fields\n");
18793 					return -EINVAL;
18794 				}
18795 
18796 				if (class == BPF_JMP)
18797 					env->insn_idx += insn->off + 1;
18798 				else
18799 					env->insn_idx += insn->imm + 1;
18800 				continue;
18801 
18802 			} else if (opcode == BPF_EXIT) {
18803 				if (BPF_SRC(insn->code) != BPF_K ||
18804 				    insn->imm != 0 ||
18805 				    insn->src_reg != BPF_REG_0 ||
18806 				    insn->dst_reg != BPF_REG_0 ||
18807 				    class == BPF_JMP32) {
18808 					verbose(env, "BPF_EXIT uses reserved fields\n");
18809 					return -EINVAL;
18810 				}
18811 process_bpf_exit_full:
18812 				/* We must do check_reference_leak here before
18813 				 * prepare_func_exit to handle the case when
18814 				 * state->curframe > 0, it may be a callback
18815 				 * function, for which reference_state must
18816 				 * match caller reference state when it exits.
18817 				 */
18818 				err = check_resource_leak(env, exception_exit, !env->cur_state->curframe,
18819 							  "BPF_EXIT instruction");
18820 				if (err)
18821 					return err;
18822 
18823 				/* The side effect of the prepare_func_exit
18824 				 * which is being skipped is that it frees
18825 				 * bpf_func_state. Typically, process_bpf_exit
18826 				 * will only be hit with outermost exit.
18827 				 * copy_verifier_state in pop_stack will handle
18828 				 * freeing of any extra bpf_func_state left over
18829 				 * from not processing all nested function
18830 				 * exits. We also skip return code checks as
18831 				 * they are not needed for exceptional exits.
18832 				 */
18833 				if (exception_exit)
18834 					goto process_bpf_exit;
18835 
18836 				if (state->curframe) {
18837 					/* exit from nested function */
18838 					err = prepare_func_exit(env, &env->insn_idx);
18839 					if (err)
18840 						return err;
18841 					do_print_state = true;
18842 					continue;
18843 				}
18844 
18845 				err = check_return_code(env, BPF_REG_0, "R0");
18846 				if (err)
18847 					return err;
18848 process_bpf_exit:
18849 				mark_verifier_state_scratched(env);
18850 				update_branch_counts(env, env->cur_state);
18851 				err = pop_stack(env, &prev_insn_idx,
18852 						&env->insn_idx, pop_log);
18853 				if (err < 0) {
18854 					if (err != -ENOENT)
18855 						return err;
18856 					break;
18857 				} else {
18858 					do_print_state = true;
18859 					continue;
18860 				}
18861 			} else {
18862 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
18863 				if (err)
18864 					return err;
18865 			}
18866 		} else if (class == BPF_LD) {
18867 			u8 mode = BPF_MODE(insn->code);
18868 
18869 			if (mode == BPF_ABS || mode == BPF_IND) {
18870 				err = check_ld_abs(env, insn);
18871 				if (err)
18872 					return err;
18873 
18874 			} else if (mode == BPF_IMM) {
18875 				err = check_ld_imm(env, insn);
18876 				if (err)
18877 					return err;
18878 
18879 				env->insn_idx++;
18880 				sanitize_mark_insn_seen(env);
18881 			} else {
18882 				verbose(env, "invalid BPF_LD mode\n");
18883 				return -EINVAL;
18884 			}
18885 		} else {
18886 			verbose(env, "unknown insn class %d\n", class);
18887 			return -EINVAL;
18888 		}
18889 
18890 		env->insn_idx++;
18891 	}
18892 
18893 	return 0;
18894 }
18895 
18896 static int find_btf_percpu_datasec(struct btf *btf)
18897 {
18898 	const struct btf_type *t;
18899 	const char *tname;
18900 	int i, n;
18901 
18902 	/*
18903 	 * Both vmlinux and module each have their own ".data..percpu"
18904 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
18905 	 * types to look at only module's own BTF types.
18906 	 */
18907 	n = btf_nr_types(btf);
18908 	if (btf_is_module(btf))
18909 		i = btf_nr_types(btf_vmlinux);
18910 	else
18911 		i = 1;
18912 
18913 	for(; i < n; i++) {
18914 		t = btf_type_by_id(btf, i);
18915 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
18916 			continue;
18917 
18918 		tname = btf_name_by_offset(btf, t->name_off);
18919 		if (!strcmp(tname, ".data..percpu"))
18920 			return i;
18921 	}
18922 
18923 	return -ENOENT;
18924 }
18925 
18926 /* replace pseudo btf_id with kernel symbol address */
18927 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
18928 			       struct bpf_insn *insn,
18929 			       struct bpf_insn_aux_data *aux)
18930 {
18931 	const struct btf_var_secinfo *vsi;
18932 	const struct btf_type *datasec;
18933 	struct btf_mod_pair *btf_mod;
18934 	const struct btf_type *t;
18935 	const char *sym_name;
18936 	bool percpu = false;
18937 	u32 type, id = insn->imm;
18938 	struct btf *btf;
18939 	s32 datasec_id;
18940 	u64 addr;
18941 	int i, btf_fd, err;
18942 
18943 	btf_fd = insn[1].imm;
18944 	if (btf_fd) {
18945 		btf = btf_get_by_fd(btf_fd);
18946 		if (IS_ERR(btf)) {
18947 			verbose(env, "invalid module BTF object FD specified.\n");
18948 			return -EINVAL;
18949 		}
18950 	} else {
18951 		if (!btf_vmlinux) {
18952 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
18953 			return -EINVAL;
18954 		}
18955 		btf = btf_vmlinux;
18956 		btf_get(btf);
18957 	}
18958 
18959 	t = btf_type_by_id(btf, id);
18960 	if (!t) {
18961 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
18962 		err = -ENOENT;
18963 		goto err_put;
18964 	}
18965 
18966 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
18967 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
18968 		err = -EINVAL;
18969 		goto err_put;
18970 	}
18971 
18972 	sym_name = btf_name_by_offset(btf, t->name_off);
18973 	addr = kallsyms_lookup_name(sym_name);
18974 	if (!addr) {
18975 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
18976 			sym_name);
18977 		err = -ENOENT;
18978 		goto err_put;
18979 	}
18980 	insn[0].imm = (u32)addr;
18981 	insn[1].imm = addr >> 32;
18982 
18983 	if (btf_type_is_func(t)) {
18984 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18985 		aux->btf_var.mem_size = 0;
18986 		goto check_btf;
18987 	}
18988 
18989 	datasec_id = find_btf_percpu_datasec(btf);
18990 	if (datasec_id > 0) {
18991 		datasec = btf_type_by_id(btf, datasec_id);
18992 		for_each_vsi(i, datasec, vsi) {
18993 			if (vsi->type == id) {
18994 				percpu = true;
18995 				break;
18996 			}
18997 		}
18998 	}
18999 
19000 	type = t->type;
19001 	t = btf_type_skip_modifiers(btf, type, NULL);
19002 	if (percpu) {
19003 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
19004 		aux->btf_var.btf = btf;
19005 		aux->btf_var.btf_id = type;
19006 	} else if (!btf_type_is_struct(t)) {
19007 		const struct btf_type *ret;
19008 		const char *tname;
19009 		u32 tsize;
19010 
19011 		/* resolve the type size of ksym. */
19012 		ret = btf_resolve_size(btf, t, &tsize);
19013 		if (IS_ERR(ret)) {
19014 			tname = btf_name_by_offset(btf, t->name_off);
19015 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
19016 				tname, PTR_ERR(ret));
19017 			err = -EINVAL;
19018 			goto err_put;
19019 		}
19020 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
19021 		aux->btf_var.mem_size = tsize;
19022 	} else {
19023 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
19024 		aux->btf_var.btf = btf;
19025 		aux->btf_var.btf_id = type;
19026 	}
19027 check_btf:
19028 	/* check whether we recorded this BTF (and maybe module) already */
19029 	for (i = 0; i < env->used_btf_cnt; i++) {
19030 		if (env->used_btfs[i].btf == btf) {
19031 			btf_put(btf);
19032 			return 0;
19033 		}
19034 	}
19035 
19036 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
19037 		err = -E2BIG;
19038 		goto err_put;
19039 	}
19040 
19041 	btf_mod = &env->used_btfs[env->used_btf_cnt];
19042 	btf_mod->btf = btf;
19043 	btf_mod->module = NULL;
19044 
19045 	/* if we reference variables from kernel module, bump its refcount */
19046 	if (btf_is_module(btf)) {
19047 		btf_mod->module = btf_try_get_module(btf);
19048 		if (!btf_mod->module) {
19049 			err = -ENXIO;
19050 			goto err_put;
19051 		}
19052 	}
19053 
19054 	env->used_btf_cnt++;
19055 
19056 	return 0;
19057 err_put:
19058 	btf_put(btf);
19059 	return err;
19060 }
19061 
19062 static bool is_tracing_prog_type(enum bpf_prog_type type)
19063 {
19064 	switch (type) {
19065 	case BPF_PROG_TYPE_KPROBE:
19066 	case BPF_PROG_TYPE_TRACEPOINT:
19067 	case BPF_PROG_TYPE_PERF_EVENT:
19068 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
19069 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
19070 		return true;
19071 	default:
19072 		return false;
19073 	}
19074 }
19075 
19076 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
19077 					struct bpf_map *map,
19078 					struct bpf_prog *prog)
19079 
19080 {
19081 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
19082 
19083 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
19084 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
19085 		if (is_tracing_prog_type(prog_type)) {
19086 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
19087 			return -EINVAL;
19088 		}
19089 	}
19090 
19091 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
19092 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
19093 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
19094 			return -EINVAL;
19095 		}
19096 
19097 		if (is_tracing_prog_type(prog_type)) {
19098 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
19099 			return -EINVAL;
19100 		}
19101 	}
19102 
19103 	if (btf_record_has_field(map->record, BPF_TIMER)) {
19104 		if (is_tracing_prog_type(prog_type)) {
19105 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
19106 			return -EINVAL;
19107 		}
19108 	}
19109 
19110 	if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
19111 		if (is_tracing_prog_type(prog_type)) {
19112 			verbose(env, "tracing progs cannot use bpf_wq yet\n");
19113 			return -EINVAL;
19114 		}
19115 	}
19116 
19117 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
19118 	    !bpf_offload_prog_map_match(prog, map)) {
19119 		verbose(env, "offload device mismatch between prog and map\n");
19120 		return -EINVAL;
19121 	}
19122 
19123 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
19124 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
19125 		return -EINVAL;
19126 	}
19127 
19128 	if (prog->sleepable)
19129 		switch (map->map_type) {
19130 		case BPF_MAP_TYPE_HASH:
19131 		case BPF_MAP_TYPE_LRU_HASH:
19132 		case BPF_MAP_TYPE_ARRAY:
19133 		case BPF_MAP_TYPE_PERCPU_HASH:
19134 		case BPF_MAP_TYPE_PERCPU_ARRAY:
19135 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
19136 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
19137 		case BPF_MAP_TYPE_HASH_OF_MAPS:
19138 		case BPF_MAP_TYPE_RINGBUF:
19139 		case BPF_MAP_TYPE_USER_RINGBUF:
19140 		case BPF_MAP_TYPE_INODE_STORAGE:
19141 		case BPF_MAP_TYPE_SK_STORAGE:
19142 		case BPF_MAP_TYPE_TASK_STORAGE:
19143 		case BPF_MAP_TYPE_CGRP_STORAGE:
19144 		case BPF_MAP_TYPE_QUEUE:
19145 		case BPF_MAP_TYPE_STACK:
19146 		case BPF_MAP_TYPE_ARENA:
19147 			break;
19148 		default:
19149 			verbose(env,
19150 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
19151 			return -EINVAL;
19152 		}
19153 
19154 	return 0;
19155 }
19156 
19157 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
19158 {
19159 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
19160 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
19161 }
19162 
19163 /* Add map behind fd to used maps list, if it's not already there, and return
19164  * its index. Also set *reused to true if this map was already in the list of
19165  * used maps.
19166  * Returns <0 on error, or >= 0 index, on success.
19167  */
19168 static int add_used_map_from_fd(struct bpf_verifier_env *env, int fd, bool *reused)
19169 {
19170 	CLASS(fd, f)(fd);
19171 	struct bpf_map *map;
19172 	int i;
19173 
19174 	map = __bpf_map_get(f);
19175 	if (IS_ERR(map)) {
19176 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
19177 		return PTR_ERR(map);
19178 	}
19179 
19180 	/* check whether we recorded this map already */
19181 	for (i = 0; i < env->used_map_cnt; i++) {
19182 		if (env->used_maps[i] == map) {
19183 			*reused = true;
19184 			return i;
19185 		}
19186 	}
19187 
19188 	if (env->used_map_cnt >= MAX_USED_MAPS) {
19189 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
19190 			MAX_USED_MAPS);
19191 		return -E2BIG;
19192 	}
19193 
19194 	if (env->prog->sleepable)
19195 		atomic64_inc(&map->sleepable_refcnt);
19196 
19197 	/* hold the map. If the program is rejected by verifier,
19198 	 * the map will be released by release_maps() or it
19199 	 * will be used by the valid program until it's unloaded
19200 	 * and all maps are released in bpf_free_used_maps()
19201 	 */
19202 	bpf_map_inc(map);
19203 
19204 	*reused = false;
19205 	env->used_maps[env->used_map_cnt++] = map;
19206 
19207 	return env->used_map_cnt - 1;
19208 }
19209 
19210 /* find and rewrite pseudo imm in ld_imm64 instructions:
19211  *
19212  * 1. if it accesses map FD, replace it with actual map pointer.
19213  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
19214  *
19215  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
19216  */
19217 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
19218 {
19219 	struct bpf_insn *insn = env->prog->insnsi;
19220 	int insn_cnt = env->prog->len;
19221 	int i, err;
19222 
19223 	err = bpf_prog_calc_tag(env->prog);
19224 	if (err)
19225 		return err;
19226 
19227 	for (i = 0; i < insn_cnt; i++, insn++) {
19228 		if (BPF_CLASS(insn->code) == BPF_LDX &&
19229 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
19230 		    insn->imm != 0)) {
19231 			verbose(env, "BPF_LDX uses reserved fields\n");
19232 			return -EINVAL;
19233 		}
19234 
19235 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
19236 			struct bpf_insn_aux_data *aux;
19237 			struct bpf_map *map;
19238 			int map_idx;
19239 			u64 addr;
19240 			u32 fd;
19241 			bool reused;
19242 
19243 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
19244 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
19245 			    insn[1].off != 0) {
19246 				verbose(env, "invalid bpf_ld_imm64 insn\n");
19247 				return -EINVAL;
19248 			}
19249 
19250 			if (insn[0].src_reg == 0)
19251 				/* valid generic load 64-bit imm */
19252 				goto next_insn;
19253 
19254 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
19255 				aux = &env->insn_aux_data[i];
19256 				err = check_pseudo_btf_id(env, insn, aux);
19257 				if (err)
19258 					return err;
19259 				goto next_insn;
19260 			}
19261 
19262 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
19263 				aux = &env->insn_aux_data[i];
19264 				aux->ptr_type = PTR_TO_FUNC;
19265 				goto next_insn;
19266 			}
19267 
19268 			/* In final convert_pseudo_ld_imm64() step, this is
19269 			 * converted into regular 64-bit imm load insn.
19270 			 */
19271 			switch (insn[0].src_reg) {
19272 			case BPF_PSEUDO_MAP_VALUE:
19273 			case BPF_PSEUDO_MAP_IDX_VALUE:
19274 				break;
19275 			case BPF_PSEUDO_MAP_FD:
19276 			case BPF_PSEUDO_MAP_IDX:
19277 				if (insn[1].imm == 0)
19278 					break;
19279 				fallthrough;
19280 			default:
19281 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
19282 				return -EINVAL;
19283 			}
19284 
19285 			switch (insn[0].src_reg) {
19286 			case BPF_PSEUDO_MAP_IDX_VALUE:
19287 			case BPF_PSEUDO_MAP_IDX:
19288 				if (bpfptr_is_null(env->fd_array)) {
19289 					verbose(env, "fd_idx without fd_array is invalid\n");
19290 					return -EPROTO;
19291 				}
19292 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
19293 							    insn[0].imm * sizeof(fd),
19294 							    sizeof(fd)))
19295 					return -EFAULT;
19296 				break;
19297 			default:
19298 				fd = insn[0].imm;
19299 				break;
19300 			}
19301 
19302 			map_idx = add_used_map_from_fd(env, fd, &reused);
19303 			if (map_idx < 0)
19304 				return map_idx;
19305 			map = env->used_maps[map_idx];
19306 
19307 			aux = &env->insn_aux_data[i];
19308 			aux->map_index = map_idx;
19309 
19310 			err = check_map_prog_compatibility(env, map, env->prog);
19311 			if (err)
19312 				return err;
19313 
19314 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
19315 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
19316 				addr = (unsigned long)map;
19317 			} else {
19318 				u32 off = insn[1].imm;
19319 
19320 				if (off >= BPF_MAX_VAR_OFF) {
19321 					verbose(env, "direct value offset of %u is not allowed\n", off);
19322 					return -EINVAL;
19323 				}
19324 
19325 				if (!map->ops->map_direct_value_addr) {
19326 					verbose(env, "no direct value access support for this map type\n");
19327 					return -EINVAL;
19328 				}
19329 
19330 				err = map->ops->map_direct_value_addr(map, &addr, off);
19331 				if (err) {
19332 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
19333 						map->value_size, off);
19334 					return err;
19335 				}
19336 
19337 				aux->map_off = off;
19338 				addr += off;
19339 			}
19340 
19341 			insn[0].imm = (u32)addr;
19342 			insn[1].imm = addr >> 32;
19343 
19344 			/* proceed with extra checks only if its newly added used map */
19345 			if (reused)
19346 				goto next_insn;
19347 
19348 			if (bpf_map_is_cgroup_storage(map) &&
19349 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
19350 				verbose(env, "only one cgroup storage of each type is allowed\n");
19351 				return -EBUSY;
19352 			}
19353 			if (map->map_type == BPF_MAP_TYPE_ARENA) {
19354 				if (env->prog->aux->arena) {
19355 					verbose(env, "Only one arena per program\n");
19356 					return -EBUSY;
19357 				}
19358 				if (!env->allow_ptr_leaks || !env->bpf_capable) {
19359 					verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
19360 					return -EPERM;
19361 				}
19362 				if (!env->prog->jit_requested) {
19363 					verbose(env, "JIT is required to use arena\n");
19364 					return -EOPNOTSUPP;
19365 				}
19366 				if (!bpf_jit_supports_arena()) {
19367 					verbose(env, "JIT doesn't support arena\n");
19368 					return -EOPNOTSUPP;
19369 				}
19370 				env->prog->aux->arena = (void *)map;
19371 				if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
19372 					verbose(env, "arena's user address must be set via map_extra or mmap()\n");
19373 					return -EINVAL;
19374 				}
19375 			}
19376 
19377 next_insn:
19378 			insn++;
19379 			i++;
19380 			continue;
19381 		}
19382 
19383 		/* Basic sanity check before we invest more work here. */
19384 		if (!bpf_opcode_in_insntable(insn->code)) {
19385 			verbose(env, "unknown opcode %02x\n", insn->code);
19386 			return -EINVAL;
19387 		}
19388 	}
19389 
19390 	/* now all pseudo BPF_LD_IMM64 instructions load valid
19391 	 * 'struct bpf_map *' into a register instead of user map_fd.
19392 	 * These pointers will be used later by verifier to validate map access.
19393 	 */
19394 	return 0;
19395 }
19396 
19397 /* drop refcnt of maps used by the rejected program */
19398 static void release_maps(struct bpf_verifier_env *env)
19399 {
19400 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
19401 			     env->used_map_cnt);
19402 }
19403 
19404 /* drop refcnt of maps used by the rejected program */
19405 static void release_btfs(struct bpf_verifier_env *env)
19406 {
19407 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
19408 }
19409 
19410 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
19411 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
19412 {
19413 	struct bpf_insn *insn = env->prog->insnsi;
19414 	int insn_cnt = env->prog->len;
19415 	int i;
19416 
19417 	for (i = 0; i < insn_cnt; i++, insn++) {
19418 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
19419 			continue;
19420 		if (insn->src_reg == BPF_PSEUDO_FUNC)
19421 			continue;
19422 		insn->src_reg = 0;
19423 	}
19424 }
19425 
19426 /* single env->prog->insni[off] instruction was replaced with the range
19427  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
19428  * [0, off) and [off, end) to new locations, so the patched range stays zero
19429  */
19430 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
19431 				 struct bpf_insn_aux_data *new_data,
19432 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
19433 {
19434 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
19435 	struct bpf_insn *insn = new_prog->insnsi;
19436 	u32 old_seen = old_data[off].seen;
19437 	u32 prog_len;
19438 	int i;
19439 
19440 	/* aux info at OFF always needs adjustment, no matter fast path
19441 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
19442 	 * original insn at old prog.
19443 	 */
19444 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
19445 
19446 	if (cnt == 1)
19447 		return;
19448 	prog_len = new_prog->len;
19449 
19450 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
19451 	memcpy(new_data + off + cnt - 1, old_data + off,
19452 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
19453 	for (i = off; i < off + cnt - 1; i++) {
19454 		/* Expand insni[off]'s seen count to the patched range. */
19455 		new_data[i].seen = old_seen;
19456 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
19457 	}
19458 	env->insn_aux_data = new_data;
19459 	vfree(old_data);
19460 }
19461 
19462 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
19463 {
19464 	int i;
19465 
19466 	if (len == 1)
19467 		return;
19468 	/* NOTE: fake 'exit' subprog should be updated as well. */
19469 	for (i = 0; i <= env->subprog_cnt; i++) {
19470 		if (env->subprog_info[i].start <= off)
19471 			continue;
19472 		env->subprog_info[i].start += len - 1;
19473 	}
19474 }
19475 
19476 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
19477 {
19478 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
19479 	int i, sz = prog->aux->size_poke_tab;
19480 	struct bpf_jit_poke_descriptor *desc;
19481 
19482 	for (i = 0; i < sz; i++) {
19483 		desc = &tab[i];
19484 		if (desc->insn_idx <= off)
19485 			continue;
19486 		desc->insn_idx += len - 1;
19487 	}
19488 }
19489 
19490 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
19491 					    const struct bpf_insn *patch, u32 len)
19492 {
19493 	struct bpf_prog *new_prog;
19494 	struct bpf_insn_aux_data *new_data = NULL;
19495 
19496 	if (len > 1) {
19497 		new_data = vzalloc(array_size(env->prog->len + len - 1,
19498 					      sizeof(struct bpf_insn_aux_data)));
19499 		if (!new_data)
19500 			return NULL;
19501 	}
19502 
19503 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
19504 	if (IS_ERR(new_prog)) {
19505 		if (PTR_ERR(new_prog) == -ERANGE)
19506 			verbose(env,
19507 				"insn %d cannot be patched due to 16-bit range\n",
19508 				env->insn_aux_data[off].orig_idx);
19509 		vfree(new_data);
19510 		return NULL;
19511 	}
19512 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
19513 	adjust_subprog_starts(env, off, len);
19514 	adjust_poke_descs(new_prog, off, len);
19515 	return new_prog;
19516 }
19517 
19518 /*
19519  * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
19520  * jump offset by 'delta'.
19521  */
19522 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
19523 {
19524 	struct bpf_insn *insn = prog->insnsi;
19525 	u32 insn_cnt = prog->len, i;
19526 	s32 imm;
19527 	s16 off;
19528 
19529 	for (i = 0; i < insn_cnt; i++, insn++) {
19530 		u8 code = insn->code;
19531 
19532 		if (tgt_idx <= i && i < tgt_idx + delta)
19533 			continue;
19534 
19535 		if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
19536 		    BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
19537 			continue;
19538 
19539 		if (insn->code == (BPF_JMP32 | BPF_JA)) {
19540 			if (i + 1 + insn->imm != tgt_idx)
19541 				continue;
19542 			if (check_add_overflow(insn->imm, delta, &imm))
19543 				return -ERANGE;
19544 			insn->imm = imm;
19545 		} else {
19546 			if (i + 1 + insn->off != tgt_idx)
19547 				continue;
19548 			if (check_add_overflow(insn->off, delta, &off))
19549 				return -ERANGE;
19550 			insn->off = off;
19551 		}
19552 	}
19553 	return 0;
19554 }
19555 
19556 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
19557 					      u32 off, u32 cnt)
19558 {
19559 	int i, j;
19560 
19561 	/* find first prog starting at or after off (first to remove) */
19562 	for (i = 0; i < env->subprog_cnt; i++)
19563 		if (env->subprog_info[i].start >= off)
19564 			break;
19565 	/* find first prog starting at or after off + cnt (first to stay) */
19566 	for (j = i; j < env->subprog_cnt; j++)
19567 		if (env->subprog_info[j].start >= off + cnt)
19568 			break;
19569 	/* if j doesn't start exactly at off + cnt, we are just removing
19570 	 * the front of previous prog
19571 	 */
19572 	if (env->subprog_info[j].start != off + cnt)
19573 		j--;
19574 
19575 	if (j > i) {
19576 		struct bpf_prog_aux *aux = env->prog->aux;
19577 		int move;
19578 
19579 		/* move fake 'exit' subprog as well */
19580 		move = env->subprog_cnt + 1 - j;
19581 
19582 		memmove(env->subprog_info + i,
19583 			env->subprog_info + j,
19584 			sizeof(*env->subprog_info) * move);
19585 		env->subprog_cnt -= j - i;
19586 
19587 		/* remove func_info */
19588 		if (aux->func_info) {
19589 			move = aux->func_info_cnt - j;
19590 
19591 			memmove(aux->func_info + i,
19592 				aux->func_info + j,
19593 				sizeof(*aux->func_info) * move);
19594 			aux->func_info_cnt -= j - i;
19595 			/* func_info->insn_off is set after all code rewrites,
19596 			 * in adjust_btf_func() - no need to adjust
19597 			 */
19598 		}
19599 	} else {
19600 		/* convert i from "first prog to remove" to "first to adjust" */
19601 		if (env->subprog_info[i].start == off)
19602 			i++;
19603 	}
19604 
19605 	/* update fake 'exit' subprog as well */
19606 	for (; i <= env->subprog_cnt; i++)
19607 		env->subprog_info[i].start -= cnt;
19608 
19609 	return 0;
19610 }
19611 
19612 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
19613 				      u32 cnt)
19614 {
19615 	struct bpf_prog *prog = env->prog;
19616 	u32 i, l_off, l_cnt, nr_linfo;
19617 	struct bpf_line_info *linfo;
19618 
19619 	nr_linfo = prog->aux->nr_linfo;
19620 	if (!nr_linfo)
19621 		return 0;
19622 
19623 	linfo = prog->aux->linfo;
19624 
19625 	/* find first line info to remove, count lines to be removed */
19626 	for (i = 0; i < nr_linfo; i++)
19627 		if (linfo[i].insn_off >= off)
19628 			break;
19629 
19630 	l_off = i;
19631 	l_cnt = 0;
19632 	for (; i < nr_linfo; i++)
19633 		if (linfo[i].insn_off < off + cnt)
19634 			l_cnt++;
19635 		else
19636 			break;
19637 
19638 	/* First live insn doesn't match first live linfo, it needs to "inherit"
19639 	 * last removed linfo.  prog is already modified, so prog->len == off
19640 	 * means no live instructions after (tail of the program was removed).
19641 	 */
19642 	if (prog->len != off && l_cnt &&
19643 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
19644 		l_cnt--;
19645 		linfo[--i].insn_off = off + cnt;
19646 	}
19647 
19648 	/* remove the line info which refer to the removed instructions */
19649 	if (l_cnt) {
19650 		memmove(linfo + l_off, linfo + i,
19651 			sizeof(*linfo) * (nr_linfo - i));
19652 
19653 		prog->aux->nr_linfo -= l_cnt;
19654 		nr_linfo = prog->aux->nr_linfo;
19655 	}
19656 
19657 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
19658 	for (i = l_off; i < nr_linfo; i++)
19659 		linfo[i].insn_off -= cnt;
19660 
19661 	/* fix up all subprogs (incl. 'exit') which start >= off */
19662 	for (i = 0; i <= env->subprog_cnt; i++)
19663 		if (env->subprog_info[i].linfo_idx > l_off) {
19664 			/* program may have started in the removed region but
19665 			 * may not be fully removed
19666 			 */
19667 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
19668 				env->subprog_info[i].linfo_idx -= l_cnt;
19669 			else
19670 				env->subprog_info[i].linfo_idx = l_off;
19671 		}
19672 
19673 	return 0;
19674 }
19675 
19676 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
19677 {
19678 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
19679 	unsigned int orig_prog_len = env->prog->len;
19680 	int err;
19681 
19682 	if (bpf_prog_is_offloaded(env->prog->aux))
19683 		bpf_prog_offload_remove_insns(env, off, cnt);
19684 
19685 	err = bpf_remove_insns(env->prog, off, cnt);
19686 	if (err)
19687 		return err;
19688 
19689 	err = adjust_subprog_starts_after_remove(env, off, cnt);
19690 	if (err)
19691 		return err;
19692 
19693 	err = bpf_adj_linfo_after_remove(env, off, cnt);
19694 	if (err)
19695 		return err;
19696 
19697 	memmove(aux_data + off,	aux_data + off + cnt,
19698 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
19699 
19700 	return 0;
19701 }
19702 
19703 /* The verifier does more data flow analysis than llvm and will not
19704  * explore branches that are dead at run time. Malicious programs can
19705  * have dead code too. Therefore replace all dead at-run-time code
19706  * with 'ja -1'.
19707  *
19708  * Just nops are not optimal, e.g. if they would sit at the end of the
19709  * program and through another bug we would manage to jump there, then
19710  * we'd execute beyond program memory otherwise. Returning exception
19711  * code also wouldn't work since we can have subprogs where the dead
19712  * code could be located.
19713  */
19714 static void sanitize_dead_code(struct bpf_verifier_env *env)
19715 {
19716 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
19717 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
19718 	struct bpf_insn *insn = env->prog->insnsi;
19719 	const int insn_cnt = env->prog->len;
19720 	int i;
19721 
19722 	for (i = 0; i < insn_cnt; i++) {
19723 		if (aux_data[i].seen)
19724 			continue;
19725 		memcpy(insn + i, &trap, sizeof(trap));
19726 		aux_data[i].zext_dst = false;
19727 	}
19728 }
19729 
19730 static bool insn_is_cond_jump(u8 code)
19731 {
19732 	u8 op;
19733 
19734 	op = BPF_OP(code);
19735 	if (BPF_CLASS(code) == BPF_JMP32)
19736 		return op != BPF_JA;
19737 
19738 	if (BPF_CLASS(code) != BPF_JMP)
19739 		return false;
19740 
19741 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
19742 }
19743 
19744 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
19745 {
19746 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
19747 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
19748 	struct bpf_insn *insn = env->prog->insnsi;
19749 	const int insn_cnt = env->prog->len;
19750 	int i;
19751 
19752 	for (i = 0; i < insn_cnt; i++, insn++) {
19753 		if (!insn_is_cond_jump(insn->code))
19754 			continue;
19755 
19756 		if (!aux_data[i + 1].seen)
19757 			ja.off = insn->off;
19758 		else if (!aux_data[i + 1 + insn->off].seen)
19759 			ja.off = 0;
19760 		else
19761 			continue;
19762 
19763 		if (bpf_prog_is_offloaded(env->prog->aux))
19764 			bpf_prog_offload_replace_insn(env, i, &ja);
19765 
19766 		memcpy(insn, &ja, sizeof(ja));
19767 	}
19768 }
19769 
19770 static int opt_remove_dead_code(struct bpf_verifier_env *env)
19771 {
19772 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
19773 	int insn_cnt = env->prog->len;
19774 	int i, err;
19775 
19776 	for (i = 0; i < insn_cnt; i++) {
19777 		int j;
19778 
19779 		j = 0;
19780 		while (i + j < insn_cnt && !aux_data[i + j].seen)
19781 			j++;
19782 		if (!j)
19783 			continue;
19784 
19785 		err = verifier_remove_insns(env, i, j);
19786 		if (err)
19787 			return err;
19788 		insn_cnt = env->prog->len;
19789 	}
19790 
19791 	return 0;
19792 }
19793 
19794 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
19795 
19796 static int opt_remove_nops(struct bpf_verifier_env *env)
19797 {
19798 	const struct bpf_insn ja = NOP;
19799 	struct bpf_insn *insn = env->prog->insnsi;
19800 	int insn_cnt = env->prog->len;
19801 	int i, err;
19802 
19803 	for (i = 0; i < insn_cnt; i++) {
19804 		if (memcmp(&insn[i], &ja, sizeof(ja)))
19805 			continue;
19806 
19807 		err = verifier_remove_insns(env, i, 1);
19808 		if (err)
19809 			return err;
19810 		insn_cnt--;
19811 		i--;
19812 	}
19813 
19814 	return 0;
19815 }
19816 
19817 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
19818 					 const union bpf_attr *attr)
19819 {
19820 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
19821 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
19822 	int i, patch_len, delta = 0, len = env->prog->len;
19823 	struct bpf_insn *insns = env->prog->insnsi;
19824 	struct bpf_prog *new_prog;
19825 	bool rnd_hi32;
19826 
19827 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
19828 	zext_patch[1] = BPF_ZEXT_REG(0);
19829 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
19830 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
19831 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
19832 	for (i = 0; i < len; i++) {
19833 		int adj_idx = i + delta;
19834 		struct bpf_insn insn;
19835 		int load_reg;
19836 
19837 		insn = insns[adj_idx];
19838 		load_reg = insn_def_regno(&insn);
19839 		if (!aux[adj_idx].zext_dst) {
19840 			u8 code, class;
19841 			u32 imm_rnd;
19842 
19843 			if (!rnd_hi32)
19844 				continue;
19845 
19846 			code = insn.code;
19847 			class = BPF_CLASS(code);
19848 			if (load_reg == -1)
19849 				continue;
19850 
19851 			/* NOTE: arg "reg" (the fourth one) is only used for
19852 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
19853 			 *       here.
19854 			 */
19855 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
19856 				if (class == BPF_LD &&
19857 				    BPF_MODE(code) == BPF_IMM)
19858 					i++;
19859 				continue;
19860 			}
19861 
19862 			/* ctx load could be transformed into wider load. */
19863 			if (class == BPF_LDX &&
19864 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
19865 				continue;
19866 
19867 			imm_rnd = get_random_u32();
19868 			rnd_hi32_patch[0] = insn;
19869 			rnd_hi32_patch[1].imm = imm_rnd;
19870 			rnd_hi32_patch[3].dst_reg = load_reg;
19871 			patch = rnd_hi32_patch;
19872 			patch_len = 4;
19873 			goto apply_patch_buffer;
19874 		}
19875 
19876 		/* Add in an zero-extend instruction if a) the JIT has requested
19877 		 * it or b) it's a CMPXCHG.
19878 		 *
19879 		 * The latter is because: BPF_CMPXCHG always loads a value into
19880 		 * R0, therefore always zero-extends. However some archs'
19881 		 * equivalent instruction only does this load when the
19882 		 * comparison is successful. This detail of CMPXCHG is
19883 		 * orthogonal to the general zero-extension behaviour of the
19884 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
19885 		 */
19886 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
19887 			continue;
19888 
19889 		/* Zero-extension is done by the caller. */
19890 		if (bpf_pseudo_kfunc_call(&insn))
19891 			continue;
19892 
19893 		if (WARN_ON(load_reg == -1)) {
19894 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
19895 			return -EFAULT;
19896 		}
19897 
19898 		zext_patch[0] = insn;
19899 		zext_patch[1].dst_reg = load_reg;
19900 		zext_patch[1].src_reg = load_reg;
19901 		patch = zext_patch;
19902 		patch_len = 2;
19903 apply_patch_buffer:
19904 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
19905 		if (!new_prog)
19906 			return -ENOMEM;
19907 		env->prog = new_prog;
19908 		insns = new_prog->insnsi;
19909 		aux = env->insn_aux_data;
19910 		delta += patch_len - 1;
19911 	}
19912 
19913 	return 0;
19914 }
19915 
19916 /* convert load instructions that access fields of a context type into a
19917  * sequence of instructions that access fields of the underlying structure:
19918  *     struct __sk_buff    -> struct sk_buff
19919  *     struct bpf_sock_ops -> struct sock
19920  */
19921 static int convert_ctx_accesses(struct bpf_verifier_env *env)
19922 {
19923 	struct bpf_subprog_info *subprogs = env->subprog_info;
19924 	const struct bpf_verifier_ops *ops = env->ops;
19925 	int i, cnt, size, ctx_field_size, delta = 0, epilogue_cnt = 0;
19926 	const int insn_cnt = env->prog->len;
19927 	struct bpf_insn *epilogue_buf = env->epilogue_buf;
19928 	struct bpf_insn *insn_buf = env->insn_buf;
19929 	struct bpf_insn *insn;
19930 	u32 target_size, size_default, off;
19931 	struct bpf_prog *new_prog;
19932 	enum bpf_access_type type;
19933 	bool is_narrower_load;
19934 	int epilogue_idx = 0;
19935 
19936 	if (ops->gen_epilogue) {
19937 		epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
19938 						 -(subprogs[0].stack_depth + 8));
19939 		if (epilogue_cnt >= INSN_BUF_SIZE) {
19940 			verbose(env, "bpf verifier is misconfigured\n");
19941 			return -EINVAL;
19942 		} else if (epilogue_cnt) {
19943 			/* Save the ARG_PTR_TO_CTX for the epilogue to use */
19944 			cnt = 0;
19945 			subprogs[0].stack_depth += 8;
19946 			insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
19947 						      -subprogs[0].stack_depth);
19948 			insn_buf[cnt++] = env->prog->insnsi[0];
19949 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
19950 			if (!new_prog)
19951 				return -ENOMEM;
19952 			env->prog = new_prog;
19953 			delta += cnt - 1;
19954 		}
19955 	}
19956 
19957 	if (ops->gen_prologue || env->seen_direct_write) {
19958 		if (!ops->gen_prologue) {
19959 			verbose(env, "bpf verifier is misconfigured\n");
19960 			return -EINVAL;
19961 		}
19962 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
19963 					env->prog);
19964 		if (cnt >= INSN_BUF_SIZE) {
19965 			verbose(env, "bpf verifier is misconfigured\n");
19966 			return -EINVAL;
19967 		} else if (cnt) {
19968 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
19969 			if (!new_prog)
19970 				return -ENOMEM;
19971 
19972 			env->prog = new_prog;
19973 			delta += cnt - 1;
19974 		}
19975 	}
19976 
19977 	if (delta)
19978 		WARN_ON(adjust_jmp_off(env->prog, 0, delta));
19979 
19980 	if (bpf_prog_is_offloaded(env->prog->aux))
19981 		return 0;
19982 
19983 	insn = env->prog->insnsi + delta;
19984 
19985 	for (i = 0; i < insn_cnt; i++, insn++) {
19986 		bpf_convert_ctx_access_t convert_ctx_access;
19987 		u8 mode;
19988 
19989 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
19990 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
19991 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
19992 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
19993 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
19994 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
19995 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
19996 			type = BPF_READ;
19997 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
19998 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
19999 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
20000 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
20001 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
20002 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
20003 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
20004 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
20005 			type = BPF_WRITE;
20006 		} else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
20007 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
20008 			   env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
20009 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
20010 			env->prog->aux->num_exentries++;
20011 			continue;
20012 		} else if (insn->code == (BPF_JMP | BPF_EXIT) &&
20013 			   epilogue_cnt &&
20014 			   i + delta < subprogs[1].start) {
20015 			/* Generate epilogue for the main prog */
20016 			if (epilogue_idx) {
20017 				/* jump back to the earlier generated epilogue */
20018 				insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
20019 				cnt = 1;
20020 			} else {
20021 				memcpy(insn_buf, epilogue_buf,
20022 				       epilogue_cnt * sizeof(*epilogue_buf));
20023 				cnt = epilogue_cnt;
20024 				/* epilogue_idx cannot be 0. It must have at
20025 				 * least one ctx ptr saving insn before the
20026 				 * epilogue.
20027 				 */
20028 				epilogue_idx = i + delta;
20029 			}
20030 			goto patch_insn_buf;
20031 		} else {
20032 			continue;
20033 		}
20034 
20035 		if (type == BPF_WRITE &&
20036 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
20037 			struct bpf_insn patch[] = {
20038 				*insn,
20039 				BPF_ST_NOSPEC(),
20040 			};
20041 
20042 			cnt = ARRAY_SIZE(patch);
20043 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
20044 			if (!new_prog)
20045 				return -ENOMEM;
20046 
20047 			delta    += cnt - 1;
20048 			env->prog = new_prog;
20049 			insn      = new_prog->insnsi + i + delta;
20050 			continue;
20051 		}
20052 
20053 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
20054 		case PTR_TO_CTX:
20055 			if (!ops->convert_ctx_access)
20056 				continue;
20057 			convert_ctx_access = ops->convert_ctx_access;
20058 			break;
20059 		case PTR_TO_SOCKET:
20060 		case PTR_TO_SOCK_COMMON:
20061 			convert_ctx_access = bpf_sock_convert_ctx_access;
20062 			break;
20063 		case PTR_TO_TCP_SOCK:
20064 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
20065 			break;
20066 		case PTR_TO_XDP_SOCK:
20067 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
20068 			break;
20069 		case PTR_TO_BTF_ID:
20070 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
20071 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
20072 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
20073 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
20074 		 * any faults for loads into such types. BPF_WRITE is disallowed
20075 		 * for this case.
20076 		 */
20077 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
20078 		case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
20079 			if (type == BPF_READ) {
20080 				if (BPF_MODE(insn->code) == BPF_MEM)
20081 					insn->code = BPF_LDX | BPF_PROBE_MEM |
20082 						     BPF_SIZE((insn)->code);
20083 				else
20084 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
20085 						     BPF_SIZE((insn)->code);
20086 				env->prog->aux->num_exentries++;
20087 			}
20088 			continue;
20089 		case PTR_TO_ARENA:
20090 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
20091 				verbose(env, "sign extending loads from arena are not supported yet\n");
20092 				return -EOPNOTSUPP;
20093 			}
20094 			insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
20095 			env->prog->aux->num_exentries++;
20096 			continue;
20097 		default:
20098 			continue;
20099 		}
20100 
20101 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
20102 		size = BPF_LDST_BYTES(insn);
20103 		mode = BPF_MODE(insn->code);
20104 
20105 		/* If the read access is a narrower load of the field,
20106 		 * convert to a 4/8-byte load, to minimum program type specific
20107 		 * convert_ctx_access changes. If conversion is successful,
20108 		 * we will apply proper mask to the result.
20109 		 */
20110 		is_narrower_load = size < ctx_field_size;
20111 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
20112 		off = insn->off;
20113 		if (is_narrower_load) {
20114 			u8 size_code;
20115 
20116 			if (type == BPF_WRITE) {
20117 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
20118 				return -EINVAL;
20119 			}
20120 
20121 			size_code = BPF_H;
20122 			if (ctx_field_size == 4)
20123 				size_code = BPF_W;
20124 			else if (ctx_field_size == 8)
20125 				size_code = BPF_DW;
20126 
20127 			insn->off = off & ~(size_default - 1);
20128 			insn->code = BPF_LDX | BPF_MEM | size_code;
20129 		}
20130 
20131 		target_size = 0;
20132 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
20133 					 &target_size);
20134 		if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
20135 		    (ctx_field_size && !target_size)) {
20136 			verbose(env, "bpf verifier is misconfigured\n");
20137 			return -EINVAL;
20138 		}
20139 
20140 		if (is_narrower_load && size < target_size) {
20141 			u8 shift = bpf_ctx_narrow_access_offset(
20142 				off, size, size_default) * 8;
20143 			if (shift && cnt + 1 >= INSN_BUF_SIZE) {
20144 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
20145 				return -EINVAL;
20146 			}
20147 			if (ctx_field_size <= 4) {
20148 				if (shift)
20149 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
20150 									insn->dst_reg,
20151 									shift);
20152 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
20153 								(1 << size * 8) - 1);
20154 			} else {
20155 				if (shift)
20156 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
20157 									insn->dst_reg,
20158 									shift);
20159 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
20160 								(1ULL << size * 8) - 1);
20161 			}
20162 		}
20163 		if (mode == BPF_MEMSX)
20164 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
20165 						       insn->dst_reg, insn->dst_reg,
20166 						       size * 8, 0);
20167 
20168 patch_insn_buf:
20169 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20170 		if (!new_prog)
20171 			return -ENOMEM;
20172 
20173 		delta += cnt - 1;
20174 
20175 		/* keep walking new program and skip insns we just inserted */
20176 		env->prog = new_prog;
20177 		insn      = new_prog->insnsi + i + delta;
20178 	}
20179 
20180 	return 0;
20181 }
20182 
20183 static int jit_subprogs(struct bpf_verifier_env *env)
20184 {
20185 	struct bpf_prog *prog = env->prog, **func, *tmp;
20186 	int i, j, subprog_start, subprog_end = 0, len, subprog;
20187 	struct bpf_map *map_ptr;
20188 	struct bpf_insn *insn;
20189 	void *old_bpf_func;
20190 	int err, num_exentries;
20191 
20192 	if (env->subprog_cnt <= 1)
20193 		return 0;
20194 
20195 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
20196 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
20197 			continue;
20198 
20199 		/* Upon error here we cannot fall back to interpreter but
20200 		 * need a hard reject of the program. Thus -EFAULT is
20201 		 * propagated in any case.
20202 		 */
20203 		subprog = find_subprog(env, i + insn->imm + 1);
20204 		if (subprog < 0) {
20205 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
20206 				  i + insn->imm + 1);
20207 			return -EFAULT;
20208 		}
20209 		/* temporarily remember subprog id inside insn instead of
20210 		 * aux_data, since next loop will split up all insns into funcs
20211 		 */
20212 		insn->off = subprog;
20213 		/* remember original imm in case JIT fails and fallback
20214 		 * to interpreter will be needed
20215 		 */
20216 		env->insn_aux_data[i].call_imm = insn->imm;
20217 		/* point imm to __bpf_call_base+1 from JITs point of view */
20218 		insn->imm = 1;
20219 		if (bpf_pseudo_func(insn)) {
20220 #if defined(MODULES_VADDR)
20221 			u64 addr = MODULES_VADDR;
20222 #else
20223 			u64 addr = VMALLOC_START;
20224 #endif
20225 			/* jit (e.g. x86_64) may emit fewer instructions
20226 			 * if it learns a u32 imm is the same as a u64 imm.
20227 			 * Set close enough to possible prog address.
20228 			 */
20229 			insn[0].imm = (u32)addr;
20230 			insn[1].imm = addr >> 32;
20231 		}
20232 	}
20233 
20234 	err = bpf_prog_alloc_jited_linfo(prog);
20235 	if (err)
20236 		goto out_undo_insn;
20237 
20238 	err = -ENOMEM;
20239 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
20240 	if (!func)
20241 		goto out_undo_insn;
20242 
20243 	for (i = 0; i < env->subprog_cnt; i++) {
20244 		subprog_start = subprog_end;
20245 		subprog_end = env->subprog_info[i + 1].start;
20246 
20247 		len = subprog_end - subprog_start;
20248 		/* bpf_prog_run() doesn't call subprogs directly,
20249 		 * hence main prog stats include the runtime of subprogs.
20250 		 * subprogs don't have IDs and not reachable via prog_get_next_id
20251 		 * func[i]->stats will never be accessed and stays NULL
20252 		 */
20253 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
20254 		if (!func[i])
20255 			goto out_free;
20256 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
20257 		       len * sizeof(struct bpf_insn));
20258 		func[i]->type = prog->type;
20259 		func[i]->len = len;
20260 		if (bpf_prog_calc_tag(func[i]))
20261 			goto out_free;
20262 		func[i]->is_func = 1;
20263 		func[i]->sleepable = prog->sleepable;
20264 		func[i]->aux->func_idx = i;
20265 		/* Below members will be freed only at prog->aux */
20266 		func[i]->aux->btf = prog->aux->btf;
20267 		func[i]->aux->func_info = prog->aux->func_info;
20268 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
20269 		func[i]->aux->poke_tab = prog->aux->poke_tab;
20270 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
20271 
20272 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
20273 			struct bpf_jit_poke_descriptor *poke;
20274 
20275 			poke = &prog->aux->poke_tab[j];
20276 			if (poke->insn_idx < subprog_end &&
20277 			    poke->insn_idx >= subprog_start)
20278 				poke->aux = func[i]->aux;
20279 		}
20280 
20281 		func[i]->aux->name[0] = 'F';
20282 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
20283 		if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE)
20284 			func[i]->aux->jits_use_priv_stack = true;
20285 
20286 		func[i]->jit_requested = 1;
20287 		func[i]->blinding_requested = prog->blinding_requested;
20288 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
20289 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
20290 		func[i]->aux->linfo = prog->aux->linfo;
20291 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
20292 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
20293 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
20294 		func[i]->aux->arena = prog->aux->arena;
20295 		num_exentries = 0;
20296 		insn = func[i]->insnsi;
20297 		for (j = 0; j < func[i]->len; j++, insn++) {
20298 			if (BPF_CLASS(insn->code) == BPF_LDX &&
20299 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
20300 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
20301 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
20302 				num_exentries++;
20303 			if ((BPF_CLASS(insn->code) == BPF_STX ||
20304 			     BPF_CLASS(insn->code) == BPF_ST) &&
20305 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
20306 				num_exentries++;
20307 			if (BPF_CLASS(insn->code) == BPF_STX &&
20308 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
20309 				num_exentries++;
20310 		}
20311 		func[i]->aux->num_exentries = num_exentries;
20312 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
20313 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
20314 		if (!i)
20315 			func[i]->aux->exception_boundary = env->seen_exception;
20316 		func[i] = bpf_int_jit_compile(func[i]);
20317 		if (!func[i]->jited) {
20318 			err = -ENOTSUPP;
20319 			goto out_free;
20320 		}
20321 		cond_resched();
20322 	}
20323 
20324 	/* at this point all bpf functions were successfully JITed
20325 	 * now populate all bpf_calls with correct addresses and
20326 	 * run last pass of JIT
20327 	 */
20328 	for (i = 0; i < env->subprog_cnt; i++) {
20329 		insn = func[i]->insnsi;
20330 		for (j = 0; j < func[i]->len; j++, insn++) {
20331 			if (bpf_pseudo_func(insn)) {
20332 				subprog = insn->off;
20333 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
20334 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
20335 				continue;
20336 			}
20337 			if (!bpf_pseudo_call(insn))
20338 				continue;
20339 			subprog = insn->off;
20340 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
20341 		}
20342 
20343 		/* we use the aux data to keep a list of the start addresses
20344 		 * of the JITed images for each function in the program
20345 		 *
20346 		 * for some architectures, such as powerpc64, the imm field
20347 		 * might not be large enough to hold the offset of the start
20348 		 * address of the callee's JITed image from __bpf_call_base
20349 		 *
20350 		 * in such cases, we can lookup the start address of a callee
20351 		 * by using its subprog id, available from the off field of
20352 		 * the call instruction, as an index for this list
20353 		 */
20354 		func[i]->aux->func = func;
20355 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
20356 		func[i]->aux->real_func_cnt = env->subprog_cnt;
20357 	}
20358 	for (i = 0; i < env->subprog_cnt; i++) {
20359 		old_bpf_func = func[i]->bpf_func;
20360 		tmp = bpf_int_jit_compile(func[i]);
20361 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
20362 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
20363 			err = -ENOTSUPP;
20364 			goto out_free;
20365 		}
20366 		cond_resched();
20367 	}
20368 
20369 	/* finally lock prog and jit images for all functions and
20370 	 * populate kallsysm. Begin at the first subprogram, since
20371 	 * bpf_prog_load will add the kallsyms for the main program.
20372 	 */
20373 	for (i = 1; i < env->subprog_cnt; i++) {
20374 		err = bpf_prog_lock_ro(func[i]);
20375 		if (err)
20376 			goto out_free;
20377 	}
20378 
20379 	for (i = 1; i < env->subprog_cnt; i++)
20380 		bpf_prog_kallsyms_add(func[i]);
20381 
20382 	/* Last step: make now unused interpreter insns from main
20383 	 * prog consistent for later dump requests, so they can
20384 	 * later look the same as if they were interpreted only.
20385 	 */
20386 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
20387 		if (bpf_pseudo_func(insn)) {
20388 			insn[0].imm = env->insn_aux_data[i].call_imm;
20389 			insn[1].imm = insn->off;
20390 			insn->off = 0;
20391 			continue;
20392 		}
20393 		if (!bpf_pseudo_call(insn))
20394 			continue;
20395 		insn->off = env->insn_aux_data[i].call_imm;
20396 		subprog = find_subprog(env, i + insn->off + 1);
20397 		insn->imm = subprog;
20398 	}
20399 
20400 	prog->jited = 1;
20401 	prog->bpf_func = func[0]->bpf_func;
20402 	prog->jited_len = func[0]->jited_len;
20403 	prog->aux->extable = func[0]->aux->extable;
20404 	prog->aux->num_exentries = func[0]->aux->num_exentries;
20405 	prog->aux->func = func;
20406 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
20407 	prog->aux->real_func_cnt = env->subprog_cnt;
20408 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
20409 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
20410 	bpf_prog_jit_attempt_done(prog);
20411 	return 0;
20412 out_free:
20413 	/* We failed JIT'ing, so at this point we need to unregister poke
20414 	 * descriptors from subprogs, so that kernel is not attempting to
20415 	 * patch it anymore as we're freeing the subprog JIT memory.
20416 	 */
20417 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
20418 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
20419 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
20420 	}
20421 	/* At this point we're guaranteed that poke descriptors are not
20422 	 * live anymore. We can just unlink its descriptor table as it's
20423 	 * released with the main prog.
20424 	 */
20425 	for (i = 0; i < env->subprog_cnt; i++) {
20426 		if (!func[i])
20427 			continue;
20428 		func[i]->aux->poke_tab = NULL;
20429 		bpf_jit_free(func[i]);
20430 	}
20431 	kfree(func);
20432 out_undo_insn:
20433 	/* cleanup main prog to be interpreted */
20434 	prog->jit_requested = 0;
20435 	prog->blinding_requested = 0;
20436 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
20437 		if (!bpf_pseudo_call(insn))
20438 			continue;
20439 		insn->off = 0;
20440 		insn->imm = env->insn_aux_data[i].call_imm;
20441 	}
20442 	bpf_prog_jit_attempt_done(prog);
20443 	return err;
20444 }
20445 
20446 static int fixup_call_args(struct bpf_verifier_env *env)
20447 {
20448 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
20449 	struct bpf_prog *prog = env->prog;
20450 	struct bpf_insn *insn = prog->insnsi;
20451 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
20452 	int i, depth;
20453 #endif
20454 	int err = 0;
20455 
20456 	if (env->prog->jit_requested &&
20457 	    !bpf_prog_is_offloaded(env->prog->aux)) {
20458 		err = jit_subprogs(env);
20459 		if (err == 0)
20460 			return 0;
20461 		if (err == -EFAULT)
20462 			return err;
20463 	}
20464 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
20465 	if (has_kfunc_call) {
20466 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
20467 		return -EINVAL;
20468 	}
20469 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
20470 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
20471 		 * have to be rejected, since interpreter doesn't support them yet.
20472 		 */
20473 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
20474 		return -EINVAL;
20475 	}
20476 	for (i = 0; i < prog->len; i++, insn++) {
20477 		if (bpf_pseudo_func(insn)) {
20478 			/* When JIT fails the progs with callback calls
20479 			 * have to be rejected, since interpreter doesn't support them yet.
20480 			 */
20481 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
20482 			return -EINVAL;
20483 		}
20484 
20485 		if (!bpf_pseudo_call(insn))
20486 			continue;
20487 		depth = get_callee_stack_depth(env, insn, i);
20488 		if (depth < 0)
20489 			return depth;
20490 		bpf_patch_call_args(insn, depth);
20491 	}
20492 	err = 0;
20493 #endif
20494 	return err;
20495 }
20496 
20497 /* replace a generic kfunc with a specialized version if necessary */
20498 static void specialize_kfunc(struct bpf_verifier_env *env,
20499 			     u32 func_id, u16 offset, unsigned long *addr)
20500 {
20501 	struct bpf_prog *prog = env->prog;
20502 	bool seen_direct_write;
20503 	void *xdp_kfunc;
20504 	bool is_rdonly;
20505 
20506 	if (bpf_dev_bound_kfunc_id(func_id)) {
20507 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
20508 		if (xdp_kfunc) {
20509 			*addr = (unsigned long)xdp_kfunc;
20510 			return;
20511 		}
20512 		/* fallback to default kfunc when not supported by netdev */
20513 	}
20514 
20515 	if (offset)
20516 		return;
20517 
20518 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
20519 		seen_direct_write = env->seen_direct_write;
20520 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
20521 
20522 		if (is_rdonly)
20523 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
20524 
20525 		/* restore env->seen_direct_write to its original value, since
20526 		 * may_access_direct_pkt_data mutates it
20527 		 */
20528 		env->seen_direct_write = seen_direct_write;
20529 	}
20530 }
20531 
20532 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
20533 					    u16 struct_meta_reg,
20534 					    u16 node_offset_reg,
20535 					    struct bpf_insn *insn,
20536 					    struct bpf_insn *insn_buf,
20537 					    int *cnt)
20538 {
20539 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
20540 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
20541 
20542 	insn_buf[0] = addr[0];
20543 	insn_buf[1] = addr[1];
20544 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
20545 	insn_buf[3] = *insn;
20546 	*cnt = 4;
20547 }
20548 
20549 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
20550 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
20551 {
20552 	const struct bpf_kfunc_desc *desc;
20553 
20554 	if (!insn->imm) {
20555 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
20556 		return -EINVAL;
20557 	}
20558 
20559 	*cnt = 0;
20560 
20561 	/* insn->imm has the btf func_id. Replace it with an offset relative to
20562 	 * __bpf_call_base, unless the JIT needs to call functions that are
20563 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
20564 	 */
20565 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
20566 	if (!desc) {
20567 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
20568 			insn->imm);
20569 		return -EFAULT;
20570 	}
20571 
20572 	if (!bpf_jit_supports_far_kfunc_call())
20573 		insn->imm = BPF_CALL_IMM(desc->addr);
20574 	if (insn->off)
20575 		return 0;
20576 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
20577 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
20578 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
20579 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
20580 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
20581 
20582 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
20583 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
20584 				insn_idx);
20585 			return -EFAULT;
20586 		}
20587 
20588 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
20589 		insn_buf[1] = addr[0];
20590 		insn_buf[2] = addr[1];
20591 		insn_buf[3] = *insn;
20592 		*cnt = 4;
20593 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
20594 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
20595 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
20596 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
20597 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
20598 
20599 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
20600 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
20601 				insn_idx);
20602 			return -EFAULT;
20603 		}
20604 
20605 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
20606 		    !kptr_struct_meta) {
20607 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
20608 				insn_idx);
20609 			return -EFAULT;
20610 		}
20611 
20612 		insn_buf[0] = addr[0];
20613 		insn_buf[1] = addr[1];
20614 		insn_buf[2] = *insn;
20615 		*cnt = 3;
20616 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
20617 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
20618 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
20619 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
20620 		int struct_meta_reg = BPF_REG_3;
20621 		int node_offset_reg = BPF_REG_4;
20622 
20623 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
20624 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
20625 			struct_meta_reg = BPF_REG_4;
20626 			node_offset_reg = BPF_REG_5;
20627 		}
20628 
20629 		if (!kptr_struct_meta) {
20630 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
20631 				insn_idx);
20632 			return -EFAULT;
20633 		}
20634 
20635 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
20636 						node_offset_reg, insn, insn_buf, cnt);
20637 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
20638 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
20639 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
20640 		*cnt = 1;
20641 	} else if (is_bpf_wq_set_callback_impl_kfunc(desc->func_id)) {
20642 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(BPF_REG_4, (long)env->prog->aux) };
20643 
20644 		insn_buf[0] = ld_addrs[0];
20645 		insn_buf[1] = ld_addrs[1];
20646 		insn_buf[2] = *insn;
20647 		*cnt = 3;
20648 	}
20649 	return 0;
20650 }
20651 
20652 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
20653 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
20654 {
20655 	struct bpf_subprog_info *info = env->subprog_info;
20656 	int cnt = env->subprog_cnt;
20657 	struct bpf_prog *prog;
20658 
20659 	/* We only reserve one slot for hidden subprogs in subprog_info. */
20660 	if (env->hidden_subprog_cnt) {
20661 		verbose(env, "verifier internal error: only one hidden subprog supported\n");
20662 		return -EFAULT;
20663 	}
20664 	/* We're not patching any existing instruction, just appending the new
20665 	 * ones for the hidden subprog. Hence all of the adjustment operations
20666 	 * in bpf_patch_insn_data are no-ops.
20667 	 */
20668 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
20669 	if (!prog)
20670 		return -ENOMEM;
20671 	env->prog = prog;
20672 	info[cnt + 1].start = info[cnt].start;
20673 	info[cnt].start = prog->len - len + 1;
20674 	env->subprog_cnt++;
20675 	env->hidden_subprog_cnt++;
20676 	return 0;
20677 }
20678 
20679 /* Do various post-verification rewrites in a single program pass.
20680  * These rewrites simplify JIT and interpreter implementations.
20681  */
20682 static int do_misc_fixups(struct bpf_verifier_env *env)
20683 {
20684 	struct bpf_prog *prog = env->prog;
20685 	enum bpf_attach_type eatype = prog->expected_attach_type;
20686 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
20687 	struct bpf_insn *insn = prog->insnsi;
20688 	const struct bpf_func_proto *fn;
20689 	const int insn_cnt = prog->len;
20690 	const struct bpf_map_ops *ops;
20691 	struct bpf_insn_aux_data *aux;
20692 	struct bpf_insn *insn_buf = env->insn_buf;
20693 	struct bpf_prog *new_prog;
20694 	struct bpf_map *map_ptr;
20695 	int i, ret, cnt, delta = 0, cur_subprog = 0;
20696 	struct bpf_subprog_info *subprogs = env->subprog_info;
20697 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
20698 	u16 stack_depth_extra = 0;
20699 
20700 	if (env->seen_exception && !env->exception_callback_subprog) {
20701 		struct bpf_insn patch[] = {
20702 			env->prog->insnsi[insn_cnt - 1],
20703 			BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
20704 			BPF_EXIT_INSN(),
20705 		};
20706 
20707 		ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
20708 		if (ret < 0)
20709 			return ret;
20710 		prog = env->prog;
20711 		insn = prog->insnsi;
20712 
20713 		env->exception_callback_subprog = env->subprog_cnt - 1;
20714 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
20715 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
20716 	}
20717 
20718 	for (i = 0; i < insn_cnt;) {
20719 		if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
20720 			if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
20721 			    (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
20722 				/* convert to 32-bit mov that clears upper 32-bit */
20723 				insn->code = BPF_ALU | BPF_MOV | BPF_X;
20724 				/* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
20725 				insn->off = 0;
20726 				insn->imm = 0;
20727 			} /* cast from as(0) to as(1) should be handled by JIT */
20728 			goto next_insn;
20729 		}
20730 
20731 		if (env->insn_aux_data[i + delta].needs_zext)
20732 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
20733 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
20734 
20735 		/* Make sdiv/smod divide-by-minus-one exceptions impossible. */
20736 		if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
20737 		     insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
20738 		     insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
20739 		     insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
20740 		    insn->off == 1 && insn->imm == -1) {
20741 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
20742 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
20743 			struct bpf_insn *patchlet;
20744 			struct bpf_insn chk_and_sdiv[] = {
20745 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
20746 					     BPF_NEG | BPF_K, insn->dst_reg,
20747 					     0, 0, 0),
20748 			};
20749 			struct bpf_insn chk_and_smod[] = {
20750 				BPF_MOV32_IMM(insn->dst_reg, 0),
20751 			};
20752 
20753 			patchlet = isdiv ? chk_and_sdiv : chk_and_smod;
20754 			cnt = isdiv ? ARRAY_SIZE(chk_and_sdiv) : ARRAY_SIZE(chk_and_smod);
20755 
20756 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
20757 			if (!new_prog)
20758 				return -ENOMEM;
20759 
20760 			delta    += cnt - 1;
20761 			env->prog = prog = new_prog;
20762 			insn      = new_prog->insnsi + i + delta;
20763 			goto next_insn;
20764 		}
20765 
20766 		/* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
20767 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
20768 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
20769 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
20770 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
20771 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
20772 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
20773 			bool is_sdiv = isdiv && insn->off == 1;
20774 			bool is_smod = !isdiv && insn->off == 1;
20775 			struct bpf_insn *patchlet;
20776 			struct bpf_insn chk_and_div[] = {
20777 				/* [R,W]x div 0 -> 0 */
20778 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
20779 					     BPF_JNE | BPF_K, insn->src_reg,
20780 					     0, 2, 0),
20781 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
20782 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
20783 				*insn,
20784 			};
20785 			struct bpf_insn chk_and_mod[] = {
20786 				/* [R,W]x mod 0 -> [R,W]x */
20787 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
20788 					     BPF_JEQ | BPF_K, insn->src_reg,
20789 					     0, 1 + (is64 ? 0 : 1), 0),
20790 				*insn,
20791 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
20792 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
20793 			};
20794 			struct bpf_insn chk_and_sdiv[] = {
20795 				/* [R,W]x sdiv 0 -> 0
20796 				 * LLONG_MIN sdiv -1 -> LLONG_MIN
20797 				 * INT_MIN sdiv -1 -> INT_MIN
20798 				 */
20799 				BPF_MOV64_REG(BPF_REG_AX, insn->src_reg),
20800 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
20801 					     BPF_ADD | BPF_K, BPF_REG_AX,
20802 					     0, 0, 1),
20803 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
20804 					     BPF_JGT | BPF_K, BPF_REG_AX,
20805 					     0, 4, 1),
20806 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
20807 					     BPF_JEQ | BPF_K, BPF_REG_AX,
20808 					     0, 1, 0),
20809 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
20810 					     BPF_MOV | BPF_K, insn->dst_reg,
20811 					     0, 0, 0),
20812 				/* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
20813 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
20814 					     BPF_NEG | BPF_K, insn->dst_reg,
20815 					     0, 0, 0),
20816 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
20817 				*insn,
20818 			};
20819 			struct bpf_insn chk_and_smod[] = {
20820 				/* [R,W]x mod 0 -> [R,W]x */
20821 				/* [R,W]x mod -1 -> 0 */
20822 				BPF_MOV64_REG(BPF_REG_AX, insn->src_reg),
20823 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
20824 					     BPF_ADD | BPF_K, BPF_REG_AX,
20825 					     0, 0, 1),
20826 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
20827 					     BPF_JGT | BPF_K, BPF_REG_AX,
20828 					     0, 3, 1),
20829 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
20830 					     BPF_JEQ | BPF_K, BPF_REG_AX,
20831 					     0, 3 + (is64 ? 0 : 1), 1),
20832 				BPF_MOV32_IMM(insn->dst_reg, 0),
20833 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
20834 				*insn,
20835 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
20836 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
20837 			};
20838 
20839 			if (is_sdiv) {
20840 				patchlet = chk_and_sdiv;
20841 				cnt = ARRAY_SIZE(chk_and_sdiv);
20842 			} else if (is_smod) {
20843 				patchlet = chk_and_smod;
20844 				cnt = ARRAY_SIZE(chk_and_smod) - (is64 ? 2 : 0);
20845 			} else {
20846 				patchlet = isdiv ? chk_and_div : chk_and_mod;
20847 				cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
20848 					      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
20849 			}
20850 
20851 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
20852 			if (!new_prog)
20853 				return -ENOMEM;
20854 
20855 			delta    += cnt - 1;
20856 			env->prog = prog = new_prog;
20857 			insn      = new_prog->insnsi + i + delta;
20858 			goto next_insn;
20859 		}
20860 
20861 		/* Make it impossible to de-reference a userspace address */
20862 		if (BPF_CLASS(insn->code) == BPF_LDX &&
20863 		    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
20864 		     BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
20865 			struct bpf_insn *patch = &insn_buf[0];
20866 			u64 uaddress_limit = bpf_arch_uaddress_limit();
20867 
20868 			if (!uaddress_limit)
20869 				goto next_insn;
20870 
20871 			*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
20872 			if (insn->off)
20873 				*patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
20874 			*patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
20875 			*patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
20876 			*patch++ = *insn;
20877 			*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
20878 			*patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
20879 
20880 			cnt = patch - insn_buf;
20881 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20882 			if (!new_prog)
20883 				return -ENOMEM;
20884 
20885 			delta    += cnt - 1;
20886 			env->prog = prog = new_prog;
20887 			insn      = new_prog->insnsi + i + delta;
20888 			goto next_insn;
20889 		}
20890 
20891 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
20892 		if (BPF_CLASS(insn->code) == BPF_LD &&
20893 		    (BPF_MODE(insn->code) == BPF_ABS ||
20894 		     BPF_MODE(insn->code) == BPF_IND)) {
20895 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
20896 			if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
20897 				verbose(env, "bpf verifier is misconfigured\n");
20898 				return -EINVAL;
20899 			}
20900 
20901 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20902 			if (!new_prog)
20903 				return -ENOMEM;
20904 
20905 			delta    += cnt - 1;
20906 			env->prog = prog = new_prog;
20907 			insn      = new_prog->insnsi + i + delta;
20908 			goto next_insn;
20909 		}
20910 
20911 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
20912 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
20913 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
20914 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
20915 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
20916 			struct bpf_insn *patch = &insn_buf[0];
20917 			bool issrc, isneg, isimm;
20918 			u32 off_reg;
20919 
20920 			aux = &env->insn_aux_data[i + delta];
20921 			if (!aux->alu_state ||
20922 			    aux->alu_state == BPF_ALU_NON_POINTER)
20923 				goto next_insn;
20924 
20925 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
20926 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
20927 				BPF_ALU_SANITIZE_SRC;
20928 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
20929 
20930 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
20931 			if (isimm) {
20932 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
20933 			} else {
20934 				if (isneg)
20935 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
20936 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
20937 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
20938 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
20939 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
20940 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
20941 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
20942 			}
20943 			if (!issrc)
20944 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
20945 			insn->src_reg = BPF_REG_AX;
20946 			if (isneg)
20947 				insn->code = insn->code == code_add ?
20948 					     code_sub : code_add;
20949 			*patch++ = *insn;
20950 			if (issrc && isneg && !isimm)
20951 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
20952 			cnt = patch - insn_buf;
20953 
20954 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20955 			if (!new_prog)
20956 				return -ENOMEM;
20957 
20958 			delta    += cnt - 1;
20959 			env->prog = prog = new_prog;
20960 			insn      = new_prog->insnsi + i + delta;
20961 			goto next_insn;
20962 		}
20963 
20964 		if (is_may_goto_insn(insn)) {
20965 			int stack_off = -stack_depth - 8;
20966 
20967 			stack_depth_extra = 8;
20968 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
20969 			if (insn->off >= 0)
20970 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
20971 			else
20972 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
20973 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
20974 			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
20975 			cnt = 4;
20976 
20977 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20978 			if (!new_prog)
20979 				return -ENOMEM;
20980 
20981 			delta += cnt - 1;
20982 			env->prog = prog = new_prog;
20983 			insn = new_prog->insnsi + i + delta;
20984 			goto next_insn;
20985 		}
20986 
20987 		if (insn->code != (BPF_JMP | BPF_CALL))
20988 			goto next_insn;
20989 		if (insn->src_reg == BPF_PSEUDO_CALL)
20990 			goto next_insn;
20991 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
20992 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
20993 			if (ret)
20994 				return ret;
20995 			if (cnt == 0)
20996 				goto next_insn;
20997 
20998 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20999 			if (!new_prog)
21000 				return -ENOMEM;
21001 
21002 			delta	 += cnt - 1;
21003 			env->prog = prog = new_prog;
21004 			insn	  = new_prog->insnsi + i + delta;
21005 			goto next_insn;
21006 		}
21007 
21008 		/* Skip inlining the helper call if the JIT does it. */
21009 		if (bpf_jit_inlines_helper_call(insn->imm))
21010 			goto next_insn;
21011 
21012 		if (insn->imm == BPF_FUNC_get_route_realm)
21013 			prog->dst_needed = 1;
21014 		if (insn->imm == BPF_FUNC_get_prandom_u32)
21015 			bpf_user_rnd_init_once();
21016 		if (insn->imm == BPF_FUNC_override_return)
21017 			prog->kprobe_override = 1;
21018 		if (insn->imm == BPF_FUNC_tail_call) {
21019 			/* If we tail call into other programs, we
21020 			 * cannot make any assumptions since they can
21021 			 * be replaced dynamically during runtime in
21022 			 * the program array.
21023 			 */
21024 			prog->cb_access = 1;
21025 			if (!allow_tail_call_in_subprogs(env))
21026 				prog->aux->stack_depth = MAX_BPF_STACK;
21027 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
21028 
21029 			/* mark bpf_tail_call as different opcode to avoid
21030 			 * conditional branch in the interpreter for every normal
21031 			 * call and to prevent accidental JITing by JIT compiler
21032 			 * that doesn't support bpf_tail_call yet
21033 			 */
21034 			insn->imm = 0;
21035 			insn->code = BPF_JMP | BPF_TAIL_CALL;
21036 
21037 			aux = &env->insn_aux_data[i + delta];
21038 			if (env->bpf_capable && !prog->blinding_requested &&
21039 			    prog->jit_requested &&
21040 			    !bpf_map_key_poisoned(aux) &&
21041 			    !bpf_map_ptr_poisoned(aux) &&
21042 			    !bpf_map_ptr_unpriv(aux)) {
21043 				struct bpf_jit_poke_descriptor desc = {
21044 					.reason = BPF_POKE_REASON_TAIL_CALL,
21045 					.tail_call.map = aux->map_ptr_state.map_ptr,
21046 					.tail_call.key = bpf_map_key_immediate(aux),
21047 					.insn_idx = i + delta,
21048 				};
21049 
21050 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
21051 				if (ret < 0) {
21052 					verbose(env, "adding tail call poke descriptor failed\n");
21053 					return ret;
21054 				}
21055 
21056 				insn->imm = ret + 1;
21057 				goto next_insn;
21058 			}
21059 
21060 			if (!bpf_map_ptr_unpriv(aux))
21061 				goto next_insn;
21062 
21063 			/* instead of changing every JIT dealing with tail_call
21064 			 * emit two extra insns:
21065 			 * if (index >= max_entries) goto out;
21066 			 * index &= array->index_mask;
21067 			 * to avoid out-of-bounds cpu speculation
21068 			 */
21069 			if (bpf_map_ptr_poisoned(aux)) {
21070 				verbose(env, "tail_call abusing map_ptr\n");
21071 				return -EINVAL;
21072 			}
21073 
21074 			map_ptr = aux->map_ptr_state.map_ptr;
21075 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
21076 						  map_ptr->max_entries, 2);
21077 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
21078 						    container_of(map_ptr,
21079 								 struct bpf_array,
21080 								 map)->index_mask);
21081 			insn_buf[2] = *insn;
21082 			cnt = 3;
21083 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21084 			if (!new_prog)
21085 				return -ENOMEM;
21086 
21087 			delta    += cnt - 1;
21088 			env->prog = prog = new_prog;
21089 			insn      = new_prog->insnsi + i + delta;
21090 			goto next_insn;
21091 		}
21092 
21093 		if (insn->imm == BPF_FUNC_timer_set_callback) {
21094 			/* The verifier will process callback_fn as many times as necessary
21095 			 * with different maps and the register states prepared by
21096 			 * set_timer_callback_state will be accurate.
21097 			 *
21098 			 * The following use case is valid:
21099 			 *   map1 is shared by prog1, prog2, prog3.
21100 			 *   prog1 calls bpf_timer_init for some map1 elements
21101 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
21102 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
21103 			 *   prog3 calls bpf_timer_start for some map1 elements.
21104 			 *     Those that were not both bpf_timer_init-ed and
21105 			 *     bpf_timer_set_callback-ed will return -EINVAL.
21106 			 */
21107 			struct bpf_insn ld_addrs[2] = {
21108 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
21109 			};
21110 
21111 			insn_buf[0] = ld_addrs[0];
21112 			insn_buf[1] = ld_addrs[1];
21113 			insn_buf[2] = *insn;
21114 			cnt = 3;
21115 
21116 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21117 			if (!new_prog)
21118 				return -ENOMEM;
21119 
21120 			delta    += cnt - 1;
21121 			env->prog = prog = new_prog;
21122 			insn      = new_prog->insnsi + i + delta;
21123 			goto patch_call_imm;
21124 		}
21125 
21126 		if (is_storage_get_function(insn->imm)) {
21127 			if (!in_sleepable(env) ||
21128 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
21129 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
21130 			else
21131 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
21132 			insn_buf[1] = *insn;
21133 			cnt = 2;
21134 
21135 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21136 			if (!new_prog)
21137 				return -ENOMEM;
21138 
21139 			delta += cnt - 1;
21140 			env->prog = prog = new_prog;
21141 			insn = new_prog->insnsi + i + delta;
21142 			goto patch_call_imm;
21143 		}
21144 
21145 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
21146 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
21147 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
21148 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
21149 			 */
21150 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
21151 			insn_buf[1] = *insn;
21152 			cnt = 2;
21153 
21154 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21155 			if (!new_prog)
21156 				return -ENOMEM;
21157 
21158 			delta += cnt - 1;
21159 			env->prog = prog = new_prog;
21160 			insn = new_prog->insnsi + i + delta;
21161 			goto patch_call_imm;
21162 		}
21163 
21164 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
21165 		 * and other inlining handlers are currently limited to 64 bit
21166 		 * only.
21167 		 */
21168 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
21169 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
21170 		     insn->imm == BPF_FUNC_map_update_elem ||
21171 		     insn->imm == BPF_FUNC_map_delete_elem ||
21172 		     insn->imm == BPF_FUNC_map_push_elem   ||
21173 		     insn->imm == BPF_FUNC_map_pop_elem    ||
21174 		     insn->imm == BPF_FUNC_map_peek_elem   ||
21175 		     insn->imm == BPF_FUNC_redirect_map    ||
21176 		     insn->imm == BPF_FUNC_for_each_map_elem ||
21177 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
21178 			aux = &env->insn_aux_data[i + delta];
21179 			if (bpf_map_ptr_poisoned(aux))
21180 				goto patch_call_imm;
21181 
21182 			map_ptr = aux->map_ptr_state.map_ptr;
21183 			ops = map_ptr->ops;
21184 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
21185 			    ops->map_gen_lookup) {
21186 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
21187 				if (cnt == -EOPNOTSUPP)
21188 					goto patch_map_ops_generic;
21189 				if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
21190 					verbose(env, "bpf verifier is misconfigured\n");
21191 					return -EINVAL;
21192 				}
21193 
21194 				new_prog = bpf_patch_insn_data(env, i + delta,
21195 							       insn_buf, cnt);
21196 				if (!new_prog)
21197 					return -ENOMEM;
21198 
21199 				delta    += cnt - 1;
21200 				env->prog = prog = new_prog;
21201 				insn      = new_prog->insnsi + i + delta;
21202 				goto next_insn;
21203 			}
21204 
21205 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
21206 				     (void *(*)(struct bpf_map *map, void *key))NULL));
21207 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
21208 				     (long (*)(struct bpf_map *map, void *key))NULL));
21209 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
21210 				     (long (*)(struct bpf_map *map, void *key, void *value,
21211 					      u64 flags))NULL));
21212 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
21213 				     (long (*)(struct bpf_map *map, void *value,
21214 					      u64 flags))NULL));
21215 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
21216 				     (long (*)(struct bpf_map *map, void *value))NULL));
21217 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
21218 				     (long (*)(struct bpf_map *map, void *value))NULL));
21219 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
21220 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
21221 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
21222 				     (long (*)(struct bpf_map *map,
21223 					      bpf_callback_t callback_fn,
21224 					      void *callback_ctx,
21225 					      u64 flags))NULL));
21226 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
21227 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
21228 
21229 patch_map_ops_generic:
21230 			switch (insn->imm) {
21231 			case BPF_FUNC_map_lookup_elem:
21232 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
21233 				goto next_insn;
21234 			case BPF_FUNC_map_update_elem:
21235 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
21236 				goto next_insn;
21237 			case BPF_FUNC_map_delete_elem:
21238 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
21239 				goto next_insn;
21240 			case BPF_FUNC_map_push_elem:
21241 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
21242 				goto next_insn;
21243 			case BPF_FUNC_map_pop_elem:
21244 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
21245 				goto next_insn;
21246 			case BPF_FUNC_map_peek_elem:
21247 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
21248 				goto next_insn;
21249 			case BPF_FUNC_redirect_map:
21250 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
21251 				goto next_insn;
21252 			case BPF_FUNC_for_each_map_elem:
21253 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
21254 				goto next_insn;
21255 			case BPF_FUNC_map_lookup_percpu_elem:
21256 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
21257 				goto next_insn;
21258 			}
21259 
21260 			goto patch_call_imm;
21261 		}
21262 
21263 		/* Implement bpf_jiffies64 inline. */
21264 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
21265 		    insn->imm == BPF_FUNC_jiffies64) {
21266 			struct bpf_insn ld_jiffies_addr[2] = {
21267 				BPF_LD_IMM64(BPF_REG_0,
21268 					     (unsigned long)&jiffies),
21269 			};
21270 
21271 			insn_buf[0] = ld_jiffies_addr[0];
21272 			insn_buf[1] = ld_jiffies_addr[1];
21273 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
21274 						  BPF_REG_0, 0);
21275 			cnt = 3;
21276 
21277 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
21278 						       cnt);
21279 			if (!new_prog)
21280 				return -ENOMEM;
21281 
21282 			delta    += cnt - 1;
21283 			env->prog = prog = new_prog;
21284 			insn      = new_prog->insnsi + i + delta;
21285 			goto next_insn;
21286 		}
21287 
21288 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
21289 		/* Implement bpf_get_smp_processor_id() inline. */
21290 		if (insn->imm == BPF_FUNC_get_smp_processor_id &&
21291 		    verifier_inlines_helper_call(env, insn->imm)) {
21292 			/* BPF_FUNC_get_smp_processor_id inlining is an
21293 			 * optimization, so if pcpu_hot.cpu_number is ever
21294 			 * changed in some incompatible and hard to support
21295 			 * way, it's fine to back out this inlining logic
21296 			 */
21297 			insn_buf[0] = BPF_MOV32_IMM(BPF_REG_0, (u32)(unsigned long)&pcpu_hot.cpu_number);
21298 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
21299 			insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
21300 			cnt = 3;
21301 
21302 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21303 			if (!new_prog)
21304 				return -ENOMEM;
21305 
21306 			delta    += cnt - 1;
21307 			env->prog = prog = new_prog;
21308 			insn      = new_prog->insnsi + i + delta;
21309 			goto next_insn;
21310 		}
21311 #endif
21312 		/* Implement bpf_get_func_arg inline. */
21313 		if (prog_type == BPF_PROG_TYPE_TRACING &&
21314 		    insn->imm == BPF_FUNC_get_func_arg) {
21315 			/* Load nr_args from ctx - 8 */
21316 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
21317 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
21318 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
21319 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
21320 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
21321 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
21322 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
21323 			insn_buf[7] = BPF_JMP_A(1);
21324 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
21325 			cnt = 9;
21326 
21327 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21328 			if (!new_prog)
21329 				return -ENOMEM;
21330 
21331 			delta    += cnt - 1;
21332 			env->prog = prog = new_prog;
21333 			insn      = new_prog->insnsi + i + delta;
21334 			goto next_insn;
21335 		}
21336 
21337 		/* Implement bpf_get_func_ret inline. */
21338 		if (prog_type == BPF_PROG_TYPE_TRACING &&
21339 		    insn->imm == BPF_FUNC_get_func_ret) {
21340 			if (eatype == BPF_TRACE_FEXIT ||
21341 			    eatype == BPF_MODIFY_RETURN) {
21342 				/* Load nr_args from ctx - 8 */
21343 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
21344 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
21345 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
21346 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
21347 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
21348 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
21349 				cnt = 6;
21350 			} else {
21351 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
21352 				cnt = 1;
21353 			}
21354 
21355 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21356 			if (!new_prog)
21357 				return -ENOMEM;
21358 
21359 			delta    += cnt - 1;
21360 			env->prog = prog = new_prog;
21361 			insn      = new_prog->insnsi + i + delta;
21362 			goto next_insn;
21363 		}
21364 
21365 		/* Implement get_func_arg_cnt inline. */
21366 		if (prog_type == BPF_PROG_TYPE_TRACING &&
21367 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
21368 			/* Load nr_args from ctx - 8 */
21369 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
21370 
21371 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
21372 			if (!new_prog)
21373 				return -ENOMEM;
21374 
21375 			env->prog = prog = new_prog;
21376 			insn      = new_prog->insnsi + i + delta;
21377 			goto next_insn;
21378 		}
21379 
21380 		/* Implement bpf_get_func_ip inline. */
21381 		if (prog_type == BPF_PROG_TYPE_TRACING &&
21382 		    insn->imm == BPF_FUNC_get_func_ip) {
21383 			/* Load IP address from ctx - 16 */
21384 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
21385 
21386 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
21387 			if (!new_prog)
21388 				return -ENOMEM;
21389 
21390 			env->prog = prog = new_prog;
21391 			insn      = new_prog->insnsi + i + delta;
21392 			goto next_insn;
21393 		}
21394 
21395 		/* Implement bpf_get_branch_snapshot inline. */
21396 		if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
21397 		    prog->jit_requested && BITS_PER_LONG == 64 &&
21398 		    insn->imm == BPF_FUNC_get_branch_snapshot) {
21399 			/* We are dealing with the following func protos:
21400 			 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
21401 			 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
21402 			 */
21403 			const u32 br_entry_size = sizeof(struct perf_branch_entry);
21404 
21405 			/* struct perf_branch_entry is part of UAPI and is
21406 			 * used as an array element, so extremely unlikely to
21407 			 * ever grow or shrink
21408 			 */
21409 			BUILD_BUG_ON(br_entry_size != 24);
21410 
21411 			/* if (unlikely(flags)) return -EINVAL */
21412 			insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
21413 
21414 			/* Transform size (bytes) into number of entries (cnt = size / 24).
21415 			 * But to avoid expensive division instruction, we implement
21416 			 * divide-by-3 through multiplication, followed by further
21417 			 * division by 8 through 3-bit right shift.
21418 			 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
21419 			 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
21420 			 *
21421 			 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
21422 			 */
21423 			insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
21424 			insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
21425 			insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
21426 
21427 			/* call perf_snapshot_branch_stack implementation */
21428 			insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
21429 			/* if (entry_cnt == 0) return -ENOENT */
21430 			insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
21431 			/* return entry_cnt * sizeof(struct perf_branch_entry) */
21432 			insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
21433 			insn_buf[7] = BPF_JMP_A(3);
21434 			/* return -EINVAL; */
21435 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
21436 			insn_buf[9] = BPF_JMP_A(1);
21437 			/* return -ENOENT; */
21438 			insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
21439 			cnt = 11;
21440 
21441 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21442 			if (!new_prog)
21443 				return -ENOMEM;
21444 
21445 			delta    += cnt - 1;
21446 			env->prog = prog = new_prog;
21447 			insn      = new_prog->insnsi + i + delta;
21448 			goto next_insn;
21449 		}
21450 
21451 		/* Implement bpf_kptr_xchg inline */
21452 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
21453 		    insn->imm == BPF_FUNC_kptr_xchg &&
21454 		    bpf_jit_supports_ptr_xchg()) {
21455 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
21456 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
21457 			cnt = 2;
21458 
21459 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21460 			if (!new_prog)
21461 				return -ENOMEM;
21462 
21463 			delta    += cnt - 1;
21464 			env->prog = prog = new_prog;
21465 			insn      = new_prog->insnsi + i + delta;
21466 			goto next_insn;
21467 		}
21468 patch_call_imm:
21469 		fn = env->ops->get_func_proto(insn->imm, env->prog);
21470 		/* all functions that have prototype and verifier allowed
21471 		 * programs to call them, must be real in-kernel functions
21472 		 */
21473 		if (!fn->func) {
21474 			verbose(env,
21475 				"kernel subsystem misconfigured func %s#%d\n",
21476 				func_id_name(insn->imm), insn->imm);
21477 			return -EFAULT;
21478 		}
21479 		insn->imm = fn->func - __bpf_call_base;
21480 next_insn:
21481 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
21482 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
21483 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
21484 			cur_subprog++;
21485 			stack_depth = subprogs[cur_subprog].stack_depth;
21486 			stack_depth_extra = 0;
21487 		}
21488 		i++;
21489 		insn++;
21490 	}
21491 
21492 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
21493 	for (i = 0; i < env->subprog_cnt; i++) {
21494 		int subprog_start = subprogs[i].start;
21495 		int stack_slots = subprogs[i].stack_extra / 8;
21496 
21497 		if (!stack_slots)
21498 			continue;
21499 		if (stack_slots > 1) {
21500 			verbose(env, "verifier bug: stack_slots supports may_goto only\n");
21501 			return -EFAULT;
21502 		}
21503 
21504 		/* Add ST insn to subprog prologue to init extra stack */
21505 		insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP,
21506 					 -subprogs[i].stack_depth, BPF_MAX_LOOPS);
21507 		/* Copy first actual insn to preserve it */
21508 		insn_buf[1] = env->prog->insnsi[subprog_start];
21509 
21510 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2);
21511 		if (!new_prog)
21512 			return -ENOMEM;
21513 		env->prog = prog = new_prog;
21514 		/*
21515 		 * If may_goto is a first insn of a prog there could be a jmp
21516 		 * insn that points to it, hence adjust all such jmps to point
21517 		 * to insn after BPF_ST that inits may_goto count.
21518 		 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
21519 		 */
21520 		WARN_ON(adjust_jmp_off(env->prog, subprog_start, 1));
21521 	}
21522 
21523 	/* Since poke tab is now finalized, publish aux to tracker. */
21524 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
21525 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
21526 		if (!map_ptr->ops->map_poke_track ||
21527 		    !map_ptr->ops->map_poke_untrack ||
21528 		    !map_ptr->ops->map_poke_run) {
21529 			verbose(env, "bpf verifier is misconfigured\n");
21530 			return -EINVAL;
21531 		}
21532 
21533 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
21534 		if (ret < 0) {
21535 			verbose(env, "tracking tail call prog failed\n");
21536 			return ret;
21537 		}
21538 	}
21539 
21540 	sort_kfunc_descs_by_imm_off(env->prog);
21541 
21542 	return 0;
21543 }
21544 
21545 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
21546 					int position,
21547 					s32 stack_base,
21548 					u32 callback_subprogno,
21549 					u32 *total_cnt)
21550 {
21551 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
21552 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
21553 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
21554 	int reg_loop_max = BPF_REG_6;
21555 	int reg_loop_cnt = BPF_REG_7;
21556 	int reg_loop_ctx = BPF_REG_8;
21557 
21558 	struct bpf_insn *insn_buf = env->insn_buf;
21559 	struct bpf_prog *new_prog;
21560 	u32 callback_start;
21561 	u32 call_insn_offset;
21562 	s32 callback_offset;
21563 	u32 cnt = 0;
21564 
21565 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
21566 	 * be careful to modify this code in sync.
21567 	 */
21568 
21569 	/* Return error and jump to the end of the patch if
21570 	 * expected number of iterations is too big.
21571 	 */
21572 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
21573 	insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
21574 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
21575 	/* spill R6, R7, R8 to use these as loop vars */
21576 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
21577 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
21578 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
21579 	/* initialize loop vars */
21580 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
21581 	insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
21582 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
21583 	/* loop header,
21584 	 * if reg_loop_cnt >= reg_loop_max skip the loop body
21585 	 */
21586 	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
21587 	/* callback call,
21588 	 * correct callback offset would be set after patching
21589 	 */
21590 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
21591 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
21592 	insn_buf[cnt++] = BPF_CALL_REL(0);
21593 	/* increment loop counter */
21594 	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
21595 	/* jump to loop header if callback returned 0 */
21596 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
21597 	/* return value of bpf_loop,
21598 	 * set R0 to the number of iterations
21599 	 */
21600 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
21601 	/* restore original values of R6, R7, R8 */
21602 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
21603 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
21604 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
21605 
21606 	*total_cnt = cnt;
21607 	new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
21608 	if (!new_prog)
21609 		return new_prog;
21610 
21611 	/* callback start is known only after patching */
21612 	callback_start = env->subprog_info[callback_subprogno].start;
21613 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
21614 	call_insn_offset = position + 12;
21615 	callback_offset = callback_start - call_insn_offset - 1;
21616 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
21617 
21618 	return new_prog;
21619 }
21620 
21621 static bool is_bpf_loop_call(struct bpf_insn *insn)
21622 {
21623 	return insn->code == (BPF_JMP | BPF_CALL) &&
21624 		insn->src_reg == 0 &&
21625 		insn->imm == BPF_FUNC_loop;
21626 }
21627 
21628 /* For all sub-programs in the program (including main) check
21629  * insn_aux_data to see if there are bpf_loop calls that require
21630  * inlining. If such calls are found the calls are replaced with a
21631  * sequence of instructions produced by `inline_bpf_loop` function and
21632  * subprog stack_depth is increased by the size of 3 registers.
21633  * This stack space is used to spill values of the R6, R7, R8.  These
21634  * registers are used to store the loop bound, counter and context
21635  * variables.
21636  */
21637 static int optimize_bpf_loop(struct bpf_verifier_env *env)
21638 {
21639 	struct bpf_subprog_info *subprogs = env->subprog_info;
21640 	int i, cur_subprog = 0, cnt, delta = 0;
21641 	struct bpf_insn *insn = env->prog->insnsi;
21642 	int insn_cnt = env->prog->len;
21643 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
21644 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
21645 	u16 stack_depth_extra = 0;
21646 
21647 	for (i = 0; i < insn_cnt; i++, insn++) {
21648 		struct bpf_loop_inline_state *inline_state =
21649 			&env->insn_aux_data[i + delta].loop_inline_state;
21650 
21651 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
21652 			struct bpf_prog *new_prog;
21653 
21654 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
21655 			new_prog = inline_bpf_loop(env,
21656 						   i + delta,
21657 						   -(stack_depth + stack_depth_extra),
21658 						   inline_state->callback_subprogno,
21659 						   &cnt);
21660 			if (!new_prog)
21661 				return -ENOMEM;
21662 
21663 			delta     += cnt - 1;
21664 			env->prog  = new_prog;
21665 			insn       = new_prog->insnsi + i + delta;
21666 		}
21667 
21668 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
21669 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
21670 			cur_subprog++;
21671 			stack_depth = subprogs[cur_subprog].stack_depth;
21672 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
21673 			stack_depth_extra = 0;
21674 		}
21675 	}
21676 
21677 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
21678 
21679 	return 0;
21680 }
21681 
21682 /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
21683  * adjust subprograms stack depth when possible.
21684  */
21685 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env)
21686 {
21687 	struct bpf_subprog_info *subprog = env->subprog_info;
21688 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
21689 	struct bpf_insn *insn = env->prog->insnsi;
21690 	int insn_cnt = env->prog->len;
21691 	u32 spills_num;
21692 	bool modified = false;
21693 	int i, j;
21694 
21695 	for (i = 0; i < insn_cnt; i++, insn++) {
21696 		if (aux[i].fastcall_spills_num > 0) {
21697 			spills_num = aux[i].fastcall_spills_num;
21698 			/* NOPs would be removed by opt_remove_nops() */
21699 			for (j = 1; j <= spills_num; ++j) {
21700 				*(insn - j) = NOP;
21701 				*(insn + j) = NOP;
21702 			}
21703 			modified = true;
21704 		}
21705 		if ((subprog + 1)->start == i + 1) {
21706 			if (modified && !subprog->keep_fastcall_stack)
21707 				subprog->stack_depth = -subprog->fastcall_stack_off;
21708 			subprog++;
21709 			modified = false;
21710 		}
21711 	}
21712 
21713 	return 0;
21714 }
21715 
21716 static void free_states(struct bpf_verifier_env *env)
21717 {
21718 	struct bpf_verifier_state_list *sl, *sln;
21719 	int i;
21720 
21721 	sl = env->free_list;
21722 	while (sl) {
21723 		sln = sl->next;
21724 		free_verifier_state(&sl->state, false);
21725 		kfree(sl);
21726 		sl = sln;
21727 	}
21728 	env->free_list = NULL;
21729 
21730 	if (!env->explored_states)
21731 		return;
21732 
21733 	for (i = 0; i < state_htab_size(env); i++) {
21734 		sl = env->explored_states[i];
21735 
21736 		while (sl) {
21737 			sln = sl->next;
21738 			free_verifier_state(&sl->state, false);
21739 			kfree(sl);
21740 			sl = sln;
21741 		}
21742 		env->explored_states[i] = NULL;
21743 	}
21744 }
21745 
21746 static int do_check_common(struct bpf_verifier_env *env, int subprog)
21747 {
21748 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
21749 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
21750 	struct bpf_verifier_state *state;
21751 	struct bpf_reg_state *regs;
21752 	int ret, i;
21753 
21754 	env->prev_linfo = NULL;
21755 	env->pass_cnt++;
21756 
21757 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
21758 	if (!state)
21759 		return -ENOMEM;
21760 	state->curframe = 0;
21761 	state->speculative = false;
21762 	state->branches = 1;
21763 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
21764 	if (!state->frame[0]) {
21765 		kfree(state);
21766 		return -ENOMEM;
21767 	}
21768 	env->cur_state = state;
21769 	init_func_state(env, state->frame[0],
21770 			BPF_MAIN_FUNC /* callsite */,
21771 			0 /* frameno */,
21772 			subprog);
21773 	state->first_insn_idx = env->subprog_info[subprog].start;
21774 	state->last_insn_idx = -1;
21775 
21776 	regs = state->frame[state->curframe]->regs;
21777 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
21778 		const char *sub_name = subprog_name(env, subprog);
21779 		struct bpf_subprog_arg_info *arg;
21780 		struct bpf_reg_state *reg;
21781 
21782 		verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
21783 		ret = btf_prepare_func_args(env, subprog);
21784 		if (ret)
21785 			goto out;
21786 
21787 		if (subprog_is_exc_cb(env, subprog)) {
21788 			state->frame[0]->in_exception_callback_fn = true;
21789 			/* We have already ensured that the callback returns an integer, just
21790 			 * like all global subprogs. We need to determine it only has a single
21791 			 * scalar argument.
21792 			 */
21793 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
21794 				verbose(env, "exception cb only supports single integer argument\n");
21795 				ret = -EINVAL;
21796 				goto out;
21797 			}
21798 		}
21799 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
21800 			arg = &sub->args[i - BPF_REG_1];
21801 			reg = &regs[i];
21802 
21803 			if (arg->arg_type == ARG_PTR_TO_CTX) {
21804 				reg->type = PTR_TO_CTX;
21805 				mark_reg_known_zero(env, regs, i);
21806 			} else if (arg->arg_type == ARG_ANYTHING) {
21807 				reg->type = SCALAR_VALUE;
21808 				mark_reg_unknown(env, regs, i);
21809 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
21810 				/* assume unspecial LOCAL dynptr type */
21811 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
21812 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
21813 				reg->type = PTR_TO_MEM;
21814 				if (arg->arg_type & PTR_MAYBE_NULL)
21815 					reg->type |= PTR_MAYBE_NULL;
21816 				mark_reg_known_zero(env, regs, i);
21817 				reg->mem_size = arg->mem_size;
21818 				reg->id = ++env->id_gen;
21819 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
21820 				reg->type = PTR_TO_BTF_ID;
21821 				if (arg->arg_type & PTR_MAYBE_NULL)
21822 					reg->type |= PTR_MAYBE_NULL;
21823 				if (arg->arg_type & PTR_UNTRUSTED)
21824 					reg->type |= PTR_UNTRUSTED;
21825 				if (arg->arg_type & PTR_TRUSTED)
21826 					reg->type |= PTR_TRUSTED;
21827 				mark_reg_known_zero(env, regs, i);
21828 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
21829 				reg->btf_id = arg->btf_id;
21830 				reg->id = ++env->id_gen;
21831 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
21832 				/* caller can pass either PTR_TO_ARENA or SCALAR */
21833 				mark_reg_unknown(env, regs, i);
21834 			} else {
21835 				WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
21836 					  i - BPF_REG_1, arg->arg_type);
21837 				ret = -EFAULT;
21838 				goto out;
21839 			}
21840 		}
21841 	} else {
21842 		/* if main BPF program has associated BTF info, validate that
21843 		 * it's matching expected signature, and otherwise mark BTF
21844 		 * info for main program as unreliable
21845 		 */
21846 		if (env->prog->aux->func_info_aux) {
21847 			ret = btf_prepare_func_args(env, 0);
21848 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
21849 				env->prog->aux->func_info_aux[0].unreliable = true;
21850 		}
21851 
21852 		/* 1st arg to a function */
21853 		regs[BPF_REG_1].type = PTR_TO_CTX;
21854 		mark_reg_known_zero(env, regs, BPF_REG_1);
21855 	}
21856 
21857 	ret = do_check(env);
21858 out:
21859 	/* check for NULL is necessary, since cur_state can be freed inside
21860 	 * do_check() under memory pressure.
21861 	 */
21862 	if (env->cur_state) {
21863 		free_verifier_state(env->cur_state, true);
21864 		env->cur_state = NULL;
21865 	}
21866 	while (!pop_stack(env, NULL, NULL, false));
21867 	if (!ret && pop_log)
21868 		bpf_vlog_reset(&env->log, 0);
21869 	free_states(env);
21870 	return ret;
21871 }
21872 
21873 /* Lazily verify all global functions based on their BTF, if they are called
21874  * from main BPF program or any of subprograms transitively.
21875  * BPF global subprogs called from dead code are not validated.
21876  * All callable global functions must pass verification.
21877  * Otherwise the whole program is rejected.
21878  * Consider:
21879  * int bar(int);
21880  * int foo(int f)
21881  * {
21882  *    return bar(f);
21883  * }
21884  * int bar(int b)
21885  * {
21886  *    ...
21887  * }
21888  * foo() will be verified first for R1=any_scalar_value. During verification it
21889  * will be assumed that bar() already verified successfully and call to bar()
21890  * from foo() will be checked for type match only. Later bar() will be verified
21891  * independently to check that it's safe for R1=any_scalar_value.
21892  */
21893 static int do_check_subprogs(struct bpf_verifier_env *env)
21894 {
21895 	struct bpf_prog_aux *aux = env->prog->aux;
21896 	struct bpf_func_info_aux *sub_aux;
21897 	int i, ret, new_cnt;
21898 
21899 	if (!aux->func_info)
21900 		return 0;
21901 
21902 	/* exception callback is presumed to be always called */
21903 	if (env->exception_callback_subprog)
21904 		subprog_aux(env, env->exception_callback_subprog)->called = true;
21905 
21906 again:
21907 	new_cnt = 0;
21908 	for (i = 1; i < env->subprog_cnt; i++) {
21909 		if (!subprog_is_global(env, i))
21910 			continue;
21911 
21912 		sub_aux = subprog_aux(env, i);
21913 		if (!sub_aux->called || sub_aux->verified)
21914 			continue;
21915 
21916 		env->insn_idx = env->subprog_info[i].start;
21917 		WARN_ON_ONCE(env->insn_idx == 0);
21918 		ret = do_check_common(env, i);
21919 		if (ret) {
21920 			return ret;
21921 		} else if (env->log.level & BPF_LOG_LEVEL) {
21922 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
21923 				i, subprog_name(env, i));
21924 		}
21925 
21926 		/* We verified new global subprog, it might have called some
21927 		 * more global subprogs that we haven't verified yet, so we
21928 		 * need to do another pass over subprogs to verify those.
21929 		 */
21930 		sub_aux->verified = true;
21931 		new_cnt++;
21932 	}
21933 
21934 	/* We can't loop forever as we verify at least one global subprog on
21935 	 * each pass.
21936 	 */
21937 	if (new_cnt)
21938 		goto again;
21939 
21940 	return 0;
21941 }
21942 
21943 static int do_check_main(struct bpf_verifier_env *env)
21944 {
21945 	int ret;
21946 
21947 	env->insn_idx = 0;
21948 	ret = do_check_common(env, 0);
21949 	if (!ret)
21950 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
21951 	return ret;
21952 }
21953 
21954 
21955 static void print_verification_stats(struct bpf_verifier_env *env)
21956 {
21957 	int i;
21958 
21959 	if (env->log.level & BPF_LOG_STATS) {
21960 		verbose(env, "verification time %lld usec\n",
21961 			div_u64(env->verification_time, 1000));
21962 		verbose(env, "stack depth ");
21963 		for (i = 0; i < env->subprog_cnt; i++) {
21964 			u32 depth = env->subprog_info[i].stack_depth;
21965 
21966 			verbose(env, "%d", depth);
21967 			if (i + 1 < env->subprog_cnt)
21968 				verbose(env, "+");
21969 		}
21970 		verbose(env, "\n");
21971 	}
21972 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
21973 		"total_states %d peak_states %d mark_read %d\n",
21974 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
21975 		env->max_states_per_insn, env->total_states,
21976 		env->peak_states, env->longest_mark_read_walk);
21977 }
21978 
21979 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
21980 {
21981 	const struct btf_type *t, *func_proto;
21982 	const struct bpf_struct_ops_desc *st_ops_desc;
21983 	const struct bpf_struct_ops *st_ops;
21984 	const struct btf_member *member;
21985 	struct bpf_prog *prog = env->prog;
21986 	u32 btf_id, member_idx;
21987 	struct btf *btf;
21988 	const char *mname;
21989 	int err;
21990 
21991 	if (!prog->gpl_compatible) {
21992 		verbose(env, "struct ops programs must have a GPL compatible license\n");
21993 		return -EINVAL;
21994 	}
21995 
21996 	if (!prog->aux->attach_btf_id)
21997 		return -ENOTSUPP;
21998 
21999 	btf = prog->aux->attach_btf;
22000 	if (btf_is_module(btf)) {
22001 		/* Make sure st_ops is valid through the lifetime of env */
22002 		env->attach_btf_mod = btf_try_get_module(btf);
22003 		if (!env->attach_btf_mod) {
22004 			verbose(env, "struct_ops module %s is not found\n",
22005 				btf_get_name(btf));
22006 			return -ENOTSUPP;
22007 		}
22008 	}
22009 
22010 	btf_id = prog->aux->attach_btf_id;
22011 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
22012 	if (!st_ops_desc) {
22013 		verbose(env, "attach_btf_id %u is not a supported struct\n",
22014 			btf_id);
22015 		return -ENOTSUPP;
22016 	}
22017 	st_ops = st_ops_desc->st_ops;
22018 
22019 	t = st_ops_desc->type;
22020 	member_idx = prog->expected_attach_type;
22021 	if (member_idx >= btf_type_vlen(t)) {
22022 		verbose(env, "attach to invalid member idx %u of struct %s\n",
22023 			member_idx, st_ops->name);
22024 		return -EINVAL;
22025 	}
22026 
22027 	member = &btf_type_member(t)[member_idx];
22028 	mname = btf_name_by_offset(btf, member->name_off);
22029 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
22030 					       NULL);
22031 	if (!func_proto) {
22032 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
22033 			mname, member_idx, st_ops->name);
22034 		return -EINVAL;
22035 	}
22036 
22037 	err = bpf_struct_ops_supported(st_ops, __btf_member_bit_offset(t, member) / 8);
22038 	if (err) {
22039 		verbose(env, "attach to unsupported member %s of struct %s\n",
22040 			mname, st_ops->name);
22041 		return err;
22042 	}
22043 
22044 	if (st_ops->check_member) {
22045 		err = st_ops->check_member(t, member, prog);
22046 
22047 		if (err) {
22048 			verbose(env, "attach to unsupported member %s of struct %s\n",
22049 				mname, st_ops->name);
22050 			return err;
22051 		}
22052 	}
22053 
22054 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
22055 		verbose(env, "Private stack not supported by jit\n");
22056 		return -EACCES;
22057 	}
22058 
22059 	/* btf_ctx_access() used this to provide argument type info */
22060 	prog->aux->ctx_arg_info =
22061 		st_ops_desc->arg_info[member_idx].info;
22062 	prog->aux->ctx_arg_info_size =
22063 		st_ops_desc->arg_info[member_idx].cnt;
22064 
22065 	prog->aux->attach_func_proto = func_proto;
22066 	prog->aux->attach_func_name = mname;
22067 	env->ops = st_ops->verifier_ops;
22068 
22069 	return 0;
22070 }
22071 #define SECURITY_PREFIX "security_"
22072 
22073 static int check_attach_modify_return(unsigned long addr, const char *func_name)
22074 {
22075 	if (within_error_injection_list(addr) ||
22076 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
22077 		return 0;
22078 
22079 	return -EINVAL;
22080 }
22081 
22082 /* list of non-sleepable functions that are otherwise on
22083  * ALLOW_ERROR_INJECTION list
22084  */
22085 BTF_SET_START(btf_non_sleepable_error_inject)
22086 /* Three functions below can be called from sleepable and non-sleepable context.
22087  * Assume non-sleepable from bpf safety point of view.
22088  */
22089 BTF_ID(func, __filemap_add_folio)
22090 #ifdef CONFIG_FAIL_PAGE_ALLOC
22091 BTF_ID(func, should_fail_alloc_page)
22092 #endif
22093 #ifdef CONFIG_FAILSLAB
22094 BTF_ID(func, should_failslab)
22095 #endif
22096 BTF_SET_END(btf_non_sleepable_error_inject)
22097 
22098 static int check_non_sleepable_error_inject(u32 btf_id)
22099 {
22100 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
22101 }
22102 
22103 int bpf_check_attach_target(struct bpf_verifier_log *log,
22104 			    const struct bpf_prog *prog,
22105 			    const struct bpf_prog *tgt_prog,
22106 			    u32 btf_id,
22107 			    struct bpf_attach_target_info *tgt_info)
22108 {
22109 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
22110 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
22111 	char trace_symbol[KSYM_SYMBOL_LEN];
22112 	const char prefix[] = "btf_trace_";
22113 	struct bpf_raw_event_map *btp;
22114 	int ret = 0, subprog = -1, i;
22115 	const struct btf_type *t;
22116 	bool conservative = true;
22117 	const char *tname, *fname;
22118 	struct btf *btf;
22119 	long addr = 0;
22120 	struct module *mod = NULL;
22121 
22122 	if (!btf_id) {
22123 		bpf_log(log, "Tracing programs must provide btf_id\n");
22124 		return -EINVAL;
22125 	}
22126 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
22127 	if (!btf) {
22128 		bpf_log(log,
22129 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
22130 		return -EINVAL;
22131 	}
22132 	t = btf_type_by_id(btf, btf_id);
22133 	if (!t) {
22134 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
22135 		return -EINVAL;
22136 	}
22137 	tname = btf_name_by_offset(btf, t->name_off);
22138 	if (!tname) {
22139 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
22140 		return -EINVAL;
22141 	}
22142 	if (tgt_prog) {
22143 		struct bpf_prog_aux *aux = tgt_prog->aux;
22144 
22145 		if (bpf_prog_is_dev_bound(prog->aux) &&
22146 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
22147 			bpf_log(log, "Target program bound device mismatch");
22148 			return -EINVAL;
22149 		}
22150 
22151 		for (i = 0; i < aux->func_info_cnt; i++)
22152 			if (aux->func_info[i].type_id == btf_id) {
22153 				subprog = i;
22154 				break;
22155 			}
22156 		if (subprog == -1) {
22157 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
22158 			return -EINVAL;
22159 		}
22160 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
22161 			bpf_log(log,
22162 				"%s programs cannot attach to exception callback\n",
22163 				prog_extension ? "Extension" : "FENTRY/FEXIT");
22164 			return -EINVAL;
22165 		}
22166 		conservative = aux->func_info_aux[subprog].unreliable;
22167 		if (prog_extension) {
22168 			if (conservative) {
22169 				bpf_log(log,
22170 					"Cannot replace static functions\n");
22171 				return -EINVAL;
22172 			}
22173 			if (!prog->jit_requested) {
22174 				bpf_log(log,
22175 					"Extension programs should be JITed\n");
22176 				return -EINVAL;
22177 			}
22178 		}
22179 		if (!tgt_prog->jited) {
22180 			bpf_log(log, "Can attach to only JITed progs\n");
22181 			return -EINVAL;
22182 		}
22183 		if (prog_tracing) {
22184 			if (aux->attach_tracing_prog) {
22185 				/*
22186 				 * Target program is an fentry/fexit which is already attached
22187 				 * to another tracing program. More levels of nesting
22188 				 * attachment are not allowed.
22189 				 */
22190 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
22191 				return -EINVAL;
22192 			}
22193 		} else if (tgt_prog->type == prog->type) {
22194 			/*
22195 			 * To avoid potential call chain cycles, prevent attaching of a
22196 			 * program extension to another extension. It's ok to attach
22197 			 * fentry/fexit to extension program.
22198 			 */
22199 			bpf_log(log, "Cannot recursively attach\n");
22200 			return -EINVAL;
22201 		}
22202 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
22203 		    prog_extension &&
22204 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
22205 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
22206 			/* Program extensions can extend all program types
22207 			 * except fentry/fexit. The reason is the following.
22208 			 * The fentry/fexit programs are used for performance
22209 			 * analysis, stats and can be attached to any program
22210 			 * type. When extension program is replacing XDP function
22211 			 * it is necessary to allow performance analysis of all
22212 			 * functions. Both original XDP program and its program
22213 			 * extension. Hence attaching fentry/fexit to
22214 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
22215 			 * fentry/fexit was allowed it would be possible to create
22216 			 * long call chain fentry->extension->fentry->extension
22217 			 * beyond reasonable stack size. Hence extending fentry
22218 			 * is not allowed.
22219 			 */
22220 			bpf_log(log, "Cannot extend fentry/fexit\n");
22221 			return -EINVAL;
22222 		}
22223 	} else {
22224 		if (prog_extension) {
22225 			bpf_log(log, "Cannot replace kernel functions\n");
22226 			return -EINVAL;
22227 		}
22228 	}
22229 
22230 	switch (prog->expected_attach_type) {
22231 	case BPF_TRACE_RAW_TP:
22232 		if (tgt_prog) {
22233 			bpf_log(log,
22234 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
22235 			return -EINVAL;
22236 		}
22237 		if (!btf_type_is_typedef(t)) {
22238 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
22239 				btf_id);
22240 			return -EINVAL;
22241 		}
22242 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
22243 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
22244 				btf_id, tname);
22245 			return -EINVAL;
22246 		}
22247 		tname += sizeof(prefix) - 1;
22248 
22249 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
22250 		 * names. Thus using bpf_raw_event_map to get argument names.
22251 		 */
22252 		btp = bpf_get_raw_tracepoint(tname);
22253 		if (!btp)
22254 			return -EINVAL;
22255 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
22256 					trace_symbol);
22257 		bpf_put_raw_tracepoint(btp);
22258 
22259 		if (fname)
22260 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
22261 
22262 		if (!fname || ret < 0) {
22263 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
22264 				prefix, tname);
22265 			t = btf_type_by_id(btf, t->type);
22266 			if (!btf_type_is_ptr(t))
22267 				/* should never happen in valid vmlinux build */
22268 				return -EINVAL;
22269 		} else {
22270 			t = btf_type_by_id(btf, ret);
22271 			if (!btf_type_is_func(t))
22272 				/* should never happen in valid vmlinux build */
22273 				return -EINVAL;
22274 		}
22275 
22276 		t = btf_type_by_id(btf, t->type);
22277 		if (!btf_type_is_func_proto(t))
22278 			/* should never happen in valid vmlinux build */
22279 			return -EINVAL;
22280 
22281 		break;
22282 	case BPF_TRACE_ITER:
22283 		if (!btf_type_is_func(t)) {
22284 			bpf_log(log, "attach_btf_id %u is not a function\n",
22285 				btf_id);
22286 			return -EINVAL;
22287 		}
22288 		t = btf_type_by_id(btf, t->type);
22289 		if (!btf_type_is_func_proto(t))
22290 			return -EINVAL;
22291 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
22292 		if (ret)
22293 			return ret;
22294 		break;
22295 	default:
22296 		if (!prog_extension)
22297 			return -EINVAL;
22298 		fallthrough;
22299 	case BPF_MODIFY_RETURN:
22300 	case BPF_LSM_MAC:
22301 	case BPF_LSM_CGROUP:
22302 	case BPF_TRACE_FENTRY:
22303 	case BPF_TRACE_FEXIT:
22304 		if (!btf_type_is_func(t)) {
22305 			bpf_log(log, "attach_btf_id %u is not a function\n",
22306 				btf_id);
22307 			return -EINVAL;
22308 		}
22309 		if (prog_extension &&
22310 		    btf_check_type_match(log, prog, btf, t))
22311 			return -EINVAL;
22312 		t = btf_type_by_id(btf, t->type);
22313 		if (!btf_type_is_func_proto(t))
22314 			return -EINVAL;
22315 
22316 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
22317 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
22318 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
22319 			return -EINVAL;
22320 
22321 		if (tgt_prog && conservative)
22322 			t = NULL;
22323 
22324 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
22325 		if (ret < 0)
22326 			return ret;
22327 
22328 		if (tgt_prog) {
22329 			if (subprog == 0)
22330 				addr = (long) tgt_prog->bpf_func;
22331 			else
22332 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
22333 		} else {
22334 			if (btf_is_module(btf)) {
22335 				mod = btf_try_get_module(btf);
22336 				if (mod)
22337 					addr = find_kallsyms_symbol_value(mod, tname);
22338 				else
22339 					addr = 0;
22340 			} else {
22341 				addr = kallsyms_lookup_name(tname);
22342 			}
22343 			if (!addr) {
22344 				module_put(mod);
22345 				bpf_log(log,
22346 					"The address of function %s cannot be found\n",
22347 					tname);
22348 				return -ENOENT;
22349 			}
22350 		}
22351 
22352 		if (prog->sleepable) {
22353 			ret = -EINVAL;
22354 			switch (prog->type) {
22355 			case BPF_PROG_TYPE_TRACING:
22356 
22357 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
22358 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
22359 				 */
22360 				if (!check_non_sleepable_error_inject(btf_id) &&
22361 				    within_error_injection_list(addr))
22362 					ret = 0;
22363 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
22364 				 * in the fmodret id set with the KF_SLEEPABLE flag.
22365 				 */
22366 				else {
22367 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
22368 										prog);
22369 
22370 					if (flags && (*flags & KF_SLEEPABLE))
22371 						ret = 0;
22372 				}
22373 				break;
22374 			case BPF_PROG_TYPE_LSM:
22375 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
22376 				 * Only some of them are sleepable.
22377 				 */
22378 				if (bpf_lsm_is_sleepable_hook(btf_id))
22379 					ret = 0;
22380 				break;
22381 			default:
22382 				break;
22383 			}
22384 			if (ret) {
22385 				module_put(mod);
22386 				bpf_log(log, "%s is not sleepable\n", tname);
22387 				return ret;
22388 			}
22389 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
22390 			if (tgt_prog) {
22391 				module_put(mod);
22392 				bpf_log(log, "can't modify return codes of BPF programs\n");
22393 				return -EINVAL;
22394 			}
22395 			ret = -EINVAL;
22396 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
22397 			    !check_attach_modify_return(addr, tname))
22398 				ret = 0;
22399 			if (ret) {
22400 				module_put(mod);
22401 				bpf_log(log, "%s() is not modifiable\n", tname);
22402 				return ret;
22403 			}
22404 		}
22405 
22406 		break;
22407 	}
22408 	tgt_info->tgt_addr = addr;
22409 	tgt_info->tgt_name = tname;
22410 	tgt_info->tgt_type = t;
22411 	tgt_info->tgt_mod = mod;
22412 	return 0;
22413 }
22414 
22415 BTF_SET_START(btf_id_deny)
22416 BTF_ID_UNUSED
22417 #ifdef CONFIG_SMP
22418 BTF_ID(func, migrate_disable)
22419 BTF_ID(func, migrate_enable)
22420 #endif
22421 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
22422 BTF_ID(func, rcu_read_unlock_strict)
22423 #endif
22424 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
22425 BTF_ID(func, preempt_count_add)
22426 BTF_ID(func, preempt_count_sub)
22427 #endif
22428 #ifdef CONFIG_PREEMPT_RCU
22429 BTF_ID(func, __rcu_read_lock)
22430 BTF_ID(func, __rcu_read_unlock)
22431 #endif
22432 BTF_SET_END(btf_id_deny)
22433 
22434 static bool can_be_sleepable(struct bpf_prog *prog)
22435 {
22436 	if (prog->type == BPF_PROG_TYPE_TRACING) {
22437 		switch (prog->expected_attach_type) {
22438 		case BPF_TRACE_FENTRY:
22439 		case BPF_TRACE_FEXIT:
22440 		case BPF_MODIFY_RETURN:
22441 		case BPF_TRACE_ITER:
22442 			return true;
22443 		default:
22444 			return false;
22445 		}
22446 	}
22447 	return prog->type == BPF_PROG_TYPE_LSM ||
22448 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
22449 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
22450 }
22451 
22452 static int check_attach_btf_id(struct bpf_verifier_env *env)
22453 {
22454 	struct bpf_prog *prog = env->prog;
22455 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
22456 	struct bpf_attach_target_info tgt_info = {};
22457 	u32 btf_id = prog->aux->attach_btf_id;
22458 	struct bpf_trampoline *tr;
22459 	int ret;
22460 	u64 key;
22461 
22462 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
22463 		if (prog->sleepable)
22464 			/* attach_btf_id checked to be zero already */
22465 			return 0;
22466 		verbose(env, "Syscall programs can only be sleepable\n");
22467 		return -EINVAL;
22468 	}
22469 
22470 	if (prog->sleepable && !can_be_sleepable(prog)) {
22471 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
22472 		return -EINVAL;
22473 	}
22474 
22475 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
22476 		return check_struct_ops_btf_id(env);
22477 
22478 	if (prog->type != BPF_PROG_TYPE_TRACING &&
22479 	    prog->type != BPF_PROG_TYPE_LSM &&
22480 	    prog->type != BPF_PROG_TYPE_EXT)
22481 		return 0;
22482 
22483 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
22484 	if (ret)
22485 		return ret;
22486 
22487 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
22488 		/* to make freplace equivalent to their targets, they need to
22489 		 * inherit env->ops and expected_attach_type for the rest of the
22490 		 * verification
22491 		 */
22492 		env->ops = bpf_verifier_ops[tgt_prog->type];
22493 		prog->expected_attach_type = tgt_prog->expected_attach_type;
22494 	}
22495 
22496 	/* store info about the attachment target that will be used later */
22497 	prog->aux->attach_func_proto = tgt_info.tgt_type;
22498 	prog->aux->attach_func_name = tgt_info.tgt_name;
22499 	prog->aux->mod = tgt_info.tgt_mod;
22500 
22501 	if (tgt_prog) {
22502 		prog->aux->saved_dst_prog_type = tgt_prog->type;
22503 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
22504 	}
22505 
22506 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
22507 		prog->aux->attach_btf_trace = true;
22508 		return 0;
22509 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
22510 		if (!bpf_iter_prog_supported(prog))
22511 			return -EINVAL;
22512 		return 0;
22513 	}
22514 
22515 	if (prog->type == BPF_PROG_TYPE_LSM) {
22516 		ret = bpf_lsm_verify_prog(&env->log, prog);
22517 		if (ret < 0)
22518 			return ret;
22519 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
22520 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
22521 		return -EINVAL;
22522 	}
22523 
22524 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
22525 	tr = bpf_trampoline_get(key, &tgt_info);
22526 	if (!tr)
22527 		return -ENOMEM;
22528 
22529 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
22530 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
22531 
22532 	prog->aux->dst_trampoline = tr;
22533 	return 0;
22534 }
22535 
22536 struct btf *bpf_get_btf_vmlinux(void)
22537 {
22538 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
22539 		mutex_lock(&bpf_verifier_lock);
22540 		if (!btf_vmlinux)
22541 			btf_vmlinux = btf_parse_vmlinux();
22542 		mutex_unlock(&bpf_verifier_lock);
22543 	}
22544 	return btf_vmlinux;
22545 }
22546 
22547 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
22548 {
22549 	u64 start_time = ktime_get_ns();
22550 	struct bpf_verifier_env *env;
22551 	int i, len, ret = -EINVAL, err;
22552 	u32 log_true_size;
22553 	bool is_priv;
22554 
22555 	/* no program is valid */
22556 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
22557 		return -EINVAL;
22558 
22559 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
22560 	 * allocate/free it every time bpf_check() is called
22561 	 */
22562 	env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
22563 	if (!env)
22564 		return -ENOMEM;
22565 
22566 	env->bt.env = env;
22567 
22568 	len = (*prog)->len;
22569 	env->insn_aux_data =
22570 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
22571 	ret = -ENOMEM;
22572 	if (!env->insn_aux_data)
22573 		goto err_free_env;
22574 	for (i = 0; i < len; i++)
22575 		env->insn_aux_data[i].orig_idx = i;
22576 	env->prog = *prog;
22577 	env->ops = bpf_verifier_ops[env->prog->type];
22578 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
22579 
22580 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
22581 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
22582 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
22583 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
22584 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
22585 
22586 	bpf_get_btf_vmlinux();
22587 
22588 	/* grab the mutex to protect few globals used by verifier */
22589 	if (!is_priv)
22590 		mutex_lock(&bpf_verifier_lock);
22591 
22592 	/* user could have requested verbose verifier output
22593 	 * and supplied buffer to store the verification trace
22594 	 */
22595 	ret = bpf_vlog_init(&env->log, attr->log_level,
22596 			    (char __user *) (unsigned long) attr->log_buf,
22597 			    attr->log_size);
22598 	if (ret)
22599 		goto err_unlock;
22600 
22601 	mark_verifier_state_clean(env);
22602 
22603 	if (IS_ERR(btf_vmlinux)) {
22604 		/* Either gcc or pahole or kernel are broken. */
22605 		verbose(env, "in-kernel BTF is malformed\n");
22606 		ret = PTR_ERR(btf_vmlinux);
22607 		goto skip_full_check;
22608 	}
22609 
22610 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
22611 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
22612 		env->strict_alignment = true;
22613 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
22614 		env->strict_alignment = false;
22615 
22616 	if (is_priv)
22617 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
22618 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
22619 
22620 	env->explored_states = kvcalloc(state_htab_size(env),
22621 				       sizeof(struct bpf_verifier_state_list *),
22622 				       GFP_USER);
22623 	ret = -ENOMEM;
22624 	if (!env->explored_states)
22625 		goto skip_full_check;
22626 
22627 	ret = check_btf_info_early(env, attr, uattr);
22628 	if (ret < 0)
22629 		goto skip_full_check;
22630 
22631 	ret = add_subprog_and_kfunc(env);
22632 	if (ret < 0)
22633 		goto skip_full_check;
22634 
22635 	ret = check_subprogs(env);
22636 	if (ret < 0)
22637 		goto skip_full_check;
22638 
22639 	ret = check_btf_info(env, attr, uattr);
22640 	if (ret < 0)
22641 		goto skip_full_check;
22642 
22643 	ret = check_attach_btf_id(env);
22644 	if (ret)
22645 		goto skip_full_check;
22646 
22647 	ret = resolve_pseudo_ldimm64(env);
22648 	if (ret < 0)
22649 		goto skip_full_check;
22650 
22651 	if (bpf_prog_is_offloaded(env->prog->aux)) {
22652 		ret = bpf_prog_offload_verifier_prep(env->prog);
22653 		if (ret)
22654 			goto skip_full_check;
22655 	}
22656 
22657 	ret = check_cfg(env);
22658 	if (ret < 0)
22659 		goto skip_full_check;
22660 
22661 	ret = mark_fastcall_patterns(env);
22662 	if (ret < 0)
22663 		goto skip_full_check;
22664 
22665 	ret = do_check_main(env);
22666 	ret = ret ?: do_check_subprogs(env);
22667 
22668 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
22669 		ret = bpf_prog_offload_finalize(env);
22670 
22671 skip_full_check:
22672 	kvfree(env->explored_states);
22673 
22674 	/* might decrease stack depth, keep it before passes that
22675 	 * allocate additional slots.
22676 	 */
22677 	if (ret == 0)
22678 		ret = remove_fastcall_spills_fills(env);
22679 
22680 	if (ret == 0)
22681 		ret = check_max_stack_depth(env);
22682 
22683 	/* instruction rewrites happen after this point */
22684 	if (ret == 0)
22685 		ret = optimize_bpf_loop(env);
22686 
22687 	if (is_priv) {
22688 		if (ret == 0)
22689 			opt_hard_wire_dead_code_branches(env);
22690 		if (ret == 0)
22691 			ret = opt_remove_dead_code(env);
22692 		if (ret == 0)
22693 			ret = opt_remove_nops(env);
22694 	} else {
22695 		if (ret == 0)
22696 			sanitize_dead_code(env);
22697 	}
22698 
22699 	if (ret == 0)
22700 		/* program is valid, convert *(u32*)(ctx + off) accesses */
22701 		ret = convert_ctx_accesses(env);
22702 
22703 	if (ret == 0)
22704 		ret = do_misc_fixups(env);
22705 
22706 	/* do 32-bit optimization after insn patching has done so those patched
22707 	 * insns could be handled correctly.
22708 	 */
22709 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
22710 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
22711 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
22712 								     : false;
22713 	}
22714 
22715 	if (ret == 0)
22716 		ret = fixup_call_args(env);
22717 
22718 	env->verification_time = ktime_get_ns() - start_time;
22719 	print_verification_stats(env);
22720 	env->prog->aux->verified_insns = env->insn_processed;
22721 
22722 	/* preserve original error even if log finalization is successful */
22723 	err = bpf_vlog_finalize(&env->log, &log_true_size);
22724 	if (err)
22725 		ret = err;
22726 
22727 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
22728 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
22729 				  &log_true_size, sizeof(log_true_size))) {
22730 		ret = -EFAULT;
22731 		goto err_release_maps;
22732 	}
22733 
22734 	if (ret)
22735 		goto err_release_maps;
22736 
22737 	if (env->used_map_cnt) {
22738 		/* if program passed verifier, update used_maps in bpf_prog_info */
22739 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
22740 							  sizeof(env->used_maps[0]),
22741 							  GFP_KERNEL);
22742 
22743 		if (!env->prog->aux->used_maps) {
22744 			ret = -ENOMEM;
22745 			goto err_release_maps;
22746 		}
22747 
22748 		memcpy(env->prog->aux->used_maps, env->used_maps,
22749 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
22750 		env->prog->aux->used_map_cnt = env->used_map_cnt;
22751 	}
22752 	if (env->used_btf_cnt) {
22753 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
22754 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
22755 							  sizeof(env->used_btfs[0]),
22756 							  GFP_KERNEL);
22757 		if (!env->prog->aux->used_btfs) {
22758 			ret = -ENOMEM;
22759 			goto err_release_maps;
22760 		}
22761 
22762 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
22763 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
22764 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
22765 	}
22766 	if (env->used_map_cnt || env->used_btf_cnt) {
22767 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
22768 		 * bpf_ld_imm64 instructions
22769 		 */
22770 		convert_pseudo_ld_imm64(env);
22771 	}
22772 
22773 	adjust_btf_func(env);
22774 
22775 err_release_maps:
22776 	if (!env->prog->aux->used_maps)
22777 		/* if we didn't copy map pointers into bpf_prog_info, release
22778 		 * them now. Otherwise free_used_maps() will release them.
22779 		 */
22780 		release_maps(env);
22781 	if (!env->prog->aux->used_btfs)
22782 		release_btfs(env);
22783 
22784 	/* extension progs temporarily inherit the attach_type of their targets
22785 	   for verification purposes, so set it back to zero before returning
22786 	 */
22787 	if (env->prog->type == BPF_PROG_TYPE_EXT)
22788 		env->prog->expected_attach_type = 0;
22789 
22790 	*prog = env->prog;
22791 
22792 	module_put(env->attach_btf_mod);
22793 err_unlock:
22794 	if (!is_priv)
22795 		mutex_unlock(&bpf_verifier_lock);
22796 	vfree(env->insn_aux_data);
22797 	kvfree(env->insn_hist);
22798 err_free_env:
22799 	kvfree(env);
22800 	return ret;
22801 }
22802