xref: /linux/kernel/bpf/verifier.c (revision cbf33b8e0b360f667b17106c15d9e2aac77a76a1)
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 enum bpf_features {
48 	BPF_FEAT_RDONLY_CAST_TO_VOID = 0,
49 	BPF_FEAT_STREAMS	     = 1,
50 	__MAX_BPF_FEAT,
51 };
52 
53 struct bpf_mem_alloc bpf_global_percpu_ma;
54 static bool bpf_global_percpu_ma_set;
55 
56 /* bpf_check() is a static code analyzer that walks eBPF program
57  * instruction by instruction and updates register/stack state.
58  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
59  *
60  * The first pass is depth-first-search to check that the program is a DAG.
61  * It rejects the following programs:
62  * - larger than BPF_MAXINSNS insns
63  * - if loop is present (detected via back-edge)
64  * - unreachable insns exist (shouldn't be a forest. program = one function)
65  * - out of bounds or malformed jumps
66  * The second pass is all possible path descent from the 1st insn.
67  * Since it's analyzing all paths through the program, the length of the
68  * analysis is limited to 64k insn, which may be hit even if total number of
69  * insn is less then 4K, but there are too many branches that change stack/regs.
70  * Number of 'branches to be analyzed' is limited to 1k
71  *
72  * On entry to each instruction, each register has a type, and the instruction
73  * changes the types of the registers depending on instruction semantics.
74  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
75  * copied to R1.
76  *
77  * All registers are 64-bit.
78  * R0 - return register
79  * R1-R5 argument passing registers
80  * R6-R9 callee saved registers
81  * R10 - frame pointer read-only
82  *
83  * At the start of BPF program the register R1 contains a pointer to bpf_context
84  * and has type PTR_TO_CTX.
85  *
86  * Verifier tracks arithmetic operations on pointers in case:
87  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
88  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
89  * 1st insn copies R10 (which has FRAME_PTR) type into R1
90  * and 2nd arithmetic instruction is pattern matched to recognize
91  * that it wants to construct a pointer to some element within stack.
92  * So after 2nd insn, the register R1 has type PTR_TO_STACK
93  * (and -20 constant is saved for further stack bounds checking).
94  * Meaning that this reg is a pointer to stack plus known immediate constant.
95  *
96  * Most of the time the registers have SCALAR_VALUE type, which
97  * means the register has some value, but it's not a valid pointer.
98  * (like pointer plus pointer becomes SCALAR_VALUE type)
99  *
100  * When verifier sees load or store instructions the type of base register
101  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
102  * four pointer types recognized by check_mem_access() function.
103  *
104  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
105  * and the range of [ptr, ptr + map's value_size) is accessible.
106  *
107  * registers used to pass values to function calls are checked against
108  * function argument constraints.
109  *
110  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
111  * It means that the register type passed to this function must be
112  * PTR_TO_STACK and it will be used inside the function as
113  * 'pointer to map element key'
114  *
115  * For example the argument constraints for bpf_map_lookup_elem():
116  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
117  *   .arg1_type = ARG_CONST_MAP_PTR,
118  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
119  *
120  * ret_type says that this function returns 'pointer to map elem value or null'
121  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
122  * 2nd argument should be a pointer to stack, which will be used inside
123  * the helper function as a pointer to map element key.
124  *
125  * On the kernel side the helper function looks like:
126  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
127  * {
128  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
129  *    void *key = (void *) (unsigned long) r2;
130  *    void *value;
131  *
132  *    here kernel can access 'key' and 'map' pointers safely, knowing that
133  *    [key, key + map->key_size) bytes are valid and were initialized on
134  *    the stack of eBPF program.
135  * }
136  *
137  * Corresponding eBPF program may look like:
138  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
139  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
140  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
141  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
142  * here verifier looks at prototype of map_lookup_elem() and sees:
143  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
144  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
145  *
146  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
147  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
148  * and were initialized prior to this call.
149  * If it's ok, then verifier allows this BPF_CALL insn and looks at
150  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
151  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
152  * returns either pointer to map value or NULL.
153  *
154  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
155  * insn, the register holding that pointer in the true branch changes state to
156  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
157  * branch. See check_cond_jmp_op().
158  *
159  * After the call R0 is set to return type of the function and registers R1-R5
160  * are set to NOT_INIT to indicate that they are no longer readable.
161  *
162  * The following reference types represent a potential reference to a kernel
163  * resource which, after first being allocated, must be checked and freed by
164  * the BPF program:
165  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
166  *
167  * When the verifier sees a helper call return a reference type, it allocates a
168  * pointer id for the reference and stores it in the current function state.
169  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
170  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
171  * passes through a NULL-check conditional. For the branch wherein the state is
172  * changed to CONST_IMM, the verifier releases the reference.
173  *
174  * For each helper function that allocates a reference, such as
175  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
176  * bpf_sk_release(). When a reference type passes into the release function,
177  * the verifier also releases the reference. If any unchecked or unreleased
178  * reference remains at the end of the program, the verifier rejects it.
179  */
180 
181 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
182 struct bpf_verifier_stack_elem {
183 	/* verifier state is 'st'
184 	 * before processing instruction 'insn_idx'
185 	 * and after processing instruction 'prev_insn_idx'
186 	 */
187 	struct bpf_verifier_state st;
188 	int insn_idx;
189 	int prev_insn_idx;
190 	struct bpf_verifier_stack_elem *next;
191 	/* length of verifier log at the time this state was pushed on stack */
192 	u32 log_pos;
193 };
194 
195 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
196 #define BPF_COMPLEXITY_LIMIT_STATES	64
197 
198 #define BPF_MAP_KEY_POISON	(1ULL << 63)
199 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
200 
201 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
202 
203 #define BPF_PRIV_STACK_MIN_SIZE		64
204 
205 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx);
206 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id);
207 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
208 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
209 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
210 static int ref_set_non_owning(struct bpf_verifier_env *env,
211 			      struct bpf_reg_state *reg);
212 static void specialize_kfunc(struct bpf_verifier_env *env,
213 			     u32 func_id, u16 offset, unsigned long *addr);
214 static bool is_trusted_reg(const struct bpf_reg_state *reg);
215 
216 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
217 {
218 	return aux->map_ptr_state.poison;
219 }
220 
221 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
222 {
223 	return aux->map_ptr_state.unpriv;
224 }
225 
226 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
227 			      struct bpf_map *map,
228 			      bool unpriv, bool poison)
229 {
230 	unpriv |= bpf_map_ptr_unpriv(aux);
231 	aux->map_ptr_state.unpriv = unpriv;
232 	aux->map_ptr_state.poison = poison;
233 	aux->map_ptr_state.map_ptr = map;
234 }
235 
236 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
237 {
238 	return aux->map_key_state & BPF_MAP_KEY_POISON;
239 }
240 
241 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
242 {
243 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
244 }
245 
246 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
247 {
248 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
249 }
250 
251 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
252 {
253 	bool poisoned = bpf_map_key_poisoned(aux);
254 
255 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
256 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
257 }
258 
259 static bool bpf_helper_call(const struct bpf_insn *insn)
260 {
261 	return insn->code == (BPF_JMP | BPF_CALL) &&
262 	       insn->src_reg == 0;
263 }
264 
265 static bool bpf_pseudo_call(const struct bpf_insn *insn)
266 {
267 	return insn->code == (BPF_JMP | BPF_CALL) &&
268 	       insn->src_reg == BPF_PSEUDO_CALL;
269 }
270 
271 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
272 {
273 	return insn->code == (BPF_JMP | BPF_CALL) &&
274 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
275 }
276 
277 struct bpf_call_arg_meta {
278 	struct bpf_map *map_ptr;
279 	bool raw_mode;
280 	bool pkt_access;
281 	u8 release_regno;
282 	int regno;
283 	int access_size;
284 	int mem_size;
285 	u64 msize_max_value;
286 	int ref_obj_id;
287 	int dynptr_id;
288 	int map_uid;
289 	int func_id;
290 	struct btf *btf;
291 	u32 btf_id;
292 	struct btf *ret_btf;
293 	u32 ret_btf_id;
294 	u32 subprogno;
295 	struct btf_field *kptr_field;
296 	s64 const_map_key;
297 };
298 
299 struct bpf_kfunc_call_arg_meta {
300 	/* In parameters */
301 	struct btf *btf;
302 	u32 func_id;
303 	u32 kfunc_flags;
304 	const struct btf_type *func_proto;
305 	const char *func_name;
306 	/* Out parameters */
307 	u32 ref_obj_id;
308 	u8 release_regno;
309 	bool r0_rdonly;
310 	u32 ret_btf_id;
311 	u64 r0_size;
312 	u32 subprogno;
313 	struct {
314 		u64 value;
315 		bool found;
316 	} arg_constant;
317 
318 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
319 	 * generally to pass info about user-defined local kptr types to later
320 	 * verification logic
321 	 *   bpf_obj_drop/bpf_percpu_obj_drop
322 	 *     Record the local kptr type to be drop'd
323 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
324 	 *     Record the local kptr type to be refcount_incr'd and use
325 	 *     arg_owning_ref to determine whether refcount_acquire should be
326 	 *     fallible
327 	 */
328 	struct btf *arg_btf;
329 	u32 arg_btf_id;
330 	bool arg_owning_ref;
331 	bool arg_prog;
332 
333 	struct {
334 		struct btf_field *field;
335 	} arg_list_head;
336 	struct {
337 		struct btf_field *field;
338 	} arg_rbtree_root;
339 	struct {
340 		enum bpf_dynptr_type type;
341 		u32 id;
342 		u32 ref_obj_id;
343 	} initialized_dynptr;
344 	struct {
345 		u8 spi;
346 		u8 frameno;
347 	} iter;
348 	struct {
349 		struct bpf_map *ptr;
350 		int uid;
351 	} map;
352 	u64 mem_size;
353 };
354 
355 struct btf *btf_vmlinux;
356 
357 static const char *btf_type_name(const struct btf *btf, u32 id)
358 {
359 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
360 }
361 
362 static DEFINE_MUTEX(bpf_verifier_lock);
363 static DEFINE_MUTEX(bpf_percpu_ma_lock);
364 
365 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
366 {
367 	struct bpf_verifier_env *env = private_data;
368 	va_list args;
369 
370 	if (!bpf_verifier_log_needed(&env->log))
371 		return;
372 
373 	va_start(args, fmt);
374 	bpf_verifier_vlog(&env->log, fmt, args);
375 	va_end(args);
376 }
377 
378 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
379 				   struct bpf_reg_state *reg,
380 				   struct bpf_retval_range range, const char *ctx,
381 				   const char *reg_name)
382 {
383 	bool unknown = true;
384 
385 	verbose(env, "%s the register %s has", ctx, reg_name);
386 	if (reg->smin_value > S64_MIN) {
387 		verbose(env, " smin=%lld", reg->smin_value);
388 		unknown = false;
389 	}
390 	if (reg->smax_value < S64_MAX) {
391 		verbose(env, " smax=%lld", reg->smax_value);
392 		unknown = false;
393 	}
394 	if (unknown)
395 		verbose(env, " unknown scalar value");
396 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
397 }
398 
399 static bool reg_not_null(const struct bpf_reg_state *reg)
400 {
401 	enum bpf_reg_type type;
402 
403 	type = reg->type;
404 	if (type_may_be_null(type))
405 		return false;
406 
407 	type = base_type(type);
408 	return type == PTR_TO_SOCKET ||
409 		type == PTR_TO_TCP_SOCK ||
410 		type == PTR_TO_MAP_VALUE ||
411 		type == PTR_TO_MAP_KEY ||
412 		type == PTR_TO_SOCK_COMMON ||
413 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
414 		(type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) ||
415 		type == CONST_PTR_TO_MAP;
416 }
417 
418 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
419 {
420 	struct btf_record *rec = NULL;
421 	struct btf_struct_meta *meta;
422 
423 	if (reg->type == PTR_TO_MAP_VALUE) {
424 		rec = reg->map_ptr->record;
425 	} else if (type_is_ptr_alloc_obj(reg->type)) {
426 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
427 		if (meta)
428 			rec = meta->record;
429 	}
430 	return rec;
431 }
432 
433 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
434 {
435 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
436 
437 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
438 }
439 
440 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
441 {
442 	struct bpf_func_info *info;
443 
444 	if (!env->prog->aux->func_info)
445 		return "";
446 
447 	info = &env->prog->aux->func_info[subprog];
448 	return btf_type_name(env->prog->aux->btf, info->type_id);
449 }
450 
451 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
452 {
453 	struct bpf_subprog_info *info = subprog_info(env, subprog);
454 
455 	info->is_cb = true;
456 	info->is_async_cb = true;
457 	info->is_exception_cb = true;
458 }
459 
460 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
461 {
462 	return subprog_info(env, subprog)->is_exception_cb;
463 }
464 
465 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
466 {
467 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK);
468 }
469 
470 static bool type_is_rdonly_mem(u32 type)
471 {
472 	return type & MEM_RDONLY;
473 }
474 
475 static bool is_acquire_function(enum bpf_func_id func_id,
476 				const struct bpf_map *map)
477 {
478 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
479 
480 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
481 	    func_id == BPF_FUNC_sk_lookup_udp ||
482 	    func_id == BPF_FUNC_skc_lookup_tcp ||
483 	    func_id == BPF_FUNC_ringbuf_reserve ||
484 	    func_id == BPF_FUNC_kptr_xchg)
485 		return true;
486 
487 	if (func_id == BPF_FUNC_map_lookup_elem &&
488 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
489 	     map_type == BPF_MAP_TYPE_SOCKHASH))
490 		return true;
491 
492 	return false;
493 }
494 
495 static bool is_ptr_cast_function(enum bpf_func_id func_id)
496 {
497 	return func_id == BPF_FUNC_tcp_sock ||
498 		func_id == BPF_FUNC_sk_fullsock ||
499 		func_id == BPF_FUNC_skc_to_tcp_sock ||
500 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
501 		func_id == BPF_FUNC_skc_to_udp6_sock ||
502 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
503 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
504 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
505 }
506 
507 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
508 {
509 	return func_id == BPF_FUNC_dynptr_data;
510 }
511 
512 static bool is_sync_callback_calling_kfunc(u32 btf_id);
513 static bool is_async_callback_calling_kfunc(u32 btf_id);
514 static bool is_callback_calling_kfunc(u32 btf_id);
515 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
516 
517 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id);
518 
519 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
520 {
521 	return func_id == BPF_FUNC_for_each_map_elem ||
522 	       func_id == BPF_FUNC_find_vma ||
523 	       func_id == BPF_FUNC_loop ||
524 	       func_id == BPF_FUNC_user_ringbuf_drain;
525 }
526 
527 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
528 {
529 	return func_id == BPF_FUNC_timer_set_callback;
530 }
531 
532 static bool is_callback_calling_function(enum bpf_func_id func_id)
533 {
534 	return is_sync_callback_calling_function(func_id) ||
535 	       is_async_callback_calling_function(func_id);
536 }
537 
538 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
539 {
540 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
541 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
542 }
543 
544 static bool is_async_callback_calling_insn(struct bpf_insn *insn)
545 {
546 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
547 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
548 }
549 
550 static bool is_may_goto_insn(struct bpf_insn *insn)
551 {
552 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
553 }
554 
555 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
556 {
557 	return is_may_goto_insn(&env->prog->insnsi[insn_idx]);
558 }
559 
560 static bool is_storage_get_function(enum bpf_func_id func_id)
561 {
562 	return func_id == BPF_FUNC_sk_storage_get ||
563 	       func_id == BPF_FUNC_inode_storage_get ||
564 	       func_id == BPF_FUNC_task_storage_get ||
565 	       func_id == BPF_FUNC_cgrp_storage_get;
566 }
567 
568 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
569 					const struct bpf_map *map)
570 {
571 	int ref_obj_uses = 0;
572 
573 	if (is_ptr_cast_function(func_id))
574 		ref_obj_uses++;
575 	if (is_acquire_function(func_id, map))
576 		ref_obj_uses++;
577 	if (is_dynptr_ref_function(func_id))
578 		ref_obj_uses++;
579 
580 	return ref_obj_uses > 1;
581 }
582 
583 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
584 {
585 	return BPF_CLASS(insn->code) == BPF_STX &&
586 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
587 	       insn->imm == BPF_CMPXCHG;
588 }
589 
590 static bool is_atomic_load_insn(const struct bpf_insn *insn)
591 {
592 	return BPF_CLASS(insn->code) == BPF_STX &&
593 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
594 	       insn->imm == BPF_LOAD_ACQ;
595 }
596 
597 static int __get_spi(s32 off)
598 {
599 	return (-off - 1) / BPF_REG_SIZE;
600 }
601 
602 static struct bpf_func_state *func(struct bpf_verifier_env *env,
603 				   const struct bpf_reg_state *reg)
604 {
605 	struct bpf_verifier_state *cur = env->cur_state;
606 
607 	return cur->frame[reg->frameno];
608 }
609 
610 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
611 {
612        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
613 
614        /* We need to check that slots between [spi - nr_slots + 1, spi] are
615 	* within [0, allocated_stack).
616 	*
617 	* Please note that the spi grows downwards. For example, a dynptr
618 	* takes the size of two stack slots; the first slot will be at
619 	* spi and the second slot will be at spi - 1.
620 	*/
621        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
622 }
623 
624 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
625 			          const char *obj_kind, int nr_slots)
626 {
627 	int off, spi;
628 
629 	if (!tnum_is_const(reg->var_off)) {
630 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
631 		return -EINVAL;
632 	}
633 
634 	off = reg->off + reg->var_off.value;
635 	if (off % BPF_REG_SIZE) {
636 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
637 		return -EINVAL;
638 	}
639 
640 	spi = __get_spi(off);
641 	if (spi + 1 < nr_slots) {
642 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
643 		return -EINVAL;
644 	}
645 
646 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
647 		return -ERANGE;
648 	return spi;
649 }
650 
651 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
652 {
653 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
654 }
655 
656 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
657 {
658 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
659 }
660 
661 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
662 {
663 	return stack_slot_obj_get_spi(env, reg, "irq_flag", 1);
664 }
665 
666 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
667 {
668 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
669 	case DYNPTR_TYPE_LOCAL:
670 		return BPF_DYNPTR_TYPE_LOCAL;
671 	case DYNPTR_TYPE_RINGBUF:
672 		return BPF_DYNPTR_TYPE_RINGBUF;
673 	case DYNPTR_TYPE_SKB:
674 		return BPF_DYNPTR_TYPE_SKB;
675 	case DYNPTR_TYPE_XDP:
676 		return BPF_DYNPTR_TYPE_XDP;
677 	case DYNPTR_TYPE_SKB_META:
678 		return BPF_DYNPTR_TYPE_SKB_META;
679 	default:
680 		return BPF_DYNPTR_TYPE_INVALID;
681 	}
682 }
683 
684 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
685 {
686 	switch (type) {
687 	case BPF_DYNPTR_TYPE_LOCAL:
688 		return DYNPTR_TYPE_LOCAL;
689 	case BPF_DYNPTR_TYPE_RINGBUF:
690 		return DYNPTR_TYPE_RINGBUF;
691 	case BPF_DYNPTR_TYPE_SKB:
692 		return DYNPTR_TYPE_SKB;
693 	case BPF_DYNPTR_TYPE_XDP:
694 		return DYNPTR_TYPE_XDP;
695 	case BPF_DYNPTR_TYPE_SKB_META:
696 		return DYNPTR_TYPE_SKB_META;
697 	default:
698 		return 0;
699 	}
700 }
701 
702 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
703 {
704 	return type == BPF_DYNPTR_TYPE_RINGBUF;
705 }
706 
707 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
708 			      enum bpf_dynptr_type type,
709 			      bool first_slot, int dynptr_id);
710 
711 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
712 				struct bpf_reg_state *reg);
713 
714 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
715 				   struct bpf_reg_state *sreg1,
716 				   struct bpf_reg_state *sreg2,
717 				   enum bpf_dynptr_type type)
718 {
719 	int id = ++env->id_gen;
720 
721 	__mark_dynptr_reg(sreg1, type, true, id);
722 	__mark_dynptr_reg(sreg2, type, false, id);
723 }
724 
725 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
726 			       struct bpf_reg_state *reg,
727 			       enum bpf_dynptr_type type)
728 {
729 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
730 }
731 
732 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
733 				        struct bpf_func_state *state, int spi);
734 
735 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
736 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
737 {
738 	struct bpf_func_state *state = func(env, reg);
739 	enum bpf_dynptr_type type;
740 	int spi, i, err;
741 
742 	spi = dynptr_get_spi(env, reg);
743 	if (spi < 0)
744 		return spi;
745 
746 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
747 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
748 	 * to ensure that for the following example:
749 	 *	[d1][d1][d2][d2]
750 	 * spi    3   2   1   0
751 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
752 	 * case they do belong to same dynptr, second call won't see slot_type
753 	 * as STACK_DYNPTR and will simply skip destruction.
754 	 */
755 	err = destroy_if_dynptr_stack_slot(env, state, spi);
756 	if (err)
757 		return err;
758 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
759 	if (err)
760 		return err;
761 
762 	for (i = 0; i < BPF_REG_SIZE; i++) {
763 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
764 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
765 	}
766 
767 	type = arg_to_dynptr_type(arg_type);
768 	if (type == BPF_DYNPTR_TYPE_INVALID)
769 		return -EINVAL;
770 
771 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
772 			       &state->stack[spi - 1].spilled_ptr, type);
773 
774 	if (dynptr_type_refcounted(type)) {
775 		/* The id is used to track proper releasing */
776 		int id;
777 
778 		if (clone_ref_obj_id)
779 			id = clone_ref_obj_id;
780 		else
781 			id = acquire_reference(env, insn_idx);
782 
783 		if (id < 0)
784 			return id;
785 
786 		state->stack[spi].spilled_ptr.ref_obj_id = id;
787 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
788 	}
789 
790 	bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
791 
792 	return 0;
793 }
794 
795 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
796 {
797 	int i;
798 
799 	for (i = 0; i < BPF_REG_SIZE; i++) {
800 		state->stack[spi].slot_type[i] = STACK_INVALID;
801 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
802 	}
803 
804 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
805 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
806 
807 	bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
808 }
809 
810 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
811 {
812 	struct bpf_func_state *state = func(env, reg);
813 	int spi, ref_obj_id, i;
814 
815 	spi = dynptr_get_spi(env, reg);
816 	if (spi < 0)
817 		return spi;
818 
819 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
820 		invalidate_dynptr(env, state, spi);
821 		return 0;
822 	}
823 
824 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
825 
826 	/* If the dynptr has a ref_obj_id, then we need to invalidate
827 	 * two things:
828 	 *
829 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
830 	 * 2) Any slices derived from this dynptr.
831 	 */
832 
833 	/* Invalidate any slices associated with this dynptr */
834 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
835 
836 	/* Invalidate any dynptr clones */
837 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
838 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
839 			continue;
840 
841 		/* it should always be the case that if the ref obj id
842 		 * matches then the stack slot also belongs to a
843 		 * dynptr
844 		 */
845 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
846 			verifier_bug(env, "misconfigured ref_obj_id");
847 			return -EFAULT;
848 		}
849 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
850 			invalidate_dynptr(env, state, i);
851 	}
852 
853 	return 0;
854 }
855 
856 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
857 			       struct bpf_reg_state *reg);
858 
859 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
860 {
861 	if (!env->allow_ptr_leaks)
862 		__mark_reg_not_init(env, reg);
863 	else
864 		__mark_reg_unknown(env, reg);
865 }
866 
867 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
868 				        struct bpf_func_state *state, int spi)
869 {
870 	struct bpf_func_state *fstate;
871 	struct bpf_reg_state *dreg;
872 	int i, dynptr_id;
873 
874 	/* We always ensure that STACK_DYNPTR is never set partially,
875 	 * hence just checking for slot_type[0] is enough. This is
876 	 * different for STACK_SPILL, where it may be only set for
877 	 * 1 byte, so code has to use is_spilled_reg.
878 	 */
879 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
880 		return 0;
881 
882 	/* Reposition spi to first slot */
883 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
884 		spi = spi + 1;
885 
886 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
887 		verbose(env, "cannot overwrite referenced dynptr\n");
888 		return -EINVAL;
889 	}
890 
891 	mark_stack_slot_scratched(env, spi);
892 	mark_stack_slot_scratched(env, spi - 1);
893 
894 	/* Writing partially to one dynptr stack slot destroys both. */
895 	for (i = 0; i < BPF_REG_SIZE; i++) {
896 		state->stack[spi].slot_type[i] = STACK_INVALID;
897 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
898 	}
899 
900 	dynptr_id = state->stack[spi].spilled_ptr.id;
901 	/* Invalidate any slices associated with this dynptr */
902 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
903 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
904 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
905 			continue;
906 		if (dreg->dynptr_id == dynptr_id)
907 			mark_reg_invalid(env, dreg);
908 	}));
909 
910 	/* Do not release reference state, we are destroying dynptr on stack,
911 	 * not using some helper to release it. Just reset register.
912 	 */
913 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
914 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
915 
916 	bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
917 
918 	return 0;
919 }
920 
921 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
922 {
923 	int spi;
924 
925 	if (reg->type == CONST_PTR_TO_DYNPTR)
926 		return false;
927 
928 	spi = dynptr_get_spi(env, reg);
929 
930 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
931 	 * error because this just means the stack state hasn't been updated yet.
932 	 * We will do check_mem_access to check and update stack bounds later.
933 	 */
934 	if (spi < 0 && spi != -ERANGE)
935 		return false;
936 
937 	/* We don't need to check if the stack slots are marked by previous
938 	 * dynptr initializations because we allow overwriting existing unreferenced
939 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
940 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
941 	 * touching are completely destructed before we reinitialize them for a new
942 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
943 	 * instead of delaying it until the end where the user will get "Unreleased
944 	 * reference" error.
945 	 */
946 	return true;
947 }
948 
949 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
950 {
951 	struct bpf_func_state *state = func(env, reg);
952 	int i, spi;
953 
954 	/* This already represents first slot of initialized bpf_dynptr.
955 	 *
956 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
957 	 * check_func_arg_reg_off's logic, so we don't need to check its
958 	 * offset and alignment.
959 	 */
960 	if (reg->type == CONST_PTR_TO_DYNPTR)
961 		return true;
962 
963 	spi = dynptr_get_spi(env, reg);
964 	if (spi < 0)
965 		return false;
966 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
967 		return false;
968 
969 	for (i = 0; i < BPF_REG_SIZE; i++) {
970 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
971 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
972 			return false;
973 	}
974 
975 	return true;
976 }
977 
978 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
979 				    enum bpf_arg_type arg_type)
980 {
981 	struct bpf_func_state *state = func(env, reg);
982 	enum bpf_dynptr_type dynptr_type;
983 	int spi;
984 
985 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
986 	if (arg_type == ARG_PTR_TO_DYNPTR)
987 		return true;
988 
989 	dynptr_type = arg_to_dynptr_type(arg_type);
990 	if (reg->type == CONST_PTR_TO_DYNPTR) {
991 		return reg->dynptr.type == dynptr_type;
992 	} else {
993 		spi = dynptr_get_spi(env, reg);
994 		if (spi < 0)
995 			return false;
996 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
997 	}
998 }
999 
1000 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1001 
1002 static bool in_rcu_cs(struct bpf_verifier_env *env);
1003 
1004 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1005 
1006 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1007 				 struct bpf_kfunc_call_arg_meta *meta,
1008 				 struct bpf_reg_state *reg, int insn_idx,
1009 				 struct btf *btf, u32 btf_id, int nr_slots)
1010 {
1011 	struct bpf_func_state *state = func(env, reg);
1012 	int spi, i, j, id;
1013 
1014 	spi = iter_get_spi(env, reg, nr_slots);
1015 	if (spi < 0)
1016 		return spi;
1017 
1018 	id = acquire_reference(env, insn_idx);
1019 	if (id < 0)
1020 		return id;
1021 
1022 	for (i = 0; i < nr_slots; i++) {
1023 		struct bpf_stack_state *slot = &state->stack[spi - i];
1024 		struct bpf_reg_state *st = &slot->spilled_ptr;
1025 
1026 		__mark_reg_known_zero(st);
1027 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1028 		if (is_kfunc_rcu_protected(meta)) {
1029 			if (in_rcu_cs(env))
1030 				st->type |= MEM_RCU;
1031 			else
1032 				st->type |= PTR_UNTRUSTED;
1033 		}
1034 		st->ref_obj_id = i == 0 ? id : 0;
1035 		st->iter.btf = btf;
1036 		st->iter.btf_id = btf_id;
1037 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1038 		st->iter.depth = 0;
1039 
1040 		for (j = 0; j < BPF_REG_SIZE; j++)
1041 			slot->slot_type[j] = STACK_ITER;
1042 
1043 		bpf_mark_stack_write(env, state->frameno, BIT(spi - i));
1044 		mark_stack_slot_scratched(env, spi - i);
1045 	}
1046 
1047 	return 0;
1048 }
1049 
1050 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1051 				   struct bpf_reg_state *reg, int nr_slots)
1052 {
1053 	struct bpf_func_state *state = func(env, reg);
1054 	int spi, i, j;
1055 
1056 	spi = iter_get_spi(env, reg, nr_slots);
1057 	if (spi < 0)
1058 		return spi;
1059 
1060 	for (i = 0; i < nr_slots; i++) {
1061 		struct bpf_stack_state *slot = &state->stack[spi - i];
1062 		struct bpf_reg_state *st = &slot->spilled_ptr;
1063 
1064 		if (i == 0)
1065 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1066 
1067 		__mark_reg_not_init(env, st);
1068 
1069 		for (j = 0; j < BPF_REG_SIZE; j++)
1070 			slot->slot_type[j] = STACK_INVALID;
1071 
1072 		bpf_mark_stack_write(env, state->frameno, BIT(spi - i));
1073 		mark_stack_slot_scratched(env, spi - i);
1074 	}
1075 
1076 	return 0;
1077 }
1078 
1079 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1080 				     struct bpf_reg_state *reg, int nr_slots)
1081 {
1082 	struct bpf_func_state *state = func(env, reg);
1083 	int spi, i, j;
1084 
1085 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1086 	 * will do check_mem_access to check and update stack bounds later, so
1087 	 * return true for that case.
1088 	 */
1089 	spi = iter_get_spi(env, reg, nr_slots);
1090 	if (spi == -ERANGE)
1091 		return true;
1092 	if (spi < 0)
1093 		return false;
1094 
1095 	for (i = 0; i < nr_slots; i++) {
1096 		struct bpf_stack_state *slot = &state->stack[spi - i];
1097 
1098 		for (j = 0; j < BPF_REG_SIZE; j++)
1099 			if (slot->slot_type[j] == STACK_ITER)
1100 				return false;
1101 	}
1102 
1103 	return true;
1104 }
1105 
1106 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1107 				   struct btf *btf, u32 btf_id, int nr_slots)
1108 {
1109 	struct bpf_func_state *state = func(env, reg);
1110 	int spi, i, j;
1111 
1112 	spi = iter_get_spi(env, reg, nr_slots);
1113 	if (spi < 0)
1114 		return -EINVAL;
1115 
1116 	for (i = 0; i < nr_slots; i++) {
1117 		struct bpf_stack_state *slot = &state->stack[spi - i];
1118 		struct bpf_reg_state *st = &slot->spilled_ptr;
1119 
1120 		if (st->type & PTR_UNTRUSTED)
1121 			return -EPROTO;
1122 		/* only main (first) slot has ref_obj_id set */
1123 		if (i == 0 && !st->ref_obj_id)
1124 			return -EINVAL;
1125 		if (i != 0 && st->ref_obj_id)
1126 			return -EINVAL;
1127 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1128 			return -EINVAL;
1129 
1130 		for (j = 0; j < BPF_REG_SIZE; j++)
1131 			if (slot->slot_type[j] != STACK_ITER)
1132 				return -EINVAL;
1133 	}
1134 
1135 	return 0;
1136 }
1137 
1138 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
1139 static int release_irq_state(struct bpf_verifier_state *state, int id);
1140 
1141 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
1142 				     struct bpf_kfunc_call_arg_meta *meta,
1143 				     struct bpf_reg_state *reg, int insn_idx,
1144 				     int kfunc_class)
1145 {
1146 	struct bpf_func_state *state = func(env, reg);
1147 	struct bpf_stack_state *slot;
1148 	struct bpf_reg_state *st;
1149 	int spi, i, id;
1150 
1151 	spi = irq_flag_get_spi(env, reg);
1152 	if (spi < 0)
1153 		return spi;
1154 
1155 	id = acquire_irq_state(env, insn_idx);
1156 	if (id < 0)
1157 		return id;
1158 
1159 	slot = &state->stack[spi];
1160 	st = &slot->spilled_ptr;
1161 
1162 	bpf_mark_stack_write(env, reg->frameno, BIT(spi));
1163 	__mark_reg_known_zero(st);
1164 	st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1165 	st->ref_obj_id = id;
1166 	st->irq.kfunc_class = kfunc_class;
1167 
1168 	for (i = 0; i < BPF_REG_SIZE; i++)
1169 		slot->slot_type[i] = STACK_IRQ_FLAG;
1170 
1171 	mark_stack_slot_scratched(env, spi);
1172 	return 0;
1173 }
1174 
1175 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1176 				      int kfunc_class)
1177 {
1178 	struct bpf_func_state *state = func(env, reg);
1179 	struct bpf_stack_state *slot;
1180 	struct bpf_reg_state *st;
1181 	int spi, i, err;
1182 
1183 	spi = irq_flag_get_spi(env, reg);
1184 	if (spi < 0)
1185 		return spi;
1186 
1187 	slot = &state->stack[spi];
1188 	st = &slot->spilled_ptr;
1189 
1190 	if (st->irq.kfunc_class != kfunc_class) {
1191 		const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1192 		const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1193 
1194 		verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n",
1195 			flag_kfunc, used_kfunc);
1196 		return -EINVAL;
1197 	}
1198 
1199 	err = release_irq_state(env->cur_state, st->ref_obj_id);
1200 	WARN_ON_ONCE(err && err != -EACCES);
1201 	if (err) {
1202 		int insn_idx = 0;
1203 
1204 		for (int i = 0; i < env->cur_state->acquired_refs; i++) {
1205 			if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) {
1206 				insn_idx = env->cur_state->refs[i].insn_idx;
1207 				break;
1208 			}
1209 		}
1210 
1211 		verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n",
1212 			env->cur_state->active_irq_id, insn_idx);
1213 		return err;
1214 	}
1215 
1216 	__mark_reg_not_init(env, st);
1217 
1218 	bpf_mark_stack_write(env, reg->frameno, BIT(spi));
1219 
1220 	for (i = 0; i < BPF_REG_SIZE; i++)
1221 		slot->slot_type[i] = STACK_INVALID;
1222 
1223 	mark_stack_slot_scratched(env, spi);
1224 	return 0;
1225 }
1226 
1227 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1228 {
1229 	struct bpf_func_state *state = func(env, reg);
1230 	struct bpf_stack_state *slot;
1231 	int spi, i;
1232 
1233 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1234 	 * will do check_mem_access to check and update stack bounds later, so
1235 	 * return true for that case.
1236 	 */
1237 	spi = irq_flag_get_spi(env, reg);
1238 	if (spi == -ERANGE)
1239 		return true;
1240 	if (spi < 0)
1241 		return false;
1242 
1243 	slot = &state->stack[spi];
1244 
1245 	for (i = 0; i < BPF_REG_SIZE; i++)
1246 		if (slot->slot_type[i] == STACK_IRQ_FLAG)
1247 			return false;
1248 	return true;
1249 }
1250 
1251 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1252 {
1253 	struct bpf_func_state *state = func(env, reg);
1254 	struct bpf_stack_state *slot;
1255 	struct bpf_reg_state *st;
1256 	int spi, i;
1257 
1258 	spi = irq_flag_get_spi(env, reg);
1259 	if (spi < 0)
1260 		return -EINVAL;
1261 
1262 	slot = &state->stack[spi];
1263 	st = &slot->spilled_ptr;
1264 
1265 	if (!st->ref_obj_id)
1266 		return -EINVAL;
1267 
1268 	for (i = 0; i < BPF_REG_SIZE; i++)
1269 		if (slot->slot_type[i] != STACK_IRQ_FLAG)
1270 			return -EINVAL;
1271 	return 0;
1272 }
1273 
1274 /* Check if given stack slot is "special":
1275  *   - spilled register state (STACK_SPILL);
1276  *   - dynptr state (STACK_DYNPTR);
1277  *   - iter state (STACK_ITER).
1278  *   - irq flag state (STACK_IRQ_FLAG)
1279  */
1280 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1281 {
1282 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1283 
1284 	switch (type) {
1285 	case STACK_SPILL:
1286 	case STACK_DYNPTR:
1287 	case STACK_ITER:
1288 	case STACK_IRQ_FLAG:
1289 		return true;
1290 	case STACK_INVALID:
1291 	case STACK_MISC:
1292 	case STACK_ZERO:
1293 		return false;
1294 	default:
1295 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1296 		return true;
1297 	}
1298 }
1299 
1300 /* The reg state of a pointer or a bounded scalar was saved when
1301  * it was spilled to the stack.
1302  */
1303 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1304 {
1305 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1306 }
1307 
1308 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1309 {
1310 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1311 	       stack->spilled_ptr.type == SCALAR_VALUE;
1312 }
1313 
1314 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1315 {
1316 	return stack->slot_type[0] == STACK_SPILL &&
1317 	       stack->spilled_ptr.type == SCALAR_VALUE;
1318 }
1319 
1320 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1321  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1322  * more precise STACK_ZERO.
1323  * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1324  * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1325  * unnecessary as both are considered equivalent when loading data and pruning,
1326  * in case of unprivileged mode it will be incorrect to allow reads of invalid
1327  * slots.
1328  */
1329 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1330 {
1331 	if (*stype == STACK_ZERO)
1332 		return;
1333 	if (*stype == STACK_INVALID)
1334 		return;
1335 	*stype = STACK_MISC;
1336 }
1337 
1338 static void scrub_spilled_slot(u8 *stype)
1339 {
1340 	if (*stype != STACK_INVALID)
1341 		*stype = STACK_MISC;
1342 }
1343 
1344 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1345  * small to hold src. This is different from krealloc since we don't want to preserve
1346  * the contents of dst.
1347  *
1348  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1349  * not be allocated.
1350  */
1351 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1352 {
1353 	size_t alloc_bytes;
1354 	void *orig = dst;
1355 	size_t bytes;
1356 
1357 	if (ZERO_OR_NULL_PTR(src))
1358 		goto out;
1359 
1360 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1361 		return NULL;
1362 
1363 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1364 	dst = krealloc(orig, alloc_bytes, flags);
1365 	if (!dst) {
1366 		kfree(orig);
1367 		return NULL;
1368 	}
1369 
1370 	memcpy(dst, src, bytes);
1371 out:
1372 	return dst ? dst : ZERO_SIZE_PTR;
1373 }
1374 
1375 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1376  * small to hold new_n items. new items are zeroed out if the array grows.
1377  *
1378  * Contrary to krealloc_array, does not free arr if new_n is zero.
1379  */
1380 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1381 {
1382 	size_t alloc_size;
1383 	void *new_arr;
1384 
1385 	if (!new_n || old_n == new_n)
1386 		goto out;
1387 
1388 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1389 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT);
1390 	if (!new_arr) {
1391 		kfree(arr);
1392 		return NULL;
1393 	}
1394 	arr = new_arr;
1395 
1396 	if (new_n > old_n)
1397 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1398 
1399 out:
1400 	return arr ? arr : ZERO_SIZE_PTR;
1401 }
1402 
1403 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
1404 {
1405 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1406 			       sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT);
1407 	if (!dst->refs)
1408 		return -ENOMEM;
1409 
1410 	dst->acquired_refs = src->acquired_refs;
1411 	dst->active_locks = src->active_locks;
1412 	dst->active_preempt_locks = src->active_preempt_locks;
1413 	dst->active_rcu_lock = src->active_rcu_lock;
1414 	dst->active_irq_id = src->active_irq_id;
1415 	dst->active_lock_id = src->active_lock_id;
1416 	dst->active_lock_ptr = src->active_lock_ptr;
1417 	return 0;
1418 }
1419 
1420 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1421 {
1422 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1423 
1424 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1425 				GFP_KERNEL_ACCOUNT);
1426 	if (!dst->stack)
1427 		return -ENOMEM;
1428 
1429 	dst->allocated_stack = src->allocated_stack;
1430 	return 0;
1431 }
1432 
1433 static int resize_reference_state(struct bpf_verifier_state *state, size_t n)
1434 {
1435 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1436 				    sizeof(struct bpf_reference_state));
1437 	if (!state->refs)
1438 		return -ENOMEM;
1439 
1440 	state->acquired_refs = n;
1441 	return 0;
1442 }
1443 
1444 /* Possibly update state->allocated_stack to be at least size bytes. Also
1445  * possibly update the function's high-water mark in its bpf_subprog_info.
1446  */
1447 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1448 {
1449 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1450 
1451 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1452 	size = round_up(size, BPF_REG_SIZE);
1453 	n = size / BPF_REG_SIZE;
1454 
1455 	if (old_n >= n)
1456 		return 0;
1457 
1458 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1459 	if (!state->stack)
1460 		return -ENOMEM;
1461 
1462 	state->allocated_stack = size;
1463 
1464 	/* update known max for given subprogram */
1465 	if (env->subprog_info[state->subprogno].stack_depth < size)
1466 		env->subprog_info[state->subprogno].stack_depth = size;
1467 
1468 	return 0;
1469 }
1470 
1471 /* Acquire a pointer id from the env and update the state->refs to include
1472  * this new pointer reference.
1473  * On success, returns a valid pointer id to associate with the register
1474  * On failure, returns a negative errno.
1475  */
1476 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1477 {
1478 	struct bpf_verifier_state *state = env->cur_state;
1479 	int new_ofs = state->acquired_refs;
1480 	int err;
1481 
1482 	err = resize_reference_state(state, state->acquired_refs + 1);
1483 	if (err)
1484 		return NULL;
1485 	state->refs[new_ofs].insn_idx = insn_idx;
1486 
1487 	return &state->refs[new_ofs];
1488 }
1489 
1490 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx)
1491 {
1492 	struct bpf_reference_state *s;
1493 
1494 	s = acquire_reference_state(env, insn_idx);
1495 	if (!s)
1496 		return -ENOMEM;
1497 	s->type = REF_TYPE_PTR;
1498 	s->id = ++env->id_gen;
1499 	return s->id;
1500 }
1501 
1502 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1503 			      int id, void *ptr)
1504 {
1505 	struct bpf_verifier_state *state = env->cur_state;
1506 	struct bpf_reference_state *s;
1507 
1508 	s = acquire_reference_state(env, insn_idx);
1509 	if (!s)
1510 		return -ENOMEM;
1511 	s->type = type;
1512 	s->id = id;
1513 	s->ptr = ptr;
1514 
1515 	state->active_locks++;
1516 	state->active_lock_id = id;
1517 	state->active_lock_ptr = ptr;
1518 	return 0;
1519 }
1520 
1521 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
1522 {
1523 	struct bpf_verifier_state *state = env->cur_state;
1524 	struct bpf_reference_state *s;
1525 
1526 	s = acquire_reference_state(env, insn_idx);
1527 	if (!s)
1528 		return -ENOMEM;
1529 	s->type = REF_TYPE_IRQ;
1530 	s->id = ++env->id_gen;
1531 
1532 	state->active_irq_id = s->id;
1533 	return s->id;
1534 }
1535 
1536 static void release_reference_state(struct bpf_verifier_state *state, int idx)
1537 {
1538 	int last_idx;
1539 	size_t rem;
1540 
1541 	/* IRQ state requires the relative ordering of elements remaining the
1542 	 * same, since it relies on the refs array to behave as a stack, so that
1543 	 * it can detect out-of-order IRQ restore. Hence use memmove to shift
1544 	 * the array instead of swapping the final element into the deleted idx.
1545 	 */
1546 	last_idx = state->acquired_refs - 1;
1547 	rem = state->acquired_refs - idx - 1;
1548 	if (last_idx && idx != last_idx)
1549 		memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem);
1550 	memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1551 	state->acquired_refs--;
1552 	return;
1553 }
1554 
1555 static bool find_reference_state(struct bpf_verifier_state *state, int ptr_id)
1556 {
1557 	int i;
1558 
1559 	for (i = 0; i < state->acquired_refs; i++)
1560 		if (state->refs[i].id == ptr_id)
1561 			return true;
1562 
1563 	return false;
1564 }
1565 
1566 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr)
1567 {
1568 	void *prev_ptr = NULL;
1569 	u32 prev_id = 0;
1570 	int i;
1571 
1572 	for (i = 0; i < state->acquired_refs; i++) {
1573 		if (state->refs[i].type == type && state->refs[i].id == id &&
1574 		    state->refs[i].ptr == ptr) {
1575 			release_reference_state(state, i);
1576 			state->active_locks--;
1577 			/* Reassign active lock (id, ptr). */
1578 			state->active_lock_id = prev_id;
1579 			state->active_lock_ptr = prev_ptr;
1580 			return 0;
1581 		}
1582 		if (state->refs[i].type & REF_TYPE_LOCK_MASK) {
1583 			prev_id = state->refs[i].id;
1584 			prev_ptr = state->refs[i].ptr;
1585 		}
1586 	}
1587 	return -EINVAL;
1588 }
1589 
1590 static int release_irq_state(struct bpf_verifier_state *state, int id)
1591 {
1592 	u32 prev_id = 0;
1593 	int i;
1594 
1595 	if (id != state->active_irq_id)
1596 		return -EACCES;
1597 
1598 	for (i = 0; i < state->acquired_refs; i++) {
1599 		if (state->refs[i].type != REF_TYPE_IRQ)
1600 			continue;
1601 		if (state->refs[i].id == id) {
1602 			release_reference_state(state, i);
1603 			state->active_irq_id = prev_id;
1604 			return 0;
1605 		} else {
1606 			prev_id = state->refs[i].id;
1607 		}
1608 	}
1609 	return -EINVAL;
1610 }
1611 
1612 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,
1613 						   int id, void *ptr)
1614 {
1615 	int i;
1616 
1617 	for (i = 0; i < state->acquired_refs; i++) {
1618 		struct bpf_reference_state *s = &state->refs[i];
1619 
1620 		if (!(s->type & type))
1621 			continue;
1622 
1623 		if (s->id == id && s->ptr == ptr)
1624 			return s;
1625 	}
1626 	return NULL;
1627 }
1628 
1629 static void update_peak_states(struct bpf_verifier_env *env)
1630 {
1631 	u32 cur_states;
1632 
1633 	cur_states = env->explored_states_size + env->free_list_size + env->num_backedges;
1634 	env->peak_states = max(env->peak_states, cur_states);
1635 }
1636 
1637 static void free_func_state(struct bpf_func_state *state)
1638 {
1639 	if (!state)
1640 		return;
1641 	kfree(state->stack);
1642 	kfree(state);
1643 }
1644 
1645 static void clear_jmp_history(struct bpf_verifier_state *state)
1646 {
1647 	kfree(state->jmp_history);
1648 	state->jmp_history = NULL;
1649 	state->jmp_history_cnt = 0;
1650 }
1651 
1652 static void free_verifier_state(struct bpf_verifier_state *state,
1653 				bool free_self)
1654 {
1655 	int i;
1656 
1657 	for (i = 0; i <= state->curframe; i++) {
1658 		free_func_state(state->frame[i]);
1659 		state->frame[i] = NULL;
1660 	}
1661 	kfree(state->refs);
1662 	clear_jmp_history(state);
1663 	if (free_self)
1664 		kfree(state);
1665 }
1666 
1667 /* struct bpf_verifier_state->parent refers to states
1668  * that are in either of env->{expored_states,free_list}.
1669  * In both cases the state is contained in struct bpf_verifier_state_list.
1670  */
1671 static struct bpf_verifier_state_list *state_parent_as_list(struct bpf_verifier_state *st)
1672 {
1673 	if (st->parent)
1674 		return container_of(st->parent, struct bpf_verifier_state_list, state);
1675 	return NULL;
1676 }
1677 
1678 static bool incomplete_read_marks(struct bpf_verifier_env *env,
1679 				  struct bpf_verifier_state *st);
1680 
1681 /* A state can be freed if it is no longer referenced:
1682  * - is in the env->free_list;
1683  * - has no children states;
1684  */
1685 static void maybe_free_verifier_state(struct bpf_verifier_env *env,
1686 				      struct bpf_verifier_state_list *sl)
1687 {
1688 	if (!sl->in_free_list
1689 	    || sl->state.branches != 0
1690 	    || incomplete_read_marks(env, &sl->state))
1691 		return;
1692 	list_del(&sl->node);
1693 	free_verifier_state(&sl->state, false);
1694 	kfree(sl);
1695 	env->free_list_size--;
1696 }
1697 
1698 /* copy verifier state from src to dst growing dst stack space
1699  * when necessary to accommodate larger src stack
1700  */
1701 static int copy_func_state(struct bpf_func_state *dst,
1702 			   const struct bpf_func_state *src)
1703 {
1704 	memcpy(dst, src, offsetof(struct bpf_func_state, stack));
1705 	return copy_stack_state(dst, src);
1706 }
1707 
1708 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1709 			       const struct bpf_verifier_state *src)
1710 {
1711 	struct bpf_func_state *dst;
1712 	int i, err;
1713 
1714 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1715 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1716 					  GFP_KERNEL_ACCOUNT);
1717 	if (!dst_state->jmp_history)
1718 		return -ENOMEM;
1719 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1720 
1721 	/* if dst has more stack frames then src frame, free them, this is also
1722 	 * necessary in case of exceptional exits using bpf_throw.
1723 	 */
1724 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1725 		free_func_state(dst_state->frame[i]);
1726 		dst_state->frame[i] = NULL;
1727 	}
1728 	err = copy_reference_state(dst_state, src);
1729 	if (err)
1730 		return err;
1731 	dst_state->speculative = src->speculative;
1732 	dst_state->in_sleepable = src->in_sleepable;
1733 	dst_state->cleaned = src->cleaned;
1734 	dst_state->curframe = src->curframe;
1735 	dst_state->branches = src->branches;
1736 	dst_state->parent = src->parent;
1737 	dst_state->first_insn_idx = src->first_insn_idx;
1738 	dst_state->last_insn_idx = src->last_insn_idx;
1739 	dst_state->dfs_depth = src->dfs_depth;
1740 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1741 	dst_state->may_goto_depth = src->may_goto_depth;
1742 	dst_state->equal_state = src->equal_state;
1743 	for (i = 0; i <= src->curframe; i++) {
1744 		dst = dst_state->frame[i];
1745 		if (!dst) {
1746 			dst = kzalloc(sizeof(*dst), GFP_KERNEL_ACCOUNT);
1747 			if (!dst)
1748 				return -ENOMEM;
1749 			dst_state->frame[i] = dst;
1750 		}
1751 		err = copy_func_state(dst, src->frame[i]);
1752 		if (err)
1753 			return err;
1754 	}
1755 	return 0;
1756 }
1757 
1758 static u32 state_htab_size(struct bpf_verifier_env *env)
1759 {
1760 	return env->prog->len;
1761 }
1762 
1763 static struct list_head *explored_state(struct bpf_verifier_env *env, int idx)
1764 {
1765 	struct bpf_verifier_state *cur = env->cur_state;
1766 	struct bpf_func_state *state = cur->frame[cur->curframe];
1767 
1768 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1769 }
1770 
1771 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1772 {
1773 	int fr;
1774 
1775 	if (a->curframe != b->curframe)
1776 		return false;
1777 
1778 	for (fr = a->curframe; fr >= 0; fr--)
1779 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1780 			return false;
1781 
1782 	return true;
1783 }
1784 
1785 /* Return IP for a given frame in a call stack */
1786 static u32 frame_insn_idx(struct bpf_verifier_state *st, u32 frame)
1787 {
1788 	return frame == st->curframe
1789 	       ? st->insn_idx
1790 	       : st->frame[frame + 1]->callsite;
1791 }
1792 
1793 /* For state @st look for a topmost frame with frame_insn_idx() in some SCC,
1794  * if such frame exists form a corresponding @callchain as an array of
1795  * call sites leading to this frame and SCC id.
1796  * E.g.:
1797  *
1798  *    void foo()  { A: loop {... SCC#1 ...}; }
1799  *    void bar()  { B: loop { C: foo(); ... SCC#2 ... }
1800  *                  D: loop { E: foo(); ... SCC#3 ... } }
1801  *    void main() { F: bar(); }
1802  *
1803  * @callchain at (A) would be either (F,SCC#2) or (F,SCC#3) depending
1804  * on @st frame call sites being (F,C,A) or (F,E,A).
1805  */
1806 static bool compute_scc_callchain(struct bpf_verifier_env *env,
1807 				  struct bpf_verifier_state *st,
1808 				  struct bpf_scc_callchain *callchain)
1809 {
1810 	u32 i, scc, insn_idx;
1811 
1812 	memset(callchain, 0, sizeof(*callchain));
1813 	for (i = 0; i <= st->curframe; i++) {
1814 		insn_idx = frame_insn_idx(st, i);
1815 		scc = env->insn_aux_data[insn_idx].scc;
1816 		if (scc) {
1817 			callchain->scc = scc;
1818 			break;
1819 		} else if (i < st->curframe) {
1820 			callchain->callsites[i] = insn_idx;
1821 		} else {
1822 			return false;
1823 		}
1824 	}
1825 	return true;
1826 }
1827 
1828 /* Check if bpf_scc_visit instance for @callchain exists. */
1829 static struct bpf_scc_visit *scc_visit_lookup(struct bpf_verifier_env *env,
1830 					      struct bpf_scc_callchain *callchain)
1831 {
1832 	struct bpf_scc_info *info = env->scc_info[callchain->scc];
1833 	struct bpf_scc_visit *visits = info->visits;
1834 	u32 i;
1835 
1836 	if (!info)
1837 		return NULL;
1838 	for (i = 0; i < info->num_visits; i++)
1839 		if (memcmp(callchain, &visits[i].callchain, sizeof(*callchain)) == 0)
1840 			return &visits[i];
1841 	return NULL;
1842 }
1843 
1844 /* Allocate a new bpf_scc_visit instance corresponding to @callchain.
1845  * Allocated instances are alive for a duration of the do_check_common()
1846  * call and are freed by free_states().
1847  */
1848 static struct bpf_scc_visit *scc_visit_alloc(struct bpf_verifier_env *env,
1849 					     struct bpf_scc_callchain *callchain)
1850 {
1851 	struct bpf_scc_visit *visit;
1852 	struct bpf_scc_info *info;
1853 	u32 scc, num_visits;
1854 	u64 new_sz;
1855 
1856 	scc = callchain->scc;
1857 	info = env->scc_info[scc];
1858 	num_visits = info ? info->num_visits : 0;
1859 	new_sz = sizeof(*info) + sizeof(struct bpf_scc_visit) * (num_visits + 1);
1860 	info = kvrealloc(env->scc_info[scc], new_sz, GFP_KERNEL_ACCOUNT);
1861 	if (!info)
1862 		return NULL;
1863 	env->scc_info[scc] = info;
1864 	info->num_visits = num_visits + 1;
1865 	visit = &info->visits[num_visits];
1866 	memset(visit, 0, sizeof(*visit));
1867 	memcpy(&visit->callchain, callchain, sizeof(*callchain));
1868 	return visit;
1869 }
1870 
1871 /* Form a string '(callsite#1,callsite#2,...,scc)' in env->tmp_str_buf */
1872 static char *format_callchain(struct bpf_verifier_env *env, struct bpf_scc_callchain *callchain)
1873 {
1874 	char *buf = env->tmp_str_buf;
1875 	int i, delta = 0;
1876 
1877 	delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "(");
1878 	for (i = 0; i < ARRAY_SIZE(callchain->callsites); i++) {
1879 		if (!callchain->callsites[i])
1880 			break;
1881 		delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u,",
1882 				  callchain->callsites[i]);
1883 	}
1884 	delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u)", callchain->scc);
1885 	return env->tmp_str_buf;
1886 }
1887 
1888 /* If callchain for @st exists (@st is in some SCC), ensure that
1889  * bpf_scc_visit instance for this callchain exists.
1890  * If instance does not exist or is empty, assign visit->entry_state to @st.
1891  */
1892 static int maybe_enter_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1893 {
1894 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1895 	struct bpf_scc_visit *visit;
1896 
1897 	if (!compute_scc_callchain(env, st, callchain))
1898 		return 0;
1899 	visit = scc_visit_lookup(env, callchain);
1900 	visit = visit ?: scc_visit_alloc(env, callchain);
1901 	if (!visit)
1902 		return -ENOMEM;
1903 	if (!visit->entry_state) {
1904 		visit->entry_state = st;
1905 		if (env->log.level & BPF_LOG_LEVEL2)
1906 			verbose(env, "SCC enter %s\n", format_callchain(env, callchain));
1907 	}
1908 	return 0;
1909 }
1910 
1911 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit);
1912 
1913 /* If callchain for @st exists (@st is in some SCC), make it empty:
1914  * - set visit->entry_state to NULL;
1915  * - flush accumulated backedges.
1916  */
1917 static int maybe_exit_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1918 {
1919 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1920 	struct bpf_scc_visit *visit;
1921 
1922 	if (!compute_scc_callchain(env, st, callchain))
1923 		return 0;
1924 	visit = scc_visit_lookup(env, callchain);
1925 	if (!visit) {
1926 		/*
1927 		 * If path traversal stops inside an SCC, corresponding bpf_scc_visit
1928 		 * must exist for non-speculative paths. For non-speculative paths
1929 		 * traversal stops when:
1930 		 * a. Verification error is found, maybe_exit_scc() is not called.
1931 		 * b. Top level BPF_EXIT is reached. Top level BPF_EXIT is not a member
1932 		 *    of any SCC.
1933 		 * c. A checkpoint is reached and matched. Checkpoints are created by
1934 		 *    is_state_visited(), which calls maybe_enter_scc(), which allocates
1935 		 *    bpf_scc_visit instances for checkpoints within SCCs.
1936 		 * (c) is the only case that can reach this point.
1937 		 */
1938 		if (!st->speculative) {
1939 			verifier_bug(env, "scc exit: no visit info for call chain %s",
1940 				     format_callchain(env, callchain));
1941 			return -EFAULT;
1942 		}
1943 		return 0;
1944 	}
1945 	if (visit->entry_state != st)
1946 		return 0;
1947 	if (env->log.level & BPF_LOG_LEVEL2)
1948 		verbose(env, "SCC exit %s\n", format_callchain(env, callchain));
1949 	visit->entry_state = NULL;
1950 	env->num_backedges -= visit->num_backedges;
1951 	visit->num_backedges = 0;
1952 	update_peak_states(env);
1953 	return propagate_backedges(env, visit);
1954 }
1955 
1956 /* Lookup an bpf_scc_visit instance corresponding to @st callchain
1957  * and add @backedge to visit->backedges. @st callchain must exist.
1958  */
1959 static int add_scc_backedge(struct bpf_verifier_env *env,
1960 			    struct bpf_verifier_state *st,
1961 			    struct bpf_scc_backedge *backedge)
1962 {
1963 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1964 	struct bpf_scc_visit *visit;
1965 
1966 	if (!compute_scc_callchain(env, st, callchain)) {
1967 		verifier_bug(env, "add backedge: no SCC in verification path, insn_idx %d",
1968 			     st->insn_idx);
1969 		return -EFAULT;
1970 	}
1971 	visit = scc_visit_lookup(env, callchain);
1972 	if (!visit) {
1973 		verifier_bug(env, "add backedge: no visit info for call chain %s",
1974 			     format_callchain(env, callchain));
1975 		return -EFAULT;
1976 	}
1977 	if (env->log.level & BPF_LOG_LEVEL2)
1978 		verbose(env, "SCC backedge %s\n", format_callchain(env, callchain));
1979 	backedge->next = visit->backedges;
1980 	visit->backedges = backedge;
1981 	visit->num_backedges++;
1982 	env->num_backedges++;
1983 	update_peak_states(env);
1984 	return 0;
1985 }
1986 
1987 /* bpf_reg_state->live marks for registers in a state @st are incomplete,
1988  * if state @st is in some SCC and not all execution paths starting at this
1989  * SCC are fully explored.
1990  */
1991 static bool incomplete_read_marks(struct bpf_verifier_env *env,
1992 				  struct bpf_verifier_state *st)
1993 {
1994 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1995 	struct bpf_scc_visit *visit;
1996 
1997 	if (!compute_scc_callchain(env, st, callchain))
1998 		return false;
1999 	visit = scc_visit_lookup(env, callchain);
2000 	if (!visit)
2001 		return false;
2002 	return !!visit->backedges;
2003 }
2004 
2005 static void free_backedges(struct bpf_scc_visit *visit)
2006 {
2007 	struct bpf_scc_backedge *backedge, *next;
2008 
2009 	for (backedge = visit->backedges; backedge; backedge = next) {
2010 		free_verifier_state(&backedge->state, false);
2011 		next = backedge->next;
2012 		kfree(backedge);
2013 	}
2014 	visit->backedges = NULL;
2015 }
2016 
2017 static int update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2018 {
2019 	struct bpf_verifier_state_list *sl = NULL, *parent_sl;
2020 	struct bpf_verifier_state *parent;
2021 	int err;
2022 
2023 	while (st) {
2024 		u32 br = --st->branches;
2025 
2026 		/* verifier_bug_if(br > 1, ...) technically makes sense here,
2027 		 * but see comment in push_stack(), hence:
2028 		 */
2029 		verifier_bug_if((int)br < 0, env, "%s:branches_to_explore=%d", __func__, br);
2030 		if (br)
2031 			break;
2032 		err = maybe_exit_scc(env, st);
2033 		if (err)
2034 			return err;
2035 		parent = st->parent;
2036 		parent_sl = state_parent_as_list(st);
2037 		if (sl)
2038 			maybe_free_verifier_state(env, sl);
2039 		st = parent;
2040 		sl = parent_sl;
2041 	}
2042 	return 0;
2043 }
2044 
2045 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2046 		     int *insn_idx, bool pop_log)
2047 {
2048 	struct bpf_verifier_state *cur = env->cur_state;
2049 	struct bpf_verifier_stack_elem *elem, *head = env->head;
2050 	int err;
2051 
2052 	if (env->head == NULL)
2053 		return -ENOENT;
2054 
2055 	if (cur) {
2056 		err = copy_verifier_state(cur, &head->st);
2057 		if (err)
2058 			return err;
2059 	}
2060 	if (pop_log)
2061 		bpf_vlog_reset(&env->log, head->log_pos);
2062 	if (insn_idx)
2063 		*insn_idx = head->insn_idx;
2064 	if (prev_insn_idx)
2065 		*prev_insn_idx = head->prev_insn_idx;
2066 	elem = head->next;
2067 	free_verifier_state(&head->st, false);
2068 	kfree(head);
2069 	env->head = elem;
2070 	env->stack_size--;
2071 	return 0;
2072 }
2073 
2074 static bool error_recoverable_with_nospec(int err)
2075 {
2076 	/* Should only return true for non-fatal errors that are allowed to
2077 	 * occur during speculative verification. For these we can insert a
2078 	 * nospec and the program might still be accepted. Do not include
2079 	 * something like ENOMEM because it is likely to re-occur for the next
2080 	 * architectural path once it has been recovered-from in all speculative
2081 	 * paths.
2082 	 */
2083 	return err == -EPERM || err == -EACCES || err == -EINVAL;
2084 }
2085 
2086 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2087 					     int insn_idx, int prev_insn_idx,
2088 					     bool speculative)
2089 {
2090 	struct bpf_verifier_state *cur = env->cur_state;
2091 	struct bpf_verifier_stack_elem *elem;
2092 	int err;
2093 
2094 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
2095 	if (!elem)
2096 		return NULL;
2097 
2098 	elem->insn_idx = insn_idx;
2099 	elem->prev_insn_idx = prev_insn_idx;
2100 	elem->next = env->head;
2101 	elem->log_pos = env->log.end_pos;
2102 	env->head = elem;
2103 	env->stack_size++;
2104 	err = copy_verifier_state(&elem->st, cur);
2105 	if (err)
2106 		return NULL;
2107 	elem->st.speculative |= speculative;
2108 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2109 		verbose(env, "The sequence of %d jumps is too complex.\n",
2110 			env->stack_size);
2111 		return NULL;
2112 	}
2113 	if (elem->st.parent) {
2114 		++elem->st.parent->branches;
2115 		/* WARN_ON(branches > 2) technically makes sense here,
2116 		 * but
2117 		 * 1. speculative states will bump 'branches' for non-branch
2118 		 * instructions
2119 		 * 2. is_state_visited() heuristics may decide not to create
2120 		 * a new state for a sequence of branches and all such current
2121 		 * and cloned states will be pointing to a single parent state
2122 		 * which might have large 'branches' count.
2123 		 */
2124 	}
2125 	return &elem->st;
2126 }
2127 
2128 #define CALLER_SAVED_REGS 6
2129 static const int caller_saved[CALLER_SAVED_REGS] = {
2130 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2131 };
2132 
2133 /* This helper doesn't clear reg->id */
2134 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2135 {
2136 	reg->var_off = tnum_const(imm);
2137 	reg->smin_value = (s64)imm;
2138 	reg->smax_value = (s64)imm;
2139 	reg->umin_value = imm;
2140 	reg->umax_value = imm;
2141 
2142 	reg->s32_min_value = (s32)imm;
2143 	reg->s32_max_value = (s32)imm;
2144 	reg->u32_min_value = (u32)imm;
2145 	reg->u32_max_value = (u32)imm;
2146 }
2147 
2148 /* Mark the unknown part of a register (variable offset or scalar value) as
2149  * known to have the value @imm.
2150  */
2151 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2152 {
2153 	/* Clear off and union(map_ptr, range) */
2154 	memset(((u8 *)reg) + sizeof(reg->type), 0,
2155 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2156 	reg->id = 0;
2157 	reg->ref_obj_id = 0;
2158 	___mark_reg_known(reg, imm);
2159 }
2160 
2161 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2162 {
2163 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2164 	reg->s32_min_value = (s32)imm;
2165 	reg->s32_max_value = (s32)imm;
2166 	reg->u32_min_value = (u32)imm;
2167 	reg->u32_max_value = (u32)imm;
2168 }
2169 
2170 /* Mark the 'variable offset' part of a register as zero.  This should be
2171  * used only on registers holding a pointer type.
2172  */
2173 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2174 {
2175 	__mark_reg_known(reg, 0);
2176 }
2177 
2178 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2179 {
2180 	__mark_reg_known(reg, 0);
2181 	reg->type = SCALAR_VALUE;
2182 	/* all scalars are assumed imprecise initially (unless unprivileged,
2183 	 * in which case everything is forced to be precise)
2184 	 */
2185 	reg->precise = !env->bpf_capable;
2186 }
2187 
2188 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2189 				struct bpf_reg_state *regs, u32 regno)
2190 {
2191 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2192 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2193 		/* Something bad happened, let's kill all regs */
2194 		for (regno = 0; regno < MAX_BPF_REG; regno++)
2195 			__mark_reg_not_init(env, regs + regno);
2196 		return;
2197 	}
2198 	__mark_reg_known_zero(regs + regno);
2199 }
2200 
2201 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2202 			      bool first_slot, int dynptr_id)
2203 {
2204 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2205 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2206 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2207 	 */
2208 	__mark_reg_known_zero(reg);
2209 	reg->type = CONST_PTR_TO_DYNPTR;
2210 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2211 	reg->id = dynptr_id;
2212 	reg->dynptr.type = type;
2213 	reg->dynptr.first_slot = first_slot;
2214 }
2215 
2216 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2217 {
2218 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2219 		const struct bpf_map *map = reg->map_ptr;
2220 
2221 		if (map->inner_map_meta) {
2222 			reg->type = CONST_PTR_TO_MAP;
2223 			reg->map_ptr = map->inner_map_meta;
2224 			/* transfer reg's id which is unique for every map_lookup_elem
2225 			 * as UID of the inner map.
2226 			 */
2227 			if (btf_record_has_field(map->inner_map_meta->record,
2228 						 BPF_TIMER | BPF_WORKQUEUE | BPF_TASK_WORK)) {
2229 				reg->map_uid = reg->id;
2230 			}
2231 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2232 			reg->type = PTR_TO_XDP_SOCK;
2233 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2234 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2235 			reg->type = PTR_TO_SOCKET;
2236 		} else {
2237 			reg->type = PTR_TO_MAP_VALUE;
2238 		}
2239 		return;
2240 	}
2241 
2242 	reg->type &= ~PTR_MAYBE_NULL;
2243 }
2244 
2245 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2246 				struct btf_field_graph_root *ds_head)
2247 {
2248 	__mark_reg_known_zero(&regs[regno]);
2249 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2250 	regs[regno].btf = ds_head->btf;
2251 	regs[regno].btf_id = ds_head->value_btf_id;
2252 	regs[regno].off = ds_head->node_offset;
2253 }
2254 
2255 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2256 {
2257 	return type_is_pkt_pointer(reg->type);
2258 }
2259 
2260 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2261 {
2262 	return reg_is_pkt_pointer(reg) ||
2263 	       reg->type == PTR_TO_PACKET_END;
2264 }
2265 
2266 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2267 {
2268 	return base_type(reg->type) == PTR_TO_MEM &&
2269 	       (reg->type &
2270 		(DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META));
2271 }
2272 
2273 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2274 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2275 				    enum bpf_reg_type which)
2276 {
2277 	/* The register can already have a range from prior markings.
2278 	 * This is fine as long as it hasn't been advanced from its
2279 	 * origin.
2280 	 */
2281 	return reg->type == which &&
2282 	       reg->id == 0 &&
2283 	       reg->off == 0 &&
2284 	       tnum_equals_const(reg->var_off, 0);
2285 }
2286 
2287 /* Reset the min/max bounds of a register */
2288 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2289 {
2290 	reg->smin_value = S64_MIN;
2291 	reg->smax_value = S64_MAX;
2292 	reg->umin_value = 0;
2293 	reg->umax_value = U64_MAX;
2294 
2295 	reg->s32_min_value = S32_MIN;
2296 	reg->s32_max_value = S32_MAX;
2297 	reg->u32_min_value = 0;
2298 	reg->u32_max_value = U32_MAX;
2299 }
2300 
2301 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2302 {
2303 	reg->smin_value = S64_MIN;
2304 	reg->smax_value = S64_MAX;
2305 	reg->umin_value = 0;
2306 	reg->umax_value = U64_MAX;
2307 }
2308 
2309 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2310 {
2311 	reg->s32_min_value = S32_MIN;
2312 	reg->s32_max_value = S32_MAX;
2313 	reg->u32_min_value = 0;
2314 	reg->u32_max_value = U32_MAX;
2315 }
2316 
2317 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2318 {
2319 	struct tnum var32_off = tnum_subreg(reg->var_off);
2320 
2321 	/* min signed is max(sign bit) | min(other bits) */
2322 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2323 			var32_off.value | (var32_off.mask & S32_MIN));
2324 	/* max signed is min(sign bit) | max(other bits) */
2325 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2326 			var32_off.value | (var32_off.mask & S32_MAX));
2327 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2328 	reg->u32_max_value = min(reg->u32_max_value,
2329 				 (u32)(var32_off.value | var32_off.mask));
2330 }
2331 
2332 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2333 {
2334 	/* min signed is max(sign bit) | min(other bits) */
2335 	reg->smin_value = max_t(s64, reg->smin_value,
2336 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2337 	/* max signed is min(sign bit) | max(other bits) */
2338 	reg->smax_value = min_t(s64, reg->smax_value,
2339 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2340 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2341 	reg->umax_value = min(reg->umax_value,
2342 			      reg->var_off.value | reg->var_off.mask);
2343 }
2344 
2345 static void __update_reg_bounds(struct bpf_reg_state *reg)
2346 {
2347 	__update_reg32_bounds(reg);
2348 	__update_reg64_bounds(reg);
2349 }
2350 
2351 /* Uses signed min/max values to inform unsigned, and vice-versa */
2352 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2353 {
2354 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
2355 	 * bits to improve our u32/s32 boundaries.
2356 	 *
2357 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
2358 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
2359 	 * [10, 20] range. But this property holds for any 64-bit range as
2360 	 * long as upper 32 bits in that entire range of values stay the same.
2361 	 *
2362 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
2363 	 * in decimal) has the same upper 32 bits throughout all the values in
2364 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
2365 	 * range.
2366 	 *
2367 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
2368 	 * following the rules outlined below about u64/s64 correspondence
2369 	 * (which equally applies to u32 vs s32 correspondence). In general it
2370 	 * depends on actual hexadecimal values of 32-bit range. They can form
2371 	 * only valid u32, or only valid s32 ranges in some cases.
2372 	 *
2373 	 * So we use all these insights to derive bounds for subregisters here.
2374 	 */
2375 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
2376 		/* u64 to u32 casting preserves validity of low 32 bits as
2377 		 * a range, if upper 32 bits are the same
2378 		 */
2379 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
2380 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
2381 
2382 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
2383 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2384 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2385 		}
2386 	}
2387 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2388 		/* low 32 bits should form a proper u32 range */
2389 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2390 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2391 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2392 		}
2393 		/* low 32 bits should form a proper s32 range */
2394 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2395 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2396 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2397 		}
2398 	}
2399 	/* Special case where upper bits form a small sequence of two
2400 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2401 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
2402 	 * going from negative numbers to positive numbers. E.g., let's say we
2403 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2404 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2405 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2406 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2407 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2408 	 * upper 32 bits. As a random example, s64 range
2409 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2410 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2411 	 */
2412 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2413 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2414 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2415 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2416 	}
2417 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2418 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2419 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2420 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2421 	}
2422 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2423 	 * try to learn from that
2424 	 */
2425 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2426 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2427 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2428 	}
2429 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2430 	 * are the same, so combine.  This works even in the negative case, e.g.
2431 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2432 	 */
2433 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2434 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2435 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2436 	}
2437 }
2438 
2439 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2440 {
2441 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2442 	 * try to learn from that. Let's do a bit of ASCII art to see when
2443 	 * this is happening. Let's take u64 range first:
2444 	 *
2445 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2446 	 * |-------------------------------|--------------------------------|
2447 	 *
2448 	 * Valid u64 range is formed when umin and umax are anywhere in the
2449 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2450 	 * straightforward. Let's see how s64 range maps onto the same range
2451 	 * of values, annotated below the line for comparison:
2452 	 *
2453 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2454 	 * |-------------------------------|--------------------------------|
2455 	 * 0                        S64_MAX S64_MIN                        -1
2456 	 *
2457 	 * So s64 values basically start in the middle and they are logically
2458 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2459 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2460 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2461 	 * more visually as mapped to sign-agnostic range of hex values.
2462 	 *
2463 	 *  u64 start                                               u64 end
2464 	 *  _______________________________________________________________
2465 	 * /                                                               \
2466 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2467 	 * |-------------------------------|--------------------------------|
2468 	 * 0                        S64_MAX S64_MIN                        -1
2469 	 *                                / \
2470 	 * >------------------------------   ------------------------------->
2471 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2472 	 *
2473 	 * What this means is that, in general, we can't always derive
2474 	 * something new about u64 from any random s64 range, and vice versa.
2475 	 *
2476 	 * But we can do that in two particular cases. One is when entire
2477 	 * u64/s64 range is *entirely* contained within left half of the above
2478 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2479 	 *
2480 	 * |-------------------------------|--------------------------------|
2481 	 *     ^                   ^            ^                 ^
2482 	 *     A                   B            C                 D
2483 	 *
2484 	 * [A, B] and [C, D] are contained entirely in their respective halves
2485 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2486 	 * will be non-negative both as u64 and s64 (and in fact it will be
2487 	 * identical ranges no matter the signedness). [C, D] treated as s64
2488 	 * will be a range of negative values, while in u64 it will be
2489 	 * non-negative range of values larger than 0x8000000000000000.
2490 	 *
2491 	 * Now, any other range here can't be represented in both u64 and s64
2492 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2493 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2494 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2495 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2496 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2497 	 * ranges as u64. Currently reg_state can't represent two segments per
2498 	 * numeric domain, so in such situations we can only derive maximal
2499 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2500 	 *
2501 	 * So we use these facts to derive umin/umax from smin/smax and vice
2502 	 * versa only if they stay within the same "half". This is equivalent
2503 	 * to checking sign bit: lower half will have sign bit as zero, upper
2504 	 * half have sign bit 1. Below in code we simplify this by just
2505 	 * casting umin/umax as smin/smax and checking if they form valid
2506 	 * range, and vice versa. Those are equivalent checks.
2507 	 */
2508 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2509 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2510 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2511 	}
2512 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2513 	 * are the same, so combine.  This works even in the negative case, e.g.
2514 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2515 	 */
2516 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2517 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2518 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2519 	} else {
2520 		/* If the s64 range crosses the sign boundary, then it's split
2521 		 * between the beginning and end of the U64 domain. In that
2522 		 * case, we can derive new bounds if the u64 range overlaps
2523 		 * with only one end of the s64 range.
2524 		 *
2525 		 * In the following example, the u64 range overlaps only with
2526 		 * positive portion of the s64 range.
2527 		 *
2528 		 * 0                                                   U64_MAX
2529 		 * |  [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx]              |
2530 		 * |----------------------------|----------------------------|
2531 		 * |xxxxx s64 range xxxxxxxxx]                       [xxxxxxx|
2532 		 * 0                     S64_MAX S64_MIN                    -1
2533 		 *
2534 		 * We can thus derive the following new s64 and u64 ranges.
2535 		 *
2536 		 * 0                                                   U64_MAX
2537 		 * |  [xxxxxx u64 range xxxxx]                               |
2538 		 * |----------------------------|----------------------------|
2539 		 * |  [xxxxxx s64 range xxxxx]                               |
2540 		 * 0                     S64_MAX S64_MIN                    -1
2541 		 *
2542 		 * If they overlap in two places, we can't derive anything
2543 		 * because reg_state can't represent two ranges per numeric
2544 		 * domain.
2545 		 *
2546 		 * 0                                                   U64_MAX
2547 		 * |  [xxxxxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxxxxx]        |
2548 		 * |----------------------------|----------------------------|
2549 		 * |xxxxx s64 range xxxxxxxxx]                    [xxxxxxxxxx|
2550 		 * 0                     S64_MAX S64_MIN                    -1
2551 		 *
2552 		 * The first condition below corresponds to the first diagram
2553 		 * above.
2554 		 */
2555 		if (reg->umax_value < (u64)reg->smin_value) {
2556 			reg->smin_value = (s64)reg->umin_value;
2557 			reg->umax_value = min_t(u64, reg->umax_value, reg->smax_value);
2558 		} else if ((u64)reg->smax_value < reg->umin_value) {
2559 			/* This second condition considers the case where the u64 range
2560 			 * overlaps with the negative portion of the s64 range:
2561 			 *
2562 			 * 0                                                   U64_MAX
2563 			 * |              [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx]  |
2564 			 * |----------------------------|----------------------------|
2565 			 * |xxxxxxxxx]                       [xxxxxxxxxxxx s64 range |
2566 			 * 0                     S64_MAX S64_MIN                    -1
2567 			 */
2568 			reg->smax_value = (s64)reg->umax_value;
2569 			reg->umin_value = max_t(u64, reg->umin_value, reg->smin_value);
2570 		}
2571 	}
2572 }
2573 
2574 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2575 {
2576 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2577 	 * values on both sides of 64-bit range in hope to have tighter range.
2578 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2579 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2580 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2581 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2582 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2583 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2584 	 * We just need to make sure that derived bounds we are intersecting
2585 	 * with are well-formed ranges in respective s64 or u64 domain, just
2586 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2587 	 */
2588 	__u64 new_umin, new_umax;
2589 	__s64 new_smin, new_smax;
2590 
2591 	/* u32 -> u64 tightening, it's always well-formed */
2592 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2593 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2594 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2595 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2596 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2597 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2598 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2599 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2600 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2601 
2602 	/* Here we would like to handle a special case after sign extending load,
2603 	 * when upper bits for a 64-bit range are all 1s or all 0s.
2604 	 *
2605 	 * Upper bits are all 1s when register is in a range:
2606 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff]
2607 	 * Upper bits are all 0s when register is in a range:
2608 	 *   [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff]
2609 	 * Together this forms are continuous range:
2610 	 *   [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff]
2611 	 *
2612 	 * Now, suppose that register range is in fact tighter:
2613 	 *   [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R)
2614 	 * Also suppose that it's 32-bit range is positive,
2615 	 * meaning that lower 32-bits of the full 64-bit register
2616 	 * are in the range:
2617 	 *   [0x0000_0000, 0x7fff_ffff] (W)
2618 	 *
2619 	 * If this happens, then any value in a range:
2620 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff]
2621 	 * is smaller than a lowest bound of the range (R):
2622 	 *   0xffff_ffff_8000_0000
2623 	 * which means that upper bits of the full 64-bit register
2624 	 * can't be all 1s, when lower bits are in range (W).
2625 	 *
2626 	 * Note that:
2627 	 *  - 0xffff_ffff_8000_0000 == (s64)S32_MIN
2628 	 *  - 0x0000_0000_7fff_ffff == (s64)S32_MAX
2629 	 * These relations are used in the conditions below.
2630 	 */
2631 	if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) {
2632 		reg->smin_value = reg->s32_min_value;
2633 		reg->smax_value = reg->s32_max_value;
2634 		reg->umin_value = reg->s32_min_value;
2635 		reg->umax_value = reg->s32_max_value;
2636 		reg->var_off = tnum_intersect(reg->var_off,
2637 					      tnum_range(reg->smin_value, reg->smax_value));
2638 	}
2639 }
2640 
2641 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2642 {
2643 	__reg32_deduce_bounds(reg);
2644 	__reg64_deduce_bounds(reg);
2645 	__reg_deduce_mixed_bounds(reg);
2646 }
2647 
2648 /* Attempts to improve var_off based on unsigned min/max information */
2649 static void __reg_bound_offset(struct bpf_reg_state *reg)
2650 {
2651 	struct tnum var64_off = tnum_intersect(reg->var_off,
2652 					       tnum_range(reg->umin_value,
2653 							  reg->umax_value));
2654 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2655 					       tnum_range(reg->u32_min_value,
2656 							  reg->u32_max_value));
2657 
2658 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2659 }
2660 
2661 static void reg_bounds_sync(struct bpf_reg_state *reg)
2662 {
2663 	/* We might have learned new bounds from the var_off. */
2664 	__update_reg_bounds(reg);
2665 	/* We might have learned something about the sign bit. */
2666 	__reg_deduce_bounds(reg);
2667 	__reg_deduce_bounds(reg);
2668 	__reg_deduce_bounds(reg);
2669 	/* We might have learned some bits from the bounds. */
2670 	__reg_bound_offset(reg);
2671 	/* Intersecting with the old var_off might have improved our bounds
2672 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2673 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2674 	 */
2675 	__update_reg_bounds(reg);
2676 }
2677 
2678 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2679 				   struct bpf_reg_state *reg, const char *ctx)
2680 {
2681 	const char *msg;
2682 
2683 	if (reg->umin_value > reg->umax_value ||
2684 	    reg->smin_value > reg->smax_value ||
2685 	    reg->u32_min_value > reg->u32_max_value ||
2686 	    reg->s32_min_value > reg->s32_max_value) {
2687 		    msg = "range bounds violation";
2688 		    goto out;
2689 	}
2690 
2691 	if (tnum_is_const(reg->var_off)) {
2692 		u64 uval = reg->var_off.value;
2693 		s64 sval = (s64)uval;
2694 
2695 		if (reg->umin_value != uval || reg->umax_value != uval ||
2696 		    reg->smin_value != sval || reg->smax_value != sval) {
2697 			msg = "const tnum out of sync with range bounds";
2698 			goto out;
2699 		}
2700 	}
2701 
2702 	if (tnum_subreg_is_const(reg->var_off)) {
2703 		u32 uval32 = tnum_subreg(reg->var_off).value;
2704 		s32 sval32 = (s32)uval32;
2705 
2706 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2707 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2708 			msg = "const subreg tnum out of sync with range bounds";
2709 			goto out;
2710 		}
2711 	}
2712 
2713 	return 0;
2714 out:
2715 	verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2716 		     "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)",
2717 		     ctx, msg, reg->umin_value, reg->umax_value,
2718 		     reg->smin_value, reg->smax_value,
2719 		     reg->u32_min_value, reg->u32_max_value,
2720 		     reg->s32_min_value, reg->s32_max_value,
2721 		     reg->var_off.value, reg->var_off.mask);
2722 	if (env->test_reg_invariants)
2723 		return -EFAULT;
2724 	__mark_reg_unbounded(reg);
2725 	return 0;
2726 }
2727 
2728 static bool __reg32_bound_s64(s32 a)
2729 {
2730 	return a >= 0 && a <= S32_MAX;
2731 }
2732 
2733 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2734 {
2735 	reg->umin_value = reg->u32_min_value;
2736 	reg->umax_value = reg->u32_max_value;
2737 
2738 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2739 	 * be positive otherwise set to worse case bounds and refine later
2740 	 * from tnum.
2741 	 */
2742 	if (__reg32_bound_s64(reg->s32_min_value) &&
2743 	    __reg32_bound_s64(reg->s32_max_value)) {
2744 		reg->smin_value = reg->s32_min_value;
2745 		reg->smax_value = reg->s32_max_value;
2746 	} else {
2747 		reg->smin_value = 0;
2748 		reg->smax_value = U32_MAX;
2749 	}
2750 }
2751 
2752 /* Mark a register as having a completely unknown (scalar) value. */
2753 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2754 {
2755 	/*
2756 	 * Clear type, off, and union(map_ptr, range) and
2757 	 * padding between 'type' and union
2758 	 */
2759 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2760 	reg->type = SCALAR_VALUE;
2761 	reg->id = 0;
2762 	reg->ref_obj_id = 0;
2763 	reg->var_off = tnum_unknown;
2764 	reg->frameno = 0;
2765 	reg->precise = false;
2766 	__mark_reg_unbounded(reg);
2767 }
2768 
2769 /* Mark a register as having a completely unknown (scalar) value,
2770  * initialize .precise as true when not bpf capable.
2771  */
2772 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2773 			       struct bpf_reg_state *reg)
2774 {
2775 	__mark_reg_unknown_imprecise(reg);
2776 	reg->precise = !env->bpf_capable;
2777 }
2778 
2779 static void mark_reg_unknown(struct bpf_verifier_env *env,
2780 			     struct bpf_reg_state *regs, u32 regno)
2781 {
2782 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2783 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2784 		/* Something bad happened, let's kill all regs except FP */
2785 		for (regno = 0; regno < BPF_REG_FP; regno++)
2786 			__mark_reg_not_init(env, regs + regno);
2787 		return;
2788 	}
2789 	__mark_reg_unknown(env, regs + regno);
2790 }
2791 
2792 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2793 				struct bpf_reg_state *regs,
2794 				u32 regno,
2795 				s32 s32_min,
2796 				s32 s32_max)
2797 {
2798 	struct bpf_reg_state *reg = regs + regno;
2799 
2800 	reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min);
2801 	reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max);
2802 
2803 	reg->smin_value = max_t(s64, reg->smin_value, s32_min);
2804 	reg->smax_value = min_t(s64, reg->smax_value, s32_max);
2805 
2806 	reg_bounds_sync(reg);
2807 
2808 	return reg_bounds_sanity_check(env, reg, "s32_range");
2809 }
2810 
2811 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2812 				struct bpf_reg_state *reg)
2813 {
2814 	__mark_reg_unknown(env, reg);
2815 	reg->type = NOT_INIT;
2816 }
2817 
2818 static void mark_reg_not_init(struct bpf_verifier_env *env,
2819 			      struct bpf_reg_state *regs, u32 regno)
2820 {
2821 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2822 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2823 		/* Something bad happened, let's kill all regs except FP */
2824 		for (regno = 0; regno < BPF_REG_FP; regno++)
2825 			__mark_reg_not_init(env, regs + regno);
2826 		return;
2827 	}
2828 	__mark_reg_not_init(env, regs + regno);
2829 }
2830 
2831 static int mark_btf_ld_reg(struct bpf_verifier_env *env,
2832 			   struct bpf_reg_state *regs, u32 regno,
2833 			   enum bpf_reg_type reg_type,
2834 			   struct btf *btf, u32 btf_id,
2835 			   enum bpf_type_flag flag)
2836 {
2837 	switch (reg_type) {
2838 	case SCALAR_VALUE:
2839 		mark_reg_unknown(env, regs, regno);
2840 		return 0;
2841 	case PTR_TO_BTF_ID:
2842 		mark_reg_known_zero(env, regs, regno);
2843 		regs[regno].type = PTR_TO_BTF_ID | flag;
2844 		regs[regno].btf = btf;
2845 		regs[regno].btf_id = btf_id;
2846 		if (type_may_be_null(flag))
2847 			regs[regno].id = ++env->id_gen;
2848 		return 0;
2849 	case PTR_TO_MEM:
2850 		mark_reg_known_zero(env, regs, regno);
2851 		regs[regno].type = PTR_TO_MEM | flag;
2852 		regs[regno].mem_size = 0;
2853 		return 0;
2854 	default:
2855 		verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__);
2856 		return -EFAULT;
2857 	}
2858 }
2859 
2860 #define DEF_NOT_SUBREG	(0)
2861 static void init_reg_state(struct bpf_verifier_env *env,
2862 			   struct bpf_func_state *state)
2863 {
2864 	struct bpf_reg_state *regs = state->regs;
2865 	int i;
2866 
2867 	for (i = 0; i < MAX_BPF_REG; i++) {
2868 		mark_reg_not_init(env, regs, i);
2869 		regs[i].subreg_def = DEF_NOT_SUBREG;
2870 	}
2871 
2872 	/* frame pointer */
2873 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2874 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2875 	regs[BPF_REG_FP].frameno = state->frameno;
2876 }
2877 
2878 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2879 {
2880 	return (struct bpf_retval_range){ minval, maxval };
2881 }
2882 
2883 #define BPF_MAIN_FUNC (-1)
2884 static void init_func_state(struct bpf_verifier_env *env,
2885 			    struct bpf_func_state *state,
2886 			    int callsite, int frameno, int subprogno)
2887 {
2888 	state->callsite = callsite;
2889 	state->frameno = frameno;
2890 	state->subprogno = subprogno;
2891 	state->callback_ret_range = retval_range(0, 0);
2892 	init_reg_state(env, state);
2893 	mark_verifier_state_scratched(env);
2894 }
2895 
2896 /* Similar to push_stack(), but for async callbacks */
2897 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2898 						int insn_idx, int prev_insn_idx,
2899 						int subprog, bool is_sleepable)
2900 {
2901 	struct bpf_verifier_stack_elem *elem;
2902 	struct bpf_func_state *frame;
2903 
2904 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
2905 	if (!elem)
2906 		return NULL;
2907 
2908 	elem->insn_idx = insn_idx;
2909 	elem->prev_insn_idx = prev_insn_idx;
2910 	elem->next = env->head;
2911 	elem->log_pos = env->log.end_pos;
2912 	env->head = elem;
2913 	env->stack_size++;
2914 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2915 		verbose(env,
2916 			"The sequence of %d jumps is too complex for async cb.\n",
2917 			env->stack_size);
2918 		return NULL;
2919 	}
2920 	/* Unlike push_stack() do not copy_verifier_state().
2921 	 * The caller state doesn't matter.
2922 	 * This is async callback. It starts in a fresh stack.
2923 	 * Initialize it similar to do_check_common().
2924 	 */
2925 	elem->st.branches = 1;
2926 	elem->st.in_sleepable = is_sleepable;
2927 	frame = kzalloc(sizeof(*frame), GFP_KERNEL_ACCOUNT);
2928 	if (!frame)
2929 		return NULL;
2930 	init_func_state(env, frame,
2931 			BPF_MAIN_FUNC /* callsite */,
2932 			0 /* frameno within this callchain */,
2933 			subprog /* subprog number within this prog */);
2934 	elem->st.frame[0] = frame;
2935 	return &elem->st;
2936 }
2937 
2938 
2939 enum reg_arg_type {
2940 	SRC_OP,		/* register is used as source operand */
2941 	DST_OP,		/* register is used as destination operand */
2942 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2943 };
2944 
2945 static int cmp_subprogs(const void *a, const void *b)
2946 {
2947 	return ((struct bpf_subprog_info *)a)->start -
2948 	       ((struct bpf_subprog_info *)b)->start;
2949 }
2950 
2951 /* Find subprogram that contains instruction at 'off' */
2952 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off)
2953 {
2954 	struct bpf_subprog_info *vals = env->subprog_info;
2955 	int l, r, m;
2956 
2957 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
2958 		return NULL;
2959 
2960 	l = 0;
2961 	r = env->subprog_cnt - 1;
2962 	while (l < r) {
2963 		m = l + (r - l + 1) / 2;
2964 		if (vals[m].start <= off)
2965 			l = m;
2966 		else
2967 			r = m - 1;
2968 	}
2969 	return &vals[l];
2970 }
2971 
2972 /* Find subprogram that starts exactly at 'off' */
2973 static int find_subprog(struct bpf_verifier_env *env, int off)
2974 {
2975 	struct bpf_subprog_info *p;
2976 
2977 	p = bpf_find_containing_subprog(env, off);
2978 	if (!p || p->start != off)
2979 		return -ENOENT;
2980 	return p - env->subprog_info;
2981 }
2982 
2983 static int add_subprog(struct bpf_verifier_env *env, int off)
2984 {
2985 	int insn_cnt = env->prog->len;
2986 	int ret;
2987 
2988 	if (off >= insn_cnt || off < 0) {
2989 		verbose(env, "call to invalid destination\n");
2990 		return -EINVAL;
2991 	}
2992 	ret = find_subprog(env, off);
2993 	if (ret >= 0)
2994 		return ret;
2995 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2996 		verbose(env, "too many subprograms\n");
2997 		return -E2BIG;
2998 	}
2999 	/* determine subprog starts. The end is one before the next starts */
3000 	env->subprog_info[env->subprog_cnt++].start = off;
3001 	sort(env->subprog_info, env->subprog_cnt,
3002 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
3003 	return env->subprog_cnt - 1;
3004 }
3005 
3006 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
3007 {
3008 	struct bpf_prog_aux *aux = env->prog->aux;
3009 	struct btf *btf = aux->btf;
3010 	const struct btf_type *t;
3011 	u32 main_btf_id, id;
3012 	const char *name;
3013 	int ret, i;
3014 
3015 	/* Non-zero func_info_cnt implies valid btf */
3016 	if (!aux->func_info_cnt)
3017 		return 0;
3018 	main_btf_id = aux->func_info[0].type_id;
3019 
3020 	t = btf_type_by_id(btf, main_btf_id);
3021 	if (!t) {
3022 		verbose(env, "invalid btf id for main subprog in func_info\n");
3023 		return -EINVAL;
3024 	}
3025 
3026 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
3027 	if (IS_ERR(name)) {
3028 		ret = PTR_ERR(name);
3029 		/* If there is no tag present, there is no exception callback */
3030 		if (ret == -ENOENT)
3031 			ret = 0;
3032 		else if (ret == -EEXIST)
3033 			verbose(env, "multiple exception callback tags for main subprog\n");
3034 		return ret;
3035 	}
3036 
3037 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
3038 	if (ret < 0) {
3039 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
3040 		return ret;
3041 	}
3042 	id = ret;
3043 	t = btf_type_by_id(btf, id);
3044 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
3045 		verbose(env, "exception callback '%s' must have global linkage\n", name);
3046 		return -EINVAL;
3047 	}
3048 	ret = 0;
3049 	for (i = 0; i < aux->func_info_cnt; i++) {
3050 		if (aux->func_info[i].type_id != id)
3051 			continue;
3052 		ret = aux->func_info[i].insn_off;
3053 		/* Further func_info and subprog checks will also happen
3054 		 * later, so assume this is the right insn_off for now.
3055 		 */
3056 		if (!ret) {
3057 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
3058 			ret = -EINVAL;
3059 		}
3060 	}
3061 	if (!ret) {
3062 		verbose(env, "exception callback type id not found in func_info\n");
3063 		ret = -EINVAL;
3064 	}
3065 	return ret;
3066 }
3067 
3068 #define MAX_KFUNC_DESCS 256
3069 #define MAX_KFUNC_BTFS	256
3070 
3071 struct bpf_kfunc_desc {
3072 	struct btf_func_model func_model;
3073 	u32 func_id;
3074 	s32 imm;
3075 	u16 offset;
3076 	unsigned long addr;
3077 };
3078 
3079 struct bpf_kfunc_btf {
3080 	struct btf *btf;
3081 	struct module *module;
3082 	u16 offset;
3083 };
3084 
3085 struct bpf_kfunc_desc_tab {
3086 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
3087 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
3088 	 * available, therefore at the end of verification do_misc_fixups()
3089 	 * sorts this by imm and offset.
3090 	 */
3091 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
3092 	u32 nr_descs;
3093 };
3094 
3095 struct bpf_kfunc_btf_tab {
3096 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
3097 	u32 nr_descs;
3098 };
3099 
3100 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
3101 {
3102 	const struct bpf_kfunc_desc *d0 = a;
3103 	const struct bpf_kfunc_desc *d1 = b;
3104 
3105 	/* func_id is not greater than BTF_MAX_TYPE */
3106 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
3107 }
3108 
3109 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
3110 {
3111 	const struct bpf_kfunc_btf *d0 = a;
3112 	const struct bpf_kfunc_btf *d1 = b;
3113 
3114 	return d0->offset - d1->offset;
3115 }
3116 
3117 static const struct bpf_kfunc_desc *
3118 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
3119 {
3120 	struct bpf_kfunc_desc desc = {
3121 		.func_id = func_id,
3122 		.offset = offset,
3123 	};
3124 	struct bpf_kfunc_desc_tab *tab;
3125 
3126 	tab = prog->aux->kfunc_tab;
3127 	return bsearch(&desc, tab->descs, tab->nr_descs,
3128 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
3129 }
3130 
3131 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
3132 		       u16 btf_fd_idx, u8 **func_addr)
3133 {
3134 	const struct bpf_kfunc_desc *desc;
3135 
3136 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
3137 	if (!desc)
3138 		return -EFAULT;
3139 
3140 	*func_addr = (u8 *)desc->addr;
3141 	return 0;
3142 }
3143 
3144 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
3145 					 s16 offset)
3146 {
3147 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
3148 	struct bpf_kfunc_btf_tab *tab;
3149 	struct bpf_kfunc_btf *b;
3150 	struct module *mod;
3151 	struct btf *btf;
3152 	int btf_fd;
3153 
3154 	tab = env->prog->aux->kfunc_btf_tab;
3155 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
3156 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
3157 	if (!b) {
3158 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
3159 			verbose(env, "too many different module BTFs\n");
3160 			return ERR_PTR(-E2BIG);
3161 		}
3162 
3163 		if (bpfptr_is_null(env->fd_array)) {
3164 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
3165 			return ERR_PTR(-EPROTO);
3166 		}
3167 
3168 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
3169 					    offset * sizeof(btf_fd),
3170 					    sizeof(btf_fd)))
3171 			return ERR_PTR(-EFAULT);
3172 
3173 		btf = btf_get_by_fd(btf_fd);
3174 		if (IS_ERR(btf)) {
3175 			verbose(env, "invalid module BTF fd specified\n");
3176 			return btf;
3177 		}
3178 
3179 		if (!btf_is_module(btf)) {
3180 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
3181 			btf_put(btf);
3182 			return ERR_PTR(-EINVAL);
3183 		}
3184 
3185 		mod = btf_try_get_module(btf);
3186 		if (!mod) {
3187 			btf_put(btf);
3188 			return ERR_PTR(-ENXIO);
3189 		}
3190 
3191 		b = &tab->descs[tab->nr_descs++];
3192 		b->btf = btf;
3193 		b->module = mod;
3194 		b->offset = offset;
3195 
3196 		/* sort() reorders entries by value, so b may no longer point
3197 		 * to the right entry after this
3198 		 */
3199 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3200 		     kfunc_btf_cmp_by_off, NULL);
3201 	} else {
3202 		btf = b->btf;
3203 	}
3204 
3205 	return btf;
3206 }
3207 
3208 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
3209 {
3210 	if (!tab)
3211 		return;
3212 
3213 	while (tab->nr_descs--) {
3214 		module_put(tab->descs[tab->nr_descs].module);
3215 		btf_put(tab->descs[tab->nr_descs].btf);
3216 	}
3217 	kfree(tab);
3218 }
3219 
3220 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
3221 {
3222 	if (offset) {
3223 		if (offset < 0) {
3224 			/* In the future, this can be allowed to increase limit
3225 			 * of fd index into fd_array, interpreted as u16.
3226 			 */
3227 			verbose(env, "negative offset disallowed for kernel module function call\n");
3228 			return ERR_PTR(-EINVAL);
3229 		}
3230 
3231 		return __find_kfunc_desc_btf(env, offset);
3232 	}
3233 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
3234 }
3235 
3236 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
3237 {
3238 	const struct btf_type *func, *func_proto;
3239 	struct bpf_kfunc_btf_tab *btf_tab;
3240 	struct bpf_kfunc_desc_tab *tab;
3241 	struct bpf_prog_aux *prog_aux;
3242 	struct bpf_kfunc_desc *desc;
3243 	const char *func_name;
3244 	struct btf *desc_btf;
3245 	unsigned long call_imm;
3246 	unsigned long addr;
3247 	int err;
3248 
3249 	prog_aux = env->prog->aux;
3250 	tab = prog_aux->kfunc_tab;
3251 	btf_tab = prog_aux->kfunc_btf_tab;
3252 	if (!tab) {
3253 		if (!btf_vmlinux) {
3254 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
3255 			return -ENOTSUPP;
3256 		}
3257 
3258 		if (!env->prog->jit_requested) {
3259 			verbose(env, "JIT is required for calling kernel function\n");
3260 			return -ENOTSUPP;
3261 		}
3262 
3263 		if (!bpf_jit_supports_kfunc_call()) {
3264 			verbose(env, "JIT does not support calling kernel function\n");
3265 			return -ENOTSUPP;
3266 		}
3267 
3268 		if (!env->prog->gpl_compatible) {
3269 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
3270 			return -EINVAL;
3271 		}
3272 
3273 		tab = kzalloc(sizeof(*tab), GFP_KERNEL_ACCOUNT);
3274 		if (!tab)
3275 			return -ENOMEM;
3276 		prog_aux->kfunc_tab = tab;
3277 	}
3278 
3279 	/* func_id == 0 is always invalid, but instead of returning an error, be
3280 	 * conservative and wait until the code elimination pass before returning
3281 	 * error, so that invalid calls that get pruned out can be in BPF programs
3282 	 * loaded from userspace.  It is also required that offset be untouched
3283 	 * for such calls.
3284 	 */
3285 	if (!func_id && !offset)
3286 		return 0;
3287 
3288 	if (!btf_tab && offset) {
3289 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL_ACCOUNT);
3290 		if (!btf_tab)
3291 			return -ENOMEM;
3292 		prog_aux->kfunc_btf_tab = btf_tab;
3293 	}
3294 
3295 	desc_btf = find_kfunc_desc_btf(env, offset);
3296 	if (IS_ERR(desc_btf)) {
3297 		verbose(env, "failed to find BTF for kernel function\n");
3298 		return PTR_ERR(desc_btf);
3299 	}
3300 
3301 	if (find_kfunc_desc(env->prog, func_id, offset))
3302 		return 0;
3303 
3304 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
3305 		verbose(env, "too many different kernel function calls\n");
3306 		return -E2BIG;
3307 	}
3308 
3309 	func = btf_type_by_id(desc_btf, func_id);
3310 	if (!func || !btf_type_is_func(func)) {
3311 		verbose(env, "kernel btf_id %u is not a function\n",
3312 			func_id);
3313 		return -EINVAL;
3314 	}
3315 	func_proto = btf_type_by_id(desc_btf, func->type);
3316 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
3317 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
3318 			func_id);
3319 		return -EINVAL;
3320 	}
3321 
3322 	func_name = btf_name_by_offset(desc_btf, func->name_off);
3323 	addr = kallsyms_lookup_name(func_name);
3324 	if (!addr) {
3325 		verbose(env, "cannot find address for kernel function %s\n",
3326 			func_name);
3327 		return -EINVAL;
3328 	}
3329 	specialize_kfunc(env, func_id, offset, &addr);
3330 
3331 	if (bpf_jit_supports_far_kfunc_call()) {
3332 		call_imm = func_id;
3333 	} else {
3334 		call_imm = BPF_CALL_IMM(addr);
3335 		/* Check whether the relative offset overflows desc->imm */
3336 		if ((unsigned long)(s32)call_imm != call_imm) {
3337 			verbose(env, "address of kernel function %s is out of range\n",
3338 				func_name);
3339 			return -EINVAL;
3340 		}
3341 	}
3342 
3343 	if (bpf_dev_bound_kfunc_id(func_id)) {
3344 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3345 		if (err)
3346 			return err;
3347 	}
3348 
3349 	desc = &tab->descs[tab->nr_descs++];
3350 	desc->func_id = func_id;
3351 	desc->imm = call_imm;
3352 	desc->offset = offset;
3353 	desc->addr = addr;
3354 	err = btf_distill_func_proto(&env->log, desc_btf,
3355 				     func_proto, func_name,
3356 				     &desc->func_model);
3357 	if (!err)
3358 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3359 		     kfunc_desc_cmp_by_id_off, NULL);
3360 	return err;
3361 }
3362 
3363 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
3364 {
3365 	const struct bpf_kfunc_desc *d0 = a;
3366 	const struct bpf_kfunc_desc *d1 = b;
3367 
3368 	if (d0->imm != d1->imm)
3369 		return d0->imm < d1->imm ? -1 : 1;
3370 	if (d0->offset != d1->offset)
3371 		return d0->offset < d1->offset ? -1 : 1;
3372 	return 0;
3373 }
3374 
3375 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
3376 {
3377 	struct bpf_kfunc_desc_tab *tab;
3378 
3379 	tab = prog->aux->kfunc_tab;
3380 	if (!tab)
3381 		return;
3382 
3383 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3384 	     kfunc_desc_cmp_by_imm_off, NULL);
3385 }
3386 
3387 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
3388 {
3389 	return !!prog->aux->kfunc_tab;
3390 }
3391 
3392 const struct btf_func_model *
3393 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3394 			 const struct bpf_insn *insn)
3395 {
3396 	const struct bpf_kfunc_desc desc = {
3397 		.imm = insn->imm,
3398 		.offset = insn->off,
3399 	};
3400 	const struct bpf_kfunc_desc *res;
3401 	struct bpf_kfunc_desc_tab *tab;
3402 
3403 	tab = prog->aux->kfunc_tab;
3404 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3405 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3406 
3407 	return res ? &res->func_model : NULL;
3408 }
3409 
3410 static int add_kfunc_in_insns(struct bpf_verifier_env *env,
3411 			      struct bpf_insn *insn, int cnt)
3412 {
3413 	int i, ret;
3414 
3415 	for (i = 0; i < cnt; i++, insn++) {
3416 		if (bpf_pseudo_kfunc_call(insn)) {
3417 			ret = add_kfunc_call(env, insn->imm, insn->off);
3418 			if (ret < 0)
3419 				return ret;
3420 		}
3421 	}
3422 	return 0;
3423 }
3424 
3425 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3426 {
3427 	struct bpf_subprog_info *subprog = env->subprog_info;
3428 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3429 	struct bpf_insn *insn = env->prog->insnsi;
3430 
3431 	/* Add entry function. */
3432 	ret = add_subprog(env, 0);
3433 	if (ret)
3434 		return ret;
3435 
3436 	for (i = 0; i < insn_cnt; i++, insn++) {
3437 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3438 		    !bpf_pseudo_kfunc_call(insn))
3439 			continue;
3440 
3441 		if (!env->bpf_capable) {
3442 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3443 			return -EPERM;
3444 		}
3445 
3446 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3447 			ret = add_subprog(env, i + insn->imm + 1);
3448 		else
3449 			ret = add_kfunc_call(env, insn->imm, insn->off);
3450 
3451 		if (ret < 0)
3452 			return ret;
3453 	}
3454 
3455 	ret = bpf_find_exception_callback_insn_off(env);
3456 	if (ret < 0)
3457 		return ret;
3458 	ex_cb_insn = ret;
3459 
3460 	/* If ex_cb_insn > 0, this means that the main program has a subprog
3461 	 * marked using BTF decl tag to serve as the exception callback.
3462 	 */
3463 	if (ex_cb_insn) {
3464 		ret = add_subprog(env, ex_cb_insn);
3465 		if (ret < 0)
3466 			return ret;
3467 		for (i = 1; i < env->subprog_cnt; i++) {
3468 			if (env->subprog_info[i].start != ex_cb_insn)
3469 				continue;
3470 			env->exception_callback_subprog = i;
3471 			mark_subprog_exc_cb(env, i);
3472 			break;
3473 		}
3474 	}
3475 
3476 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3477 	 * logic. 'subprog_cnt' should not be increased.
3478 	 */
3479 	subprog[env->subprog_cnt].start = insn_cnt;
3480 
3481 	if (env->log.level & BPF_LOG_LEVEL2)
3482 		for (i = 0; i < env->subprog_cnt; i++)
3483 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3484 
3485 	return 0;
3486 }
3487 
3488 static int check_subprogs(struct bpf_verifier_env *env)
3489 {
3490 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3491 	struct bpf_subprog_info *subprog = env->subprog_info;
3492 	struct bpf_insn *insn = env->prog->insnsi;
3493 	int insn_cnt = env->prog->len;
3494 
3495 	/* now check that all jumps are within the same subprog */
3496 	subprog_start = subprog[cur_subprog].start;
3497 	subprog_end = subprog[cur_subprog + 1].start;
3498 	for (i = 0; i < insn_cnt; i++) {
3499 		u8 code = insn[i].code;
3500 
3501 		if (code == (BPF_JMP | BPF_CALL) &&
3502 		    insn[i].src_reg == 0 &&
3503 		    insn[i].imm == BPF_FUNC_tail_call) {
3504 			subprog[cur_subprog].has_tail_call = true;
3505 			subprog[cur_subprog].tail_call_reachable = true;
3506 		}
3507 		if (BPF_CLASS(code) == BPF_LD &&
3508 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3509 			subprog[cur_subprog].has_ld_abs = true;
3510 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3511 			goto next;
3512 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3513 			goto next;
3514 		off = i + bpf_jmp_offset(&insn[i]) + 1;
3515 		if (off < subprog_start || off >= subprog_end) {
3516 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3517 			return -EINVAL;
3518 		}
3519 next:
3520 		if (i == subprog_end - 1) {
3521 			/* to avoid fall-through from one subprog into another
3522 			 * the last insn of the subprog should be either exit
3523 			 * or unconditional jump back or bpf_throw call
3524 			 */
3525 			if (code != (BPF_JMP | BPF_EXIT) &&
3526 			    code != (BPF_JMP32 | BPF_JA) &&
3527 			    code != (BPF_JMP | BPF_JA)) {
3528 				verbose(env, "last insn is not an exit or jmp\n");
3529 				return -EINVAL;
3530 			}
3531 			subprog_start = subprog_end;
3532 			cur_subprog++;
3533 			if (cur_subprog < env->subprog_cnt)
3534 				subprog_end = subprog[cur_subprog + 1].start;
3535 		}
3536 	}
3537 	return 0;
3538 }
3539 
3540 static int mark_stack_slot_obj_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3541 				    int spi, int nr_slots)
3542 {
3543 	int err, i;
3544 
3545 	for (i = 0; i < nr_slots; i++) {
3546 		err = bpf_mark_stack_read(env, reg->frameno, env->insn_idx, BIT(spi - i));
3547 		if (err)
3548 			return err;
3549 		mark_stack_slot_scratched(env, spi - i);
3550 	}
3551 	return 0;
3552 }
3553 
3554 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3555 {
3556 	int spi;
3557 
3558 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3559 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3560 	 * check_kfunc_call.
3561 	 */
3562 	if (reg->type == CONST_PTR_TO_DYNPTR)
3563 		return 0;
3564 	spi = dynptr_get_spi(env, reg);
3565 	if (spi < 0)
3566 		return spi;
3567 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3568 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3569 	 * read.
3570 	 */
3571 	return mark_stack_slot_obj_read(env, reg, spi, BPF_DYNPTR_NR_SLOTS);
3572 }
3573 
3574 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3575 			  int spi, int nr_slots)
3576 {
3577 	return mark_stack_slot_obj_read(env, reg, spi, nr_slots);
3578 }
3579 
3580 static int mark_irq_flag_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3581 {
3582 	int spi;
3583 
3584 	spi = irq_flag_get_spi(env, reg);
3585 	if (spi < 0)
3586 		return spi;
3587 	return mark_stack_slot_obj_read(env, reg, spi, 1);
3588 }
3589 
3590 /* This function is supposed to be used by the following 32-bit optimization
3591  * code only. It returns TRUE if the source or destination register operates
3592  * on 64-bit, otherwise return FALSE.
3593  */
3594 static bool is_reg64(struct bpf_insn *insn,
3595 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3596 {
3597 	u8 code, class, op;
3598 
3599 	code = insn->code;
3600 	class = BPF_CLASS(code);
3601 	op = BPF_OP(code);
3602 	if (class == BPF_JMP) {
3603 		/* BPF_EXIT for "main" will reach here. Return TRUE
3604 		 * conservatively.
3605 		 */
3606 		if (op == BPF_EXIT)
3607 			return true;
3608 		if (op == BPF_CALL) {
3609 			/* BPF to BPF call will reach here because of marking
3610 			 * caller saved clobber with DST_OP_NO_MARK for which we
3611 			 * don't care the register def because they are anyway
3612 			 * marked as NOT_INIT already.
3613 			 */
3614 			if (insn->src_reg == BPF_PSEUDO_CALL)
3615 				return false;
3616 			/* Helper call will reach here because of arg type
3617 			 * check, conservatively return TRUE.
3618 			 */
3619 			if (t == SRC_OP)
3620 				return true;
3621 
3622 			return false;
3623 		}
3624 	}
3625 
3626 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3627 		return false;
3628 
3629 	if (class == BPF_ALU64 || class == BPF_JMP ||
3630 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3631 		return true;
3632 
3633 	if (class == BPF_ALU || class == BPF_JMP32)
3634 		return false;
3635 
3636 	if (class == BPF_LDX) {
3637 		if (t != SRC_OP)
3638 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3639 		/* LDX source must be ptr. */
3640 		return true;
3641 	}
3642 
3643 	if (class == BPF_STX) {
3644 		/* BPF_STX (including atomic variants) has one or more source
3645 		 * operands, one of which is a ptr. Check whether the caller is
3646 		 * asking about it.
3647 		 */
3648 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3649 			return true;
3650 		return BPF_SIZE(code) == BPF_DW;
3651 	}
3652 
3653 	if (class == BPF_LD) {
3654 		u8 mode = BPF_MODE(code);
3655 
3656 		/* LD_IMM64 */
3657 		if (mode == BPF_IMM)
3658 			return true;
3659 
3660 		/* Both LD_IND and LD_ABS return 32-bit data. */
3661 		if (t != SRC_OP)
3662 			return  false;
3663 
3664 		/* Implicit ctx ptr. */
3665 		if (regno == BPF_REG_6)
3666 			return true;
3667 
3668 		/* Explicit source could be any width. */
3669 		return true;
3670 	}
3671 
3672 	if (class == BPF_ST)
3673 		/* The only source register for BPF_ST is a ptr. */
3674 		return true;
3675 
3676 	/* Conservatively return true at default. */
3677 	return true;
3678 }
3679 
3680 /* Return the regno defined by the insn, or -1. */
3681 static int insn_def_regno(const struct bpf_insn *insn)
3682 {
3683 	switch (BPF_CLASS(insn->code)) {
3684 	case BPF_JMP:
3685 	case BPF_JMP32:
3686 	case BPF_ST:
3687 		return -1;
3688 	case BPF_STX:
3689 		if (BPF_MODE(insn->code) == BPF_ATOMIC ||
3690 		    BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) {
3691 			if (insn->imm == BPF_CMPXCHG)
3692 				return BPF_REG_0;
3693 			else if (insn->imm == BPF_LOAD_ACQ)
3694 				return insn->dst_reg;
3695 			else if (insn->imm & BPF_FETCH)
3696 				return insn->src_reg;
3697 		}
3698 		return -1;
3699 	default:
3700 		return insn->dst_reg;
3701 	}
3702 }
3703 
3704 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3705 static bool insn_has_def32(struct bpf_insn *insn)
3706 {
3707 	int dst_reg = insn_def_regno(insn);
3708 
3709 	if (dst_reg == -1)
3710 		return false;
3711 
3712 	return !is_reg64(insn, dst_reg, NULL, DST_OP);
3713 }
3714 
3715 static void mark_insn_zext(struct bpf_verifier_env *env,
3716 			   struct bpf_reg_state *reg)
3717 {
3718 	s32 def_idx = reg->subreg_def;
3719 
3720 	if (def_idx == DEF_NOT_SUBREG)
3721 		return;
3722 
3723 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3724 	/* The dst will be zero extended, so won't be sub-register anymore. */
3725 	reg->subreg_def = DEF_NOT_SUBREG;
3726 }
3727 
3728 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3729 			   enum reg_arg_type t)
3730 {
3731 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3732 	struct bpf_reg_state *reg;
3733 	bool rw64;
3734 
3735 	if (regno >= MAX_BPF_REG) {
3736 		verbose(env, "R%d is invalid\n", regno);
3737 		return -EINVAL;
3738 	}
3739 
3740 	mark_reg_scratched(env, regno);
3741 
3742 	reg = &regs[regno];
3743 	rw64 = is_reg64(insn, regno, reg, t);
3744 	if (t == SRC_OP) {
3745 		/* check whether register used as source operand can be read */
3746 		if (reg->type == NOT_INIT) {
3747 			verbose(env, "R%d !read_ok\n", regno);
3748 			return -EACCES;
3749 		}
3750 		/* We don't need to worry about FP liveness because it's read-only */
3751 		if (regno == BPF_REG_FP)
3752 			return 0;
3753 
3754 		if (rw64)
3755 			mark_insn_zext(env, reg);
3756 
3757 		return 0;
3758 	} else {
3759 		/* check whether register used as dest operand can be written to */
3760 		if (regno == BPF_REG_FP) {
3761 			verbose(env, "frame pointer is read only\n");
3762 			return -EACCES;
3763 		}
3764 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3765 		if (t == DST_OP)
3766 			mark_reg_unknown(env, regs, regno);
3767 	}
3768 	return 0;
3769 }
3770 
3771 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3772 			 enum reg_arg_type t)
3773 {
3774 	struct bpf_verifier_state *vstate = env->cur_state;
3775 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3776 
3777 	return __check_reg_arg(env, state->regs, regno, t);
3778 }
3779 
3780 static int insn_stack_access_flags(int frameno, int spi)
3781 {
3782 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3783 }
3784 
3785 static int insn_stack_access_spi(int insn_flags)
3786 {
3787 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3788 }
3789 
3790 static int insn_stack_access_frameno(int insn_flags)
3791 {
3792 	return insn_flags & INSN_F_FRAMENO_MASK;
3793 }
3794 
3795 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3796 {
3797 	env->insn_aux_data[idx].jmp_point = true;
3798 }
3799 
3800 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3801 {
3802 	return env->insn_aux_data[insn_idx].jmp_point;
3803 }
3804 
3805 #define LR_FRAMENO_BITS	3
3806 #define LR_SPI_BITS	6
3807 #define LR_ENTRY_BITS	(LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3808 #define LR_SIZE_BITS	4
3809 #define LR_FRAMENO_MASK	((1ull << LR_FRAMENO_BITS) - 1)
3810 #define LR_SPI_MASK	((1ull << LR_SPI_BITS)     - 1)
3811 #define LR_SIZE_MASK	((1ull << LR_SIZE_BITS)    - 1)
3812 #define LR_SPI_OFF	LR_FRAMENO_BITS
3813 #define LR_IS_REG_OFF	(LR_SPI_BITS + LR_FRAMENO_BITS)
3814 #define LINKED_REGS_MAX	6
3815 
3816 struct linked_reg {
3817 	u8 frameno;
3818 	union {
3819 		u8 spi;
3820 		u8 regno;
3821 	};
3822 	bool is_reg;
3823 };
3824 
3825 struct linked_regs {
3826 	int cnt;
3827 	struct linked_reg entries[LINKED_REGS_MAX];
3828 };
3829 
3830 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3831 {
3832 	if (s->cnt < LINKED_REGS_MAX)
3833 		return &s->entries[s->cnt++];
3834 
3835 	return NULL;
3836 }
3837 
3838 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track
3839  * number of elements currently in stack.
3840  * Pack one history entry for linked registers as 10 bits in the following format:
3841  * - 3-bits frameno
3842  * - 6-bits spi_or_reg
3843  * - 1-bit  is_reg
3844  */
3845 static u64 linked_regs_pack(struct linked_regs *s)
3846 {
3847 	u64 val = 0;
3848 	int i;
3849 
3850 	for (i = 0; i < s->cnt; ++i) {
3851 		struct linked_reg *e = &s->entries[i];
3852 		u64 tmp = 0;
3853 
3854 		tmp |= e->frameno;
3855 		tmp |= e->spi << LR_SPI_OFF;
3856 		tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
3857 
3858 		val <<= LR_ENTRY_BITS;
3859 		val |= tmp;
3860 	}
3861 	val <<= LR_SIZE_BITS;
3862 	val |= s->cnt;
3863 	return val;
3864 }
3865 
3866 static void linked_regs_unpack(u64 val, struct linked_regs *s)
3867 {
3868 	int i;
3869 
3870 	s->cnt = val & LR_SIZE_MASK;
3871 	val >>= LR_SIZE_BITS;
3872 
3873 	for (i = 0; i < s->cnt; ++i) {
3874 		struct linked_reg *e = &s->entries[i];
3875 
3876 		e->frameno =  val & LR_FRAMENO_MASK;
3877 		e->spi     = (val >> LR_SPI_OFF) & LR_SPI_MASK;
3878 		e->is_reg  = (val >> LR_IS_REG_OFF) & 0x1;
3879 		val >>= LR_ENTRY_BITS;
3880 	}
3881 }
3882 
3883 /* for any branch, call, exit record the history of jmps in the given state */
3884 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3885 			    int insn_flags, u64 linked_regs)
3886 {
3887 	u32 cnt = cur->jmp_history_cnt;
3888 	struct bpf_jmp_history_entry *p;
3889 	size_t alloc_size;
3890 
3891 	/* combine instruction flags if we already recorded this instruction */
3892 	if (env->cur_hist_ent) {
3893 		/* atomic instructions push insn_flags twice, for READ and
3894 		 * WRITE sides, but they should agree on stack slot
3895 		 */
3896 		verifier_bug_if((env->cur_hist_ent->flags & insn_flags) &&
3897 				(env->cur_hist_ent->flags & insn_flags) != insn_flags,
3898 				env, "insn history: insn_idx %d cur flags %x new flags %x",
3899 				env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3900 		env->cur_hist_ent->flags |= insn_flags;
3901 		verifier_bug_if(env->cur_hist_ent->linked_regs != 0, env,
3902 				"insn history: insn_idx %d linked_regs: %#llx",
3903 				env->insn_idx, env->cur_hist_ent->linked_regs);
3904 		env->cur_hist_ent->linked_regs = linked_regs;
3905 		return 0;
3906 	}
3907 
3908 	cnt++;
3909 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3910 	p = krealloc(cur->jmp_history, alloc_size, GFP_KERNEL_ACCOUNT);
3911 	if (!p)
3912 		return -ENOMEM;
3913 	cur->jmp_history = p;
3914 
3915 	p = &cur->jmp_history[cnt - 1];
3916 	p->idx = env->insn_idx;
3917 	p->prev_idx = env->prev_insn_idx;
3918 	p->flags = insn_flags;
3919 	p->linked_regs = linked_regs;
3920 	cur->jmp_history_cnt = cnt;
3921 	env->cur_hist_ent = p;
3922 
3923 	return 0;
3924 }
3925 
3926 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3927 						        u32 hist_end, int insn_idx)
3928 {
3929 	if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3930 		return &st->jmp_history[hist_end - 1];
3931 	return NULL;
3932 }
3933 
3934 /* Backtrack one insn at a time. If idx is not at the top of recorded
3935  * history then previous instruction came from straight line execution.
3936  * Return -ENOENT if we exhausted all instructions within given state.
3937  *
3938  * It's legal to have a bit of a looping with the same starting and ending
3939  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3940  * instruction index is the same as state's first_idx doesn't mean we are
3941  * done. If there is still some jump history left, we should keep going. We
3942  * need to take into account that we might have a jump history between given
3943  * state's parent and itself, due to checkpointing. In this case, we'll have
3944  * history entry recording a jump from last instruction of parent state and
3945  * first instruction of given state.
3946  */
3947 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3948 			     u32 *history)
3949 {
3950 	u32 cnt = *history;
3951 
3952 	if (i == st->first_insn_idx) {
3953 		if (cnt == 0)
3954 			return -ENOENT;
3955 		if (cnt == 1 && st->jmp_history[0].idx == i)
3956 			return -ENOENT;
3957 	}
3958 
3959 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3960 		i = st->jmp_history[cnt - 1].prev_idx;
3961 		(*history)--;
3962 	} else {
3963 		i--;
3964 	}
3965 	return i;
3966 }
3967 
3968 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3969 {
3970 	const struct btf_type *func;
3971 	struct btf *desc_btf;
3972 
3973 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3974 		return NULL;
3975 
3976 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3977 	if (IS_ERR(desc_btf))
3978 		return "<error>";
3979 
3980 	func = btf_type_by_id(desc_btf, insn->imm);
3981 	return btf_name_by_offset(desc_btf, func->name_off);
3982 }
3983 
3984 static void verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
3985 {
3986 	const struct bpf_insn_cbs cbs = {
3987 		.cb_call	= disasm_kfunc_name,
3988 		.cb_print	= verbose,
3989 		.private_data	= env,
3990 	};
3991 
3992 	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3993 }
3994 
3995 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3996 {
3997 	bt->frame = frame;
3998 }
3999 
4000 static inline void bt_reset(struct backtrack_state *bt)
4001 {
4002 	struct bpf_verifier_env *env = bt->env;
4003 
4004 	memset(bt, 0, sizeof(*bt));
4005 	bt->env = env;
4006 }
4007 
4008 static inline u32 bt_empty(struct backtrack_state *bt)
4009 {
4010 	u64 mask = 0;
4011 	int i;
4012 
4013 	for (i = 0; i <= bt->frame; i++)
4014 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
4015 
4016 	return mask == 0;
4017 }
4018 
4019 static inline int bt_subprog_enter(struct backtrack_state *bt)
4020 {
4021 	if (bt->frame == MAX_CALL_FRAMES - 1) {
4022 		verifier_bug(bt->env, "subprog enter from frame %d", bt->frame);
4023 		return -EFAULT;
4024 	}
4025 	bt->frame++;
4026 	return 0;
4027 }
4028 
4029 static inline int bt_subprog_exit(struct backtrack_state *bt)
4030 {
4031 	if (bt->frame == 0) {
4032 		verifier_bug(bt->env, "subprog exit from frame 0");
4033 		return -EFAULT;
4034 	}
4035 	bt->frame--;
4036 	return 0;
4037 }
4038 
4039 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4040 {
4041 	bt->reg_masks[frame] |= 1 << reg;
4042 }
4043 
4044 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4045 {
4046 	bt->reg_masks[frame] &= ~(1 << reg);
4047 }
4048 
4049 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
4050 {
4051 	bt_set_frame_reg(bt, bt->frame, reg);
4052 }
4053 
4054 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
4055 {
4056 	bt_clear_frame_reg(bt, bt->frame, reg);
4057 }
4058 
4059 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4060 {
4061 	bt->stack_masks[frame] |= 1ull << slot;
4062 }
4063 
4064 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4065 {
4066 	bt->stack_masks[frame] &= ~(1ull << slot);
4067 }
4068 
4069 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
4070 {
4071 	return bt->reg_masks[frame];
4072 }
4073 
4074 static inline u32 bt_reg_mask(struct backtrack_state *bt)
4075 {
4076 	return bt->reg_masks[bt->frame];
4077 }
4078 
4079 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
4080 {
4081 	return bt->stack_masks[frame];
4082 }
4083 
4084 static inline u64 bt_stack_mask(struct backtrack_state *bt)
4085 {
4086 	return bt->stack_masks[bt->frame];
4087 }
4088 
4089 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
4090 {
4091 	return bt->reg_masks[bt->frame] & (1 << reg);
4092 }
4093 
4094 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
4095 {
4096 	return bt->reg_masks[frame] & (1 << reg);
4097 }
4098 
4099 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
4100 {
4101 	return bt->stack_masks[frame] & (1ull << slot);
4102 }
4103 
4104 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
4105 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
4106 {
4107 	DECLARE_BITMAP(mask, 64);
4108 	bool first = true;
4109 	int i, n;
4110 
4111 	buf[0] = '\0';
4112 
4113 	bitmap_from_u64(mask, reg_mask);
4114 	for_each_set_bit(i, mask, 32) {
4115 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
4116 		first = false;
4117 		buf += n;
4118 		buf_sz -= n;
4119 		if (buf_sz < 0)
4120 			break;
4121 	}
4122 }
4123 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
4124 void bpf_fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
4125 {
4126 	DECLARE_BITMAP(mask, 64);
4127 	bool first = true;
4128 	int i, n;
4129 
4130 	buf[0] = '\0';
4131 
4132 	bitmap_from_u64(mask, stack_mask);
4133 	for_each_set_bit(i, mask, 64) {
4134 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
4135 		first = false;
4136 		buf += n;
4137 		buf_sz -= n;
4138 		if (buf_sz < 0)
4139 			break;
4140 	}
4141 }
4142 
4143 /* If any register R in hist->linked_regs is marked as precise in bt,
4144  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
4145  */
4146 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
4147 {
4148 	struct linked_regs linked_regs;
4149 	bool some_precise = false;
4150 	int i;
4151 
4152 	if (!hist || hist->linked_regs == 0)
4153 		return;
4154 
4155 	linked_regs_unpack(hist->linked_regs, &linked_regs);
4156 	for (i = 0; i < linked_regs.cnt; ++i) {
4157 		struct linked_reg *e = &linked_regs.entries[i];
4158 
4159 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
4160 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
4161 			some_precise = true;
4162 			break;
4163 		}
4164 	}
4165 
4166 	if (!some_precise)
4167 		return;
4168 
4169 	for (i = 0; i < linked_regs.cnt; ++i) {
4170 		struct linked_reg *e = &linked_regs.entries[i];
4171 
4172 		if (e->is_reg)
4173 			bt_set_frame_reg(bt, e->frameno, e->regno);
4174 		else
4175 			bt_set_frame_slot(bt, e->frameno, e->spi);
4176 	}
4177 }
4178 
4179 /* For given verifier state backtrack_insn() is called from the last insn to
4180  * the first insn. Its purpose is to compute a bitmask of registers and
4181  * stack slots that needs precision in the parent verifier state.
4182  *
4183  * @idx is an index of the instruction we are currently processing;
4184  * @subseq_idx is an index of the subsequent instruction that:
4185  *   - *would be* executed next, if jump history is viewed in forward order;
4186  *   - *was* processed previously during backtracking.
4187  */
4188 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
4189 			  struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
4190 {
4191 	struct bpf_insn *insn = env->prog->insnsi + idx;
4192 	u8 class = BPF_CLASS(insn->code);
4193 	u8 opcode = BPF_OP(insn->code);
4194 	u8 mode = BPF_MODE(insn->code);
4195 	u32 dreg = insn->dst_reg;
4196 	u32 sreg = insn->src_reg;
4197 	u32 spi, i, fr;
4198 
4199 	if (insn->code == 0)
4200 		return 0;
4201 	if (env->log.level & BPF_LOG_LEVEL2) {
4202 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
4203 		verbose(env, "mark_precise: frame%d: regs=%s ",
4204 			bt->frame, env->tmp_str_buf);
4205 		bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
4206 		verbose(env, "stack=%s before ", env->tmp_str_buf);
4207 		verbose(env, "%d: ", idx);
4208 		verbose_insn(env, insn);
4209 	}
4210 
4211 	/* If there is a history record that some registers gained range at this insn,
4212 	 * propagate precision marks to those registers, so that bt_is_reg_set()
4213 	 * accounts for these registers.
4214 	 */
4215 	bt_sync_linked_regs(bt, hist);
4216 
4217 	if (class == BPF_ALU || class == BPF_ALU64) {
4218 		if (!bt_is_reg_set(bt, dreg))
4219 			return 0;
4220 		if (opcode == BPF_END || opcode == BPF_NEG) {
4221 			/* sreg is reserved and unused
4222 			 * dreg still need precision before this insn
4223 			 */
4224 			return 0;
4225 		} else if (opcode == BPF_MOV) {
4226 			if (BPF_SRC(insn->code) == BPF_X) {
4227 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
4228 				 * dreg needs precision after this insn
4229 				 * sreg needs precision before this insn
4230 				 */
4231 				bt_clear_reg(bt, dreg);
4232 				if (sreg != BPF_REG_FP)
4233 					bt_set_reg(bt, sreg);
4234 			} else {
4235 				/* dreg = K
4236 				 * dreg needs precision after this insn.
4237 				 * Corresponding register is already marked
4238 				 * as precise=true in this verifier state.
4239 				 * No further markings in parent are necessary
4240 				 */
4241 				bt_clear_reg(bt, dreg);
4242 			}
4243 		} else {
4244 			if (BPF_SRC(insn->code) == BPF_X) {
4245 				/* dreg += sreg
4246 				 * both dreg and sreg need precision
4247 				 * before this insn
4248 				 */
4249 				if (sreg != BPF_REG_FP)
4250 					bt_set_reg(bt, sreg);
4251 			} /* else dreg += K
4252 			   * dreg still needs precision before this insn
4253 			   */
4254 		}
4255 	} else if (class == BPF_LDX || is_atomic_load_insn(insn)) {
4256 		if (!bt_is_reg_set(bt, dreg))
4257 			return 0;
4258 		bt_clear_reg(bt, dreg);
4259 
4260 		/* scalars can only be spilled into stack w/o losing precision.
4261 		 * Load from any other memory can be zero extended.
4262 		 * The desire to keep that precision is already indicated
4263 		 * by 'precise' mark in corresponding register of this state.
4264 		 * No further tracking necessary.
4265 		 */
4266 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4267 			return 0;
4268 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
4269 		 * that [fp - off] slot contains scalar that needs to be
4270 		 * tracked with precision
4271 		 */
4272 		spi = insn_stack_access_spi(hist->flags);
4273 		fr = insn_stack_access_frameno(hist->flags);
4274 		bt_set_frame_slot(bt, fr, spi);
4275 	} else if (class == BPF_STX || class == BPF_ST) {
4276 		if (bt_is_reg_set(bt, dreg))
4277 			/* stx & st shouldn't be using _scalar_ dst_reg
4278 			 * to access memory. It means backtracking
4279 			 * encountered a case of pointer subtraction.
4280 			 */
4281 			return -ENOTSUPP;
4282 		/* scalars can only be spilled into stack */
4283 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4284 			return 0;
4285 		spi = insn_stack_access_spi(hist->flags);
4286 		fr = insn_stack_access_frameno(hist->flags);
4287 		if (!bt_is_frame_slot_set(bt, fr, spi))
4288 			return 0;
4289 		bt_clear_frame_slot(bt, fr, spi);
4290 		if (class == BPF_STX)
4291 			bt_set_reg(bt, sreg);
4292 	} else if (class == BPF_JMP || class == BPF_JMP32) {
4293 		if (bpf_pseudo_call(insn)) {
4294 			int subprog_insn_idx, subprog;
4295 
4296 			subprog_insn_idx = idx + insn->imm + 1;
4297 			subprog = find_subprog(env, subprog_insn_idx);
4298 			if (subprog < 0)
4299 				return -EFAULT;
4300 
4301 			if (subprog_is_global(env, subprog)) {
4302 				/* check that jump history doesn't have any
4303 				 * extra instructions from subprog; the next
4304 				 * instruction after call to global subprog
4305 				 * should be literally next instruction in
4306 				 * caller program
4307 				 */
4308 				verifier_bug_if(idx + 1 != subseq_idx, env,
4309 						"extra insn from subprog");
4310 				/* r1-r5 are invalidated after subprog call,
4311 				 * so for global func call it shouldn't be set
4312 				 * anymore
4313 				 */
4314 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4315 					verifier_bug(env, "global subprog unexpected regs %x",
4316 						     bt_reg_mask(bt));
4317 					return -EFAULT;
4318 				}
4319 				/* global subprog always sets R0 */
4320 				bt_clear_reg(bt, BPF_REG_0);
4321 				return 0;
4322 			} else {
4323 				/* static subprog call instruction, which
4324 				 * means that we are exiting current subprog,
4325 				 * so only r1-r5 could be still requested as
4326 				 * precise, r0 and r6-r10 or any stack slot in
4327 				 * the current frame should be zero by now
4328 				 */
4329 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4330 					verifier_bug(env, "static subprog unexpected regs %x",
4331 						     bt_reg_mask(bt));
4332 					return -EFAULT;
4333 				}
4334 				/* we are now tracking register spills correctly,
4335 				 * so any instance of leftover slots is a bug
4336 				 */
4337 				if (bt_stack_mask(bt) != 0) {
4338 					verifier_bug(env,
4339 						     "static subprog leftover stack slots %llx",
4340 						     bt_stack_mask(bt));
4341 					return -EFAULT;
4342 				}
4343 				/* propagate r1-r5 to the caller */
4344 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
4345 					if (bt_is_reg_set(bt, i)) {
4346 						bt_clear_reg(bt, i);
4347 						bt_set_frame_reg(bt, bt->frame - 1, i);
4348 					}
4349 				}
4350 				if (bt_subprog_exit(bt))
4351 					return -EFAULT;
4352 				return 0;
4353 			}
4354 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
4355 			/* exit from callback subprog to callback-calling helper or
4356 			 * kfunc call. Use idx/subseq_idx check to discern it from
4357 			 * straight line code backtracking.
4358 			 * Unlike the subprog call handling above, we shouldn't
4359 			 * propagate precision of r1-r5 (if any requested), as they are
4360 			 * not actually arguments passed directly to callback subprogs
4361 			 */
4362 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4363 				verifier_bug(env, "callback unexpected regs %x",
4364 					     bt_reg_mask(bt));
4365 				return -EFAULT;
4366 			}
4367 			if (bt_stack_mask(bt) != 0) {
4368 				verifier_bug(env, "callback leftover stack slots %llx",
4369 					     bt_stack_mask(bt));
4370 				return -EFAULT;
4371 			}
4372 			/* clear r1-r5 in callback subprog's mask */
4373 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4374 				bt_clear_reg(bt, i);
4375 			if (bt_subprog_exit(bt))
4376 				return -EFAULT;
4377 			return 0;
4378 		} else if (opcode == BPF_CALL) {
4379 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
4380 			 * catch this error later. Make backtracking conservative
4381 			 * with ENOTSUPP.
4382 			 */
4383 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
4384 				return -ENOTSUPP;
4385 			/* regular helper call sets R0 */
4386 			bt_clear_reg(bt, BPF_REG_0);
4387 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4388 				/* if backtracking was looking for registers R1-R5
4389 				 * they should have been found already.
4390 				 */
4391 				verifier_bug(env, "backtracking call unexpected regs %x",
4392 					     bt_reg_mask(bt));
4393 				return -EFAULT;
4394 			}
4395 		} else if (opcode == BPF_EXIT) {
4396 			bool r0_precise;
4397 
4398 			/* Backtracking to a nested function call, 'idx' is a part of
4399 			 * the inner frame 'subseq_idx' is a part of the outer frame.
4400 			 * In case of a regular function call, instructions giving
4401 			 * precision to registers R1-R5 should have been found already.
4402 			 * In case of a callback, it is ok to have R1-R5 marked for
4403 			 * backtracking, as these registers are set by the function
4404 			 * invoking callback.
4405 			 */
4406 			if (subseq_idx >= 0 && bpf_calls_callback(env, subseq_idx))
4407 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4408 					bt_clear_reg(bt, i);
4409 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4410 				verifier_bug(env, "backtracking exit unexpected regs %x",
4411 					     bt_reg_mask(bt));
4412 				return -EFAULT;
4413 			}
4414 
4415 			/* BPF_EXIT in subprog or callback always returns
4416 			 * right after the call instruction, so by checking
4417 			 * whether the instruction at subseq_idx-1 is subprog
4418 			 * call or not we can distinguish actual exit from
4419 			 * *subprog* from exit from *callback*. In the former
4420 			 * case, we need to propagate r0 precision, if
4421 			 * necessary. In the former we never do that.
4422 			 */
4423 			r0_precise = subseq_idx - 1 >= 0 &&
4424 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
4425 				     bt_is_reg_set(bt, BPF_REG_0);
4426 
4427 			bt_clear_reg(bt, BPF_REG_0);
4428 			if (bt_subprog_enter(bt))
4429 				return -EFAULT;
4430 
4431 			if (r0_precise)
4432 				bt_set_reg(bt, BPF_REG_0);
4433 			/* r6-r9 and stack slots will stay set in caller frame
4434 			 * bitmasks until we return back from callee(s)
4435 			 */
4436 			return 0;
4437 		} else if (BPF_SRC(insn->code) == BPF_X) {
4438 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
4439 				return 0;
4440 			/* dreg <cond> sreg
4441 			 * Both dreg and sreg need precision before
4442 			 * this insn. If only sreg was marked precise
4443 			 * before it would be equally necessary to
4444 			 * propagate it to dreg.
4445 			 */
4446 			if (!hist || !(hist->flags & INSN_F_SRC_REG_STACK))
4447 				bt_set_reg(bt, sreg);
4448 			if (!hist || !(hist->flags & INSN_F_DST_REG_STACK))
4449 				bt_set_reg(bt, dreg);
4450 		} else if (BPF_SRC(insn->code) == BPF_K) {
4451 			 /* dreg <cond> K
4452 			  * Only dreg still needs precision before
4453 			  * this insn, so for the K-based conditional
4454 			  * there is nothing new to be marked.
4455 			  */
4456 		}
4457 	} else if (class == BPF_LD) {
4458 		if (!bt_is_reg_set(bt, dreg))
4459 			return 0;
4460 		bt_clear_reg(bt, dreg);
4461 		/* It's ld_imm64 or ld_abs or ld_ind.
4462 		 * For ld_imm64 no further tracking of precision
4463 		 * into parent is necessary
4464 		 */
4465 		if (mode == BPF_IND || mode == BPF_ABS)
4466 			/* to be analyzed */
4467 			return -ENOTSUPP;
4468 	}
4469 	/* Propagate precision marks to linked registers, to account for
4470 	 * registers marked as precise in this function.
4471 	 */
4472 	bt_sync_linked_regs(bt, hist);
4473 	return 0;
4474 }
4475 
4476 /* the scalar precision tracking algorithm:
4477  * . at the start all registers have precise=false.
4478  * . scalar ranges are tracked as normal through alu and jmp insns.
4479  * . once precise value of the scalar register is used in:
4480  *   .  ptr + scalar alu
4481  *   . if (scalar cond K|scalar)
4482  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
4483  *   backtrack through the verifier states and mark all registers and
4484  *   stack slots with spilled constants that these scalar registers
4485  *   should be precise.
4486  * . during state pruning two registers (or spilled stack slots)
4487  *   are equivalent if both are not precise.
4488  *
4489  * Note the verifier cannot simply walk register parentage chain,
4490  * since many different registers and stack slots could have been
4491  * used to compute single precise scalar.
4492  *
4493  * The approach of starting with precise=true for all registers and then
4494  * backtrack to mark a register as not precise when the verifier detects
4495  * that program doesn't care about specific value (e.g., when helper
4496  * takes register as ARG_ANYTHING parameter) is not safe.
4497  *
4498  * It's ok to walk single parentage chain of the verifier states.
4499  * It's possible that this backtracking will go all the way till 1st insn.
4500  * All other branches will be explored for needing precision later.
4501  *
4502  * The backtracking needs to deal with cases like:
4503  *   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)
4504  * r9 -= r8
4505  * r5 = r9
4506  * if r5 > 0x79f goto pc+7
4507  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4508  * r5 += 1
4509  * ...
4510  * call bpf_perf_event_output#25
4511  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4512  *
4513  * and this case:
4514  * r6 = 1
4515  * call foo // uses callee's r6 inside to compute r0
4516  * r0 += r6
4517  * if r0 == 0 goto
4518  *
4519  * to track above reg_mask/stack_mask needs to be independent for each frame.
4520  *
4521  * Also if parent's curframe > frame where backtracking started,
4522  * the verifier need to mark registers in both frames, otherwise callees
4523  * may incorrectly prune callers. This is similar to
4524  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4525  *
4526  * For now backtracking falls back into conservative marking.
4527  */
4528 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4529 				     struct bpf_verifier_state *st)
4530 {
4531 	struct bpf_func_state *func;
4532 	struct bpf_reg_state *reg;
4533 	int i, j;
4534 
4535 	if (env->log.level & BPF_LOG_LEVEL2) {
4536 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4537 			st->curframe);
4538 	}
4539 
4540 	/* big hammer: mark all scalars precise in this path.
4541 	 * pop_stack may still get !precise scalars.
4542 	 * We also skip current state and go straight to first parent state,
4543 	 * because precision markings in current non-checkpointed state are
4544 	 * not needed. See why in the comment in __mark_chain_precision below.
4545 	 */
4546 	for (st = st->parent; st; st = st->parent) {
4547 		for (i = 0; i <= st->curframe; i++) {
4548 			func = st->frame[i];
4549 			for (j = 0; j < BPF_REG_FP; j++) {
4550 				reg = &func->regs[j];
4551 				if (reg->type != SCALAR_VALUE || reg->precise)
4552 					continue;
4553 				reg->precise = true;
4554 				if (env->log.level & BPF_LOG_LEVEL2) {
4555 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4556 						i, j);
4557 				}
4558 			}
4559 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4560 				if (!is_spilled_reg(&func->stack[j]))
4561 					continue;
4562 				reg = &func->stack[j].spilled_ptr;
4563 				if (reg->type != SCALAR_VALUE || reg->precise)
4564 					continue;
4565 				reg->precise = true;
4566 				if (env->log.level & BPF_LOG_LEVEL2) {
4567 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4568 						i, -(j + 1) * 8);
4569 				}
4570 			}
4571 		}
4572 	}
4573 }
4574 
4575 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4576 {
4577 	struct bpf_func_state *func;
4578 	struct bpf_reg_state *reg;
4579 	int i, j;
4580 
4581 	for (i = 0; i <= st->curframe; i++) {
4582 		func = st->frame[i];
4583 		for (j = 0; j < BPF_REG_FP; j++) {
4584 			reg = &func->regs[j];
4585 			if (reg->type != SCALAR_VALUE)
4586 				continue;
4587 			reg->precise = false;
4588 		}
4589 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4590 			if (!is_spilled_reg(&func->stack[j]))
4591 				continue;
4592 			reg = &func->stack[j].spilled_ptr;
4593 			if (reg->type != SCALAR_VALUE)
4594 				continue;
4595 			reg->precise = false;
4596 		}
4597 	}
4598 }
4599 
4600 /*
4601  * __mark_chain_precision() backtracks BPF program instruction sequence and
4602  * chain of verifier states making sure that register *regno* (if regno >= 0)
4603  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4604  * SCALARS, as well as any other registers and slots that contribute to
4605  * a tracked state of given registers/stack slots, depending on specific BPF
4606  * assembly instructions (see backtrack_insns() for exact instruction handling
4607  * logic). This backtracking relies on recorded jmp_history and is able to
4608  * traverse entire chain of parent states. This process ends only when all the
4609  * necessary registers/slots and their transitive dependencies are marked as
4610  * precise.
4611  *
4612  * One important and subtle aspect is that precise marks *do not matter* in
4613  * the currently verified state (current state). It is important to understand
4614  * why this is the case.
4615  *
4616  * First, note that current state is the state that is not yet "checkpointed",
4617  * i.e., it is not yet put into env->explored_states, and it has no children
4618  * states as well. It's ephemeral, and can end up either a) being discarded if
4619  * compatible explored state is found at some point or BPF_EXIT instruction is
4620  * reached or b) checkpointed and put into env->explored_states, branching out
4621  * into one or more children states.
4622  *
4623  * In the former case, precise markings in current state are completely
4624  * ignored by state comparison code (see regsafe() for details). Only
4625  * checkpointed ("old") state precise markings are important, and if old
4626  * state's register/slot is precise, regsafe() assumes current state's
4627  * register/slot as precise and checks value ranges exactly and precisely. If
4628  * states turn out to be compatible, current state's necessary precise
4629  * markings and any required parent states' precise markings are enforced
4630  * after the fact with propagate_precision() logic, after the fact. But it's
4631  * important to realize that in this case, even after marking current state
4632  * registers/slots as precise, we immediately discard current state. So what
4633  * actually matters is any of the precise markings propagated into current
4634  * state's parent states, which are always checkpointed (due to b) case above).
4635  * As such, for scenario a) it doesn't matter if current state has precise
4636  * markings set or not.
4637  *
4638  * Now, for the scenario b), checkpointing and forking into child(ren)
4639  * state(s). Note that before current state gets to checkpointing step, any
4640  * processed instruction always assumes precise SCALAR register/slot
4641  * knowledge: if precise value or range is useful to prune jump branch, BPF
4642  * verifier takes this opportunity enthusiastically. Similarly, when
4643  * register's value is used to calculate offset or memory address, exact
4644  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4645  * what we mentioned above about state comparison ignoring precise markings
4646  * during state comparison, BPF verifier ignores and also assumes precise
4647  * markings *at will* during instruction verification process. But as verifier
4648  * assumes precision, it also propagates any precision dependencies across
4649  * parent states, which are not yet finalized, so can be further restricted
4650  * based on new knowledge gained from restrictions enforced by their children
4651  * states. This is so that once those parent states are finalized, i.e., when
4652  * they have no more active children state, state comparison logic in
4653  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4654  * required for correctness.
4655  *
4656  * To build a bit more intuition, note also that once a state is checkpointed,
4657  * the path we took to get to that state is not important. This is crucial
4658  * property for state pruning. When state is checkpointed and finalized at
4659  * some instruction index, it can be correctly and safely used to "short
4660  * circuit" any *compatible* state that reaches exactly the same instruction
4661  * index. I.e., if we jumped to that instruction from a completely different
4662  * code path than original finalized state was derived from, it doesn't
4663  * matter, current state can be discarded because from that instruction
4664  * forward having a compatible state will ensure we will safely reach the
4665  * exit. States describe preconditions for further exploration, but completely
4666  * forget the history of how we got here.
4667  *
4668  * This also means that even if we needed precise SCALAR range to get to
4669  * finalized state, but from that point forward *that same* SCALAR register is
4670  * never used in a precise context (i.e., it's precise value is not needed for
4671  * correctness), it's correct and safe to mark such register as "imprecise"
4672  * (i.e., precise marking set to false). This is what we rely on when we do
4673  * not set precise marking in current state. If no child state requires
4674  * precision for any given SCALAR register, it's safe to dictate that it can
4675  * be imprecise. If any child state does require this register to be precise,
4676  * we'll mark it precise later retroactively during precise markings
4677  * propagation from child state to parent states.
4678  *
4679  * Skipping precise marking setting in current state is a mild version of
4680  * relying on the above observation. But we can utilize this property even
4681  * more aggressively by proactively forgetting any precise marking in the
4682  * current state (which we inherited from the parent state), right before we
4683  * checkpoint it and branch off into new child state. This is done by
4684  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4685  * finalized states which help in short circuiting more future states.
4686  */
4687 static int __mark_chain_precision(struct bpf_verifier_env *env,
4688 				  struct bpf_verifier_state *starting_state,
4689 				  int regno,
4690 				  bool *changed)
4691 {
4692 	struct bpf_verifier_state *st = starting_state;
4693 	struct backtrack_state *bt = &env->bt;
4694 	int first_idx = st->first_insn_idx;
4695 	int last_idx = starting_state->insn_idx;
4696 	int subseq_idx = -1;
4697 	struct bpf_func_state *func;
4698 	bool tmp, skip_first = true;
4699 	struct bpf_reg_state *reg;
4700 	int i, fr, err;
4701 
4702 	if (!env->bpf_capable)
4703 		return 0;
4704 
4705 	changed = changed ?: &tmp;
4706 	/* set frame number from which we are starting to backtrack */
4707 	bt_init(bt, starting_state->curframe);
4708 
4709 	/* Do sanity checks against current state of register and/or stack
4710 	 * slot, but don't set precise flag in current state, as precision
4711 	 * tracking in the current state is unnecessary.
4712 	 */
4713 	func = st->frame[bt->frame];
4714 	if (regno >= 0) {
4715 		reg = &func->regs[regno];
4716 		if (reg->type != SCALAR_VALUE) {
4717 			verifier_bug(env, "backtracking misuse");
4718 			return -EFAULT;
4719 		}
4720 		bt_set_reg(bt, regno);
4721 	}
4722 
4723 	if (bt_empty(bt))
4724 		return 0;
4725 
4726 	for (;;) {
4727 		DECLARE_BITMAP(mask, 64);
4728 		u32 history = st->jmp_history_cnt;
4729 		struct bpf_jmp_history_entry *hist;
4730 
4731 		if (env->log.level & BPF_LOG_LEVEL2) {
4732 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4733 				bt->frame, last_idx, first_idx, subseq_idx);
4734 		}
4735 
4736 		if (last_idx < 0) {
4737 			/* we are at the entry into subprog, which
4738 			 * is expected for global funcs, but only if
4739 			 * requested precise registers are R1-R5
4740 			 * (which are global func's input arguments)
4741 			 */
4742 			if (st->curframe == 0 &&
4743 			    st->frame[0]->subprogno > 0 &&
4744 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4745 			    bt_stack_mask(bt) == 0 &&
4746 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4747 				bitmap_from_u64(mask, bt_reg_mask(bt));
4748 				for_each_set_bit(i, mask, 32) {
4749 					reg = &st->frame[0]->regs[i];
4750 					bt_clear_reg(bt, i);
4751 					if (reg->type == SCALAR_VALUE) {
4752 						reg->precise = true;
4753 						*changed = true;
4754 					}
4755 				}
4756 				return 0;
4757 			}
4758 
4759 			verifier_bug(env, "backtracking func entry subprog %d reg_mask %x stack_mask %llx",
4760 				     st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4761 			return -EFAULT;
4762 		}
4763 
4764 		for (i = last_idx;;) {
4765 			if (skip_first) {
4766 				err = 0;
4767 				skip_first = false;
4768 			} else {
4769 				hist = get_jmp_hist_entry(st, history, i);
4770 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4771 			}
4772 			if (err == -ENOTSUPP) {
4773 				mark_all_scalars_precise(env, starting_state);
4774 				bt_reset(bt);
4775 				return 0;
4776 			} else if (err) {
4777 				return err;
4778 			}
4779 			if (bt_empty(bt))
4780 				/* Found assignment(s) into tracked register in this state.
4781 				 * Since this state is already marked, just return.
4782 				 * Nothing to be tracked further in the parent state.
4783 				 */
4784 				return 0;
4785 			subseq_idx = i;
4786 			i = get_prev_insn_idx(st, i, &history);
4787 			if (i == -ENOENT)
4788 				break;
4789 			if (i >= env->prog->len) {
4790 				/* This can happen if backtracking reached insn 0
4791 				 * and there are still reg_mask or stack_mask
4792 				 * to backtrack.
4793 				 * It means the backtracking missed the spot where
4794 				 * particular register was initialized with a constant.
4795 				 */
4796 				verifier_bug(env, "backtracking idx %d", i);
4797 				return -EFAULT;
4798 			}
4799 		}
4800 		st = st->parent;
4801 		if (!st)
4802 			break;
4803 
4804 		for (fr = bt->frame; fr >= 0; fr--) {
4805 			func = st->frame[fr];
4806 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4807 			for_each_set_bit(i, mask, 32) {
4808 				reg = &func->regs[i];
4809 				if (reg->type != SCALAR_VALUE) {
4810 					bt_clear_frame_reg(bt, fr, i);
4811 					continue;
4812 				}
4813 				if (reg->precise) {
4814 					bt_clear_frame_reg(bt, fr, i);
4815 				} else {
4816 					reg->precise = true;
4817 					*changed = true;
4818 				}
4819 			}
4820 
4821 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4822 			for_each_set_bit(i, mask, 64) {
4823 				if (verifier_bug_if(i >= func->allocated_stack / BPF_REG_SIZE,
4824 						    env, "stack slot %d, total slots %d",
4825 						    i, func->allocated_stack / BPF_REG_SIZE))
4826 					return -EFAULT;
4827 
4828 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4829 					bt_clear_frame_slot(bt, fr, i);
4830 					continue;
4831 				}
4832 				reg = &func->stack[i].spilled_ptr;
4833 				if (reg->precise) {
4834 					bt_clear_frame_slot(bt, fr, i);
4835 				} else {
4836 					reg->precise = true;
4837 					*changed = true;
4838 				}
4839 			}
4840 			if (env->log.level & BPF_LOG_LEVEL2) {
4841 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4842 					     bt_frame_reg_mask(bt, fr));
4843 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4844 					fr, env->tmp_str_buf);
4845 				bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4846 					       bt_frame_stack_mask(bt, fr));
4847 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4848 				print_verifier_state(env, st, fr, true);
4849 			}
4850 		}
4851 
4852 		if (bt_empty(bt))
4853 			return 0;
4854 
4855 		subseq_idx = first_idx;
4856 		last_idx = st->last_insn_idx;
4857 		first_idx = st->first_insn_idx;
4858 	}
4859 
4860 	/* if we still have requested precise regs or slots, we missed
4861 	 * something (e.g., stack access through non-r10 register), so
4862 	 * fallback to marking all precise
4863 	 */
4864 	if (!bt_empty(bt)) {
4865 		mark_all_scalars_precise(env, starting_state);
4866 		bt_reset(bt);
4867 	}
4868 
4869 	return 0;
4870 }
4871 
4872 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4873 {
4874 	return __mark_chain_precision(env, env->cur_state, regno, NULL);
4875 }
4876 
4877 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4878  * desired reg and stack masks across all relevant frames
4879  */
4880 static int mark_chain_precision_batch(struct bpf_verifier_env *env,
4881 				      struct bpf_verifier_state *starting_state)
4882 {
4883 	return __mark_chain_precision(env, starting_state, -1, NULL);
4884 }
4885 
4886 static bool is_spillable_regtype(enum bpf_reg_type type)
4887 {
4888 	switch (base_type(type)) {
4889 	case PTR_TO_MAP_VALUE:
4890 	case PTR_TO_STACK:
4891 	case PTR_TO_CTX:
4892 	case PTR_TO_PACKET:
4893 	case PTR_TO_PACKET_META:
4894 	case PTR_TO_PACKET_END:
4895 	case PTR_TO_FLOW_KEYS:
4896 	case CONST_PTR_TO_MAP:
4897 	case PTR_TO_SOCKET:
4898 	case PTR_TO_SOCK_COMMON:
4899 	case PTR_TO_TCP_SOCK:
4900 	case PTR_TO_XDP_SOCK:
4901 	case PTR_TO_BTF_ID:
4902 	case PTR_TO_BUF:
4903 	case PTR_TO_MEM:
4904 	case PTR_TO_FUNC:
4905 	case PTR_TO_MAP_KEY:
4906 	case PTR_TO_ARENA:
4907 		return true;
4908 	default:
4909 		return false;
4910 	}
4911 }
4912 
4913 /* Does this register contain a constant zero? */
4914 static bool register_is_null(struct bpf_reg_state *reg)
4915 {
4916 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4917 }
4918 
4919 /* check if register is a constant scalar value */
4920 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4921 {
4922 	return reg->type == SCALAR_VALUE &&
4923 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4924 }
4925 
4926 /* assuming is_reg_const() is true, return constant value of a register */
4927 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4928 {
4929 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4930 }
4931 
4932 static bool __is_pointer_value(bool allow_ptr_leaks,
4933 			       const struct bpf_reg_state *reg)
4934 {
4935 	if (allow_ptr_leaks)
4936 		return false;
4937 
4938 	return reg->type != SCALAR_VALUE;
4939 }
4940 
4941 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4942 					struct bpf_reg_state *src_reg)
4943 {
4944 	if (src_reg->type != SCALAR_VALUE)
4945 		return;
4946 
4947 	if (src_reg->id & BPF_ADD_CONST) {
4948 		/*
4949 		 * The verifier is processing rX = rY insn and
4950 		 * rY->id has special linked register already.
4951 		 * Cleared it, since multiple rX += const are not supported.
4952 		 */
4953 		src_reg->id = 0;
4954 		src_reg->off = 0;
4955 	}
4956 
4957 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
4958 		/* Ensure that src_reg has a valid ID that will be copied to
4959 		 * dst_reg and then will be used by sync_linked_regs() to
4960 		 * propagate min/max range.
4961 		 */
4962 		src_reg->id = ++env->id_gen;
4963 }
4964 
4965 /* Copy src state preserving dst->parent and dst->live fields */
4966 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4967 {
4968 	*dst = *src;
4969 }
4970 
4971 static void save_register_state(struct bpf_verifier_env *env,
4972 				struct bpf_func_state *state,
4973 				int spi, struct bpf_reg_state *reg,
4974 				int size)
4975 {
4976 	int i;
4977 
4978 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4979 
4980 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4981 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4982 
4983 	/* size < 8 bytes spill */
4984 	for (; i; i--)
4985 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4986 }
4987 
4988 static bool is_bpf_st_mem(struct bpf_insn *insn)
4989 {
4990 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4991 }
4992 
4993 static int get_reg_width(struct bpf_reg_state *reg)
4994 {
4995 	return fls64(reg->umax_value);
4996 }
4997 
4998 /* See comment for mark_fastcall_pattern_for_call() */
4999 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
5000 					  struct bpf_func_state *state, int insn_idx, int off)
5001 {
5002 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
5003 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
5004 	int i;
5005 
5006 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
5007 		return;
5008 	/* access to the region [max_stack_depth .. fastcall_stack_off)
5009 	 * from something that is not a part of the fastcall pattern,
5010 	 * disable fastcall rewrites for current subprogram by setting
5011 	 * fastcall_stack_off to a value smaller than any possible offset.
5012 	 */
5013 	subprog->fastcall_stack_off = S16_MIN;
5014 	/* reset fastcall aux flags within subprogram,
5015 	 * happens at most once per subprogram
5016 	 */
5017 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
5018 		aux[i].fastcall_spills_num = 0;
5019 		aux[i].fastcall_pattern = 0;
5020 	}
5021 }
5022 
5023 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
5024  * stack boundary and alignment are checked in check_mem_access()
5025  */
5026 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
5027 				       /* stack frame we're writing to */
5028 				       struct bpf_func_state *state,
5029 				       int off, int size, int value_regno,
5030 				       int insn_idx)
5031 {
5032 	struct bpf_func_state *cur; /* state of the current function */
5033 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
5034 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5035 	struct bpf_reg_state *reg = NULL;
5036 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
5037 
5038 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
5039 	 * so it's aligned access and [off, off + size) are within stack limits
5040 	 */
5041 	if (!env->allow_ptr_leaks &&
5042 	    is_spilled_reg(&state->stack[spi]) &&
5043 	    !is_spilled_scalar_reg(&state->stack[spi]) &&
5044 	    size != BPF_REG_SIZE) {
5045 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
5046 		return -EACCES;
5047 	}
5048 
5049 	cur = env->cur_state->frame[env->cur_state->curframe];
5050 	if (value_regno >= 0)
5051 		reg = &cur->regs[value_regno];
5052 	if (!env->bypass_spec_v4) {
5053 		bool sanitize = reg && is_spillable_regtype(reg->type);
5054 
5055 		for (i = 0; i < size; i++) {
5056 			u8 type = state->stack[spi].slot_type[i];
5057 
5058 			if (type != STACK_MISC && type != STACK_ZERO) {
5059 				sanitize = true;
5060 				break;
5061 			}
5062 		}
5063 
5064 		if (sanitize)
5065 			env->insn_aux_data[insn_idx].nospec_result = true;
5066 	}
5067 
5068 	err = destroy_if_dynptr_stack_slot(env, state, spi);
5069 	if (err)
5070 		return err;
5071 
5072 	if (!(off % BPF_REG_SIZE) && size == BPF_REG_SIZE) {
5073 		/* only mark the slot as written if all 8 bytes were written
5074 		 * otherwise read propagation may incorrectly stop too soon
5075 		 * when stack slots are partially written.
5076 		 * This heuristic means that read propagation will be
5077 		 * conservative, since it will add reg_live_read marks
5078 		 * to stack slots all the way to first state when programs
5079 		 * writes+reads less than 8 bytes
5080 		 */
5081 		bpf_mark_stack_write(env, state->frameno, BIT(spi));
5082 	}
5083 
5084 	check_fastcall_stack_contract(env, state, insn_idx, off);
5085 	mark_stack_slot_scratched(env, spi);
5086 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
5087 		bool reg_value_fits;
5088 
5089 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
5090 		/* Make sure that reg had an ID to build a relation on spill. */
5091 		if (reg_value_fits)
5092 			assign_scalar_id_before_mov(env, reg);
5093 		save_register_state(env, state, spi, reg, size);
5094 		/* Break the relation on a narrowing spill. */
5095 		if (!reg_value_fits)
5096 			state->stack[spi].spilled_ptr.id = 0;
5097 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
5098 		   env->bpf_capable) {
5099 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
5100 
5101 		memset(tmp_reg, 0, sizeof(*tmp_reg));
5102 		__mark_reg_known(tmp_reg, insn->imm);
5103 		tmp_reg->type = SCALAR_VALUE;
5104 		save_register_state(env, state, spi, tmp_reg, size);
5105 	} else if (reg && is_spillable_regtype(reg->type)) {
5106 		/* register containing pointer is being spilled into stack */
5107 		if (size != BPF_REG_SIZE) {
5108 			verbose_linfo(env, insn_idx, "; ");
5109 			verbose(env, "invalid size of register spill\n");
5110 			return -EACCES;
5111 		}
5112 		if (state != cur && reg->type == PTR_TO_STACK) {
5113 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
5114 			return -EINVAL;
5115 		}
5116 		save_register_state(env, state, spi, reg, size);
5117 	} else {
5118 		u8 type = STACK_MISC;
5119 
5120 		/* regular write of data into stack destroys any spilled ptr */
5121 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5122 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
5123 		if (is_stack_slot_special(&state->stack[spi]))
5124 			for (i = 0; i < BPF_REG_SIZE; i++)
5125 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
5126 
5127 		/* when we zero initialize stack slots mark them as such */
5128 		if ((reg && register_is_null(reg)) ||
5129 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
5130 			/* STACK_ZERO case happened because register spill
5131 			 * wasn't properly aligned at the stack slot boundary,
5132 			 * so it's not a register spill anymore; force
5133 			 * originating register to be precise to make
5134 			 * STACK_ZERO correct for subsequent states
5135 			 */
5136 			err = mark_chain_precision(env, value_regno);
5137 			if (err)
5138 				return err;
5139 			type = STACK_ZERO;
5140 		}
5141 
5142 		/* Mark slots affected by this stack write. */
5143 		for (i = 0; i < size; i++)
5144 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
5145 		insn_flags = 0; /* not a register spill */
5146 	}
5147 
5148 	if (insn_flags)
5149 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5150 	return 0;
5151 }
5152 
5153 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
5154  * known to contain a variable offset.
5155  * This function checks whether the write is permitted and conservatively
5156  * tracks the effects of the write, considering that each stack slot in the
5157  * dynamic range is potentially written to.
5158  *
5159  * 'off' includes 'regno->off'.
5160  * 'value_regno' can be -1, meaning that an unknown value is being written to
5161  * the stack.
5162  *
5163  * Spilled pointers in range are not marked as written because we don't know
5164  * what's going to be actually written. This means that read propagation for
5165  * future reads cannot be terminated by this write.
5166  *
5167  * For privileged programs, uninitialized stack slots are considered
5168  * initialized by this write (even though we don't know exactly what offsets
5169  * are going to be written to). The idea is that we don't want the verifier to
5170  * reject future reads that access slots written to through variable offsets.
5171  */
5172 static int check_stack_write_var_off(struct bpf_verifier_env *env,
5173 				     /* func where register points to */
5174 				     struct bpf_func_state *state,
5175 				     int ptr_regno, int off, int size,
5176 				     int value_regno, int insn_idx)
5177 {
5178 	struct bpf_func_state *cur; /* state of the current function */
5179 	int min_off, max_off;
5180 	int i, err;
5181 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
5182 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5183 	bool writing_zero = false;
5184 	/* set if the fact that we're writing a zero is used to let any
5185 	 * stack slots remain STACK_ZERO
5186 	 */
5187 	bool zero_used = false;
5188 
5189 	cur = env->cur_state->frame[env->cur_state->curframe];
5190 	ptr_reg = &cur->regs[ptr_regno];
5191 	min_off = ptr_reg->smin_value + off;
5192 	max_off = ptr_reg->smax_value + off + size;
5193 	if (value_regno >= 0)
5194 		value_reg = &cur->regs[value_regno];
5195 	if ((value_reg && register_is_null(value_reg)) ||
5196 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
5197 		writing_zero = true;
5198 
5199 	for (i = min_off; i < max_off; i++) {
5200 		int spi;
5201 
5202 		spi = __get_spi(i);
5203 		err = destroy_if_dynptr_stack_slot(env, state, spi);
5204 		if (err)
5205 			return err;
5206 	}
5207 
5208 	check_fastcall_stack_contract(env, state, insn_idx, min_off);
5209 	/* Variable offset writes destroy any spilled pointers in range. */
5210 	for (i = min_off; i < max_off; i++) {
5211 		u8 new_type, *stype;
5212 		int slot, spi;
5213 
5214 		slot = -i - 1;
5215 		spi = slot / BPF_REG_SIZE;
5216 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5217 		mark_stack_slot_scratched(env, spi);
5218 
5219 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
5220 			/* Reject the write if range we may write to has not
5221 			 * been initialized beforehand. If we didn't reject
5222 			 * here, the ptr status would be erased below (even
5223 			 * though not all slots are actually overwritten),
5224 			 * possibly opening the door to leaks.
5225 			 *
5226 			 * We do however catch STACK_INVALID case below, and
5227 			 * only allow reading possibly uninitialized memory
5228 			 * later for CAP_PERFMON, as the write may not happen to
5229 			 * that slot.
5230 			 */
5231 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
5232 				insn_idx, i);
5233 			return -EINVAL;
5234 		}
5235 
5236 		/* If writing_zero and the spi slot contains a spill of value 0,
5237 		 * maintain the spill type.
5238 		 */
5239 		if (writing_zero && *stype == STACK_SPILL &&
5240 		    is_spilled_scalar_reg(&state->stack[spi])) {
5241 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
5242 
5243 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
5244 				zero_used = true;
5245 				continue;
5246 			}
5247 		}
5248 
5249 		/* Erase all other spilled pointers. */
5250 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5251 
5252 		/* Update the slot type. */
5253 		new_type = STACK_MISC;
5254 		if (writing_zero && *stype == STACK_ZERO) {
5255 			new_type = STACK_ZERO;
5256 			zero_used = true;
5257 		}
5258 		/* If the slot is STACK_INVALID, we check whether it's OK to
5259 		 * pretend that it will be initialized by this write. The slot
5260 		 * might not actually be written to, and so if we mark it as
5261 		 * initialized future reads might leak uninitialized memory.
5262 		 * For privileged programs, we will accept such reads to slots
5263 		 * that may or may not be written because, if we're reject
5264 		 * them, the error would be too confusing.
5265 		 */
5266 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
5267 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
5268 					insn_idx, i);
5269 			return -EINVAL;
5270 		}
5271 		*stype = new_type;
5272 	}
5273 	if (zero_used) {
5274 		/* backtracking doesn't work for STACK_ZERO yet. */
5275 		err = mark_chain_precision(env, value_regno);
5276 		if (err)
5277 			return err;
5278 	}
5279 	return 0;
5280 }
5281 
5282 /* When register 'dst_regno' is assigned some values from stack[min_off,
5283  * max_off), we set the register's type according to the types of the
5284  * respective stack slots. If all the stack values are known to be zeros, then
5285  * so is the destination reg. Otherwise, the register is considered to be
5286  * SCALAR. This function does not deal with register filling; the caller must
5287  * ensure that all spilled registers in the stack range have been marked as
5288  * read.
5289  */
5290 static void mark_reg_stack_read(struct bpf_verifier_env *env,
5291 				/* func where src register points to */
5292 				struct bpf_func_state *ptr_state,
5293 				int min_off, int max_off, int dst_regno)
5294 {
5295 	struct bpf_verifier_state *vstate = env->cur_state;
5296 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5297 	int i, slot, spi;
5298 	u8 *stype;
5299 	int zeros = 0;
5300 
5301 	for (i = min_off; i < max_off; i++) {
5302 		slot = -i - 1;
5303 		spi = slot / BPF_REG_SIZE;
5304 		mark_stack_slot_scratched(env, spi);
5305 		stype = ptr_state->stack[spi].slot_type;
5306 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
5307 			break;
5308 		zeros++;
5309 	}
5310 	if (zeros == max_off - min_off) {
5311 		/* Any access_size read into register is zero extended,
5312 		 * so the whole register == const_zero.
5313 		 */
5314 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
5315 	} else {
5316 		/* have read misc data from the stack */
5317 		mark_reg_unknown(env, state->regs, dst_regno);
5318 	}
5319 }
5320 
5321 /* Read the stack at 'off' and put the results into the register indicated by
5322  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
5323  * spilled reg.
5324  *
5325  * 'dst_regno' can be -1, meaning that the read value is not going to a
5326  * register.
5327  *
5328  * The access is assumed to be within the current stack bounds.
5329  */
5330 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
5331 				      /* func where src register points to */
5332 				      struct bpf_func_state *reg_state,
5333 				      int off, int size, int dst_regno)
5334 {
5335 	struct bpf_verifier_state *vstate = env->cur_state;
5336 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5337 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
5338 	struct bpf_reg_state *reg;
5339 	u8 *stype, type;
5340 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
5341 	int err;
5342 
5343 	stype = reg_state->stack[spi].slot_type;
5344 	reg = &reg_state->stack[spi].spilled_ptr;
5345 
5346 	mark_stack_slot_scratched(env, spi);
5347 	check_fastcall_stack_contract(env, state, env->insn_idx, off);
5348 	err = bpf_mark_stack_read(env, reg_state->frameno, env->insn_idx, BIT(spi));
5349 	if (err)
5350 		return err;
5351 
5352 	if (is_spilled_reg(&reg_state->stack[spi])) {
5353 		u8 spill_size = 1;
5354 
5355 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
5356 			spill_size++;
5357 
5358 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
5359 			if (reg->type != SCALAR_VALUE) {
5360 				verbose_linfo(env, env->insn_idx, "; ");
5361 				verbose(env, "invalid size of register fill\n");
5362 				return -EACCES;
5363 			}
5364 
5365 			if (dst_regno < 0)
5366 				return 0;
5367 
5368 			if (size <= spill_size &&
5369 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
5370 				/* The earlier check_reg_arg() has decided the
5371 				 * subreg_def for this insn.  Save it first.
5372 				 */
5373 				s32 subreg_def = state->regs[dst_regno].subreg_def;
5374 
5375 				copy_register_state(&state->regs[dst_regno], reg);
5376 				state->regs[dst_regno].subreg_def = subreg_def;
5377 
5378 				/* Break the relation on a narrowing fill.
5379 				 * coerce_reg_to_size will adjust the boundaries.
5380 				 */
5381 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
5382 					state->regs[dst_regno].id = 0;
5383 			} else {
5384 				int spill_cnt = 0, zero_cnt = 0;
5385 
5386 				for (i = 0; i < size; i++) {
5387 					type = stype[(slot - i) % BPF_REG_SIZE];
5388 					if (type == STACK_SPILL) {
5389 						spill_cnt++;
5390 						continue;
5391 					}
5392 					if (type == STACK_MISC)
5393 						continue;
5394 					if (type == STACK_ZERO) {
5395 						zero_cnt++;
5396 						continue;
5397 					}
5398 					if (type == STACK_INVALID && env->allow_uninit_stack)
5399 						continue;
5400 					verbose(env, "invalid read from stack off %d+%d size %d\n",
5401 						off, i, size);
5402 					return -EACCES;
5403 				}
5404 
5405 				if (spill_cnt == size &&
5406 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
5407 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5408 					/* this IS register fill, so keep insn_flags */
5409 				} else if (zero_cnt == size) {
5410 					/* similarly to mark_reg_stack_read(), preserve zeroes */
5411 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5412 					insn_flags = 0; /* not restoring original register state */
5413 				} else {
5414 					mark_reg_unknown(env, state->regs, dst_regno);
5415 					insn_flags = 0; /* not restoring original register state */
5416 				}
5417 			}
5418 		} else if (dst_regno >= 0) {
5419 			/* restore register state from stack */
5420 			copy_register_state(&state->regs[dst_regno], reg);
5421 			/* mark reg as written since spilled pointer state likely
5422 			 * has its liveness marks cleared by is_state_visited()
5423 			 * which resets stack/reg liveness for state transitions
5424 			 */
5425 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
5426 			/* If dst_regno==-1, the caller is asking us whether
5427 			 * it is acceptable to use this value as a SCALAR_VALUE
5428 			 * (e.g. for XADD).
5429 			 * We must not allow unprivileged callers to do that
5430 			 * with spilled pointers.
5431 			 */
5432 			verbose(env, "leaking pointer from stack off %d\n",
5433 				off);
5434 			return -EACCES;
5435 		}
5436 	} else {
5437 		for (i = 0; i < size; i++) {
5438 			type = stype[(slot - i) % BPF_REG_SIZE];
5439 			if (type == STACK_MISC)
5440 				continue;
5441 			if (type == STACK_ZERO)
5442 				continue;
5443 			if (type == STACK_INVALID && env->allow_uninit_stack)
5444 				continue;
5445 			verbose(env, "invalid read from stack off %d+%d size %d\n",
5446 				off, i, size);
5447 			return -EACCES;
5448 		}
5449 		if (dst_regno >= 0)
5450 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
5451 		insn_flags = 0; /* we are not restoring spilled register */
5452 	}
5453 	if (insn_flags)
5454 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5455 	return 0;
5456 }
5457 
5458 enum bpf_access_src {
5459 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
5460 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
5461 };
5462 
5463 static int check_stack_range_initialized(struct bpf_verifier_env *env,
5464 					 int regno, int off, int access_size,
5465 					 bool zero_size_allowed,
5466 					 enum bpf_access_type type,
5467 					 struct bpf_call_arg_meta *meta);
5468 
5469 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5470 {
5471 	return cur_regs(env) + regno;
5472 }
5473 
5474 /* Read the stack at 'ptr_regno + off' and put the result into the register
5475  * 'dst_regno'.
5476  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5477  * but not its variable offset.
5478  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5479  *
5480  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5481  * filling registers (i.e. reads of spilled register cannot be detected when
5482  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5483  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5484  * offset; for a fixed offset check_stack_read_fixed_off should be used
5485  * instead.
5486  */
5487 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5488 				    int ptr_regno, int off, int size, int dst_regno)
5489 {
5490 	/* The state of the source register. */
5491 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5492 	struct bpf_func_state *ptr_state = func(env, reg);
5493 	int err;
5494 	int min_off, max_off;
5495 
5496 	/* Note that we pass a NULL meta, so raw access will not be permitted.
5497 	 */
5498 	err = check_stack_range_initialized(env, ptr_regno, off, size,
5499 					    false, BPF_READ, NULL);
5500 	if (err)
5501 		return err;
5502 
5503 	min_off = reg->smin_value + off;
5504 	max_off = reg->smax_value + off;
5505 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5506 	check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
5507 	return 0;
5508 }
5509 
5510 /* check_stack_read dispatches to check_stack_read_fixed_off or
5511  * check_stack_read_var_off.
5512  *
5513  * The caller must ensure that the offset falls within the allocated stack
5514  * bounds.
5515  *
5516  * 'dst_regno' is a register which will receive the value from the stack. It
5517  * can be -1, meaning that the read value is not going to a register.
5518  */
5519 static int check_stack_read(struct bpf_verifier_env *env,
5520 			    int ptr_regno, int off, int size,
5521 			    int dst_regno)
5522 {
5523 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5524 	struct bpf_func_state *state = func(env, reg);
5525 	int err;
5526 	/* Some accesses are only permitted with a static offset. */
5527 	bool var_off = !tnum_is_const(reg->var_off);
5528 
5529 	/* The offset is required to be static when reads don't go to a
5530 	 * register, in order to not leak pointers (see
5531 	 * check_stack_read_fixed_off).
5532 	 */
5533 	if (dst_regno < 0 && var_off) {
5534 		char tn_buf[48];
5535 
5536 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5537 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5538 			tn_buf, off, size);
5539 		return -EACCES;
5540 	}
5541 	/* Variable offset is prohibited for unprivileged mode for simplicity
5542 	 * since it requires corresponding support in Spectre masking for stack
5543 	 * ALU. See also retrieve_ptr_limit(). The check in
5544 	 * check_stack_access_for_ptr_arithmetic() called by
5545 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5546 	 * with variable offsets, therefore no check is required here. Further,
5547 	 * just checking it here would be insufficient as speculative stack
5548 	 * writes could still lead to unsafe speculative behaviour.
5549 	 */
5550 	if (!var_off) {
5551 		off += reg->var_off.value;
5552 		err = check_stack_read_fixed_off(env, state, off, size,
5553 						 dst_regno);
5554 	} else {
5555 		/* Variable offset stack reads need more conservative handling
5556 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5557 		 * branch.
5558 		 */
5559 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5560 					       dst_regno);
5561 	}
5562 	return err;
5563 }
5564 
5565 
5566 /* check_stack_write dispatches to check_stack_write_fixed_off or
5567  * check_stack_write_var_off.
5568  *
5569  * 'ptr_regno' is the register used as a pointer into the stack.
5570  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5571  * 'value_regno' is the register whose value we're writing to the stack. It can
5572  * be -1, meaning that we're not writing from a register.
5573  *
5574  * The caller must ensure that the offset falls within the maximum stack size.
5575  */
5576 static int check_stack_write(struct bpf_verifier_env *env,
5577 			     int ptr_regno, int off, int size,
5578 			     int value_regno, int insn_idx)
5579 {
5580 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5581 	struct bpf_func_state *state = func(env, reg);
5582 	int err;
5583 
5584 	if (tnum_is_const(reg->var_off)) {
5585 		off += reg->var_off.value;
5586 		err = check_stack_write_fixed_off(env, state, off, size,
5587 						  value_regno, insn_idx);
5588 	} else {
5589 		/* Variable offset stack reads need more conservative handling
5590 		 * than fixed offset ones.
5591 		 */
5592 		err = check_stack_write_var_off(env, state,
5593 						ptr_regno, off, size,
5594 						value_regno, insn_idx);
5595 	}
5596 	return err;
5597 }
5598 
5599 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5600 				 int off, int size, enum bpf_access_type type)
5601 {
5602 	struct bpf_reg_state *regs = cur_regs(env);
5603 	struct bpf_map *map = regs[regno].map_ptr;
5604 	u32 cap = bpf_map_flags_to_cap(map);
5605 
5606 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5607 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5608 			map->value_size, off, size);
5609 		return -EACCES;
5610 	}
5611 
5612 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5613 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5614 			map->value_size, off, size);
5615 		return -EACCES;
5616 	}
5617 
5618 	return 0;
5619 }
5620 
5621 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5622 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5623 			      int off, int size, u32 mem_size,
5624 			      bool zero_size_allowed)
5625 {
5626 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5627 	struct bpf_reg_state *reg;
5628 
5629 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5630 		return 0;
5631 
5632 	reg = &cur_regs(env)[regno];
5633 	switch (reg->type) {
5634 	case PTR_TO_MAP_KEY:
5635 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5636 			mem_size, off, size);
5637 		break;
5638 	case PTR_TO_MAP_VALUE:
5639 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5640 			mem_size, off, size);
5641 		break;
5642 	case PTR_TO_PACKET:
5643 	case PTR_TO_PACKET_META:
5644 	case PTR_TO_PACKET_END:
5645 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5646 			off, size, regno, reg->id, off, mem_size);
5647 		break;
5648 	case PTR_TO_MEM:
5649 	default:
5650 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5651 			mem_size, off, size);
5652 	}
5653 
5654 	return -EACCES;
5655 }
5656 
5657 /* check read/write into a memory region with possible variable offset */
5658 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5659 				   int off, int size, u32 mem_size,
5660 				   bool zero_size_allowed)
5661 {
5662 	struct bpf_verifier_state *vstate = env->cur_state;
5663 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5664 	struct bpf_reg_state *reg = &state->regs[regno];
5665 	int err;
5666 
5667 	/* We may have adjusted the register pointing to memory region, so we
5668 	 * need to try adding each of min_value and max_value to off
5669 	 * to make sure our theoretical access will be safe.
5670 	 *
5671 	 * The minimum value is only important with signed
5672 	 * comparisons where we can't assume the floor of a
5673 	 * value is 0.  If we are using signed variables for our
5674 	 * index'es we need to make sure that whatever we use
5675 	 * will have a set floor within our range.
5676 	 */
5677 	if (reg->smin_value < 0 &&
5678 	    (reg->smin_value == S64_MIN ||
5679 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5680 	      reg->smin_value + off < 0)) {
5681 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5682 			regno);
5683 		return -EACCES;
5684 	}
5685 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5686 				 mem_size, zero_size_allowed);
5687 	if (err) {
5688 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5689 			regno);
5690 		return err;
5691 	}
5692 
5693 	/* If we haven't set a max value then we need to bail since we can't be
5694 	 * sure we won't do bad things.
5695 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5696 	 */
5697 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5698 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5699 			regno);
5700 		return -EACCES;
5701 	}
5702 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5703 				 mem_size, zero_size_allowed);
5704 	if (err) {
5705 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5706 			regno);
5707 		return err;
5708 	}
5709 
5710 	return 0;
5711 }
5712 
5713 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5714 			       const struct bpf_reg_state *reg, int regno,
5715 			       bool fixed_off_ok)
5716 {
5717 	/* Access to this pointer-typed register or passing it to a helper
5718 	 * is only allowed in its original, unmodified form.
5719 	 */
5720 
5721 	if (reg->off < 0) {
5722 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5723 			reg_type_str(env, reg->type), regno, reg->off);
5724 		return -EACCES;
5725 	}
5726 
5727 	if (!fixed_off_ok && reg->off) {
5728 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5729 			reg_type_str(env, reg->type), regno, reg->off);
5730 		return -EACCES;
5731 	}
5732 
5733 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5734 		char tn_buf[48];
5735 
5736 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5737 		verbose(env, "variable %s access var_off=%s disallowed\n",
5738 			reg_type_str(env, reg->type), tn_buf);
5739 		return -EACCES;
5740 	}
5741 
5742 	return 0;
5743 }
5744 
5745 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5746 		             const struct bpf_reg_state *reg, int regno)
5747 {
5748 	return __check_ptr_off_reg(env, reg, regno, false);
5749 }
5750 
5751 static int map_kptr_match_type(struct bpf_verifier_env *env,
5752 			       struct btf_field *kptr_field,
5753 			       struct bpf_reg_state *reg, u32 regno)
5754 {
5755 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5756 	int perm_flags;
5757 	const char *reg_name = "";
5758 
5759 	if (btf_is_kernel(reg->btf)) {
5760 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5761 
5762 		/* Only unreferenced case accepts untrusted pointers */
5763 		if (kptr_field->type == BPF_KPTR_UNREF)
5764 			perm_flags |= PTR_UNTRUSTED;
5765 	} else {
5766 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5767 		if (kptr_field->type == BPF_KPTR_PERCPU)
5768 			perm_flags |= MEM_PERCPU;
5769 	}
5770 
5771 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5772 		goto bad_type;
5773 
5774 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5775 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5776 
5777 	/* For ref_ptr case, release function check should ensure we get one
5778 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5779 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5780 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5781 	 * reg->off and reg->ref_obj_id are not needed here.
5782 	 */
5783 	if (__check_ptr_off_reg(env, reg, regno, true))
5784 		return -EACCES;
5785 
5786 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5787 	 * we also need to take into account the reg->off.
5788 	 *
5789 	 * We want to support cases like:
5790 	 *
5791 	 * struct foo {
5792 	 *         struct bar br;
5793 	 *         struct baz bz;
5794 	 * };
5795 	 *
5796 	 * struct foo *v;
5797 	 * v = func();	      // PTR_TO_BTF_ID
5798 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5799 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5800 	 *                    // first member type of struct after comparison fails
5801 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5802 	 *                    // to match type
5803 	 *
5804 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5805 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5806 	 * the struct to match type against first member of struct, i.e. reject
5807 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5808 	 * strict mode to true for type match.
5809 	 */
5810 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5811 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5812 				  kptr_field->type != BPF_KPTR_UNREF))
5813 		goto bad_type;
5814 	return 0;
5815 bad_type:
5816 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5817 		reg_type_str(env, reg->type), reg_name);
5818 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5819 	if (kptr_field->type == BPF_KPTR_UNREF)
5820 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5821 			targ_name);
5822 	else
5823 		verbose(env, "\n");
5824 	return -EINVAL;
5825 }
5826 
5827 static bool in_sleepable(struct bpf_verifier_env *env)
5828 {
5829 	return env->prog->sleepable ||
5830 	       (env->cur_state && env->cur_state->in_sleepable);
5831 }
5832 
5833 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5834  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5835  */
5836 static bool in_rcu_cs(struct bpf_verifier_env *env)
5837 {
5838 	return env->cur_state->active_rcu_lock ||
5839 	       env->cur_state->active_locks ||
5840 	       !in_sleepable(env);
5841 }
5842 
5843 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5844 BTF_SET_START(rcu_protected_types)
5845 #ifdef CONFIG_NET
5846 BTF_ID(struct, prog_test_ref_kfunc)
5847 #endif
5848 #ifdef CONFIG_CGROUPS
5849 BTF_ID(struct, cgroup)
5850 #endif
5851 #ifdef CONFIG_BPF_JIT
5852 BTF_ID(struct, bpf_cpumask)
5853 #endif
5854 BTF_ID(struct, task_struct)
5855 #ifdef CONFIG_CRYPTO
5856 BTF_ID(struct, bpf_crypto_ctx)
5857 #endif
5858 BTF_SET_END(rcu_protected_types)
5859 
5860 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5861 {
5862 	if (!btf_is_kernel(btf))
5863 		return true;
5864 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5865 }
5866 
5867 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5868 {
5869 	struct btf_struct_meta *meta;
5870 
5871 	if (btf_is_kernel(kptr_field->kptr.btf))
5872 		return NULL;
5873 
5874 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5875 				    kptr_field->kptr.btf_id);
5876 
5877 	return meta ? meta->record : NULL;
5878 }
5879 
5880 static bool rcu_safe_kptr(const struct btf_field *field)
5881 {
5882 	const struct btf_field_kptr *kptr = &field->kptr;
5883 
5884 	return field->type == BPF_KPTR_PERCPU ||
5885 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5886 }
5887 
5888 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5889 {
5890 	struct btf_record *rec;
5891 	u32 ret;
5892 
5893 	ret = PTR_MAYBE_NULL;
5894 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5895 		ret |= MEM_RCU;
5896 		if (kptr_field->type == BPF_KPTR_PERCPU)
5897 			ret |= MEM_PERCPU;
5898 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5899 			ret |= MEM_ALLOC;
5900 
5901 		rec = kptr_pointee_btf_record(kptr_field);
5902 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5903 			ret |= NON_OWN_REF;
5904 	} else {
5905 		ret |= PTR_UNTRUSTED;
5906 	}
5907 
5908 	return ret;
5909 }
5910 
5911 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
5912 			    struct btf_field *field)
5913 {
5914 	struct bpf_reg_state *reg;
5915 	const struct btf_type *t;
5916 
5917 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
5918 	mark_reg_known_zero(env, cur_regs(env), regno);
5919 	reg = reg_state(env, regno);
5920 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
5921 	reg->mem_size = t->size;
5922 	reg->id = ++env->id_gen;
5923 
5924 	return 0;
5925 }
5926 
5927 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5928 				 int value_regno, int insn_idx,
5929 				 struct btf_field *kptr_field)
5930 {
5931 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5932 	int class = BPF_CLASS(insn->code);
5933 	struct bpf_reg_state *val_reg;
5934 	int ret;
5935 
5936 	/* Things we already checked for in check_map_access and caller:
5937 	 *  - Reject cases where variable offset may touch kptr
5938 	 *  - size of access (must be BPF_DW)
5939 	 *  - tnum_is_const(reg->var_off)
5940 	 *  - kptr_field->offset == off + reg->var_off.value
5941 	 */
5942 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5943 	if (BPF_MODE(insn->code) != BPF_MEM) {
5944 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5945 		return -EACCES;
5946 	}
5947 
5948 	/* We only allow loading referenced kptr, since it will be marked as
5949 	 * untrusted, similar to unreferenced kptr.
5950 	 */
5951 	if (class != BPF_LDX &&
5952 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5953 		verbose(env, "store to referenced kptr disallowed\n");
5954 		return -EACCES;
5955 	}
5956 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
5957 		verbose(env, "store to uptr disallowed\n");
5958 		return -EACCES;
5959 	}
5960 
5961 	if (class == BPF_LDX) {
5962 		if (kptr_field->type == BPF_UPTR)
5963 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
5964 
5965 		/* We can simply mark the value_regno receiving the pointer
5966 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5967 		 */
5968 		ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID,
5969 				      kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5970 				      btf_ld_kptr_type(env, kptr_field));
5971 		if (ret < 0)
5972 			return ret;
5973 	} else if (class == BPF_STX) {
5974 		val_reg = reg_state(env, value_regno);
5975 		if (!register_is_null(val_reg) &&
5976 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5977 			return -EACCES;
5978 	} else if (class == BPF_ST) {
5979 		if (insn->imm) {
5980 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5981 				kptr_field->offset);
5982 			return -EACCES;
5983 		}
5984 	} else {
5985 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5986 		return -EACCES;
5987 	}
5988 	return 0;
5989 }
5990 
5991 /* check read/write into a map element with possible variable offset */
5992 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5993 			    int off, int size, bool zero_size_allowed,
5994 			    enum bpf_access_src src)
5995 {
5996 	struct bpf_verifier_state *vstate = env->cur_state;
5997 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5998 	struct bpf_reg_state *reg = &state->regs[regno];
5999 	struct bpf_map *map = reg->map_ptr;
6000 	struct btf_record *rec;
6001 	int err, i;
6002 
6003 	err = check_mem_region_access(env, regno, off, size, map->value_size,
6004 				      zero_size_allowed);
6005 	if (err)
6006 		return err;
6007 
6008 	if (IS_ERR_OR_NULL(map->record))
6009 		return 0;
6010 	rec = map->record;
6011 	for (i = 0; i < rec->cnt; i++) {
6012 		struct btf_field *field = &rec->fields[i];
6013 		u32 p = field->offset;
6014 
6015 		/* If any part of a field  can be touched by load/store, reject
6016 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
6017 		 * it is sufficient to check x1 < y2 && y1 < x2.
6018 		 */
6019 		if (reg->smin_value + off < p + field->size &&
6020 		    p < reg->umax_value + off + size) {
6021 			switch (field->type) {
6022 			case BPF_KPTR_UNREF:
6023 			case BPF_KPTR_REF:
6024 			case BPF_KPTR_PERCPU:
6025 			case BPF_UPTR:
6026 				if (src != ACCESS_DIRECT) {
6027 					verbose(env, "%s cannot be accessed indirectly by helper\n",
6028 						btf_field_type_name(field->type));
6029 					return -EACCES;
6030 				}
6031 				if (!tnum_is_const(reg->var_off)) {
6032 					verbose(env, "%s access cannot have variable offset\n",
6033 						btf_field_type_name(field->type));
6034 					return -EACCES;
6035 				}
6036 				if (p != off + reg->var_off.value) {
6037 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
6038 						btf_field_type_name(field->type),
6039 						p, off + reg->var_off.value);
6040 					return -EACCES;
6041 				}
6042 				if (size != bpf_size_to_bytes(BPF_DW)) {
6043 					verbose(env, "%s access size must be BPF_DW\n",
6044 						btf_field_type_name(field->type));
6045 					return -EACCES;
6046 				}
6047 				break;
6048 			default:
6049 				verbose(env, "%s cannot be accessed directly by load/store\n",
6050 					btf_field_type_name(field->type));
6051 				return -EACCES;
6052 			}
6053 		}
6054 	}
6055 	return 0;
6056 }
6057 
6058 #define MAX_PACKET_OFF 0xffff
6059 
6060 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
6061 				       const struct bpf_call_arg_meta *meta,
6062 				       enum bpf_access_type t)
6063 {
6064 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
6065 
6066 	switch (prog_type) {
6067 	/* Program types only with direct read access go here! */
6068 	case BPF_PROG_TYPE_LWT_IN:
6069 	case BPF_PROG_TYPE_LWT_OUT:
6070 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
6071 	case BPF_PROG_TYPE_SK_REUSEPORT:
6072 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6073 	case BPF_PROG_TYPE_CGROUP_SKB:
6074 		if (t == BPF_WRITE)
6075 			return false;
6076 		fallthrough;
6077 
6078 	/* Program types with direct read + write access go here! */
6079 	case BPF_PROG_TYPE_SCHED_CLS:
6080 	case BPF_PROG_TYPE_SCHED_ACT:
6081 	case BPF_PROG_TYPE_XDP:
6082 	case BPF_PROG_TYPE_LWT_XMIT:
6083 	case BPF_PROG_TYPE_SK_SKB:
6084 	case BPF_PROG_TYPE_SK_MSG:
6085 		if (meta)
6086 			return meta->pkt_access;
6087 
6088 		env->seen_direct_write = true;
6089 		return true;
6090 
6091 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
6092 		if (t == BPF_WRITE)
6093 			env->seen_direct_write = true;
6094 
6095 		return true;
6096 
6097 	default:
6098 		return false;
6099 	}
6100 }
6101 
6102 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
6103 			       int size, bool zero_size_allowed)
6104 {
6105 	struct bpf_reg_state *regs = cur_regs(env);
6106 	struct bpf_reg_state *reg = &regs[regno];
6107 	int err;
6108 
6109 	/* We may have added a variable offset to the packet pointer; but any
6110 	 * reg->range we have comes after that.  We are only checking the fixed
6111 	 * offset.
6112 	 */
6113 
6114 	/* We don't allow negative numbers, because we aren't tracking enough
6115 	 * detail to prove they're safe.
6116 	 */
6117 	if (reg->smin_value < 0) {
6118 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6119 			regno);
6120 		return -EACCES;
6121 	}
6122 
6123 	err = reg->range < 0 ? -EINVAL :
6124 	      __check_mem_access(env, regno, off, size, reg->range,
6125 				 zero_size_allowed);
6126 	if (err) {
6127 		verbose(env, "R%d offset is outside of the packet\n", regno);
6128 		return err;
6129 	}
6130 
6131 	/* __check_mem_access has made sure "off + size - 1" is within u16.
6132 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
6133 	 * otherwise find_good_pkt_pointers would have refused to set range info
6134 	 * that __check_mem_access would have rejected this pkt access.
6135 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
6136 	 */
6137 	env->prog->aux->max_pkt_offset =
6138 		max_t(u32, env->prog->aux->max_pkt_offset,
6139 		      off + reg->umax_value + size - 1);
6140 
6141 	return err;
6142 }
6143 
6144 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
6145 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
6146 			    enum bpf_access_type t, struct bpf_insn_access_aux *info)
6147 {
6148 	if (env->ops->is_valid_access &&
6149 	    env->ops->is_valid_access(off, size, t, env->prog, info)) {
6150 		/* A non zero info.ctx_field_size indicates that this field is a
6151 		 * candidate for later verifier transformation to load the whole
6152 		 * field and then apply a mask when accessed with a narrower
6153 		 * access than actual ctx access size. A zero info.ctx_field_size
6154 		 * will only allow for whole field access and rejects any other
6155 		 * type of narrower access.
6156 		 */
6157 		if (base_type(info->reg_type) == PTR_TO_BTF_ID) {
6158 			if (info->ref_obj_id &&
6159 			    !find_reference_state(env->cur_state, info->ref_obj_id)) {
6160 				verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n",
6161 					off);
6162 				return -EACCES;
6163 			}
6164 		} else {
6165 			env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size;
6166 		}
6167 		/* remember the offset of last byte accessed in ctx */
6168 		if (env->prog->aux->max_ctx_offset < off + size)
6169 			env->prog->aux->max_ctx_offset = off + size;
6170 		return 0;
6171 	}
6172 
6173 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
6174 	return -EACCES;
6175 }
6176 
6177 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
6178 				  int size)
6179 {
6180 	if (size < 0 || off < 0 ||
6181 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
6182 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
6183 			off, size);
6184 		return -EACCES;
6185 	}
6186 	return 0;
6187 }
6188 
6189 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
6190 			     u32 regno, int off, int size,
6191 			     enum bpf_access_type t)
6192 {
6193 	struct bpf_reg_state *regs = cur_regs(env);
6194 	struct bpf_reg_state *reg = &regs[regno];
6195 	struct bpf_insn_access_aux info = {};
6196 	bool valid;
6197 
6198 	if (reg->smin_value < 0) {
6199 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6200 			regno);
6201 		return -EACCES;
6202 	}
6203 
6204 	switch (reg->type) {
6205 	case PTR_TO_SOCK_COMMON:
6206 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
6207 		break;
6208 	case PTR_TO_SOCKET:
6209 		valid = bpf_sock_is_valid_access(off, size, t, &info);
6210 		break;
6211 	case PTR_TO_TCP_SOCK:
6212 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
6213 		break;
6214 	case PTR_TO_XDP_SOCK:
6215 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
6216 		break;
6217 	default:
6218 		valid = false;
6219 	}
6220 
6221 
6222 	if (valid) {
6223 		env->insn_aux_data[insn_idx].ctx_field_size =
6224 			info.ctx_field_size;
6225 		return 0;
6226 	}
6227 
6228 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
6229 		regno, reg_type_str(env, reg->type), off, size);
6230 
6231 	return -EACCES;
6232 }
6233 
6234 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
6235 {
6236 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
6237 }
6238 
6239 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
6240 {
6241 	const struct bpf_reg_state *reg = reg_state(env, regno);
6242 
6243 	return reg->type == PTR_TO_CTX;
6244 }
6245 
6246 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
6247 {
6248 	const struct bpf_reg_state *reg = reg_state(env, regno);
6249 
6250 	return type_is_sk_pointer(reg->type);
6251 }
6252 
6253 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
6254 {
6255 	const struct bpf_reg_state *reg = reg_state(env, regno);
6256 
6257 	return type_is_pkt_pointer(reg->type);
6258 }
6259 
6260 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
6261 {
6262 	const struct bpf_reg_state *reg = reg_state(env, regno);
6263 
6264 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
6265 	return reg->type == PTR_TO_FLOW_KEYS;
6266 }
6267 
6268 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
6269 {
6270 	const struct bpf_reg_state *reg = reg_state(env, regno);
6271 
6272 	return reg->type == PTR_TO_ARENA;
6273 }
6274 
6275 /* Return false if @regno contains a pointer whose type isn't supported for
6276  * atomic instruction @insn.
6277  */
6278 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno,
6279 			       struct bpf_insn *insn)
6280 {
6281 	if (is_ctx_reg(env, regno))
6282 		return false;
6283 	if (is_pkt_reg(env, regno))
6284 		return false;
6285 	if (is_flow_key_reg(env, regno))
6286 		return false;
6287 	if (is_sk_reg(env, regno))
6288 		return false;
6289 	if (is_arena_reg(env, regno))
6290 		return bpf_jit_supports_insn(insn, true);
6291 
6292 	return true;
6293 }
6294 
6295 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
6296 #ifdef CONFIG_NET
6297 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
6298 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6299 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
6300 #endif
6301 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
6302 };
6303 
6304 static bool is_trusted_reg(const struct bpf_reg_state *reg)
6305 {
6306 	/* A referenced register is always trusted. */
6307 	if (reg->ref_obj_id)
6308 		return true;
6309 
6310 	/* Types listed in the reg2btf_ids are always trusted */
6311 	if (reg2btf_ids[base_type(reg->type)] &&
6312 	    !bpf_type_has_unsafe_modifiers(reg->type))
6313 		return true;
6314 
6315 	/* If a register is not referenced, it is trusted if it has the
6316 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
6317 	 * other type modifiers may be safe, but we elect to take an opt-in
6318 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
6319 	 * not.
6320 	 *
6321 	 * Eventually, we should make PTR_TRUSTED the single source of truth
6322 	 * for whether a register is trusted.
6323 	 */
6324 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
6325 	       !bpf_type_has_unsafe_modifiers(reg->type);
6326 }
6327 
6328 static bool is_rcu_reg(const struct bpf_reg_state *reg)
6329 {
6330 	return reg->type & MEM_RCU;
6331 }
6332 
6333 static void clear_trusted_flags(enum bpf_type_flag *flag)
6334 {
6335 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
6336 }
6337 
6338 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
6339 				   const struct bpf_reg_state *reg,
6340 				   int off, int size, bool strict)
6341 {
6342 	struct tnum reg_off;
6343 	int ip_align;
6344 
6345 	/* Byte size accesses are always allowed. */
6346 	if (!strict || size == 1)
6347 		return 0;
6348 
6349 	/* For platforms that do not have a Kconfig enabling
6350 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
6351 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
6352 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
6353 	 * to this code only in strict mode where we want to emulate
6354 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
6355 	 * unconditional IP align value of '2'.
6356 	 */
6357 	ip_align = 2;
6358 
6359 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
6360 	if (!tnum_is_aligned(reg_off, size)) {
6361 		char tn_buf[48];
6362 
6363 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6364 		verbose(env,
6365 			"misaligned packet access off %d+%s+%d+%d size %d\n",
6366 			ip_align, tn_buf, reg->off, off, size);
6367 		return -EACCES;
6368 	}
6369 
6370 	return 0;
6371 }
6372 
6373 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
6374 				       const struct bpf_reg_state *reg,
6375 				       const char *pointer_desc,
6376 				       int off, int size, bool strict)
6377 {
6378 	struct tnum reg_off;
6379 
6380 	/* Byte size accesses are always allowed. */
6381 	if (!strict || size == 1)
6382 		return 0;
6383 
6384 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
6385 	if (!tnum_is_aligned(reg_off, size)) {
6386 		char tn_buf[48];
6387 
6388 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6389 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
6390 			pointer_desc, tn_buf, reg->off, off, size);
6391 		return -EACCES;
6392 	}
6393 
6394 	return 0;
6395 }
6396 
6397 static int check_ptr_alignment(struct bpf_verifier_env *env,
6398 			       const struct bpf_reg_state *reg, int off,
6399 			       int size, bool strict_alignment_once)
6400 {
6401 	bool strict = env->strict_alignment || strict_alignment_once;
6402 	const char *pointer_desc = "";
6403 
6404 	switch (reg->type) {
6405 	case PTR_TO_PACKET:
6406 	case PTR_TO_PACKET_META:
6407 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
6408 		 * right in front, treat it the very same way.
6409 		 */
6410 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
6411 	case PTR_TO_FLOW_KEYS:
6412 		pointer_desc = "flow keys ";
6413 		break;
6414 	case PTR_TO_MAP_KEY:
6415 		pointer_desc = "key ";
6416 		break;
6417 	case PTR_TO_MAP_VALUE:
6418 		pointer_desc = "value ";
6419 		break;
6420 	case PTR_TO_CTX:
6421 		pointer_desc = "context ";
6422 		break;
6423 	case PTR_TO_STACK:
6424 		pointer_desc = "stack ";
6425 		/* The stack spill tracking logic in check_stack_write_fixed_off()
6426 		 * and check_stack_read_fixed_off() relies on stack accesses being
6427 		 * aligned.
6428 		 */
6429 		strict = true;
6430 		break;
6431 	case PTR_TO_SOCKET:
6432 		pointer_desc = "sock ";
6433 		break;
6434 	case PTR_TO_SOCK_COMMON:
6435 		pointer_desc = "sock_common ";
6436 		break;
6437 	case PTR_TO_TCP_SOCK:
6438 		pointer_desc = "tcp_sock ";
6439 		break;
6440 	case PTR_TO_XDP_SOCK:
6441 		pointer_desc = "xdp_sock ";
6442 		break;
6443 	case PTR_TO_ARENA:
6444 		return 0;
6445 	default:
6446 		break;
6447 	}
6448 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
6449 					   strict);
6450 }
6451 
6452 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
6453 {
6454 	if (!bpf_jit_supports_private_stack())
6455 		return NO_PRIV_STACK;
6456 
6457 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
6458 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
6459 	 * explicitly.
6460 	 */
6461 	switch (prog->type) {
6462 	case BPF_PROG_TYPE_KPROBE:
6463 	case BPF_PROG_TYPE_TRACEPOINT:
6464 	case BPF_PROG_TYPE_PERF_EVENT:
6465 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6466 		return PRIV_STACK_ADAPTIVE;
6467 	case BPF_PROG_TYPE_TRACING:
6468 	case BPF_PROG_TYPE_LSM:
6469 	case BPF_PROG_TYPE_STRUCT_OPS:
6470 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
6471 			return PRIV_STACK_ADAPTIVE;
6472 		fallthrough;
6473 	default:
6474 		break;
6475 	}
6476 
6477 	return NO_PRIV_STACK;
6478 }
6479 
6480 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
6481 {
6482 	if (env->prog->jit_requested)
6483 		return round_up(stack_depth, 16);
6484 
6485 	/* round up to 32-bytes, since this is granularity
6486 	 * of interpreter stack size
6487 	 */
6488 	return round_up(max_t(u32, stack_depth, 1), 32);
6489 }
6490 
6491 /* starting from main bpf function walk all instructions of the function
6492  * and recursively walk all callees that given function can call.
6493  * Ignore jump and exit insns.
6494  * Since recursion is prevented by check_cfg() this algorithm
6495  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
6496  */
6497 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
6498 					 bool priv_stack_supported)
6499 {
6500 	struct bpf_subprog_info *subprog = env->subprog_info;
6501 	struct bpf_insn *insn = env->prog->insnsi;
6502 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
6503 	bool tail_call_reachable = false;
6504 	int ret_insn[MAX_CALL_FRAMES];
6505 	int ret_prog[MAX_CALL_FRAMES];
6506 	int j;
6507 
6508 	i = subprog[idx].start;
6509 	if (!priv_stack_supported)
6510 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6511 process_func:
6512 	/* protect against potential stack overflow that might happen when
6513 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
6514 	 * depth for such case down to 256 so that the worst case scenario
6515 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
6516 	 * 8k).
6517 	 *
6518 	 * To get the idea what might happen, see an example:
6519 	 * func1 -> sub rsp, 128
6520 	 *  subfunc1 -> sub rsp, 256
6521 	 *  tailcall1 -> add rsp, 256
6522 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
6523 	 *   subfunc2 -> sub rsp, 64
6524 	 *   subfunc22 -> sub rsp, 128
6525 	 *   tailcall2 -> add rsp, 128
6526 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
6527 	 *
6528 	 * tailcall will unwind the current stack frame but it will not get rid
6529 	 * of caller's stack as shown on the example above.
6530 	 */
6531 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
6532 		verbose(env,
6533 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
6534 			depth);
6535 		return -EACCES;
6536 	}
6537 
6538 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
6539 	if (priv_stack_supported) {
6540 		/* Request private stack support only if the subprog stack
6541 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
6542 		 * avoid jit penalty if the stack usage is small.
6543 		 */
6544 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
6545 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
6546 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
6547 	}
6548 
6549 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6550 		if (subprog_depth > MAX_BPF_STACK) {
6551 			verbose(env, "stack size of subprog %d is %d. Too large\n",
6552 				idx, subprog_depth);
6553 			return -EACCES;
6554 		}
6555 	} else {
6556 		depth += subprog_depth;
6557 		if (depth > MAX_BPF_STACK) {
6558 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
6559 				frame + 1, depth);
6560 			return -EACCES;
6561 		}
6562 	}
6563 continue_func:
6564 	subprog_end = subprog[idx + 1].start;
6565 	for (; i < subprog_end; i++) {
6566 		int next_insn, sidx;
6567 
6568 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
6569 			bool err = false;
6570 
6571 			if (!is_bpf_throw_kfunc(insn + i))
6572 				continue;
6573 			if (subprog[idx].is_cb)
6574 				err = true;
6575 			for (int c = 0; c < frame && !err; c++) {
6576 				if (subprog[ret_prog[c]].is_cb) {
6577 					err = true;
6578 					break;
6579 				}
6580 			}
6581 			if (!err)
6582 				continue;
6583 			verbose(env,
6584 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
6585 				i, idx);
6586 			return -EINVAL;
6587 		}
6588 
6589 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
6590 			continue;
6591 		/* remember insn and function to return to */
6592 		ret_insn[frame] = i + 1;
6593 		ret_prog[frame] = idx;
6594 
6595 		/* find the callee */
6596 		next_insn = i + insn[i].imm + 1;
6597 		sidx = find_subprog(env, next_insn);
6598 		if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn))
6599 			return -EFAULT;
6600 		if (subprog[sidx].is_async_cb) {
6601 			if (subprog[sidx].has_tail_call) {
6602 				verifier_bug(env, "subprog has tail_call and async cb");
6603 				return -EFAULT;
6604 			}
6605 			/* async callbacks don't increase bpf prog stack size unless called directly */
6606 			if (!bpf_pseudo_call(insn + i))
6607 				continue;
6608 			if (subprog[sidx].is_exception_cb) {
6609 				verbose(env, "insn %d cannot call exception cb directly", i);
6610 				return -EINVAL;
6611 			}
6612 		}
6613 		i = next_insn;
6614 		idx = sidx;
6615 		if (!priv_stack_supported)
6616 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6617 
6618 		if (subprog[idx].has_tail_call)
6619 			tail_call_reachable = true;
6620 
6621 		frame++;
6622 		if (frame >= MAX_CALL_FRAMES) {
6623 			verbose(env, "the call stack of %d frames is too deep !\n",
6624 				frame);
6625 			return -E2BIG;
6626 		}
6627 		goto process_func;
6628 	}
6629 	/* if tail call got detected across bpf2bpf calls then mark each of the
6630 	 * currently present subprog frames as tail call reachable subprogs;
6631 	 * this info will be utilized by JIT so that we will be preserving the
6632 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
6633 	 */
6634 	if (tail_call_reachable)
6635 		for (j = 0; j < frame; j++) {
6636 			if (subprog[ret_prog[j]].is_exception_cb) {
6637 				verbose(env, "cannot tail call within exception cb\n");
6638 				return -EINVAL;
6639 			}
6640 			subprog[ret_prog[j]].tail_call_reachable = true;
6641 		}
6642 	if (subprog[0].tail_call_reachable)
6643 		env->prog->aux->tail_call_reachable = true;
6644 
6645 	/* end of for() loop means the last insn of the 'subprog'
6646 	 * was reached. Doesn't matter whether it was JA or EXIT
6647 	 */
6648 	if (frame == 0)
6649 		return 0;
6650 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
6651 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6652 	frame--;
6653 	i = ret_insn[frame];
6654 	idx = ret_prog[frame];
6655 	goto continue_func;
6656 }
6657 
6658 static int check_max_stack_depth(struct bpf_verifier_env *env)
6659 {
6660 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
6661 	struct bpf_subprog_info *si = env->subprog_info;
6662 	bool priv_stack_supported;
6663 	int ret;
6664 
6665 	for (int i = 0; i < env->subprog_cnt; i++) {
6666 		if (si[i].has_tail_call) {
6667 			priv_stack_mode = NO_PRIV_STACK;
6668 			break;
6669 		}
6670 	}
6671 
6672 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
6673 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
6674 
6675 	/* All async_cb subprogs use normal kernel stack. If a particular
6676 	 * subprog appears in both main prog and async_cb subtree, that
6677 	 * subprog will use normal kernel stack to avoid potential nesting.
6678 	 * The reverse subprog traversal ensures when main prog subtree is
6679 	 * checked, the subprogs appearing in async_cb subtrees are already
6680 	 * marked as using normal kernel stack, so stack size checking can
6681 	 * be done properly.
6682 	 */
6683 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
6684 		if (!i || si[i].is_async_cb) {
6685 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
6686 			ret = check_max_stack_depth_subprog(env, i, priv_stack_supported);
6687 			if (ret < 0)
6688 				return ret;
6689 		}
6690 	}
6691 
6692 	for (int i = 0; i < env->subprog_cnt; i++) {
6693 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6694 			env->prog->aux->jits_use_priv_stack = true;
6695 			break;
6696 		}
6697 	}
6698 
6699 	return 0;
6700 }
6701 
6702 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6703 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6704 				  const struct bpf_insn *insn, int idx)
6705 {
6706 	int start = idx + insn->imm + 1, subprog;
6707 
6708 	subprog = find_subprog(env, start);
6709 	if (verifier_bug_if(subprog < 0, env, "get stack depth: no program at insn %d", start))
6710 		return -EFAULT;
6711 	return env->subprog_info[subprog].stack_depth;
6712 }
6713 #endif
6714 
6715 static int __check_buffer_access(struct bpf_verifier_env *env,
6716 				 const char *buf_info,
6717 				 const struct bpf_reg_state *reg,
6718 				 int regno, int off, int size)
6719 {
6720 	if (off < 0) {
6721 		verbose(env,
6722 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6723 			regno, buf_info, off, size);
6724 		return -EACCES;
6725 	}
6726 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6727 		char tn_buf[48];
6728 
6729 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6730 		verbose(env,
6731 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6732 			regno, off, tn_buf);
6733 		return -EACCES;
6734 	}
6735 
6736 	return 0;
6737 }
6738 
6739 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6740 				  const struct bpf_reg_state *reg,
6741 				  int regno, int off, int size)
6742 {
6743 	int err;
6744 
6745 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6746 	if (err)
6747 		return err;
6748 
6749 	if (off + size > env->prog->aux->max_tp_access)
6750 		env->prog->aux->max_tp_access = off + size;
6751 
6752 	return 0;
6753 }
6754 
6755 static int check_buffer_access(struct bpf_verifier_env *env,
6756 			       const struct bpf_reg_state *reg,
6757 			       int regno, int off, int size,
6758 			       bool zero_size_allowed,
6759 			       u32 *max_access)
6760 {
6761 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6762 	int err;
6763 
6764 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6765 	if (err)
6766 		return err;
6767 
6768 	if (off + size > *max_access)
6769 		*max_access = off + size;
6770 
6771 	return 0;
6772 }
6773 
6774 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6775 static void zext_32_to_64(struct bpf_reg_state *reg)
6776 {
6777 	reg->var_off = tnum_subreg(reg->var_off);
6778 	__reg_assign_32_into_64(reg);
6779 }
6780 
6781 /* truncate register to smaller size (in bytes)
6782  * must be called with size < BPF_REG_SIZE
6783  */
6784 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6785 {
6786 	u64 mask;
6787 
6788 	/* clear high bits in bit representation */
6789 	reg->var_off = tnum_cast(reg->var_off, size);
6790 
6791 	/* fix arithmetic bounds */
6792 	mask = ((u64)1 << (size * 8)) - 1;
6793 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6794 		reg->umin_value &= mask;
6795 		reg->umax_value &= mask;
6796 	} else {
6797 		reg->umin_value = 0;
6798 		reg->umax_value = mask;
6799 	}
6800 	reg->smin_value = reg->umin_value;
6801 	reg->smax_value = reg->umax_value;
6802 
6803 	/* If size is smaller than 32bit register the 32bit register
6804 	 * values are also truncated so we push 64-bit bounds into
6805 	 * 32-bit bounds. Above were truncated < 32-bits already.
6806 	 */
6807 	if (size < 4)
6808 		__mark_reg32_unbounded(reg);
6809 
6810 	reg_bounds_sync(reg);
6811 }
6812 
6813 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6814 {
6815 	if (size == 1) {
6816 		reg->smin_value = reg->s32_min_value = S8_MIN;
6817 		reg->smax_value = reg->s32_max_value = S8_MAX;
6818 	} else if (size == 2) {
6819 		reg->smin_value = reg->s32_min_value = S16_MIN;
6820 		reg->smax_value = reg->s32_max_value = S16_MAX;
6821 	} else {
6822 		/* size == 4 */
6823 		reg->smin_value = reg->s32_min_value = S32_MIN;
6824 		reg->smax_value = reg->s32_max_value = S32_MAX;
6825 	}
6826 	reg->umin_value = reg->u32_min_value = 0;
6827 	reg->umax_value = U64_MAX;
6828 	reg->u32_max_value = U32_MAX;
6829 	reg->var_off = tnum_unknown;
6830 }
6831 
6832 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6833 {
6834 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6835 	u64 top_smax_value, top_smin_value;
6836 	u64 num_bits = size * 8;
6837 
6838 	if (tnum_is_const(reg->var_off)) {
6839 		u64_cval = reg->var_off.value;
6840 		if (size == 1)
6841 			reg->var_off = tnum_const((s8)u64_cval);
6842 		else if (size == 2)
6843 			reg->var_off = tnum_const((s16)u64_cval);
6844 		else
6845 			/* size == 4 */
6846 			reg->var_off = tnum_const((s32)u64_cval);
6847 
6848 		u64_cval = reg->var_off.value;
6849 		reg->smax_value = reg->smin_value = u64_cval;
6850 		reg->umax_value = reg->umin_value = u64_cval;
6851 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6852 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6853 		return;
6854 	}
6855 
6856 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6857 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6858 
6859 	if (top_smax_value != top_smin_value)
6860 		goto out;
6861 
6862 	/* find the s64_min and s64_min after sign extension */
6863 	if (size == 1) {
6864 		init_s64_max = (s8)reg->smax_value;
6865 		init_s64_min = (s8)reg->smin_value;
6866 	} else if (size == 2) {
6867 		init_s64_max = (s16)reg->smax_value;
6868 		init_s64_min = (s16)reg->smin_value;
6869 	} else {
6870 		init_s64_max = (s32)reg->smax_value;
6871 		init_s64_min = (s32)reg->smin_value;
6872 	}
6873 
6874 	s64_max = max(init_s64_max, init_s64_min);
6875 	s64_min = min(init_s64_max, init_s64_min);
6876 
6877 	/* both of s64_max/s64_min positive or negative */
6878 	if ((s64_max >= 0) == (s64_min >= 0)) {
6879 		reg->s32_min_value = reg->smin_value = s64_min;
6880 		reg->s32_max_value = reg->smax_value = s64_max;
6881 		reg->u32_min_value = reg->umin_value = s64_min;
6882 		reg->u32_max_value = reg->umax_value = s64_max;
6883 		reg->var_off = tnum_range(s64_min, s64_max);
6884 		return;
6885 	}
6886 
6887 out:
6888 	set_sext64_default_val(reg, size);
6889 }
6890 
6891 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6892 {
6893 	if (size == 1) {
6894 		reg->s32_min_value = S8_MIN;
6895 		reg->s32_max_value = S8_MAX;
6896 	} else {
6897 		/* size == 2 */
6898 		reg->s32_min_value = S16_MIN;
6899 		reg->s32_max_value = S16_MAX;
6900 	}
6901 	reg->u32_min_value = 0;
6902 	reg->u32_max_value = U32_MAX;
6903 	reg->var_off = tnum_subreg(tnum_unknown);
6904 }
6905 
6906 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6907 {
6908 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6909 	u32 top_smax_value, top_smin_value;
6910 	u32 num_bits = size * 8;
6911 
6912 	if (tnum_is_const(reg->var_off)) {
6913 		u32_val = reg->var_off.value;
6914 		if (size == 1)
6915 			reg->var_off = tnum_const((s8)u32_val);
6916 		else
6917 			reg->var_off = tnum_const((s16)u32_val);
6918 
6919 		u32_val = reg->var_off.value;
6920 		reg->s32_min_value = reg->s32_max_value = u32_val;
6921 		reg->u32_min_value = reg->u32_max_value = u32_val;
6922 		return;
6923 	}
6924 
6925 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6926 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6927 
6928 	if (top_smax_value != top_smin_value)
6929 		goto out;
6930 
6931 	/* find the s32_min and s32_min after sign extension */
6932 	if (size == 1) {
6933 		init_s32_max = (s8)reg->s32_max_value;
6934 		init_s32_min = (s8)reg->s32_min_value;
6935 	} else {
6936 		/* size == 2 */
6937 		init_s32_max = (s16)reg->s32_max_value;
6938 		init_s32_min = (s16)reg->s32_min_value;
6939 	}
6940 	s32_max = max(init_s32_max, init_s32_min);
6941 	s32_min = min(init_s32_max, init_s32_min);
6942 
6943 	if ((s32_min >= 0) == (s32_max >= 0)) {
6944 		reg->s32_min_value = s32_min;
6945 		reg->s32_max_value = s32_max;
6946 		reg->u32_min_value = (u32)s32_min;
6947 		reg->u32_max_value = (u32)s32_max;
6948 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6949 		return;
6950 	}
6951 
6952 out:
6953 	set_sext32_default_val(reg, size);
6954 }
6955 
6956 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6957 {
6958 	/* A map is considered read-only if the following condition are true:
6959 	 *
6960 	 * 1) BPF program side cannot change any of the map content. The
6961 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6962 	 *    and was set at map creation time.
6963 	 * 2) The map value(s) have been initialized from user space by a
6964 	 *    loader and then "frozen", such that no new map update/delete
6965 	 *    operations from syscall side are possible for the rest of
6966 	 *    the map's lifetime from that point onwards.
6967 	 * 3) Any parallel/pending map update/delete operations from syscall
6968 	 *    side have been completed. Only after that point, it's safe to
6969 	 *    assume that map value(s) are immutable.
6970 	 */
6971 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6972 	       READ_ONCE(map->frozen) &&
6973 	       !bpf_map_write_active(map);
6974 }
6975 
6976 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6977 			       bool is_ldsx)
6978 {
6979 	void *ptr;
6980 	u64 addr;
6981 	int err;
6982 
6983 	err = map->ops->map_direct_value_addr(map, &addr, off);
6984 	if (err)
6985 		return err;
6986 	ptr = (void *)(long)addr + off;
6987 
6988 	switch (size) {
6989 	case sizeof(u8):
6990 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6991 		break;
6992 	case sizeof(u16):
6993 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6994 		break;
6995 	case sizeof(u32):
6996 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6997 		break;
6998 	case sizeof(u64):
6999 		*val = *(u64 *)ptr;
7000 		break;
7001 	default:
7002 		return -EINVAL;
7003 	}
7004 	return 0;
7005 }
7006 
7007 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
7008 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
7009 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
7010 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
7011 
7012 /*
7013  * Allow list few fields as RCU trusted or full trusted.
7014  * This logic doesn't allow mix tagging and will be removed once GCC supports
7015  * btf_type_tag.
7016  */
7017 
7018 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
7019 BTF_TYPE_SAFE_RCU(struct task_struct) {
7020 	const cpumask_t *cpus_ptr;
7021 	struct css_set __rcu *cgroups;
7022 	struct task_struct __rcu *real_parent;
7023 	struct task_struct *group_leader;
7024 };
7025 
7026 BTF_TYPE_SAFE_RCU(struct cgroup) {
7027 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
7028 	struct kernfs_node *kn;
7029 };
7030 
7031 BTF_TYPE_SAFE_RCU(struct css_set) {
7032 	struct cgroup *dfl_cgrp;
7033 };
7034 
7035 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) {
7036 	struct cgroup *cgroup;
7037 };
7038 
7039 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
7040 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
7041 	struct file __rcu *exe_file;
7042 };
7043 
7044 /* skb->sk, req->sk are not RCU protected, but we mark them as such
7045  * because bpf prog accessible sockets are SOCK_RCU_FREE.
7046  */
7047 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
7048 	struct sock *sk;
7049 };
7050 
7051 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
7052 	struct sock *sk;
7053 };
7054 
7055 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
7056 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
7057 	struct seq_file *seq;
7058 };
7059 
7060 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
7061 	struct bpf_iter_meta *meta;
7062 	struct task_struct *task;
7063 };
7064 
7065 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
7066 	struct file *file;
7067 };
7068 
7069 BTF_TYPE_SAFE_TRUSTED(struct file) {
7070 	struct inode *f_inode;
7071 };
7072 
7073 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {
7074 	struct inode *d_inode;
7075 };
7076 
7077 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
7078 	struct sock *sk;
7079 };
7080 
7081 static bool type_is_rcu(struct bpf_verifier_env *env,
7082 			struct bpf_reg_state *reg,
7083 			const char *field_name, u32 btf_id)
7084 {
7085 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
7086 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
7087 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
7088 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state));
7089 
7090 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
7091 }
7092 
7093 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
7094 				struct bpf_reg_state *reg,
7095 				const char *field_name, u32 btf_id)
7096 {
7097 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
7098 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
7099 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
7100 
7101 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
7102 }
7103 
7104 static bool type_is_trusted(struct bpf_verifier_env *env,
7105 			    struct bpf_reg_state *reg,
7106 			    const char *field_name, u32 btf_id)
7107 {
7108 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
7109 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
7110 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
7111 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
7112 
7113 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
7114 }
7115 
7116 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
7117 				    struct bpf_reg_state *reg,
7118 				    const char *field_name, u32 btf_id)
7119 {
7120 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
7121 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
7122 
7123 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
7124 					  "__safe_trusted_or_null");
7125 }
7126 
7127 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
7128 				   struct bpf_reg_state *regs,
7129 				   int regno, int off, int size,
7130 				   enum bpf_access_type atype,
7131 				   int value_regno)
7132 {
7133 	struct bpf_reg_state *reg = regs + regno;
7134 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
7135 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
7136 	const char *field_name = NULL;
7137 	enum bpf_type_flag flag = 0;
7138 	u32 btf_id = 0;
7139 	int ret;
7140 
7141 	if (!env->allow_ptr_leaks) {
7142 		verbose(env,
7143 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7144 			tname);
7145 		return -EPERM;
7146 	}
7147 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
7148 		verbose(env,
7149 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
7150 			tname);
7151 		return -EINVAL;
7152 	}
7153 	if (off < 0) {
7154 		verbose(env,
7155 			"R%d is ptr_%s invalid negative access: off=%d\n",
7156 			regno, tname, off);
7157 		return -EACCES;
7158 	}
7159 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
7160 		char tn_buf[48];
7161 
7162 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7163 		verbose(env,
7164 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
7165 			regno, tname, off, tn_buf);
7166 		return -EACCES;
7167 	}
7168 
7169 	if (reg->type & MEM_USER) {
7170 		verbose(env,
7171 			"R%d is ptr_%s access user memory: off=%d\n",
7172 			regno, tname, off);
7173 		return -EACCES;
7174 	}
7175 
7176 	if (reg->type & MEM_PERCPU) {
7177 		verbose(env,
7178 			"R%d is ptr_%s access percpu memory: off=%d\n",
7179 			regno, tname, off);
7180 		return -EACCES;
7181 	}
7182 
7183 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
7184 		if (!btf_is_kernel(reg->btf)) {
7185 			verifier_bug(env, "reg->btf must be kernel btf");
7186 			return -EFAULT;
7187 		}
7188 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
7189 	} else {
7190 		/* Writes are permitted with default btf_struct_access for
7191 		 * program allocated objects (which always have ref_obj_id > 0),
7192 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
7193 		 */
7194 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
7195 			verbose(env, "only read is supported\n");
7196 			return -EACCES;
7197 		}
7198 
7199 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
7200 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
7201 			verifier_bug(env, "ref_obj_id for allocated object must be non-zero");
7202 			return -EFAULT;
7203 		}
7204 
7205 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
7206 	}
7207 
7208 	if (ret < 0)
7209 		return ret;
7210 
7211 	if (ret != PTR_TO_BTF_ID) {
7212 		/* just mark; */
7213 
7214 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
7215 		/* If this is an untrusted pointer, all pointers formed by walking it
7216 		 * also inherit the untrusted flag.
7217 		 */
7218 		flag = PTR_UNTRUSTED;
7219 
7220 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
7221 		/* By default any pointer obtained from walking a trusted pointer is no
7222 		 * longer trusted, unless the field being accessed has explicitly been
7223 		 * marked as inheriting its parent's state of trust (either full or RCU).
7224 		 * For example:
7225 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
7226 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
7227 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
7228 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
7229 		 *
7230 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
7231 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
7232 		 */
7233 		if (type_is_trusted(env, reg, field_name, btf_id)) {
7234 			flag |= PTR_TRUSTED;
7235 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
7236 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
7237 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
7238 			if (type_is_rcu(env, reg, field_name, btf_id)) {
7239 				/* ignore __rcu tag and mark it MEM_RCU */
7240 				flag |= MEM_RCU;
7241 			} else if (flag & MEM_RCU ||
7242 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
7243 				/* __rcu tagged pointers can be NULL */
7244 				flag |= MEM_RCU | PTR_MAYBE_NULL;
7245 
7246 				/* We always trust them */
7247 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
7248 				    flag & PTR_UNTRUSTED)
7249 					flag &= ~PTR_UNTRUSTED;
7250 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
7251 				/* keep as-is */
7252 			} else {
7253 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
7254 				clear_trusted_flags(&flag);
7255 			}
7256 		} else {
7257 			/*
7258 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
7259 			 * aggressively mark as untrusted otherwise such
7260 			 * pointers will be plain PTR_TO_BTF_ID without flags
7261 			 * and will be allowed to be passed into helpers for
7262 			 * compat reasons.
7263 			 */
7264 			flag = PTR_UNTRUSTED;
7265 		}
7266 	} else {
7267 		/* Old compat. Deprecated */
7268 		clear_trusted_flags(&flag);
7269 	}
7270 
7271 	if (atype == BPF_READ && value_regno >= 0) {
7272 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
7273 		if (ret < 0)
7274 			return ret;
7275 	}
7276 
7277 	return 0;
7278 }
7279 
7280 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
7281 				   struct bpf_reg_state *regs,
7282 				   int regno, int off, int size,
7283 				   enum bpf_access_type atype,
7284 				   int value_regno)
7285 {
7286 	struct bpf_reg_state *reg = regs + regno;
7287 	struct bpf_map *map = reg->map_ptr;
7288 	struct bpf_reg_state map_reg;
7289 	enum bpf_type_flag flag = 0;
7290 	const struct btf_type *t;
7291 	const char *tname;
7292 	u32 btf_id;
7293 	int ret;
7294 
7295 	if (!btf_vmlinux) {
7296 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
7297 		return -ENOTSUPP;
7298 	}
7299 
7300 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
7301 		verbose(env, "map_ptr access not supported for map type %d\n",
7302 			map->map_type);
7303 		return -ENOTSUPP;
7304 	}
7305 
7306 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
7307 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
7308 
7309 	if (!env->allow_ptr_leaks) {
7310 		verbose(env,
7311 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7312 			tname);
7313 		return -EPERM;
7314 	}
7315 
7316 	if (off < 0) {
7317 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
7318 			regno, tname, off);
7319 		return -EACCES;
7320 	}
7321 
7322 	if (atype != BPF_READ) {
7323 		verbose(env, "only read from %s is supported\n", tname);
7324 		return -EACCES;
7325 	}
7326 
7327 	/* Simulate access to a PTR_TO_BTF_ID */
7328 	memset(&map_reg, 0, sizeof(map_reg));
7329 	ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID,
7330 			      btf_vmlinux, *map->ops->map_btf_id, 0);
7331 	if (ret < 0)
7332 		return ret;
7333 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
7334 	if (ret < 0)
7335 		return ret;
7336 
7337 	if (value_regno >= 0) {
7338 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
7339 		if (ret < 0)
7340 			return ret;
7341 	}
7342 
7343 	return 0;
7344 }
7345 
7346 /* Check that the stack access at the given offset is within bounds. The
7347  * maximum valid offset is -1.
7348  *
7349  * The minimum valid offset is -MAX_BPF_STACK for writes, and
7350  * -state->allocated_stack for reads.
7351  */
7352 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
7353                                           s64 off,
7354                                           struct bpf_func_state *state,
7355                                           enum bpf_access_type t)
7356 {
7357 	int min_valid_off;
7358 
7359 	if (t == BPF_WRITE || env->allow_uninit_stack)
7360 		min_valid_off = -MAX_BPF_STACK;
7361 	else
7362 		min_valid_off = -state->allocated_stack;
7363 
7364 	if (off < min_valid_off || off > -1)
7365 		return -EACCES;
7366 	return 0;
7367 }
7368 
7369 /* Check that the stack access at 'regno + off' falls within the maximum stack
7370  * bounds.
7371  *
7372  * 'off' includes `regno->offset`, but not its dynamic part (if any).
7373  */
7374 static int check_stack_access_within_bounds(
7375 		struct bpf_verifier_env *env,
7376 		int regno, int off, int access_size,
7377 		enum bpf_access_type type)
7378 {
7379 	struct bpf_reg_state *regs = cur_regs(env);
7380 	struct bpf_reg_state *reg = regs + regno;
7381 	struct bpf_func_state *state = func(env, reg);
7382 	s64 min_off, max_off;
7383 	int err;
7384 	char *err_extra;
7385 
7386 	if (type == BPF_READ)
7387 		err_extra = " read from";
7388 	else
7389 		err_extra = " write to";
7390 
7391 	if (tnum_is_const(reg->var_off)) {
7392 		min_off = (s64)reg->var_off.value + off;
7393 		max_off = min_off + access_size;
7394 	} else {
7395 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
7396 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
7397 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
7398 				err_extra, regno);
7399 			return -EACCES;
7400 		}
7401 		min_off = reg->smin_value + off;
7402 		max_off = reg->smax_value + off + access_size;
7403 	}
7404 
7405 	err = check_stack_slot_within_bounds(env, min_off, state, type);
7406 	if (!err && max_off > 0)
7407 		err = -EINVAL; /* out of stack access into non-negative offsets */
7408 	if (!err && access_size < 0)
7409 		/* access_size should not be negative (or overflow an int); others checks
7410 		 * along the way should have prevented such an access.
7411 		 */
7412 		err = -EFAULT; /* invalid negative access size; integer overflow? */
7413 
7414 	if (err) {
7415 		if (tnum_is_const(reg->var_off)) {
7416 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
7417 				err_extra, regno, off, access_size);
7418 		} else {
7419 			char tn_buf[48];
7420 
7421 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7422 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
7423 				err_extra, regno, tn_buf, off, access_size);
7424 		}
7425 		return err;
7426 	}
7427 
7428 	/* Note that there is no stack access with offset zero, so the needed stack
7429 	 * size is -min_off, not -min_off+1.
7430 	 */
7431 	return grow_stack_state(env, state, -min_off /* size */);
7432 }
7433 
7434 static bool get_func_retval_range(struct bpf_prog *prog,
7435 				  struct bpf_retval_range *range)
7436 {
7437 	if (prog->type == BPF_PROG_TYPE_LSM &&
7438 		prog->expected_attach_type == BPF_LSM_MAC &&
7439 		!bpf_lsm_get_retval_range(prog, range)) {
7440 		return true;
7441 	}
7442 	return false;
7443 }
7444 
7445 /* check whether memory at (regno + off) is accessible for t = (read | write)
7446  * if t==write, value_regno is a register which value is stored into memory
7447  * if t==read, value_regno is a register which will receive the value from memory
7448  * if t==write && value_regno==-1, some unknown value is stored into memory
7449  * if t==read && value_regno==-1, don't care what we read from memory
7450  */
7451 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
7452 			    int off, int bpf_size, enum bpf_access_type t,
7453 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
7454 {
7455 	struct bpf_reg_state *regs = cur_regs(env);
7456 	struct bpf_reg_state *reg = regs + regno;
7457 	int size, err = 0;
7458 
7459 	size = bpf_size_to_bytes(bpf_size);
7460 	if (size < 0)
7461 		return size;
7462 
7463 	/* alignment checks will add in reg->off themselves */
7464 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
7465 	if (err)
7466 		return err;
7467 
7468 	/* for access checks, reg->off is just part of off */
7469 	off += reg->off;
7470 
7471 	if (reg->type == PTR_TO_MAP_KEY) {
7472 		if (t == BPF_WRITE) {
7473 			verbose(env, "write to change key R%d not allowed\n", regno);
7474 			return -EACCES;
7475 		}
7476 
7477 		err = check_mem_region_access(env, regno, off, size,
7478 					      reg->map_ptr->key_size, false);
7479 		if (err)
7480 			return err;
7481 		if (value_regno >= 0)
7482 			mark_reg_unknown(env, regs, value_regno);
7483 	} else if (reg->type == PTR_TO_MAP_VALUE) {
7484 		struct btf_field *kptr_field = NULL;
7485 
7486 		if (t == BPF_WRITE && value_regno >= 0 &&
7487 		    is_pointer_value(env, value_regno)) {
7488 			verbose(env, "R%d leaks addr into map\n", value_regno);
7489 			return -EACCES;
7490 		}
7491 		err = check_map_access_type(env, regno, off, size, t);
7492 		if (err)
7493 			return err;
7494 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
7495 		if (err)
7496 			return err;
7497 		if (tnum_is_const(reg->var_off))
7498 			kptr_field = btf_record_find(reg->map_ptr->record,
7499 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
7500 		if (kptr_field) {
7501 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
7502 		} else if (t == BPF_READ && value_regno >= 0) {
7503 			struct bpf_map *map = reg->map_ptr;
7504 
7505 			/* if map is read-only, track its contents as scalars */
7506 			if (tnum_is_const(reg->var_off) &&
7507 			    bpf_map_is_rdonly(map) &&
7508 			    map->ops->map_direct_value_addr) {
7509 				int map_off = off + reg->var_off.value;
7510 				u64 val = 0;
7511 
7512 				err = bpf_map_direct_read(map, map_off, size,
7513 							  &val, is_ldsx);
7514 				if (err)
7515 					return err;
7516 
7517 				regs[value_regno].type = SCALAR_VALUE;
7518 				__mark_reg_known(&regs[value_regno], val);
7519 			} else {
7520 				mark_reg_unknown(env, regs, value_regno);
7521 			}
7522 		}
7523 	} else if (base_type(reg->type) == PTR_TO_MEM) {
7524 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7525 		bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED);
7526 
7527 		if (type_may_be_null(reg->type)) {
7528 			verbose(env, "R%d invalid mem access '%s'\n", regno,
7529 				reg_type_str(env, reg->type));
7530 			return -EACCES;
7531 		}
7532 
7533 		if (t == BPF_WRITE && rdonly_mem) {
7534 			verbose(env, "R%d cannot write into %s\n",
7535 				regno, reg_type_str(env, reg->type));
7536 			return -EACCES;
7537 		}
7538 
7539 		if (t == BPF_WRITE && value_regno >= 0 &&
7540 		    is_pointer_value(env, value_regno)) {
7541 			verbose(env, "R%d leaks addr into mem\n", value_regno);
7542 			return -EACCES;
7543 		}
7544 
7545 		/*
7546 		 * Accesses to untrusted PTR_TO_MEM are done through probe
7547 		 * instructions, hence no need to check bounds in that case.
7548 		 */
7549 		if (!rdonly_untrusted)
7550 			err = check_mem_region_access(env, regno, off, size,
7551 						      reg->mem_size, false);
7552 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7553 			mark_reg_unknown(env, regs, value_regno);
7554 	} else if (reg->type == PTR_TO_CTX) {
7555 		struct bpf_retval_range range;
7556 		struct bpf_insn_access_aux info = {
7557 			.reg_type = SCALAR_VALUE,
7558 			.is_ldsx = is_ldsx,
7559 			.log = &env->log,
7560 		};
7561 
7562 		if (t == BPF_WRITE && value_regno >= 0 &&
7563 		    is_pointer_value(env, value_regno)) {
7564 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
7565 			return -EACCES;
7566 		}
7567 
7568 		err = check_ptr_off_reg(env, reg, regno);
7569 		if (err < 0)
7570 			return err;
7571 
7572 		err = check_ctx_access(env, insn_idx, off, size, t, &info);
7573 		if (err)
7574 			verbose_linfo(env, insn_idx, "; ");
7575 		if (!err && t == BPF_READ && value_regno >= 0) {
7576 			/* ctx access returns either a scalar, or a
7577 			 * PTR_TO_PACKET[_META,_END]. In the latter
7578 			 * case, we know the offset is zero.
7579 			 */
7580 			if (info.reg_type == SCALAR_VALUE) {
7581 				if (info.is_retval && get_func_retval_range(env->prog, &range)) {
7582 					err = __mark_reg_s32_range(env, regs, value_regno,
7583 								   range.minval, range.maxval);
7584 					if (err)
7585 						return err;
7586 				} else {
7587 					mark_reg_unknown(env, regs, value_regno);
7588 				}
7589 			} else {
7590 				mark_reg_known_zero(env, regs,
7591 						    value_regno);
7592 				if (type_may_be_null(info.reg_type))
7593 					regs[value_regno].id = ++env->id_gen;
7594 				/* A load of ctx field could have different
7595 				 * actual load size with the one encoded in the
7596 				 * insn. When the dst is PTR, it is for sure not
7597 				 * a sub-register.
7598 				 */
7599 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
7600 				if (base_type(info.reg_type) == PTR_TO_BTF_ID) {
7601 					regs[value_regno].btf = info.btf;
7602 					regs[value_regno].btf_id = info.btf_id;
7603 					regs[value_regno].ref_obj_id = info.ref_obj_id;
7604 				}
7605 			}
7606 			regs[value_regno].type = info.reg_type;
7607 		}
7608 
7609 	} else if (reg->type == PTR_TO_STACK) {
7610 		/* Basic bounds checks. */
7611 		err = check_stack_access_within_bounds(env, regno, off, size, t);
7612 		if (err)
7613 			return err;
7614 
7615 		if (t == BPF_READ)
7616 			err = check_stack_read(env, regno, off, size,
7617 					       value_regno);
7618 		else
7619 			err = check_stack_write(env, regno, off, size,
7620 						value_regno, insn_idx);
7621 	} else if (reg_is_pkt_pointer(reg)) {
7622 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7623 			verbose(env, "cannot write into packet\n");
7624 			return -EACCES;
7625 		}
7626 		if (t == BPF_WRITE && value_regno >= 0 &&
7627 		    is_pointer_value(env, value_regno)) {
7628 			verbose(env, "R%d leaks addr into packet\n",
7629 				value_regno);
7630 			return -EACCES;
7631 		}
7632 		err = check_packet_access(env, regno, off, size, false);
7633 		if (!err && t == BPF_READ && value_regno >= 0)
7634 			mark_reg_unknown(env, regs, value_regno);
7635 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
7636 		if (t == BPF_WRITE && value_regno >= 0 &&
7637 		    is_pointer_value(env, value_regno)) {
7638 			verbose(env, "R%d leaks addr into flow keys\n",
7639 				value_regno);
7640 			return -EACCES;
7641 		}
7642 
7643 		err = check_flow_keys_access(env, off, size);
7644 		if (!err && t == BPF_READ && value_regno >= 0)
7645 			mark_reg_unknown(env, regs, value_regno);
7646 	} else if (type_is_sk_pointer(reg->type)) {
7647 		if (t == BPF_WRITE) {
7648 			verbose(env, "R%d cannot write into %s\n",
7649 				regno, reg_type_str(env, reg->type));
7650 			return -EACCES;
7651 		}
7652 		err = check_sock_access(env, insn_idx, regno, off, size, t);
7653 		if (!err && value_regno >= 0)
7654 			mark_reg_unknown(env, regs, value_regno);
7655 	} else if (reg->type == PTR_TO_TP_BUFFER) {
7656 		err = check_tp_buffer_access(env, reg, regno, off, size);
7657 		if (!err && t == BPF_READ && value_regno >= 0)
7658 			mark_reg_unknown(env, regs, value_regno);
7659 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7660 		   !type_may_be_null(reg->type)) {
7661 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
7662 					      value_regno);
7663 	} else if (reg->type == CONST_PTR_TO_MAP) {
7664 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7665 					      value_regno);
7666 	} else if (base_type(reg->type) == PTR_TO_BUF) {
7667 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7668 		u32 *max_access;
7669 
7670 		if (rdonly_mem) {
7671 			if (t == BPF_WRITE) {
7672 				verbose(env, "R%d cannot write into %s\n",
7673 					regno, reg_type_str(env, reg->type));
7674 				return -EACCES;
7675 			}
7676 			max_access = &env->prog->aux->max_rdonly_access;
7677 		} else {
7678 			max_access = &env->prog->aux->max_rdwr_access;
7679 		}
7680 
7681 		err = check_buffer_access(env, reg, regno, off, size, false,
7682 					  max_access);
7683 
7684 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7685 			mark_reg_unknown(env, regs, value_regno);
7686 	} else if (reg->type == PTR_TO_ARENA) {
7687 		if (t == BPF_READ && value_regno >= 0)
7688 			mark_reg_unknown(env, regs, value_regno);
7689 	} else {
7690 		verbose(env, "R%d invalid mem access '%s'\n", regno,
7691 			reg_type_str(env, reg->type));
7692 		return -EACCES;
7693 	}
7694 
7695 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7696 	    regs[value_regno].type == SCALAR_VALUE) {
7697 		if (!is_ldsx)
7698 			/* b/h/w load zero-extends, mark upper bits as known 0 */
7699 			coerce_reg_to_size(&regs[value_regno], size);
7700 		else
7701 			coerce_reg_to_size_sx(&regs[value_regno], size);
7702 	}
7703 	return err;
7704 }
7705 
7706 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7707 			     bool allow_trust_mismatch);
7708 
7709 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
7710 			  bool strict_alignment_once, bool is_ldsx,
7711 			  bool allow_trust_mismatch, const char *ctx)
7712 {
7713 	struct bpf_reg_state *regs = cur_regs(env);
7714 	enum bpf_reg_type src_reg_type;
7715 	int err;
7716 
7717 	/* check src operand */
7718 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7719 	if (err)
7720 		return err;
7721 
7722 	/* check dst operand */
7723 	err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7724 	if (err)
7725 		return err;
7726 
7727 	src_reg_type = regs[insn->src_reg].type;
7728 
7729 	/* Check if (src_reg + off) is readable. The state of dst_reg will be
7730 	 * updated by this call.
7731 	 */
7732 	err = check_mem_access(env, env->insn_idx, insn->src_reg, insn->off,
7733 			       BPF_SIZE(insn->code), BPF_READ, insn->dst_reg,
7734 			       strict_alignment_once, is_ldsx);
7735 	err = err ?: save_aux_ptr_type(env, src_reg_type,
7736 				       allow_trust_mismatch);
7737 	err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], ctx);
7738 
7739 	return err;
7740 }
7741 
7742 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,
7743 			   bool strict_alignment_once)
7744 {
7745 	struct bpf_reg_state *regs = cur_regs(env);
7746 	enum bpf_reg_type dst_reg_type;
7747 	int err;
7748 
7749 	/* check src1 operand */
7750 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7751 	if (err)
7752 		return err;
7753 
7754 	/* check src2 operand */
7755 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7756 	if (err)
7757 		return err;
7758 
7759 	dst_reg_type = regs[insn->dst_reg].type;
7760 
7761 	/* Check if (dst_reg + off) is writeable. */
7762 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7763 			       BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg,
7764 			       strict_alignment_once, false);
7765 	err = err ?: save_aux_ptr_type(env, dst_reg_type, false);
7766 
7767 	return err;
7768 }
7769 
7770 static int check_atomic_rmw(struct bpf_verifier_env *env,
7771 			    struct bpf_insn *insn)
7772 {
7773 	int load_reg;
7774 	int err;
7775 
7776 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7777 		verbose(env, "invalid atomic operand size\n");
7778 		return -EINVAL;
7779 	}
7780 
7781 	/* check src1 operand */
7782 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7783 	if (err)
7784 		return err;
7785 
7786 	/* check src2 operand */
7787 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7788 	if (err)
7789 		return err;
7790 
7791 	if (insn->imm == BPF_CMPXCHG) {
7792 		/* Check comparison of R0 with memory location */
7793 		const u32 aux_reg = BPF_REG_0;
7794 
7795 		err = check_reg_arg(env, aux_reg, SRC_OP);
7796 		if (err)
7797 			return err;
7798 
7799 		if (is_pointer_value(env, aux_reg)) {
7800 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7801 			return -EACCES;
7802 		}
7803 	}
7804 
7805 	if (is_pointer_value(env, insn->src_reg)) {
7806 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7807 		return -EACCES;
7808 	}
7809 
7810 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7811 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7812 			insn->dst_reg,
7813 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7814 		return -EACCES;
7815 	}
7816 
7817 	if (insn->imm & BPF_FETCH) {
7818 		if (insn->imm == BPF_CMPXCHG)
7819 			load_reg = BPF_REG_0;
7820 		else
7821 			load_reg = insn->src_reg;
7822 
7823 		/* check and record load of old value */
7824 		err = check_reg_arg(env, load_reg, DST_OP);
7825 		if (err)
7826 			return err;
7827 	} else {
7828 		/* This instruction accesses a memory location but doesn't
7829 		 * actually load it into a register.
7830 		 */
7831 		load_reg = -1;
7832 	}
7833 
7834 	/* Check whether we can read the memory, with second call for fetch
7835 	 * case to simulate the register fill.
7836 	 */
7837 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7838 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7839 	if (!err && load_reg >= 0)
7840 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
7841 				       insn->off, BPF_SIZE(insn->code),
7842 				       BPF_READ, load_reg, true, false);
7843 	if (err)
7844 		return err;
7845 
7846 	if (is_arena_reg(env, insn->dst_reg)) {
7847 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
7848 		if (err)
7849 			return err;
7850 	}
7851 	/* Check whether we can write into the same memory. */
7852 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7853 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7854 	if (err)
7855 		return err;
7856 	return 0;
7857 }
7858 
7859 static int check_atomic_load(struct bpf_verifier_env *env,
7860 			     struct bpf_insn *insn)
7861 {
7862 	int err;
7863 
7864 	err = check_load_mem(env, insn, true, false, false, "atomic_load");
7865 	if (err)
7866 		return err;
7867 
7868 	if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) {
7869 		verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n",
7870 			insn->src_reg,
7871 			reg_type_str(env, reg_state(env, insn->src_reg)->type));
7872 		return -EACCES;
7873 	}
7874 
7875 	return 0;
7876 }
7877 
7878 static int check_atomic_store(struct bpf_verifier_env *env,
7879 			      struct bpf_insn *insn)
7880 {
7881 	int err;
7882 
7883 	err = check_store_reg(env, insn, true);
7884 	if (err)
7885 		return err;
7886 
7887 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7888 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7889 			insn->dst_reg,
7890 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7891 		return -EACCES;
7892 	}
7893 
7894 	return 0;
7895 }
7896 
7897 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn)
7898 {
7899 	switch (insn->imm) {
7900 	case BPF_ADD:
7901 	case BPF_ADD | BPF_FETCH:
7902 	case BPF_AND:
7903 	case BPF_AND | BPF_FETCH:
7904 	case BPF_OR:
7905 	case BPF_OR | BPF_FETCH:
7906 	case BPF_XOR:
7907 	case BPF_XOR | BPF_FETCH:
7908 	case BPF_XCHG:
7909 	case BPF_CMPXCHG:
7910 		return check_atomic_rmw(env, insn);
7911 	case BPF_LOAD_ACQ:
7912 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
7913 			verbose(env,
7914 				"64-bit load-acquires are only supported on 64-bit arches\n");
7915 			return -EOPNOTSUPP;
7916 		}
7917 		return check_atomic_load(env, insn);
7918 	case BPF_STORE_REL:
7919 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
7920 			verbose(env,
7921 				"64-bit store-releases are only supported on 64-bit arches\n");
7922 			return -EOPNOTSUPP;
7923 		}
7924 		return check_atomic_store(env, insn);
7925 	default:
7926 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n",
7927 			insn->imm);
7928 		return -EINVAL;
7929 	}
7930 }
7931 
7932 /* When register 'regno' is used to read the stack (either directly or through
7933  * a helper function) make sure that it's within stack boundary and, depending
7934  * on the access type and privileges, that all elements of the stack are
7935  * initialized.
7936  *
7937  * 'off' includes 'regno->off', but not its dynamic part (if any).
7938  *
7939  * All registers that have been spilled on the stack in the slots within the
7940  * read offsets are marked as read.
7941  */
7942 static int check_stack_range_initialized(
7943 		struct bpf_verifier_env *env, int regno, int off,
7944 		int access_size, bool zero_size_allowed,
7945 		enum bpf_access_type type, struct bpf_call_arg_meta *meta)
7946 {
7947 	struct bpf_reg_state *reg = reg_state(env, regno);
7948 	struct bpf_func_state *state = func(env, reg);
7949 	int err, min_off, max_off, i, j, slot, spi;
7950 	/* Some accesses can write anything into the stack, others are
7951 	 * read-only.
7952 	 */
7953 	bool clobber = false;
7954 
7955 	if (access_size == 0 && !zero_size_allowed) {
7956 		verbose(env, "invalid zero-sized read\n");
7957 		return -EACCES;
7958 	}
7959 
7960 	if (type == BPF_WRITE)
7961 		clobber = true;
7962 
7963 	err = check_stack_access_within_bounds(env, regno, off, access_size, type);
7964 	if (err)
7965 		return err;
7966 
7967 
7968 	if (tnum_is_const(reg->var_off)) {
7969 		min_off = max_off = reg->var_off.value + off;
7970 	} else {
7971 		/* Variable offset is prohibited for unprivileged mode for
7972 		 * simplicity since it requires corresponding support in
7973 		 * Spectre masking for stack ALU.
7974 		 * See also retrieve_ptr_limit().
7975 		 */
7976 		if (!env->bypass_spec_v1) {
7977 			char tn_buf[48];
7978 
7979 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7980 			verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
7981 				regno, tn_buf);
7982 			return -EACCES;
7983 		}
7984 		/* Only initialized buffer on stack is allowed to be accessed
7985 		 * with variable offset. With uninitialized buffer it's hard to
7986 		 * guarantee that whole memory is marked as initialized on
7987 		 * helper return since specific bounds are unknown what may
7988 		 * cause uninitialized stack leaking.
7989 		 */
7990 		if (meta && meta->raw_mode)
7991 			meta = NULL;
7992 
7993 		min_off = reg->smin_value + off;
7994 		max_off = reg->smax_value + off;
7995 	}
7996 
7997 	if (meta && meta->raw_mode) {
7998 		/* Ensure we won't be overwriting dynptrs when simulating byte
7999 		 * by byte access in check_helper_call using meta.access_size.
8000 		 * This would be a problem if we have a helper in the future
8001 		 * which takes:
8002 		 *
8003 		 *	helper(uninit_mem, len, dynptr)
8004 		 *
8005 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
8006 		 * may end up writing to dynptr itself when touching memory from
8007 		 * arg 1. This can be relaxed on a case by case basis for known
8008 		 * safe cases, but reject due to the possibilitiy of aliasing by
8009 		 * default.
8010 		 */
8011 		for (i = min_off; i < max_off + access_size; i++) {
8012 			int stack_off = -i - 1;
8013 
8014 			spi = __get_spi(i);
8015 			/* raw_mode may write past allocated_stack */
8016 			if (state->allocated_stack <= stack_off)
8017 				continue;
8018 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
8019 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
8020 				return -EACCES;
8021 			}
8022 		}
8023 		meta->access_size = access_size;
8024 		meta->regno = regno;
8025 		return 0;
8026 	}
8027 
8028 	for (i = min_off; i < max_off + access_size; i++) {
8029 		u8 *stype;
8030 
8031 		slot = -i - 1;
8032 		spi = slot / BPF_REG_SIZE;
8033 		if (state->allocated_stack <= slot) {
8034 			verbose(env, "allocated_stack too small\n");
8035 			return -EFAULT;
8036 		}
8037 
8038 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
8039 		if (*stype == STACK_MISC)
8040 			goto mark;
8041 		if ((*stype == STACK_ZERO) ||
8042 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
8043 			if (clobber) {
8044 				/* helper can write anything into the stack */
8045 				*stype = STACK_MISC;
8046 			}
8047 			goto mark;
8048 		}
8049 
8050 		if (is_spilled_reg(&state->stack[spi]) &&
8051 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
8052 		     env->allow_ptr_leaks)) {
8053 			if (clobber) {
8054 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
8055 				for (j = 0; j < BPF_REG_SIZE; j++)
8056 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
8057 			}
8058 			goto mark;
8059 		}
8060 
8061 		if (tnum_is_const(reg->var_off)) {
8062 			verbose(env, "invalid read from stack R%d off %d+%d size %d\n",
8063 				regno, min_off, i - min_off, access_size);
8064 		} else {
8065 			char tn_buf[48];
8066 
8067 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8068 			verbose(env, "invalid read from stack R%d var_off %s+%d size %d\n",
8069 				regno, tn_buf, i - min_off, access_size);
8070 		}
8071 		return -EACCES;
8072 mark:
8073 		/* reading any byte out of 8-byte 'spill_slot' will cause
8074 		 * the whole slot to be marked as 'read'
8075 		 */
8076 		err = bpf_mark_stack_read(env, reg->frameno, env->insn_idx, BIT(spi));
8077 		if (err)
8078 			return err;
8079 		/* We do not call bpf_mark_stack_write(), as we can not
8080 		 * be sure that whether stack slot is written to or not. Hence,
8081 		 * we must still conservatively propagate reads upwards even if
8082 		 * helper may write to the entire memory range.
8083 		 */
8084 	}
8085 	return 0;
8086 }
8087 
8088 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
8089 				   int access_size, enum bpf_access_type access_type,
8090 				   bool zero_size_allowed,
8091 				   struct bpf_call_arg_meta *meta)
8092 {
8093 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8094 	u32 *max_access;
8095 
8096 	switch (base_type(reg->type)) {
8097 	case PTR_TO_PACKET:
8098 	case PTR_TO_PACKET_META:
8099 		return check_packet_access(env, regno, reg->off, access_size,
8100 					   zero_size_allowed);
8101 	case PTR_TO_MAP_KEY:
8102 		if (access_type == BPF_WRITE) {
8103 			verbose(env, "R%d cannot write into %s\n", regno,
8104 				reg_type_str(env, reg->type));
8105 			return -EACCES;
8106 		}
8107 		return check_mem_region_access(env, regno, reg->off, access_size,
8108 					       reg->map_ptr->key_size, false);
8109 	case PTR_TO_MAP_VALUE:
8110 		if (check_map_access_type(env, regno, reg->off, access_size, access_type))
8111 			return -EACCES;
8112 		return check_map_access(env, regno, reg->off, access_size,
8113 					zero_size_allowed, ACCESS_HELPER);
8114 	case PTR_TO_MEM:
8115 		if (type_is_rdonly_mem(reg->type)) {
8116 			if (access_type == BPF_WRITE) {
8117 				verbose(env, "R%d cannot write into %s\n", regno,
8118 					reg_type_str(env, reg->type));
8119 				return -EACCES;
8120 			}
8121 		}
8122 		return check_mem_region_access(env, regno, reg->off,
8123 					       access_size, reg->mem_size,
8124 					       zero_size_allowed);
8125 	case PTR_TO_BUF:
8126 		if (type_is_rdonly_mem(reg->type)) {
8127 			if (access_type == BPF_WRITE) {
8128 				verbose(env, "R%d cannot write into %s\n", regno,
8129 					reg_type_str(env, reg->type));
8130 				return -EACCES;
8131 			}
8132 
8133 			max_access = &env->prog->aux->max_rdonly_access;
8134 		} else {
8135 			max_access = &env->prog->aux->max_rdwr_access;
8136 		}
8137 		return check_buffer_access(env, reg, regno, reg->off,
8138 					   access_size, zero_size_allowed,
8139 					   max_access);
8140 	case PTR_TO_STACK:
8141 		return check_stack_range_initialized(
8142 				env,
8143 				regno, reg->off, access_size,
8144 				zero_size_allowed, access_type, meta);
8145 	case PTR_TO_BTF_ID:
8146 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
8147 					       access_size, BPF_READ, -1);
8148 	case PTR_TO_CTX:
8149 		/* in case the function doesn't know how to access the context,
8150 		 * (because we are in a program of type SYSCALL for example), we
8151 		 * can not statically check its size.
8152 		 * Dynamically check it now.
8153 		 */
8154 		if (!env->ops->convert_ctx_access) {
8155 			int offset = access_size - 1;
8156 
8157 			/* Allow zero-byte read from PTR_TO_CTX */
8158 			if (access_size == 0)
8159 				return zero_size_allowed ? 0 : -EACCES;
8160 
8161 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
8162 						access_type, -1, false, false);
8163 		}
8164 
8165 		fallthrough;
8166 	default: /* scalar_value or invalid ptr */
8167 		/* Allow zero-byte read from NULL, regardless of pointer type */
8168 		if (zero_size_allowed && access_size == 0 &&
8169 		    register_is_null(reg))
8170 			return 0;
8171 
8172 		verbose(env, "R%d type=%s ", regno,
8173 			reg_type_str(env, reg->type));
8174 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
8175 		return -EACCES;
8176 	}
8177 }
8178 
8179 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
8180  * size.
8181  *
8182  * @regno is the register containing the access size. regno-1 is the register
8183  * containing the pointer.
8184  */
8185 static int check_mem_size_reg(struct bpf_verifier_env *env,
8186 			      struct bpf_reg_state *reg, u32 regno,
8187 			      enum bpf_access_type access_type,
8188 			      bool zero_size_allowed,
8189 			      struct bpf_call_arg_meta *meta)
8190 {
8191 	int err;
8192 
8193 	/* This is used to refine r0 return value bounds for helpers
8194 	 * that enforce this value as an upper bound on return values.
8195 	 * See do_refine_retval_range() for helpers that can refine
8196 	 * the return value. C type of helper is u32 so we pull register
8197 	 * bound from umax_value however, if negative verifier errors
8198 	 * out. Only upper bounds can be learned because retval is an
8199 	 * int type and negative retvals are allowed.
8200 	 */
8201 	meta->msize_max_value = reg->umax_value;
8202 
8203 	/* The register is SCALAR_VALUE; the access check happens using
8204 	 * its boundaries. For unprivileged variable accesses, disable
8205 	 * raw mode so that the program is required to initialize all
8206 	 * the memory that the helper could just partially fill up.
8207 	 */
8208 	if (!tnum_is_const(reg->var_off))
8209 		meta = NULL;
8210 
8211 	if (reg->smin_value < 0) {
8212 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
8213 			regno);
8214 		return -EACCES;
8215 	}
8216 
8217 	if (reg->umin_value == 0 && !zero_size_allowed) {
8218 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
8219 			regno, reg->umin_value, reg->umax_value);
8220 		return -EACCES;
8221 	}
8222 
8223 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
8224 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
8225 			regno);
8226 		return -EACCES;
8227 	}
8228 	err = check_helper_mem_access(env, regno - 1, reg->umax_value,
8229 				      access_type, zero_size_allowed, meta);
8230 	if (!err)
8231 		err = mark_chain_precision(env, regno);
8232 	return err;
8233 }
8234 
8235 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8236 			 u32 regno, u32 mem_size)
8237 {
8238 	bool may_be_null = type_may_be_null(reg->type);
8239 	struct bpf_reg_state saved_reg;
8240 	int err;
8241 
8242 	if (register_is_null(reg))
8243 		return 0;
8244 
8245 	/* Assuming that the register contains a value check if the memory
8246 	 * access is safe. Temporarily save and restore the register's state as
8247 	 * the conversion shouldn't be visible to a caller.
8248 	 */
8249 	if (may_be_null) {
8250 		saved_reg = *reg;
8251 		mark_ptr_not_null_reg(reg);
8252 	}
8253 
8254 	err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL);
8255 	err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL);
8256 
8257 	if (may_be_null)
8258 		*reg = saved_reg;
8259 
8260 	return err;
8261 }
8262 
8263 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8264 				    u32 regno)
8265 {
8266 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
8267 	bool may_be_null = type_may_be_null(mem_reg->type);
8268 	struct bpf_reg_state saved_reg;
8269 	struct bpf_call_arg_meta meta;
8270 	int err;
8271 
8272 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
8273 
8274 	memset(&meta, 0, sizeof(meta));
8275 
8276 	if (may_be_null) {
8277 		saved_reg = *mem_reg;
8278 		mark_ptr_not_null_reg(mem_reg);
8279 	}
8280 
8281 	err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta);
8282 	err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta);
8283 
8284 	if (may_be_null)
8285 		*mem_reg = saved_reg;
8286 
8287 	return err;
8288 }
8289 
8290 enum {
8291 	PROCESS_SPIN_LOCK = (1 << 0),
8292 	PROCESS_RES_LOCK  = (1 << 1),
8293 	PROCESS_LOCK_IRQ  = (1 << 2),
8294 };
8295 
8296 /* Implementation details:
8297  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
8298  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
8299  * Two bpf_map_lookups (even with the same key) will have different reg->id.
8300  * Two separate bpf_obj_new will also have different reg->id.
8301  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
8302  * clears reg->id after value_or_null->value transition, since the verifier only
8303  * cares about the range of access to valid map value pointer and doesn't care
8304  * about actual address of the map element.
8305  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
8306  * reg->id > 0 after value_or_null->value transition. By doing so
8307  * two bpf_map_lookups will be considered two different pointers that
8308  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
8309  * returned from bpf_obj_new.
8310  * The verifier allows taking only one bpf_spin_lock at a time to avoid
8311  * dead-locks.
8312  * Since only one bpf_spin_lock is allowed the checks are simpler than
8313  * reg_is_refcounted() logic. The verifier needs to remember only
8314  * one spin_lock instead of array of acquired_refs.
8315  * env->cur_state->active_locks remembers which map value element or allocated
8316  * object got locked and clears it after bpf_spin_unlock.
8317  */
8318 static int process_spin_lock(struct bpf_verifier_env *env, int regno, int flags)
8319 {
8320 	bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK;
8321 	const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin";
8322 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8323 	struct bpf_verifier_state *cur = env->cur_state;
8324 	bool is_const = tnum_is_const(reg->var_off);
8325 	bool is_irq = flags & PROCESS_LOCK_IRQ;
8326 	u64 val = reg->var_off.value;
8327 	struct bpf_map *map = NULL;
8328 	struct btf *btf = NULL;
8329 	struct btf_record *rec;
8330 	u32 spin_lock_off;
8331 	int err;
8332 
8333 	if (!is_const) {
8334 		verbose(env,
8335 			"R%d doesn't have constant offset. %s_lock has to be at the constant offset\n",
8336 			regno, lock_str);
8337 		return -EINVAL;
8338 	}
8339 	if (reg->type == PTR_TO_MAP_VALUE) {
8340 		map = reg->map_ptr;
8341 		if (!map->btf) {
8342 			verbose(env,
8343 				"map '%s' has to have BTF in order to use %s_lock\n",
8344 				map->name, lock_str);
8345 			return -EINVAL;
8346 		}
8347 	} else {
8348 		btf = reg->btf;
8349 	}
8350 
8351 	rec = reg_btf_record(reg);
8352 	if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) {
8353 		verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local",
8354 			map ? map->name : "kptr", lock_str);
8355 		return -EINVAL;
8356 	}
8357 	spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off;
8358 	if (spin_lock_off != val + reg->off) {
8359 		verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n",
8360 			val + reg->off, lock_str, spin_lock_off);
8361 		return -EINVAL;
8362 	}
8363 	if (is_lock) {
8364 		void *ptr;
8365 		int type;
8366 
8367 		if (map)
8368 			ptr = map;
8369 		else
8370 			ptr = btf;
8371 
8372 		if (!is_res_lock && cur->active_locks) {
8373 			if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) {
8374 				verbose(env,
8375 					"Locking two bpf_spin_locks are not allowed\n");
8376 				return -EINVAL;
8377 			}
8378 		} else if (is_res_lock && cur->active_locks) {
8379 			if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) {
8380 				verbose(env, "Acquiring the same lock again, AA deadlock detected\n");
8381 				return -EINVAL;
8382 			}
8383 		}
8384 
8385 		if (is_res_lock && is_irq)
8386 			type = REF_TYPE_RES_LOCK_IRQ;
8387 		else if (is_res_lock)
8388 			type = REF_TYPE_RES_LOCK;
8389 		else
8390 			type = REF_TYPE_LOCK;
8391 		err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr);
8392 		if (err < 0) {
8393 			verbose(env, "Failed to acquire lock state\n");
8394 			return err;
8395 		}
8396 	} else {
8397 		void *ptr;
8398 		int type;
8399 
8400 		if (map)
8401 			ptr = map;
8402 		else
8403 			ptr = btf;
8404 
8405 		if (!cur->active_locks) {
8406 			verbose(env, "%s_unlock without taking a lock\n", lock_str);
8407 			return -EINVAL;
8408 		}
8409 
8410 		if (is_res_lock && is_irq)
8411 			type = REF_TYPE_RES_LOCK_IRQ;
8412 		else if (is_res_lock)
8413 			type = REF_TYPE_RES_LOCK;
8414 		else
8415 			type = REF_TYPE_LOCK;
8416 		if (!find_lock_state(cur, type, reg->id, ptr)) {
8417 			verbose(env, "%s_unlock of different lock\n", lock_str);
8418 			return -EINVAL;
8419 		}
8420 		if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) {
8421 			verbose(env, "%s_unlock cannot be out of order\n", lock_str);
8422 			return -EINVAL;
8423 		}
8424 		if (release_lock_state(cur, type, reg->id, ptr)) {
8425 			verbose(env, "%s_unlock of different lock\n", lock_str);
8426 			return -EINVAL;
8427 		}
8428 
8429 		invalidate_non_owning_refs(env);
8430 	}
8431 	return 0;
8432 }
8433 
8434 /* Check if @regno is a pointer to a specific field in a map value */
8435 static int check_map_field_pointer(struct bpf_verifier_env *env, u32 regno,
8436 				   enum btf_field_type field_type)
8437 {
8438 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8439 	bool is_const = tnum_is_const(reg->var_off);
8440 	struct bpf_map *map = reg->map_ptr;
8441 	u64 val = reg->var_off.value;
8442 	const char *struct_name = btf_field_type_name(field_type);
8443 	int field_off = -1;
8444 
8445 	if (!is_const) {
8446 		verbose(env,
8447 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
8448 			regno, struct_name);
8449 		return -EINVAL;
8450 	}
8451 	if (!map->btf) {
8452 		verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name,
8453 			struct_name);
8454 		return -EINVAL;
8455 	}
8456 	if (!btf_record_has_field(map->record, field_type)) {
8457 		verbose(env, "map '%s' has no valid %s\n", map->name, struct_name);
8458 		return -EINVAL;
8459 	}
8460 	switch (field_type) {
8461 	case BPF_TIMER:
8462 		field_off = map->record->timer_off;
8463 		break;
8464 	case BPF_TASK_WORK:
8465 		field_off = map->record->task_work_off;
8466 		break;
8467 	default:
8468 		verifier_bug(env, "unsupported BTF field type: %s\n", struct_name);
8469 		return -EINVAL;
8470 	}
8471 	if (field_off != val + reg->off) {
8472 		verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n",
8473 			val + reg->off, struct_name, field_off);
8474 		return -EINVAL;
8475 	}
8476 	return 0;
8477 }
8478 
8479 static int process_timer_func(struct bpf_verifier_env *env, int regno,
8480 			      struct bpf_call_arg_meta *meta)
8481 {
8482 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8483 	struct bpf_map *map = reg->map_ptr;
8484 	int err;
8485 
8486 	err = check_map_field_pointer(env, regno, BPF_TIMER);
8487 	if (err)
8488 		return err;
8489 
8490 	if (meta->map_ptr) {
8491 		verifier_bug(env, "Two map pointers in a timer helper");
8492 		return -EFAULT;
8493 	}
8494 	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
8495 		verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n");
8496 		return -EOPNOTSUPP;
8497 	}
8498 	meta->map_uid = reg->map_uid;
8499 	meta->map_ptr = map;
8500 	return 0;
8501 }
8502 
8503 static int process_wq_func(struct bpf_verifier_env *env, int regno,
8504 			   struct bpf_kfunc_call_arg_meta *meta)
8505 {
8506 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8507 	struct bpf_map *map = reg->map_ptr;
8508 	u64 val = reg->var_off.value;
8509 
8510 	if (map->record->wq_off != val + reg->off) {
8511 		verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n",
8512 			val + reg->off, map->record->wq_off);
8513 		return -EINVAL;
8514 	}
8515 	meta->map.uid = reg->map_uid;
8516 	meta->map.ptr = map;
8517 	return 0;
8518 }
8519 
8520 static int process_task_work_func(struct bpf_verifier_env *env, int regno,
8521 				  struct bpf_kfunc_call_arg_meta *meta)
8522 {
8523 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8524 	struct bpf_map *map = reg->map_ptr;
8525 	int err;
8526 
8527 	err = check_map_field_pointer(env, regno, BPF_TASK_WORK);
8528 	if (err)
8529 		return err;
8530 
8531 	if (meta->map.ptr) {
8532 		verifier_bug(env, "Two map pointers in a bpf_task_work helper");
8533 		return -EFAULT;
8534 	}
8535 	meta->map.uid = reg->map_uid;
8536 	meta->map.ptr = map;
8537 	return 0;
8538 }
8539 
8540 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
8541 			     struct bpf_call_arg_meta *meta)
8542 {
8543 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8544 	struct btf_field *kptr_field;
8545 	struct bpf_map *map_ptr;
8546 	struct btf_record *rec;
8547 	u32 kptr_off;
8548 
8549 	if (type_is_ptr_alloc_obj(reg->type)) {
8550 		rec = reg_btf_record(reg);
8551 	} else { /* PTR_TO_MAP_VALUE */
8552 		map_ptr = reg->map_ptr;
8553 		if (!map_ptr->btf) {
8554 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
8555 				map_ptr->name);
8556 			return -EINVAL;
8557 		}
8558 		rec = map_ptr->record;
8559 		meta->map_ptr = map_ptr;
8560 	}
8561 
8562 	if (!tnum_is_const(reg->var_off)) {
8563 		verbose(env,
8564 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
8565 			regno);
8566 		return -EINVAL;
8567 	}
8568 
8569 	if (!btf_record_has_field(rec, BPF_KPTR)) {
8570 		verbose(env, "R%d has no valid kptr\n", regno);
8571 		return -EINVAL;
8572 	}
8573 
8574 	kptr_off = reg->off + reg->var_off.value;
8575 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
8576 	if (!kptr_field) {
8577 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
8578 		return -EACCES;
8579 	}
8580 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
8581 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
8582 		return -EACCES;
8583 	}
8584 	meta->kptr_field = kptr_field;
8585 	return 0;
8586 }
8587 
8588 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
8589  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
8590  *
8591  * In both cases we deal with the first 8 bytes, but need to mark the next 8
8592  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
8593  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
8594  *
8595  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
8596  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
8597  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
8598  * mutate the view of the dynptr and also possibly destroy it. In the latter
8599  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
8600  * memory that dynptr points to.
8601  *
8602  * The verifier will keep track both levels of mutation (bpf_dynptr's in
8603  * reg->type and the memory's in reg->dynptr.type), but there is no support for
8604  * readonly dynptr view yet, hence only the first case is tracked and checked.
8605  *
8606  * This is consistent with how C applies the const modifier to a struct object,
8607  * where the pointer itself inside bpf_dynptr becomes const but not what it
8608  * points to.
8609  *
8610  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
8611  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
8612  */
8613 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
8614 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
8615 {
8616 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8617 	int err;
8618 
8619 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
8620 		verbose(env,
8621 			"arg#%d expected pointer to stack or const struct bpf_dynptr\n",
8622 			regno - 1);
8623 		return -EINVAL;
8624 	}
8625 
8626 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
8627 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
8628 	 */
8629 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
8630 		verifier_bug(env, "misconfigured dynptr helper type flags");
8631 		return -EFAULT;
8632 	}
8633 
8634 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
8635 	 *		 constructing a mutable bpf_dynptr object.
8636 	 *
8637 	 *		 Currently, this is only possible with PTR_TO_STACK
8638 	 *		 pointing to a region of at least 16 bytes which doesn't
8639 	 *		 contain an existing bpf_dynptr.
8640 	 *
8641 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
8642 	 *		 mutated or destroyed. However, the memory it points to
8643 	 *		 may be mutated.
8644 	 *
8645 	 *  None       - Points to a initialized dynptr that can be mutated and
8646 	 *		 destroyed, including mutation of the memory it points
8647 	 *		 to.
8648 	 */
8649 	if (arg_type & MEM_UNINIT) {
8650 		int i;
8651 
8652 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
8653 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
8654 			return -EINVAL;
8655 		}
8656 
8657 		/* we write BPF_DW bits (8 bytes) at a time */
8658 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8659 			err = check_mem_access(env, insn_idx, regno,
8660 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8661 			if (err)
8662 				return err;
8663 		}
8664 
8665 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
8666 	} else /* MEM_RDONLY and None case from above */ {
8667 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
8668 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
8669 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
8670 			return -EINVAL;
8671 		}
8672 
8673 		if (!is_dynptr_reg_valid_init(env, reg)) {
8674 			verbose(env,
8675 				"Expected an initialized dynptr as arg #%d\n",
8676 				regno - 1);
8677 			return -EINVAL;
8678 		}
8679 
8680 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
8681 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
8682 			verbose(env,
8683 				"Expected a dynptr of type %s as arg #%d\n",
8684 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1);
8685 			return -EINVAL;
8686 		}
8687 
8688 		err = mark_dynptr_read(env, reg);
8689 	}
8690 	return err;
8691 }
8692 
8693 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
8694 {
8695 	struct bpf_func_state *state = func(env, reg);
8696 
8697 	return state->stack[spi].spilled_ptr.ref_obj_id;
8698 }
8699 
8700 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8701 {
8702 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8703 }
8704 
8705 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8706 {
8707 	return meta->kfunc_flags & KF_ITER_NEW;
8708 }
8709 
8710 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8711 {
8712 	return meta->kfunc_flags & KF_ITER_NEXT;
8713 }
8714 
8715 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8716 {
8717 	return meta->kfunc_flags & KF_ITER_DESTROY;
8718 }
8719 
8720 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
8721 			      const struct btf_param *arg)
8722 {
8723 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
8724 	 * kfunc is iter state pointer
8725 	 */
8726 	if (is_iter_kfunc(meta))
8727 		return arg_idx == 0;
8728 
8729 	/* iter passed as an argument to a generic kfunc */
8730 	return btf_param_match_suffix(meta->btf, arg, "__iter");
8731 }
8732 
8733 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
8734 			    struct bpf_kfunc_call_arg_meta *meta)
8735 {
8736 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8737 	const struct btf_type *t;
8738 	int spi, err, i, nr_slots, btf_id;
8739 
8740 	if (reg->type != PTR_TO_STACK) {
8741 		verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1);
8742 		return -EINVAL;
8743 	}
8744 
8745 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8746 	 * ensures struct convention, so we wouldn't need to do any BTF
8747 	 * validation here. But given iter state can be passed as a parameter
8748 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8749 	 * conservative here.
8750 	 */
8751 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1);
8752 	if (btf_id < 0) {
8753 		verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1);
8754 		return -EINVAL;
8755 	}
8756 	t = btf_type_by_id(meta->btf, btf_id);
8757 	nr_slots = t->size / BPF_REG_SIZE;
8758 
8759 	if (is_iter_new_kfunc(meta)) {
8760 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
8761 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8762 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
8763 				iter_type_str(meta->btf, btf_id), regno - 1);
8764 			return -EINVAL;
8765 		}
8766 
8767 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8768 			err = check_mem_access(env, insn_idx, regno,
8769 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8770 			if (err)
8771 				return err;
8772 		}
8773 
8774 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8775 		if (err)
8776 			return err;
8777 	} else {
8778 		/* iter_next() or iter_destroy(), as well as any kfunc
8779 		 * accepting iter argument, expect initialized iter state
8780 		 */
8781 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8782 		switch (err) {
8783 		case 0:
8784 			break;
8785 		case -EINVAL:
8786 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
8787 				iter_type_str(meta->btf, btf_id), regno - 1);
8788 			return err;
8789 		case -EPROTO:
8790 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8791 			return err;
8792 		default:
8793 			return err;
8794 		}
8795 
8796 		spi = iter_get_spi(env, reg, nr_slots);
8797 		if (spi < 0)
8798 			return spi;
8799 
8800 		err = mark_iter_read(env, reg, spi, nr_slots);
8801 		if (err)
8802 			return err;
8803 
8804 		/* remember meta->iter info for process_iter_next_call() */
8805 		meta->iter.spi = spi;
8806 		meta->iter.frameno = reg->frameno;
8807 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
8808 
8809 		if (is_iter_destroy_kfunc(meta)) {
8810 			err = unmark_stack_slots_iter(env, reg, nr_slots);
8811 			if (err)
8812 				return err;
8813 		}
8814 	}
8815 
8816 	return 0;
8817 }
8818 
8819 /* Look for a previous loop entry at insn_idx: nearest parent state
8820  * stopped at insn_idx with callsites matching those in cur->frame.
8821  */
8822 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
8823 						  struct bpf_verifier_state *cur,
8824 						  int insn_idx)
8825 {
8826 	struct bpf_verifier_state_list *sl;
8827 	struct bpf_verifier_state *st;
8828 	struct list_head *pos, *head;
8829 
8830 	/* Explored states are pushed in stack order, most recent states come first */
8831 	head = explored_state(env, insn_idx);
8832 	list_for_each(pos, head) {
8833 		sl = container_of(pos, struct bpf_verifier_state_list, node);
8834 		/* If st->branches != 0 state is a part of current DFS verification path,
8835 		 * hence cur & st for a loop.
8836 		 */
8837 		st = &sl->state;
8838 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
8839 		    st->dfs_depth < cur->dfs_depth)
8840 			return st;
8841 	}
8842 
8843 	return NULL;
8844 }
8845 
8846 static void reset_idmap_scratch(struct bpf_verifier_env *env);
8847 static bool regs_exact(const struct bpf_reg_state *rold,
8848 		       const struct bpf_reg_state *rcur,
8849 		       struct bpf_idmap *idmap);
8850 
8851 static void maybe_widen_reg(struct bpf_verifier_env *env,
8852 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8853 			    struct bpf_idmap *idmap)
8854 {
8855 	if (rold->type != SCALAR_VALUE)
8856 		return;
8857 	if (rold->type != rcur->type)
8858 		return;
8859 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
8860 		return;
8861 	__mark_reg_unknown(env, rcur);
8862 }
8863 
8864 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
8865 				   struct bpf_verifier_state *old,
8866 				   struct bpf_verifier_state *cur)
8867 {
8868 	struct bpf_func_state *fold, *fcur;
8869 	int i, fr;
8870 
8871 	reset_idmap_scratch(env);
8872 	for (fr = old->curframe; fr >= 0; fr--) {
8873 		fold = old->frame[fr];
8874 		fcur = cur->frame[fr];
8875 
8876 		for (i = 0; i < MAX_BPF_REG; i++)
8877 			maybe_widen_reg(env,
8878 					&fold->regs[i],
8879 					&fcur->regs[i],
8880 					&env->idmap_scratch);
8881 
8882 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
8883 			if (!is_spilled_reg(&fold->stack[i]) ||
8884 			    !is_spilled_reg(&fcur->stack[i]))
8885 				continue;
8886 
8887 			maybe_widen_reg(env,
8888 					&fold->stack[i].spilled_ptr,
8889 					&fcur->stack[i].spilled_ptr,
8890 					&env->idmap_scratch);
8891 		}
8892 	}
8893 	return 0;
8894 }
8895 
8896 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
8897 						 struct bpf_kfunc_call_arg_meta *meta)
8898 {
8899 	int iter_frameno = meta->iter.frameno;
8900 	int iter_spi = meta->iter.spi;
8901 
8902 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8903 }
8904 
8905 /* process_iter_next_call() is called when verifier gets to iterator's next
8906  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
8907  * to it as just "iter_next()" in comments below.
8908  *
8909  * BPF verifier relies on a crucial contract for any iter_next()
8910  * implementation: it should *eventually* return NULL, and once that happens
8911  * it should keep returning NULL. That is, once iterator exhausts elements to
8912  * iterate, it should never reset or spuriously return new elements.
8913  *
8914  * With the assumption of such contract, process_iter_next_call() simulates
8915  * a fork in the verifier state to validate loop logic correctness and safety
8916  * without having to simulate infinite amount of iterations.
8917  *
8918  * In current state, we first assume that iter_next() returned NULL and
8919  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
8920  * conditions we should not form an infinite loop and should eventually reach
8921  * exit.
8922  *
8923  * Besides that, we also fork current state and enqueue it for later
8924  * verification. In a forked state we keep iterator state as ACTIVE
8925  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
8926  * also bump iteration depth to prevent erroneous infinite loop detection
8927  * later on (see iter_active_depths_differ() comment for details). In this
8928  * state we assume that we'll eventually loop back to another iter_next()
8929  * calls (it could be in exactly same location or in some other instruction,
8930  * it doesn't matter, we don't make any unnecessary assumptions about this,
8931  * everything revolves around iterator state in a stack slot, not which
8932  * instruction is calling iter_next()). When that happens, we either will come
8933  * to iter_next() with equivalent state and can conclude that next iteration
8934  * will proceed in exactly the same way as we just verified, so it's safe to
8935  * assume that loop converges. If not, we'll go on another iteration
8936  * simulation with a different input state, until all possible starting states
8937  * are validated or we reach maximum number of instructions limit.
8938  *
8939  * This way, we will either exhaustively discover all possible input states
8940  * that iterator loop can start with and eventually will converge, or we'll
8941  * effectively regress into bounded loop simulation logic and either reach
8942  * maximum number of instructions if loop is not provably convergent, or there
8943  * is some statically known limit on number of iterations (e.g., if there is
8944  * an explicit `if n > 100 then break;` statement somewhere in the loop).
8945  *
8946  * Iteration convergence logic in is_state_visited() relies on exact
8947  * states comparison, which ignores read and precision marks.
8948  * This is necessary because read and precision marks are not finalized
8949  * while in the loop. Exact comparison might preclude convergence for
8950  * simple programs like below:
8951  *
8952  *     i = 0;
8953  *     while(iter_next(&it))
8954  *       i++;
8955  *
8956  * At each iteration step i++ would produce a new distinct state and
8957  * eventually instruction processing limit would be reached.
8958  *
8959  * To avoid such behavior speculatively forget (widen) range for
8960  * imprecise scalar registers, if those registers were not precise at the
8961  * end of the previous iteration and do not match exactly.
8962  *
8963  * This is a conservative heuristic that allows to verify wide range of programs,
8964  * however it precludes verification of programs that conjure an
8965  * imprecise value on the first loop iteration and use it as precise on a second.
8966  * For example, the following safe program would fail to verify:
8967  *
8968  *     struct bpf_num_iter it;
8969  *     int arr[10];
8970  *     int i = 0, a = 0;
8971  *     bpf_iter_num_new(&it, 0, 10);
8972  *     while (bpf_iter_num_next(&it)) {
8973  *       if (a == 0) {
8974  *         a = 1;
8975  *         i = 7; // Because i changed verifier would forget
8976  *                // it's range on second loop entry.
8977  *       } else {
8978  *         arr[i] = 42; // This would fail to verify.
8979  *       }
8980  *     }
8981  *     bpf_iter_num_destroy(&it);
8982  */
8983 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8984 				  struct bpf_kfunc_call_arg_meta *meta)
8985 {
8986 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
8987 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8988 	struct bpf_reg_state *cur_iter, *queued_iter;
8989 
8990 	BTF_TYPE_EMIT(struct bpf_iter);
8991 
8992 	cur_iter = get_iter_from_state(cur_st, meta);
8993 
8994 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8995 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8996 		verifier_bug(env, "unexpected iterator state %d (%s)",
8997 			     cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8998 		return -EFAULT;
8999 	}
9000 
9001 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
9002 		/* Because iter_next() call is a checkpoint is_state_visitied()
9003 		 * should guarantee parent state with same call sites and insn_idx.
9004 		 */
9005 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
9006 		    !same_callsites(cur_st->parent, cur_st)) {
9007 			verifier_bug(env, "bad parent state for iter next call");
9008 			return -EFAULT;
9009 		}
9010 		/* Note cur_st->parent in the call below, it is necessary to skip
9011 		 * checkpoint created for cur_st by is_state_visited()
9012 		 * right at this instruction.
9013 		 */
9014 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
9015 		/* branch out active iter state */
9016 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
9017 		if (!queued_st)
9018 			return -ENOMEM;
9019 
9020 		queued_iter = get_iter_from_state(queued_st, meta);
9021 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
9022 		queued_iter->iter.depth++;
9023 		if (prev_st)
9024 			widen_imprecise_scalars(env, prev_st, queued_st);
9025 
9026 		queued_fr = queued_st->frame[queued_st->curframe];
9027 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
9028 	}
9029 
9030 	/* switch to DRAINED state, but keep the depth unchanged */
9031 	/* mark current iter state as drained and assume returned NULL */
9032 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
9033 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
9034 
9035 	return 0;
9036 }
9037 
9038 static bool arg_type_is_mem_size(enum bpf_arg_type type)
9039 {
9040 	return type == ARG_CONST_SIZE ||
9041 	       type == ARG_CONST_SIZE_OR_ZERO;
9042 }
9043 
9044 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
9045 {
9046 	return base_type(type) == ARG_PTR_TO_MEM &&
9047 	       type & MEM_UNINIT;
9048 }
9049 
9050 static bool arg_type_is_release(enum bpf_arg_type type)
9051 {
9052 	return type & OBJ_RELEASE;
9053 }
9054 
9055 static bool arg_type_is_dynptr(enum bpf_arg_type type)
9056 {
9057 	return base_type(type) == ARG_PTR_TO_DYNPTR;
9058 }
9059 
9060 static int resolve_map_arg_type(struct bpf_verifier_env *env,
9061 				 const struct bpf_call_arg_meta *meta,
9062 				 enum bpf_arg_type *arg_type)
9063 {
9064 	if (!meta->map_ptr) {
9065 		/* kernel subsystem misconfigured verifier */
9066 		verifier_bug(env, "invalid map_ptr to access map->type");
9067 		return -EFAULT;
9068 	}
9069 
9070 	switch (meta->map_ptr->map_type) {
9071 	case BPF_MAP_TYPE_SOCKMAP:
9072 	case BPF_MAP_TYPE_SOCKHASH:
9073 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
9074 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
9075 		} else {
9076 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
9077 			return -EINVAL;
9078 		}
9079 		break;
9080 	case BPF_MAP_TYPE_BLOOM_FILTER:
9081 		if (meta->func_id == BPF_FUNC_map_peek_elem)
9082 			*arg_type = ARG_PTR_TO_MAP_VALUE;
9083 		break;
9084 	default:
9085 		break;
9086 	}
9087 	return 0;
9088 }
9089 
9090 struct bpf_reg_types {
9091 	const enum bpf_reg_type types[10];
9092 	u32 *btf_id;
9093 };
9094 
9095 static const struct bpf_reg_types sock_types = {
9096 	.types = {
9097 		PTR_TO_SOCK_COMMON,
9098 		PTR_TO_SOCKET,
9099 		PTR_TO_TCP_SOCK,
9100 		PTR_TO_XDP_SOCK,
9101 	},
9102 };
9103 
9104 #ifdef CONFIG_NET
9105 static const struct bpf_reg_types btf_id_sock_common_types = {
9106 	.types = {
9107 		PTR_TO_SOCK_COMMON,
9108 		PTR_TO_SOCKET,
9109 		PTR_TO_TCP_SOCK,
9110 		PTR_TO_XDP_SOCK,
9111 		PTR_TO_BTF_ID,
9112 		PTR_TO_BTF_ID | PTR_TRUSTED,
9113 	},
9114 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9115 };
9116 #endif
9117 
9118 static const struct bpf_reg_types mem_types = {
9119 	.types = {
9120 		PTR_TO_STACK,
9121 		PTR_TO_PACKET,
9122 		PTR_TO_PACKET_META,
9123 		PTR_TO_MAP_KEY,
9124 		PTR_TO_MAP_VALUE,
9125 		PTR_TO_MEM,
9126 		PTR_TO_MEM | MEM_RINGBUF,
9127 		PTR_TO_BUF,
9128 		PTR_TO_BTF_ID | PTR_TRUSTED,
9129 	},
9130 };
9131 
9132 static const struct bpf_reg_types spin_lock_types = {
9133 	.types = {
9134 		PTR_TO_MAP_VALUE,
9135 		PTR_TO_BTF_ID | MEM_ALLOC,
9136 	}
9137 };
9138 
9139 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
9140 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
9141 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
9142 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
9143 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
9144 static const struct bpf_reg_types btf_ptr_types = {
9145 	.types = {
9146 		PTR_TO_BTF_ID,
9147 		PTR_TO_BTF_ID | PTR_TRUSTED,
9148 		PTR_TO_BTF_ID | MEM_RCU,
9149 	},
9150 };
9151 static const struct bpf_reg_types percpu_btf_ptr_types = {
9152 	.types = {
9153 		PTR_TO_BTF_ID | MEM_PERCPU,
9154 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
9155 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
9156 	}
9157 };
9158 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
9159 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
9160 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
9161 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
9162 static const struct bpf_reg_types kptr_xchg_dest_types = {
9163 	.types = {
9164 		PTR_TO_MAP_VALUE,
9165 		PTR_TO_BTF_ID | MEM_ALLOC
9166 	}
9167 };
9168 static const struct bpf_reg_types dynptr_types = {
9169 	.types = {
9170 		PTR_TO_STACK,
9171 		CONST_PTR_TO_DYNPTR,
9172 	}
9173 };
9174 
9175 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
9176 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
9177 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
9178 	[ARG_CONST_SIZE]		= &scalar_types,
9179 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
9180 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
9181 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
9182 	[ARG_PTR_TO_CTX]		= &context_types,
9183 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
9184 #ifdef CONFIG_NET
9185 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
9186 #endif
9187 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
9188 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
9189 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
9190 	[ARG_PTR_TO_MEM]		= &mem_types,
9191 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
9192 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
9193 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
9194 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
9195 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
9196 	[ARG_PTR_TO_TIMER]		= &timer_types,
9197 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
9198 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
9199 };
9200 
9201 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
9202 			  enum bpf_arg_type arg_type,
9203 			  const u32 *arg_btf_id,
9204 			  struct bpf_call_arg_meta *meta)
9205 {
9206 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
9207 	enum bpf_reg_type expected, type = reg->type;
9208 	const struct bpf_reg_types *compatible;
9209 	int i, j;
9210 
9211 	compatible = compatible_reg_types[base_type(arg_type)];
9212 	if (!compatible) {
9213 		verifier_bug(env, "unsupported arg type %d", arg_type);
9214 		return -EFAULT;
9215 	}
9216 
9217 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
9218 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
9219 	 *
9220 	 * Same for MAYBE_NULL:
9221 	 *
9222 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
9223 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
9224 	 *
9225 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
9226 	 *
9227 	 * Therefore we fold these flags depending on the arg_type before comparison.
9228 	 */
9229 	if (arg_type & MEM_RDONLY)
9230 		type &= ~MEM_RDONLY;
9231 	if (arg_type & PTR_MAYBE_NULL)
9232 		type &= ~PTR_MAYBE_NULL;
9233 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
9234 		type &= ~DYNPTR_TYPE_FLAG_MASK;
9235 
9236 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
9237 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) {
9238 		type &= ~MEM_ALLOC;
9239 		type &= ~MEM_PERCPU;
9240 	}
9241 
9242 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
9243 		expected = compatible->types[i];
9244 		if (expected == NOT_INIT)
9245 			break;
9246 
9247 		if (type == expected)
9248 			goto found;
9249 	}
9250 
9251 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
9252 	for (j = 0; j + 1 < i; j++)
9253 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
9254 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
9255 	return -EACCES;
9256 
9257 found:
9258 	if (base_type(reg->type) != PTR_TO_BTF_ID)
9259 		return 0;
9260 
9261 	if (compatible == &mem_types) {
9262 		if (!(arg_type & MEM_RDONLY)) {
9263 			verbose(env,
9264 				"%s() may write into memory pointed by R%d type=%s\n",
9265 				func_id_name(meta->func_id),
9266 				regno, reg_type_str(env, reg->type));
9267 			return -EACCES;
9268 		}
9269 		return 0;
9270 	}
9271 
9272 	switch ((int)reg->type) {
9273 	case PTR_TO_BTF_ID:
9274 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9275 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
9276 	case PTR_TO_BTF_ID | MEM_RCU:
9277 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
9278 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
9279 	{
9280 		/* For bpf_sk_release, it needs to match against first member
9281 		 * 'struct sock_common', hence make an exception for it. This
9282 		 * allows bpf_sk_release to work for multiple socket types.
9283 		 */
9284 		bool strict_type_match = arg_type_is_release(arg_type) &&
9285 					 meta->func_id != BPF_FUNC_sk_release;
9286 
9287 		if (type_may_be_null(reg->type) &&
9288 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
9289 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
9290 			return -EACCES;
9291 		}
9292 
9293 		if (!arg_btf_id) {
9294 			if (!compatible->btf_id) {
9295 				verifier_bug(env, "missing arg compatible BTF ID");
9296 				return -EFAULT;
9297 			}
9298 			arg_btf_id = compatible->btf_id;
9299 		}
9300 
9301 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
9302 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9303 				return -EACCES;
9304 		} else {
9305 			if (arg_btf_id == BPF_PTR_POISON) {
9306 				verbose(env, "verifier internal error:");
9307 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
9308 					regno);
9309 				return -EACCES;
9310 			}
9311 
9312 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
9313 						  btf_vmlinux, *arg_btf_id,
9314 						  strict_type_match)) {
9315 				verbose(env, "R%d is of type %s but %s is expected\n",
9316 					regno, btf_type_name(reg->btf, reg->btf_id),
9317 					btf_type_name(btf_vmlinux, *arg_btf_id));
9318 				return -EACCES;
9319 			}
9320 		}
9321 		break;
9322 	}
9323 	case PTR_TO_BTF_ID | MEM_ALLOC:
9324 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
9325 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
9326 		    meta->func_id != BPF_FUNC_kptr_xchg) {
9327 			verifier_bug(env, "unimplemented handling of MEM_ALLOC");
9328 			return -EFAULT;
9329 		}
9330 		/* Check if local kptr in src arg matches kptr in dst arg */
9331 		if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) {
9332 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9333 				return -EACCES;
9334 		}
9335 		break;
9336 	case PTR_TO_BTF_ID | MEM_PERCPU:
9337 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
9338 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
9339 		/* Handled by helper specific checks */
9340 		break;
9341 	default:
9342 		verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match");
9343 		return -EFAULT;
9344 	}
9345 	return 0;
9346 }
9347 
9348 static struct btf_field *
9349 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
9350 {
9351 	struct btf_field *field;
9352 	struct btf_record *rec;
9353 
9354 	rec = reg_btf_record(reg);
9355 	if (!rec)
9356 		return NULL;
9357 
9358 	field = btf_record_find(rec, off, fields);
9359 	if (!field)
9360 		return NULL;
9361 
9362 	return field;
9363 }
9364 
9365 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
9366 				  const struct bpf_reg_state *reg, int regno,
9367 				  enum bpf_arg_type arg_type)
9368 {
9369 	u32 type = reg->type;
9370 
9371 	/* When referenced register is passed to release function, its fixed
9372 	 * offset must be 0.
9373 	 *
9374 	 * We will check arg_type_is_release reg has ref_obj_id when storing
9375 	 * meta->release_regno.
9376 	 */
9377 	if (arg_type_is_release(arg_type)) {
9378 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
9379 		 * may not directly point to the object being released, but to
9380 		 * dynptr pointing to such object, which might be at some offset
9381 		 * on the stack. In that case, we simply to fallback to the
9382 		 * default handling.
9383 		 */
9384 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
9385 			return 0;
9386 
9387 		/* Doing check_ptr_off_reg check for the offset will catch this
9388 		 * because fixed_off_ok is false, but checking here allows us
9389 		 * to give the user a better error message.
9390 		 */
9391 		if (reg->off) {
9392 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
9393 				regno);
9394 			return -EINVAL;
9395 		}
9396 		return __check_ptr_off_reg(env, reg, regno, false);
9397 	}
9398 
9399 	switch (type) {
9400 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
9401 	case PTR_TO_STACK:
9402 	case PTR_TO_PACKET:
9403 	case PTR_TO_PACKET_META:
9404 	case PTR_TO_MAP_KEY:
9405 	case PTR_TO_MAP_VALUE:
9406 	case PTR_TO_MEM:
9407 	case PTR_TO_MEM | MEM_RDONLY:
9408 	case PTR_TO_MEM | MEM_RINGBUF:
9409 	case PTR_TO_BUF:
9410 	case PTR_TO_BUF | MEM_RDONLY:
9411 	case PTR_TO_ARENA:
9412 	case SCALAR_VALUE:
9413 		return 0;
9414 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
9415 	 * fixed offset.
9416 	 */
9417 	case PTR_TO_BTF_ID:
9418 	case PTR_TO_BTF_ID | MEM_ALLOC:
9419 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9420 	case PTR_TO_BTF_ID | MEM_RCU:
9421 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
9422 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
9423 		/* When referenced PTR_TO_BTF_ID is passed to release function,
9424 		 * its fixed offset must be 0. In the other cases, fixed offset
9425 		 * can be non-zero. This was already checked above. So pass
9426 		 * fixed_off_ok as true to allow fixed offset for all other
9427 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
9428 		 * still need to do checks instead of returning.
9429 		 */
9430 		return __check_ptr_off_reg(env, reg, regno, true);
9431 	default:
9432 		return __check_ptr_off_reg(env, reg, regno, false);
9433 	}
9434 }
9435 
9436 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
9437 						const struct bpf_func_proto *fn,
9438 						struct bpf_reg_state *regs)
9439 {
9440 	struct bpf_reg_state *state = NULL;
9441 	int i;
9442 
9443 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
9444 		if (arg_type_is_dynptr(fn->arg_type[i])) {
9445 			if (state) {
9446 				verbose(env, "verifier internal error: multiple dynptr args\n");
9447 				return NULL;
9448 			}
9449 			state = &regs[BPF_REG_1 + i];
9450 		}
9451 
9452 	if (!state)
9453 		verbose(env, "verifier internal error: no dynptr arg found\n");
9454 
9455 	return state;
9456 }
9457 
9458 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9459 {
9460 	struct bpf_func_state *state = func(env, reg);
9461 	int spi;
9462 
9463 	if (reg->type == CONST_PTR_TO_DYNPTR)
9464 		return reg->id;
9465 	spi = dynptr_get_spi(env, reg);
9466 	if (spi < 0)
9467 		return spi;
9468 	return state->stack[spi].spilled_ptr.id;
9469 }
9470 
9471 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9472 {
9473 	struct bpf_func_state *state = func(env, reg);
9474 	int spi;
9475 
9476 	if (reg->type == CONST_PTR_TO_DYNPTR)
9477 		return reg->ref_obj_id;
9478 	spi = dynptr_get_spi(env, reg);
9479 	if (spi < 0)
9480 		return spi;
9481 	return state->stack[spi].spilled_ptr.ref_obj_id;
9482 }
9483 
9484 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
9485 					    struct bpf_reg_state *reg)
9486 {
9487 	struct bpf_func_state *state = func(env, reg);
9488 	int spi;
9489 
9490 	if (reg->type == CONST_PTR_TO_DYNPTR)
9491 		return reg->dynptr.type;
9492 
9493 	spi = __get_spi(reg->off);
9494 	if (spi < 0) {
9495 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
9496 		return BPF_DYNPTR_TYPE_INVALID;
9497 	}
9498 
9499 	return state->stack[spi].spilled_ptr.dynptr.type;
9500 }
9501 
9502 static int check_reg_const_str(struct bpf_verifier_env *env,
9503 			       struct bpf_reg_state *reg, u32 regno)
9504 {
9505 	struct bpf_map *map = reg->map_ptr;
9506 	int err;
9507 	int map_off;
9508 	u64 map_addr;
9509 	char *str_ptr;
9510 
9511 	if (reg->type != PTR_TO_MAP_VALUE)
9512 		return -EINVAL;
9513 
9514 	if (!bpf_map_is_rdonly(map)) {
9515 		verbose(env, "R%d does not point to a readonly map'\n", regno);
9516 		return -EACCES;
9517 	}
9518 
9519 	if (!tnum_is_const(reg->var_off)) {
9520 		verbose(env, "R%d is not a constant address'\n", regno);
9521 		return -EACCES;
9522 	}
9523 
9524 	if (!map->ops->map_direct_value_addr) {
9525 		verbose(env, "no direct value access support for this map type\n");
9526 		return -EACCES;
9527 	}
9528 
9529 	err = check_map_access(env, regno, reg->off,
9530 			       map->value_size - reg->off, false,
9531 			       ACCESS_HELPER);
9532 	if (err)
9533 		return err;
9534 
9535 	map_off = reg->off + reg->var_off.value;
9536 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
9537 	if (err) {
9538 		verbose(env, "direct value access on string failed\n");
9539 		return err;
9540 	}
9541 
9542 	str_ptr = (char *)(long)(map_addr);
9543 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
9544 		verbose(env, "string is not zero-terminated\n");
9545 		return -EINVAL;
9546 	}
9547 	return 0;
9548 }
9549 
9550 /* Returns constant key value in `value` if possible, else negative error */
9551 static int get_constant_map_key(struct bpf_verifier_env *env,
9552 				struct bpf_reg_state *key,
9553 				u32 key_size,
9554 				s64 *value)
9555 {
9556 	struct bpf_func_state *state = func(env, key);
9557 	struct bpf_reg_state *reg;
9558 	int slot, spi, off;
9559 	int spill_size = 0;
9560 	int zero_size = 0;
9561 	int stack_off;
9562 	int i, err;
9563 	u8 *stype;
9564 
9565 	if (!env->bpf_capable)
9566 		return -EOPNOTSUPP;
9567 	if (key->type != PTR_TO_STACK)
9568 		return -EOPNOTSUPP;
9569 	if (!tnum_is_const(key->var_off))
9570 		return -EOPNOTSUPP;
9571 
9572 	stack_off = key->off + key->var_off.value;
9573 	slot = -stack_off - 1;
9574 	spi = slot / BPF_REG_SIZE;
9575 	off = slot % BPF_REG_SIZE;
9576 	stype = state->stack[spi].slot_type;
9577 
9578 	/* First handle precisely tracked STACK_ZERO */
9579 	for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
9580 		zero_size++;
9581 	if (zero_size >= key_size) {
9582 		*value = 0;
9583 		return 0;
9584 	}
9585 
9586 	/* Check that stack contains a scalar spill of expected size */
9587 	if (!is_spilled_scalar_reg(&state->stack[spi]))
9588 		return -EOPNOTSUPP;
9589 	for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
9590 		spill_size++;
9591 	if (spill_size != key_size)
9592 		return -EOPNOTSUPP;
9593 
9594 	reg = &state->stack[spi].spilled_ptr;
9595 	if (!tnum_is_const(reg->var_off))
9596 		/* Stack value not statically known */
9597 		return -EOPNOTSUPP;
9598 
9599 	/* We are relying on a constant value. So mark as precise
9600 	 * to prevent pruning on it.
9601 	 */
9602 	bt_set_frame_slot(&env->bt, key->frameno, spi);
9603 	err = mark_chain_precision_batch(env, env->cur_state);
9604 	if (err < 0)
9605 		return err;
9606 
9607 	*value = reg->var_off.value;
9608 	return 0;
9609 }
9610 
9611 static bool can_elide_value_nullness(enum bpf_map_type type);
9612 
9613 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
9614 			  struct bpf_call_arg_meta *meta,
9615 			  const struct bpf_func_proto *fn,
9616 			  int insn_idx)
9617 {
9618 	u32 regno = BPF_REG_1 + arg;
9619 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
9620 	enum bpf_arg_type arg_type = fn->arg_type[arg];
9621 	enum bpf_reg_type type = reg->type;
9622 	u32 *arg_btf_id = NULL;
9623 	u32 key_size;
9624 	int err = 0;
9625 
9626 	if (arg_type == ARG_DONTCARE)
9627 		return 0;
9628 
9629 	err = check_reg_arg(env, regno, SRC_OP);
9630 	if (err)
9631 		return err;
9632 
9633 	if (arg_type == ARG_ANYTHING) {
9634 		if (is_pointer_value(env, regno)) {
9635 			verbose(env, "R%d leaks addr into helper function\n",
9636 				regno);
9637 			return -EACCES;
9638 		}
9639 		return 0;
9640 	}
9641 
9642 	if (type_is_pkt_pointer(type) &&
9643 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
9644 		verbose(env, "helper access to the packet is not allowed\n");
9645 		return -EACCES;
9646 	}
9647 
9648 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
9649 		err = resolve_map_arg_type(env, meta, &arg_type);
9650 		if (err)
9651 			return err;
9652 	}
9653 
9654 	if (register_is_null(reg) && type_may_be_null(arg_type))
9655 		/* A NULL register has a SCALAR_VALUE type, so skip
9656 		 * type checking.
9657 		 */
9658 		goto skip_type_check;
9659 
9660 	/* arg_btf_id and arg_size are in a union. */
9661 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
9662 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
9663 		arg_btf_id = fn->arg_btf_id[arg];
9664 
9665 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
9666 	if (err)
9667 		return err;
9668 
9669 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
9670 	if (err)
9671 		return err;
9672 
9673 skip_type_check:
9674 	if (arg_type_is_release(arg_type)) {
9675 		if (arg_type_is_dynptr(arg_type)) {
9676 			struct bpf_func_state *state = func(env, reg);
9677 			int spi;
9678 
9679 			/* Only dynptr created on stack can be released, thus
9680 			 * the get_spi and stack state checks for spilled_ptr
9681 			 * should only be done before process_dynptr_func for
9682 			 * PTR_TO_STACK.
9683 			 */
9684 			if (reg->type == PTR_TO_STACK) {
9685 				spi = dynptr_get_spi(env, reg);
9686 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
9687 					verbose(env, "arg %d is an unacquired reference\n", regno);
9688 					return -EINVAL;
9689 				}
9690 			} else {
9691 				verbose(env, "cannot release unowned const bpf_dynptr\n");
9692 				return -EINVAL;
9693 			}
9694 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
9695 			verbose(env, "R%d must be referenced when passed to release function\n",
9696 				regno);
9697 			return -EINVAL;
9698 		}
9699 		if (meta->release_regno) {
9700 			verifier_bug(env, "more than one release argument");
9701 			return -EFAULT;
9702 		}
9703 		meta->release_regno = regno;
9704 	}
9705 
9706 	if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) {
9707 		if (meta->ref_obj_id) {
9708 			verbose(env, "more than one arg with ref_obj_id R%d %u %u",
9709 				regno, reg->ref_obj_id,
9710 				meta->ref_obj_id);
9711 			return -EACCES;
9712 		}
9713 		meta->ref_obj_id = reg->ref_obj_id;
9714 	}
9715 
9716 	switch (base_type(arg_type)) {
9717 	case ARG_CONST_MAP_PTR:
9718 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
9719 		if (meta->map_ptr) {
9720 			/* Use map_uid (which is unique id of inner map) to reject:
9721 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
9722 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
9723 			 * if (inner_map1 && inner_map2) {
9724 			 *     timer = bpf_map_lookup_elem(inner_map1);
9725 			 *     if (timer)
9726 			 *         // mismatch would have been allowed
9727 			 *         bpf_timer_init(timer, inner_map2);
9728 			 * }
9729 			 *
9730 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
9731 			 */
9732 			if (meta->map_ptr != reg->map_ptr ||
9733 			    meta->map_uid != reg->map_uid) {
9734 				verbose(env,
9735 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
9736 					meta->map_uid, reg->map_uid);
9737 				return -EINVAL;
9738 			}
9739 		}
9740 		meta->map_ptr = reg->map_ptr;
9741 		meta->map_uid = reg->map_uid;
9742 		break;
9743 	case ARG_PTR_TO_MAP_KEY:
9744 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
9745 		 * check that [key, key + map->key_size) are within
9746 		 * stack limits and initialized
9747 		 */
9748 		if (!meta->map_ptr) {
9749 			/* in function declaration map_ptr must come before
9750 			 * map_key, so that it's verified and known before
9751 			 * we have to check map_key here. Otherwise it means
9752 			 * that kernel subsystem misconfigured verifier
9753 			 */
9754 			verifier_bug(env, "invalid map_ptr to access map->key");
9755 			return -EFAULT;
9756 		}
9757 		key_size = meta->map_ptr->key_size;
9758 		err = check_helper_mem_access(env, regno, key_size, BPF_READ, false, NULL);
9759 		if (err)
9760 			return err;
9761 		if (can_elide_value_nullness(meta->map_ptr->map_type)) {
9762 			err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
9763 			if (err < 0) {
9764 				meta->const_map_key = -1;
9765 				if (err == -EOPNOTSUPP)
9766 					err = 0;
9767 				else
9768 					return err;
9769 			}
9770 		}
9771 		break;
9772 	case ARG_PTR_TO_MAP_VALUE:
9773 		if (type_may_be_null(arg_type) && register_is_null(reg))
9774 			return 0;
9775 
9776 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
9777 		 * check [value, value + map->value_size) validity
9778 		 */
9779 		if (!meta->map_ptr) {
9780 			/* kernel subsystem misconfigured verifier */
9781 			verifier_bug(env, "invalid map_ptr to access map->value");
9782 			return -EFAULT;
9783 		}
9784 		meta->raw_mode = arg_type & MEM_UNINIT;
9785 		err = check_helper_mem_access(env, regno, meta->map_ptr->value_size,
9786 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9787 					      false, meta);
9788 		break;
9789 	case ARG_PTR_TO_PERCPU_BTF_ID:
9790 		if (!reg->btf_id) {
9791 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
9792 			return -EACCES;
9793 		}
9794 		meta->ret_btf = reg->btf;
9795 		meta->ret_btf_id = reg->btf_id;
9796 		break;
9797 	case ARG_PTR_TO_SPIN_LOCK:
9798 		if (in_rbtree_lock_required_cb(env)) {
9799 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
9800 			return -EACCES;
9801 		}
9802 		if (meta->func_id == BPF_FUNC_spin_lock) {
9803 			err = process_spin_lock(env, regno, PROCESS_SPIN_LOCK);
9804 			if (err)
9805 				return err;
9806 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
9807 			err = process_spin_lock(env, regno, 0);
9808 			if (err)
9809 				return err;
9810 		} else {
9811 			verifier_bug(env, "spin lock arg on unexpected helper");
9812 			return -EFAULT;
9813 		}
9814 		break;
9815 	case ARG_PTR_TO_TIMER:
9816 		err = process_timer_func(env, regno, meta);
9817 		if (err)
9818 			return err;
9819 		break;
9820 	case ARG_PTR_TO_FUNC:
9821 		meta->subprogno = reg->subprogno;
9822 		break;
9823 	case ARG_PTR_TO_MEM:
9824 		/* The access to this pointer is only checked when we hit the
9825 		 * next is_mem_size argument below.
9826 		 */
9827 		meta->raw_mode = arg_type & MEM_UNINIT;
9828 		if (arg_type & MEM_FIXED_SIZE) {
9829 			err = check_helper_mem_access(env, regno, fn->arg_size[arg],
9830 						      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9831 						      false, meta);
9832 			if (err)
9833 				return err;
9834 			if (arg_type & MEM_ALIGNED)
9835 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
9836 		}
9837 		break;
9838 	case ARG_CONST_SIZE:
9839 		err = check_mem_size_reg(env, reg, regno,
9840 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9841 					 BPF_WRITE : BPF_READ,
9842 					 false, meta);
9843 		break;
9844 	case ARG_CONST_SIZE_OR_ZERO:
9845 		err = check_mem_size_reg(env, reg, regno,
9846 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9847 					 BPF_WRITE : BPF_READ,
9848 					 true, meta);
9849 		break;
9850 	case ARG_PTR_TO_DYNPTR:
9851 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
9852 		if (err)
9853 			return err;
9854 		break;
9855 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
9856 		if (!tnum_is_const(reg->var_off)) {
9857 			verbose(env, "R%d is not a known constant'\n",
9858 				regno);
9859 			return -EACCES;
9860 		}
9861 		meta->mem_size = reg->var_off.value;
9862 		err = mark_chain_precision(env, regno);
9863 		if (err)
9864 			return err;
9865 		break;
9866 	case ARG_PTR_TO_CONST_STR:
9867 	{
9868 		err = check_reg_const_str(env, reg, regno);
9869 		if (err)
9870 			return err;
9871 		break;
9872 	}
9873 	case ARG_KPTR_XCHG_DEST:
9874 		err = process_kptr_func(env, regno, meta);
9875 		if (err)
9876 			return err;
9877 		break;
9878 	}
9879 
9880 	return err;
9881 }
9882 
9883 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
9884 {
9885 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
9886 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9887 
9888 	if (func_id != BPF_FUNC_map_update_elem &&
9889 	    func_id != BPF_FUNC_map_delete_elem)
9890 		return false;
9891 
9892 	/* It's not possible to get access to a locked struct sock in these
9893 	 * contexts, so updating is safe.
9894 	 */
9895 	switch (type) {
9896 	case BPF_PROG_TYPE_TRACING:
9897 		if (eatype == BPF_TRACE_ITER)
9898 			return true;
9899 		break;
9900 	case BPF_PROG_TYPE_SOCK_OPS:
9901 		/* map_update allowed only via dedicated helpers with event type checks */
9902 		if (func_id == BPF_FUNC_map_delete_elem)
9903 			return true;
9904 		break;
9905 	case BPF_PROG_TYPE_SOCKET_FILTER:
9906 	case BPF_PROG_TYPE_SCHED_CLS:
9907 	case BPF_PROG_TYPE_SCHED_ACT:
9908 	case BPF_PROG_TYPE_XDP:
9909 	case BPF_PROG_TYPE_SK_REUSEPORT:
9910 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
9911 	case BPF_PROG_TYPE_SK_LOOKUP:
9912 		return true;
9913 	default:
9914 		break;
9915 	}
9916 
9917 	verbose(env, "cannot update sockmap in this context\n");
9918 	return false;
9919 }
9920 
9921 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
9922 {
9923 	return env->prog->jit_requested &&
9924 	       bpf_jit_supports_subprog_tailcalls();
9925 }
9926 
9927 static int check_map_func_compatibility(struct bpf_verifier_env *env,
9928 					struct bpf_map *map, int func_id)
9929 {
9930 	if (!map)
9931 		return 0;
9932 
9933 	/* We need a two way check, first is from map perspective ... */
9934 	switch (map->map_type) {
9935 	case BPF_MAP_TYPE_PROG_ARRAY:
9936 		if (func_id != BPF_FUNC_tail_call)
9937 			goto error;
9938 		break;
9939 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
9940 		if (func_id != BPF_FUNC_perf_event_read &&
9941 		    func_id != BPF_FUNC_perf_event_output &&
9942 		    func_id != BPF_FUNC_skb_output &&
9943 		    func_id != BPF_FUNC_perf_event_read_value &&
9944 		    func_id != BPF_FUNC_xdp_output)
9945 			goto error;
9946 		break;
9947 	case BPF_MAP_TYPE_RINGBUF:
9948 		if (func_id != BPF_FUNC_ringbuf_output &&
9949 		    func_id != BPF_FUNC_ringbuf_reserve &&
9950 		    func_id != BPF_FUNC_ringbuf_query &&
9951 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
9952 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
9953 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
9954 			goto error;
9955 		break;
9956 	case BPF_MAP_TYPE_USER_RINGBUF:
9957 		if (func_id != BPF_FUNC_user_ringbuf_drain)
9958 			goto error;
9959 		break;
9960 	case BPF_MAP_TYPE_STACK_TRACE:
9961 		if (func_id != BPF_FUNC_get_stackid)
9962 			goto error;
9963 		break;
9964 	case BPF_MAP_TYPE_CGROUP_ARRAY:
9965 		if (func_id != BPF_FUNC_skb_under_cgroup &&
9966 		    func_id != BPF_FUNC_current_task_under_cgroup)
9967 			goto error;
9968 		break;
9969 	case BPF_MAP_TYPE_CGROUP_STORAGE:
9970 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
9971 		if (func_id != BPF_FUNC_get_local_storage)
9972 			goto error;
9973 		break;
9974 	case BPF_MAP_TYPE_DEVMAP:
9975 	case BPF_MAP_TYPE_DEVMAP_HASH:
9976 		if (func_id != BPF_FUNC_redirect_map &&
9977 		    func_id != BPF_FUNC_map_lookup_elem)
9978 			goto error;
9979 		break;
9980 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
9981 	 * appear.
9982 	 */
9983 	case BPF_MAP_TYPE_CPUMAP:
9984 		if (func_id != BPF_FUNC_redirect_map)
9985 			goto error;
9986 		break;
9987 	case BPF_MAP_TYPE_XSKMAP:
9988 		if (func_id != BPF_FUNC_redirect_map &&
9989 		    func_id != BPF_FUNC_map_lookup_elem)
9990 			goto error;
9991 		break;
9992 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
9993 	case BPF_MAP_TYPE_HASH_OF_MAPS:
9994 		if (func_id != BPF_FUNC_map_lookup_elem)
9995 			goto error;
9996 		break;
9997 	case BPF_MAP_TYPE_SOCKMAP:
9998 		if (func_id != BPF_FUNC_sk_redirect_map &&
9999 		    func_id != BPF_FUNC_sock_map_update &&
10000 		    func_id != BPF_FUNC_msg_redirect_map &&
10001 		    func_id != BPF_FUNC_sk_select_reuseport &&
10002 		    func_id != BPF_FUNC_map_lookup_elem &&
10003 		    !may_update_sockmap(env, func_id))
10004 			goto error;
10005 		break;
10006 	case BPF_MAP_TYPE_SOCKHASH:
10007 		if (func_id != BPF_FUNC_sk_redirect_hash &&
10008 		    func_id != BPF_FUNC_sock_hash_update &&
10009 		    func_id != BPF_FUNC_msg_redirect_hash &&
10010 		    func_id != BPF_FUNC_sk_select_reuseport &&
10011 		    func_id != BPF_FUNC_map_lookup_elem &&
10012 		    !may_update_sockmap(env, func_id))
10013 			goto error;
10014 		break;
10015 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
10016 		if (func_id != BPF_FUNC_sk_select_reuseport)
10017 			goto error;
10018 		break;
10019 	case BPF_MAP_TYPE_QUEUE:
10020 	case BPF_MAP_TYPE_STACK:
10021 		if (func_id != BPF_FUNC_map_peek_elem &&
10022 		    func_id != BPF_FUNC_map_pop_elem &&
10023 		    func_id != BPF_FUNC_map_push_elem)
10024 			goto error;
10025 		break;
10026 	case BPF_MAP_TYPE_SK_STORAGE:
10027 		if (func_id != BPF_FUNC_sk_storage_get &&
10028 		    func_id != BPF_FUNC_sk_storage_delete &&
10029 		    func_id != BPF_FUNC_kptr_xchg)
10030 			goto error;
10031 		break;
10032 	case BPF_MAP_TYPE_INODE_STORAGE:
10033 		if (func_id != BPF_FUNC_inode_storage_get &&
10034 		    func_id != BPF_FUNC_inode_storage_delete &&
10035 		    func_id != BPF_FUNC_kptr_xchg)
10036 			goto error;
10037 		break;
10038 	case BPF_MAP_TYPE_TASK_STORAGE:
10039 		if (func_id != BPF_FUNC_task_storage_get &&
10040 		    func_id != BPF_FUNC_task_storage_delete &&
10041 		    func_id != BPF_FUNC_kptr_xchg)
10042 			goto error;
10043 		break;
10044 	case BPF_MAP_TYPE_CGRP_STORAGE:
10045 		if (func_id != BPF_FUNC_cgrp_storage_get &&
10046 		    func_id != BPF_FUNC_cgrp_storage_delete &&
10047 		    func_id != BPF_FUNC_kptr_xchg)
10048 			goto error;
10049 		break;
10050 	case BPF_MAP_TYPE_BLOOM_FILTER:
10051 		if (func_id != BPF_FUNC_map_peek_elem &&
10052 		    func_id != BPF_FUNC_map_push_elem)
10053 			goto error;
10054 		break;
10055 	default:
10056 		break;
10057 	}
10058 
10059 	/* ... and second from the function itself. */
10060 	switch (func_id) {
10061 	case BPF_FUNC_tail_call:
10062 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
10063 			goto error;
10064 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
10065 			verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n");
10066 			return -EINVAL;
10067 		}
10068 		break;
10069 	case BPF_FUNC_perf_event_read:
10070 	case BPF_FUNC_perf_event_output:
10071 	case BPF_FUNC_perf_event_read_value:
10072 	case BPF_FUNC_skb_output:
10073 	case BPF_FUNC_xdp_output:
10074 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
10075 			goto error;
10076 		break;
10077 	case BPF_FUNC_ringbuf_output:
10078 	case BPF_FUNC_ringbuf_reserve:
10079 	case BPF_FUNC_ringbuf_query:
10080 	case BPF_FUNC_ringbuf_reserve_dynptr:
10081 	case BPF_FUNC_ringbuf_submit_dynptr:
10082 	case BPF_FUNC_ringbuf_discard_dynptr:
10083 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
10084 			goto error;
10085 		break;
10086 	case BPF_FUNC_user_ringbuf_drain:
10087 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
10088 			goto error;
10089 		break;
10090 	case BPF_FUNC_get_stackid:
10091 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
10092 			goto error;
10093 		break;
10094 	case BPF_FUNC_current_task_under_cgroup:
10095 	case BPF_FUNC_skb_under_cgroup:
10096 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
10097 			goto error;
10098 		break;
10099 	case BPF_FUNC_redirect_map:
10100 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
10101 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
10102 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
10103 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
10104 			goto error;
10105 		break;
10106 	case BPF_FUNC_sk_redirect_map:
10107 	case BPF_FUNC_msg_redirect_map:
10108 	case BPF_FUNC_sock_map_update:
10109 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
10110 			goto error;
10111 		break;
10112 	case BPF_FUNC_sk_redirect_hash:
10113 	case BPF_FUNC_msg_redirect_hash:
10114 	case BPF_FUNC_sock_hash_update:
10115 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
10116 			goto error;
10117 		break;
10118 	case BPF_FUNC_get_local_storage:
10119 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
10120 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
10121 			goto error;
10122 		break;
10123 	case BPF_FUNC_sk_select_reuseport:
10124 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
10125 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
10126 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
10127 			goto error;
10128 		break;
10129 	case BPF_FUNC_map_pop_elem:
10130 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10131 		    map->map_type != BPF_MAP_TYPE_STACK)
10132 			goto error;
10133 		break;
10134 	case BPF_FUNC_map_peek_elem:
10135 	case BPF_FUNC_map_push_elem:
10136 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10137 		    map->map_type != BPF_MAP_TYPE_STACK &&
10138 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
10139 			goto error;
10140 		break;
10141 	case BPF_FUNC_map_lookup_percpu_elem:
10142 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
10143 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10144 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
10145 			goto error;
10146 		break;
10147 	case BPF_FUNC_sk_storage_get:
10148 	case BPF_FUNC_sk_storage_delete:
10149 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
10150 			goto error;
10151 		break;
10152 	case BPF_FUNC_inode_storage_get:
10153 	case BPF_FUNC_inode_storage_delete:
10154 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
10155 			goto error;
10156 		break;
10157 	case BPF_FUNC_task_storage_get:
10158 	case BPF_FUNC_task_storage_delete:
10159 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
10160 			goto error;
10161 		break;
10162 	case BPF_FUNC_cgrp_storage_get:
10163 	case BPF_FUNC_cgrp_storage_delete:
10164 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
10165 			goto error;
10166 		break;
10167 	default:
10168 		break;
10169 	}
10170 
10171 	return 0;
10172 error:
10173 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
10174 		map->map_type, func_id_name(func_id), func_id);
10175 	return -EINVAL;
10176 }
10177 
10178 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
10179 {
10180 	int count = 0;
10181 
10182 	if (arg_type_is_raw_mem(fn->arg1_type))
10183 		count++;
10184 	if (arg_type_is_raw_mem(fn->arg2_type))
10185 		count++;
10186 	if (arg_type_is_raw_mem(fn->arg3_type))
10187 		count++;
10188 	if (arg_type_is_raw_mem(fn->arg4_type))
10189 		count++;
10190 	if (arg_type_is_raw_mem(fn->arg5_type))
10191 		count++;
10192 
10193 	/* We only support one arg being in raw mode at the moment,
10194 	 * which is sufficient for the helper functions we have
10195 	 * right now.
10196 	 */
10197 	return count <= 1;
10198 }
10199 
10200 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
10201 {
10202 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
10203 	bool has_size = fn->arg_size[arg] != 0;
10204 	bool is_next_size = false;
10205 
10206 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
10207 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
10208 
10209 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
10210 		return is_next_size;
10211 
10212 	return has_size == is_next_size || is_next_size == is_fixed;
10213 }
10214 
10215 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
10216 {
10217 	/* bpf_xxx(..., buf, len) call will access 'len'
10218 	 * bytes from memory 'buf'. Both arg types need
10219 	 * to be paired, so make sure there's no buggy
10220 	 * helper function specification.
10221 	 */
10222 	if (arg_type_is_mem_size(fn->arg1_type) ||
10223 	    check_args_pair_invalid(fn, 0) ||
10224 	    check_args_pair_invalid(fn, 1) ||
10225 	    check_args_pair_invalid(fn, 2) ||
10226 	    check_args_pair_invalid(fn, 3) ||
10227 	    check_args_pair_invalid(fn, 4))
10228 		return false;
10229 
10230 	return true;
10231 }
10232 
10233 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
10234 {
10235 	int i;
10236 
10237 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10238 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
10239 			return !!fn->arg_btf_id[i];
10240 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
10241 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
10242 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
10243 		    /* arg_btf_id and arg_size are in a union. */
10244 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
10245 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
10246 			return false;
10247 	}
10248 
10249 	return true;
10250 }
10251 
10252 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
10253 {
10254 	return check_raw_mode_ok(fn) &&
10255 	       check_arg_pair_ok(fn) &&
10256 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
10257 }
10258 
10259 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
10260  * are now invalid, so turn them into unknown SCALAR_VALUE.
10261  *
10262  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
10263  * since these slices point to packet data.
10264  */
10265 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
10266 {
10267 	struct bpf_func_state *state;
10268 	struct bpf_reg_state *reg;
10269 
10270 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10271 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
10272 			mark_reg_invalid(env, reg);
10273 	}));
10274 }
10275 
10276 enum {
10277 	AT_PKT_END = -1,
10278 	BEYOND_PKT_END = -2,
10279 };
10280 
10281 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
10282 {
10283 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10284 	struct bpf_reg_state *reg = &state->regs[regn];
10285 
10286 	if (reg->type != PTR_TO_PACKET)
10287 		/* PTR_TO_PACKET_META is not supported yet */
10288 		return;
10289 
10290 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
10291 	 * How far beyond pkt_end it goes is unknown.
10292 	 * if (!range_open) it's the case of pkt >= pkt_end
10293 	 * if (range_open) it's the case of pkt > pkt_end
10294 	 * hence this pointer is at least 1 byte bigger than pkt_end
10295 	 */
10296 	if (range_open)
10297 		reg->range = BEYOND_PKT_END;
10298 	else
10299 		reg->range = AT_PKT_END;
10300 }
10301 
10302 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id)
10303 {
10304 	int i;
10305 
10306 	for (i = 0; i < state->acquired_refs; i++) {
10307 		if (state->refs[i].type != REF_TYPE_PTR)
10308 			continue;
10309 		if (state->refs[i].id == ref_obj_id) {
10310 			release_reference_state(state, i);
10311 			return 0;
10312 		}
10313 	}
10314 	return -EINVAL;
10315 }
10316 
10317 /* The pointer with the specified id has released its reference to kernel
10318  * resources. Identify all copies of the same pointer and clear the reference.
10319  *
10320  * This is the release function corresponding to acquire_reference(). Idempotent.
10321  */
10322 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id)
10323 {
10324 	struct bpf_verifier_state *vstate = env->cur_state;
10325 	struct bpf_func_state *state;
10326 	struct bpf_reg_state *reg;
10327 	int err;
10328 
10329 	err = release_reference_nomark(vstate, ref_obj_id);
10330 	if (err)
10331 		return err;
10332 
10333 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10334 		if (reg->ref_obj_id == ref_obj_id)
10335 			mark_reg_invalid(env, reg);
10336 	}));
10337 
10338 	return 0;
10339 }
10340 
10341 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
10342 {
10343 	struct bpf_func_state *unused;
10344 	struct bpf_reg_state *reg;
10345 
10346 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10347 		if (type_is_non_owning_ref(reg->type))
10348 			mark_reg_invalid(env, reg);
10349 	}));
10350 }
10351 
10352 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
10353 				    struct bpf_reg_state *regs)
10354 {
10355 	int i;
10356 
10357 	/* after the call registers r0 - r5 were scratched */
10358 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10359 		mark_reg_not_init(env, regs, caller_saved[i]);
10360 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
10361 	}
10362 }
10363 
10364 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
10365 				   struct bpf_func_state *caller,
10366 				   struct bpf_func_state *callee,
10367 				   int insn_idx);
10368 
10369 static bool is_task_work_add_kfunc(u32 func_id);
10370 
10371 static int set_callee_state(struct bpf_verifier_env *env,
10372 			    struct bpf_func_state *caller,
10373 			    struct bpf_func_state *callee, int insn_idx);
10374 
10375 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
10376 			    set_callee_state_fn set_callee_state_cb,
10377 			    struct bpf_verifier_state *state)
10378 {
10379 	struct bpf_func_state *caller, *callee;
10380 	int err;
10381 
10382 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
10383 		verbose(env, "the call stack of %d frames is too deep\n",
10384 			state->curframe + 2);
10385 		return -E2BIG;
10386 	}
10387 
10388 	if (state->frame[state->curframe + 1]) {
10389 		verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
10390 		return -EFAULT;
10391 	}
10392 
10393 	caller = state->frame[state->curframe];
10394 	callee = kzalloc(sizeof(*callee), GFP_KERNEL_ACCOUNT);
10395 	if (!callee)
10396 		return -ENOMEM;
10397 	state->frame[state->curframe + 1] = callee;
10398 
10399 	/* callee cannot access r0, r6 - r9 for reading and has to write
10400 	 * into its own stack before reading from it.
10401 	 * callee can read/write into caller's stack
10402 	 */
10403 	init_func_state(env, callee,
10404 			/* remember the callsite, it will be used by bpf_exit */
10405 			callsite,
10406 			state->curframe + 1 /* frameno within this callchain */,
10407 			subprog /* subprog number within this prog */);
10408 	err = set_callee_state_cb(env, caller, callee, callsite);
10409 	if (err)
10410 		goto err_out;
10411 
10412 	/* only increment it after check_reg_arg() finished */
10413 	state->curframe++;
10414 
10415 	return 0;
10416 
10417 err_out:
10418 	free_func_state(callee);
10419 	state->frame[state->curframe + 1] = NULL;
10420 	return err;
10421 }
10422 
10423 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
10424 				    const struct btf *btf,
10425 				    struct bpf_reg_state *regs)
10426 {
10427 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
10428 	struct bpf_verifier_log *log = &env->log;
10429 	u32 i;
10430 	int ret;
10431 
10432 	ret = btf_prepare_func_args(env, subprog);
10433 	if (ret)
10434 		return ret;
10435 
10436 	/* check that BTF function arguments match actual types that the
10437 	 * verifier sees.
10438 	 */
10439 	for (i = 0; i < sub->arg_cnt; i++) {
10440 		u32 regno = i + 1;
10441 		struct bpf_reg_state *reg = &regs[regno];
10442 		struct bpf_subprog_arg_info *arg = &sub->args[i];
10443 
10444 		if (arg->arg_type == ARG_ANYTHING) {
10445 			if (reg->type != SCALAR_VALUE) {
10446 				bpf_log(log, "R%d is not a scalar\n", regno);
10447 				return -EINVAL;
10448 			}
10449 		} else if (arg->arg_type & PTR_UNTRUSTED) {
10450 			/*
10451 			 * Anything is allowed for untrusted arguments, as these are
10452 			 * read-only and probe read instructions would protect against
10453 			 * invalid memory access.
10454 			 */
10455 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
10456 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10457 			if (ret < 0)
10458 				return ret;
10459 			/* If function expects ctx type in BTF check that caller
10460 			 * is passing PTR_TO_CTX.
10461 			 */
10462 			if (reg->type != PTR_TO_CTX) {
10463 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
10464 				return -EINVAL;
10465 			}
10466 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
10467 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10468 			if (ret < 0)
10469 				return ret;
10470 			if (check_mem_reg(env, reg, regno, arg->mem_size))
10471 				return -EINVAL;
10472 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
10473 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
10474 				return -EINVAL;
10475 			}
10476 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
10477 			/*
10478 			 * Can pass any value and the kernel won't crash, but
10479 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
10480 			 * else is a bug in the bpf program. Point it out to
10481 			 * the user at the verification time instead of
10482 			 * run-time debug nightmare.
10483 			 */
10484 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
10485 				bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
10486 				return -EINVAL;
10487 			}
10488 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
10489 			ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
10490 			if (ret)
10491 				return ret;
10492 
10493 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
10494 			if (ret)
10495 				return ret;
10496 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
10497 			struct bpf_call_arg_meta meta;
10498 			int err;
10499 
10500 			if (register_is_null(reg) && type_may_be_null(arg->arg_type))
10501 				continue;
10502 
10503 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
10504 			err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
10505 			err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
10506 			if (err)
10507 				return err;
10508 		} else {
10509 			verifier_bug(env, "unrecognized arg#%d type %d", i, arg->arg_type);
10510 			return -EFAULT;
10511 		}
10512 	}
10513 
10514 	return 0;
10515 }
10516 
10517 /* Compare BTF of a function call with given bpf_reg_state.
10518  * Returns:
10519  * EFAULT - there is a verifier bug. Abort verification.
10520  * EINVAL - there is a type mismatch or BTF is not available.
10521  * 0 - BTF matches with what bpf_reg_state expects.
10522  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
10523  */
10524 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
10525 				  struct bpf_reg_state *regs)
10526 {
10527 	struct bpf_prog *prog = env->prog;
10528 	struct btf *btf = prog->aux->btf;
10529 	u32 btf_id;
10530 	int err;
10531 
10532 	if (!prog->aux->func_info)
10533 		return -EINVAL;
10534 
10535 	btf_id = prog->aux->func_info[subprog].type_id;
10536 	if (!btf_id)
10537 		return -EFAULT;
10538 
10539 	if (prog->aux->func_info_aux[subprog].unreliable)
10540 		return -EINVAL;
10541 
10542 	err = btf_check_func_arg_match(env, subprog, btf, regs);
10543 	/* Compiler optimizations can remove arguments from static functions
10544 	 * or mismatched type can be passed into a global function.
10545 	 * In such cases mark the function as unreliable from BTF point of view.
10546 	 */
10547 	if (err)
10548 		prog->aux->func_info_aux[subprog].unreliable = true;
10549 	return err;
10550 }
10551 
10552 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10553 			      int insn_idx, int subprog,
10554 			      set_callee_state_fn set_callee_state_cb)
10555 {
10556 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
10557 	struct bpf_func_state *caller, *callee;
10558 	int err;
10559 
10560 	caller = state->frame[state->curframe];
10561 	err = btf_check_subprog_call(env, subprog, caller->regs);
10562 	if (err == -EFAULT)
10563 		return err;
10564 
10565 	/* set_callee_state is used for direct subprog calls, but we are
10566 	 * interested in validating only BPF helpers that can call subprogs as
10567 	 * callbacks
10568 	 */
10569 	env->subprog_info[subprog].is_cb = true;
10570 	if (bpf_pseudo_kfunc_call(insn) &&
10571 	    !is_callback_calling_kfunc(insn->imm)) {
10572 		verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
10573 			     func_id_name(insn->imm), insn->imm);
10574 		return -EFAULT;
10575 	} else if (!bpf_pseudo_kfunc_call(insn) &&
10576 		   !is_callback_calling_function(insn->imm)) { /* helper */
10577 		verifier_bug(env, "helper %s#%d not marked as callback-calling",
10578 			     func_id_name(insn->imm), insn->imm);
10579 		return -EFAULT;
10580 	}
10581 
10582 	if (is_async_callback_calling_insn(insn)) {
10583 		struct bpf_verifier_state *async_cb;
10584 
10585 		/* there is no real recursion here. timer and workqueue callbacks are async */
10586 		env->subprog_info[subprog].is_async_cb = true;
10587 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
10588 					 insn_idx, subprog,
10589 					 is_bpf_wq_set_callback_impl_kfunc(insn->imm) ||
10590 					 is_task_work_add_kfunc(insn->imm));
10591 		if (!async_cb)
10592 			return -EFAULT;
10593 		callee = async_cb->frame[0];
10594 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
10595 
10596 		/* Convert bpf_timer_set_callback() args into timer callback args */
10597 		err = set_callee_state_cb(env, caller, callee, insn_idx);
10598 		if (err)
10599 			return err;
10600 
10601 		return 0;
10602 	}
10603 
10604 	/* for callback functions enqueue entry to callback and
10605 	 * proceed with next instruction within current frame.
10606 	 */
10607 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
10608 	if (!callback_state)
10609 		return -ENOMEM;
10610 
10611 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
10612 			       callback_state);
10613 	if (err)
10614 		return err;
10615 
10616 	callback_state->callback_unroll_depth++;
10617 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
10618 	caller->callback_depth = 0;
10619 	return 0;
10620 }
10621 
10622 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10623 			   int *insn_idx)
10624 {
10625 	struct bpf_verifier_state *state = env->cur_state;
10626 	struct bpf_func_state *caller;
10627 	int err, subprog, target_insn;
10628 
10629 	target_insn = *insn_idx + insn->imm + 1;
10630 	subprog = find_subprog(env, target_insn);
10631 	if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program",
10632 			    target_insn))
10633 		return -EFAULT;
10634 
10635 	caller = state->frame[state->curframe];
10636 	err = btf_check_subprog_call(env, subprog, caller->regs);
10637 	if (err == -EFAULT)
10638 		return err;
10639 	if (subprog_is_global(env, subprog)) {
10640 		const char *sub_name = subprog_name(env, subprog);
10641 
10642 		if (env->cur_state->active_locks) {
10643 			verbose(env, "global function calls are not allowed while holding a lock,\n"
10644 				     "use static function instead\n");
10645 			return -EINVAL;
10646 		}
10647 
10648 		if (env->subprog_info[subprog].might_sleep &&
10649 		    (env->cur_state->active_rcu_lock || env->cur_state->active_preempt_locks ||
10650 		     env->cur_state->active_irq_id || !in_sleepable(env))) {
10651 			verbose(env, "global functions that may sleep are not allowed in non-sleepable context,\n"
10652 				     "i.e., in a RCU/IRQ/preempt-disabled section, or in\n"
10653 				     "a non-sleepable BPF program context\n");
10654 			return -EINVAL;
10655 		}
10656 
10657 		if (err) {
10658 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
10659 				subprog, sub_name);
10660 			return err;
10661 		}
10662 
10663 		verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
10664 			subprog, sub_name);
10665 		if (env->subprog_info[subprog].changes_pkt_data)
10666 			clear_all_pkt_pointers(env);
10667 		/* mark global subprog for verifying after main prog */
10668 		subprog_aux(env, subprog)->called = true;
10669 		clear_caller_saved_regs(env, caller->regs);
10670 
10671 		/* All global functions return a 64-bit SCALAR_VALUE */
10672 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
10673 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10674 
10675 		/* continue with next insn after call */
10676 		return 0;
10677 	}
10678 
10679 	/* for regular function entry setup new frame and continue
10680 	 * from that frame.
10681 	 */
10682 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
10683 	if (err)
10684 		return err;
10685 
10686 	clear_caller_saved_regs(env, caller->regs);
10687 
10688 	/* and go analyze first insn of the callee */
10689 	*insn_idx = env->subprog_info[subprog].start - 1;
10690 
10691 	bpf_reset_live_stack_callchain(env);
10692 
10693 	if (env->log.level & BPF_LOG_LEVEL) {
10694 		verbose(env, "caller:\n");
10695 		print_verifier_state(env, state, caller->frameno, true);
10696 		verbose(env, "callee:\n");
10697 		print_verifier_state(env, state, state->curframe, true);
10698 	}
10699 
10700 	return 0;
10701 }
10702 
10703 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
10704 				   struct bpf_func_state *caller,
10705 				   struct bpf_func_state *callee)
10706 {
10707 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
10708 	 *      void *callback_ctx, u64 flags);
10709 	 * callback_fn(struct bpf_map *map, void *key, void *value,
10710 	 *      void *callback_ctx);
10711 	 */
10712 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10713 
10714 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10715 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10716 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10717 
10718 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10719 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10720 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10721 
10722 	/* pointer to stack or null */
10723 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
10724 
10725 	/* unused */
10726 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10727 	return 0;
10728 }
10729 
10730 static int set_callee_state(struct bpf_verifier_env *env,
10731 			    struct bpf_func_state *caller,
10732 			    struct bpf_func_state *callee, int insn_idx)
10733 {
10734 	int i;
10735 
10736 	/* copy r1 - r5 args that callee can access.  The copy includes parent
10737 	 * pointers, which connects us up to the liveness chain
10738 	 */
10739 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
10740 		callee->regs[i] = caller->regs[i];
10741 	return 0;
10742 }
10743 
10744 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
10745 				       struct bpf_func_state *caller,
10746 				       struct bpf_func_state *callee,
10747 				       int insn_idx)
10748 {
10749 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
10750 	struct bpf_map *map;
10751 	int err;
10752 
10753 	/* valid map_ptr and poison value does not matter */
10754 	map = insn_aux->map_ptr_state.map_ptr;
10755 	if (!map->ops->map_set_for_each_callback_args ||
10756 	    !map->ops->map_for_each_callback) {
10757 		verbose(env, "callback function not allowed for map\n");
10758 		return -ENOTSUPP;
10759 	}
10760 
10761 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
10762 	if (err)
10763 		return err;
10764 
10765 	callee->in_callback_fn = true;
10766 	callee->callback_ret_range = retval_range(0, 1);
10767 	return 0;
10768 }
10769 
10770 static int set_loop_callback_state(struct bpf_verifier_env *env,
10771 				   struct bpf_func_state *caller,
10772 				   struct bpf_func_state *callee,
10773 				   int insn_idx)
10774 {
10775 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
10776 	 *	    u64 flags);
10777 	 * callback_fn(u64 index, void *callback_ctx);
10778 	 */
10779 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
10780 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10781 
10782 	/* unused */
10783 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10784 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10785 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10786 
10787 	callee->in_callback_fn = true;
10788 	callee->callback_ret_range = retval_range(0, 1);
10789 	return 0;
10790 }
10791 
10792 static int set_timer_callback_state(struct bpf_verifier_env *env,
10793 				    struct bpf_func_state *caller,
10794 				    struct bpf_func_state *callee,
10795 				    int insn_idx)
10796 {
10797 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
10798 
10799 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
10800 	 * callback_fn(struct bpf_map *map, void *key, void *value);
10801 	 */
10802 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10803 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10804 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
10805 
10806 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10807 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10808 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
10809 
10810 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10811 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10812 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
10813 
10814 	/* unused */
10815 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10816 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10817 	callee->in_async_callback_fn = true;
10818 	callee->callback_ret_range = retval_range(0, 0);
10819 	return 0;
10820 }
10821 
10822 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
10823 				       struct bpf_func_state *caller,
10824 				       struct bpf_func_state *callee,
10825 				       int insn_idx)
10826 {
10827 	/* bpf_find_vma(struct task_struct *task, u64 addr,
10828 	 *               void *callback_fn, void *callback_ctx, u64 flags)
10829 	 * (callback_fn)(struct task_struct *task,
10830 	 *               struct vm_area_struct *vma, void *callback_ctx);
10831 	 */
10832 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10833 
10834 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
10835 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10836 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
10837 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
10838 
10839 	/* pointer to stack or null */
10840 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
10841 
10842 	/* unused */
10843 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10844 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10845 	callee->in_callback_fn = true;
10846 	callee->callback_ret_range = retval_range(0, 1);
10847 	return 0;
10848 }
10849 
10850 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
10851 					   struct bpf_func_state *caller,
10852 					   struct bpf_func_state *callee,
10853 					   int insn_idx)
10854 {
10855 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
10856 	 *			  callback_ctx, u64 flags);
10857 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
10858 	 */
10859 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
10860 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
10861 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10862 
10863 	/* unused */
10864 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10865 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10866 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10867 
10868 	callee->in_callback_fn = true;
10869 	callee->callback_ret_range = retval_range(0, 1);
10870 	return 0;
10871 }
10872 
10873 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
10874 					 struct bpf_func_state *caller,
10875 					 struct bpf_func_state *callee,
10876 					 int insn_idx)
10877 {
10878 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
10879 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
10880 	 *
10881 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
10882 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
10883 	 * by this point, so look at 'root'
10884 	 */
10885 	struct btf_field *field;
10886 
10887 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
10888 				      BPF_RB_ROOT);
10889 	if (!field || !field->graph_root.value_btf_id)
10890 		return -EFAULT;
10891 
10892 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
10893 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
10894 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
10895 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
10896 
10897 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10898 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10899 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10900 	callee->in_callback_fn = true;
10901 	callee->callback_ret_range = retval_range(0, 1);
10902 	return 0;
10903 }
10904 
10905 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env,
10906 						 struct bpf_func_state *caller,
10907 						 struct bpf_func_state *callee,
10908 						 int insn_idx)
10909 {
10910 	struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr;
10911 
10912 	/*
10913 	 * callback_fn(struct bpf_map *map, void *key, void *value);
10914 	 */
10915 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10916 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10917 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
10918 
10919 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10920 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10921 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
10922 
10923 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10924 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10925 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
10926 
10927 	/* unused */
10928 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10929 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10930 	callee->in_async_callback_fn = true;
10931 	callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
10932 	return 0;
10933 }
10934 
10935 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
10936 
10937 /* Are we currently verifying the callback for a rbtree helper that must
10938  * be called with lock held? If so, no need to complain about unreleased
10939  * lock
10940  */
10941 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
10942 {
10943 	struct bpf_verifier_state *state = env->cur_state;
10944 	struct bpf_insn *insn = env->prog->insnsi;
10945 	struct bpf_func_state *callee;
10946 	int kfunc_btf_id;
10947 
10948 	if (!state->curframe)
10949 		return false;
10950 
10951 	callee = state->frame[state->curframe];
10952 
10953 	if (!callee->in_callback_fn)
10954 		return false;
10955 
10956 	kfunc_btf_id = insn[callee->callsite].imm;
10957 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
10958 }
10959 
10960 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg,
10961 				bool return_32bit)
10962 {
10963 	if (return_32bit)
10964 		return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval;
10965 	else
10966 		return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
10967 }
10968 
10969 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
10970 {
10971 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
10972 	struct bpf_func_state *caller, *callee;
10973 	struct bpf_reg_state *r0;
10974 	bool in_callback_fn;
10975 	int err;
10976 
10977 	callee = state->frame[state->curframe];
10978 	r0 = &callee->regs[BPF_REG_0];
10979 	if (r0->type == PTR_TO_STACK) {
10980 		/* technically it's ok to return caller's stack pointer
10981 		 * (or caller's caller's pointer) back to the caller,
10982 		 * since these pointers are valid. Only current stack
10983 		 * pointer will be invalid as soon as function exits,
10984 		 * but let's be conservative
10985 		 */
10986 		verbose(env, "cannot return stack pointer to the caller\n");
10987 		return -EINVAL;
10988 	}
10989 
10990 	caller = state->frame[state->curframe - 1];
10991 	if (callee->in_callback_fn) {
10992 		if (r0->type != SCALAR_VALUE) {
10993 			verbose(env, "R0 not a scalar value\n");
10994 			return -EACCES;
10995 		}
10996 
10997 		/* we are going to rely on register's precise value */
10998 		err = mark_chain_precision(env, BPF_REG_0);
10999 		if (err)
11000 			return err;
11001 
11002 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
11003 		if (!retval_range_within(callee->callback_ret_range, r0, false)) {
11004 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
11005 					       "At callback return", "R0");
11006 			return -EINVAL;
11007 		}
11008 		if (!bpf_calls_callback(env, callee->callsite)) {
11009 			verifier_bug(env, "in callback at %d, callsite %d !calls_callback",
11010 				     *insn_idx, callee->callsite);
11011 			return -EFAULT;
11012 		}
11013 	} else {
11014 		/* return to the caller whatever r0 had in the callee */
11015 		caller->regs[BPF_REG_0] = *r0;
11016 	}
11017 
11018 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
11019 	 * there function call logic would reschedule callback visit. If iteration
11020 	 * converges is_state_visited() would prune that visit eventually.
11021 	 */
11022 	in_callback_fn = callee->in_callback_fn;
11023 	if (in_callback_fn)
11024 		*insn_idx = callee->callsite;
11025 	else
11026 		*insn_idx = callee->callsite + 1;
11027 
11028 	if (env->log.level & BPF_LOG_LEVEL) {
11029 		verbose(env, "returning from callee:\n");
11030 		print_verifier_state(env, state, callee->frameno, true);
11031 		verbose(env, "to caller at %d:\n", *insn_idx);
11032 		print_verifier_state(env, state, caller->frameno, true);
11033 	}
11034 	/* clear everything in the callee. In case of exceptional exits using
11035 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
11036 	free_func_state(callee);
11037 	state->frame[state->curframe--] = NULL;
11038 
11039 	/* for callbacks widen imprecise scalars to make programs like below verify:
11040 	 *
11041 	 *   struct ctx { int i; }
11042 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
11043 	 *   ...
11044 	 *   struct ctx = { .i = 0; }
11045 	 *   bpf_loop(100, cb, &ctx, 0);
11046 	 *
11047 	 * This is similar to what is done in process_iter_next_call() for open
11048 	 * coded iterators.
11049 	 */
11050 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
11051 	if (prev_st) {
11052 		err = widen_imprecise_scalars(env, prev_st, state);
11053 		if (err)
11054 			return err;
11055 	}
11056 	return 0;
11057 }
11058 
11059 static int do_refine_retval_range(struct bpf_verifier_env *env,
11060 				  struct bpf_reg_state *regs, int ret_type,
11061 				  int func_id,
11062 				  struct bpf_call_arg_meta *meta)
11063 {
11064 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
11065 
11066 	if (ret_type != RET_INTEGER)
11067 		return 0;
11068 
11069 	switch (func_id) {
11070 	case BPF_FUNC_get_stack:
11071 	case BPF_FUNC_get_task_stack:
11072 	case BPF_FUNC_probe_read_str:
11073 	case BPF_FUNC_probe_read_kernel_str:
11074 	case BPF_FUNC_probe_read_user_str:
11075 		ret_reg->smax_value = meta->msize_max_value;
11076 		ret_reg->s32_max_value = meta->msize_max_value;
11077 		ret_reg->smin_value = -MAX_ERRNO;
11078 		ret_reg->s32_min_value = -MAX_ERRNO;
11079 		reg_bounds_sync(ret_reg);
11080 		break;
11081 	case BPF_FUNC_get_smp_processor_id:
11082 		ret_reg->umax_value = nr_cpu_ids - 1;
11083 		ret_reg->u32_max_value = nr_cpu_ids - 1;
11084 		ret_reg->smax_value = nr_cpu_ids - 1;
11085 		ret_reg->s32_max_value = nr_cpu_ids - 1;
11086 		ret_reg->umin_value = 0;
11087 		ret_reg->u32_min_value = 0;
11088 		ret_reg->smin_value = 0;
11089 		ret_reg->s32_min_value = 0;
11090 		reg_bounds_sync(ret_reg);
11091 		break;
11092 	}
11093 
11094 	return reg_bounds_sanity_check(env, ret_reg, "retval");
11095 }
11096 
11097 static int
11098 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11099 		int func_id, int insn_idx)
11100 {
11101 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11102 	struct bpf_map *map = meta->map_ptr;
11103 
11104 	if (func_id != BPF_FUNC_tail_call &&
11105 	    func_id != BPF_FUNC_map_lookup_elem &&
11106 	    func_id != BPF_FUNC_map_update_elem &&
11107 	    func_id != BPF_FUNC_map_delete_elem &&
11108 	    func_id != BPF_FUNC_map_push_elem &&
11109 	    func_id != BPF_FUNC_map_pop_elem &&
11110 	    func_id != BPF_FUNC_map_peek_elem &&
11111 	    func_id != BPF_FUNC_for_each_map_elem &&
11112 	    func_id != BPF_FUNC_redirect_map &&
11113 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
11114 		return 0;
11115 
11116 	if (map == NULL) {
11117 		verifier_bug(env, "expected map for helper call");
11118 		return -EFAULT;
11119 	}
11120 
11121 	/* In case of read-only, some additional restrictions
11122 	 * need to be applied in order to prevent altering the
11123 	 * state of the map from program side.
11124 	 */
11125 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
11126 	    (func_id == BPF_FUNC_map_delete_elem ||
11127 	     func_id == BPF_FUNC_map_update_elem ||
11128 	     func_id == BPF_FUNC_map_push_elem ||
11129 	     func_id == BPF_FUNC_map_pop_elem)) {
11130 		verbose(env, "write into map forbidden\n");
11131 		return -EACCES;
11132 	}
11133 
11134 	if (!aux->map_ptr_state.map_ptr)
11135 		bpf_map_ptr_store(aux, meta->map_ptr,
11136 				  !meta->map_ptr->bypass_spec_v1, false);
11137 	else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
11138 		bpf_map_ptr_store(aux, meta->map_ptr,
11139 				  !meta->map_ptr->bypass_spec_v1, true);
11140 	return 0;
11141 }
11142 
11143 static int
11144 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11145 		int func_id, int insn_idx)
11146 {
11147 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11148 	struct bpf_reg_state *regs = cur_regs(env), *reg;
11149 	struct bpf_map *map = meta->map_ptr;
11150 	u64 val, max;
11151 	int err;
11152 
11153 	if (func_id != BPF_FUNC_tail_call)
11154 		return 0;
11155 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
11156 		verbose(env, "expected prog array map for tail call");
11157 		return -EINVAL;
11158 	}
11159 
11160 	reg = &regs[BPF_REG_3];
11161 	val = reg->var_off.value;
11162 	max = map->max_entries;
11163 
11164 	if (!(is_reg_const(reg, false) && val < max)) {
11165 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11166 		return 0;
11167 	}
11168 
11169 	err = mark_chain_precision(env, BPF_REG_3);
11170 	if (err)
11171 		return err;
11172 	if (bpf_map_key_unseen(aux))
11173 		bpf_map_key_store(aux, val);
11174 	else if (!bpf_map_key_poisoned(aux) &&
11175 		  bpf_map_key_immediate(aux) != val)
11176 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11177 	return 0;
11178 }
11179 
11180 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
11181 {
11182 	struct bpf_verifier_state *state = env->cur_state;
11183 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11184 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
11185 	bool refs_lingering = false;
11186 	int i;
11187 
11188 	if (!exception_exit && cur_func(env)->frameno)
11189 		return 0;
11190 
11191 	for (i = 0; i < state->acquired_refs; i++) {
11192 		if (state->refs[i].type != REF_TYPE_PTR)
11193 			continue;
11194 		/* Allow struct_ops programs to return a referenced kptr back to
11195 		 * kernel. Type checks are performed later in check_return_code.
11196 		 */
11197 		if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
11198 		    reg->ref_obj_id == state->refs[i].id)
11199 			continue;
11200 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
11201 			state->refs[i].id, state->refs[i].insn_idx);
11202 		refs_lingering = true;
11203 	}
11204 	return refs_lingering ? -EINVAL : 0;
11205 }
11206 
11207 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
11208 {
11209 	int err;
11210 
11211 	if (check_lock && env->cur_state->active_locks) {
11212 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
11213 		return -EINVAL;
11214 	}
11215 
11216 	err = check_reference_leak(env, exception_exit);
11217 	if (err) {
11218 		verbose(env, "%s would lead to reference leak\n", prefix);
11219 		return err;
11220 	}
11221 
11222 	if (check_lock && env->cur_state->active_irq_id) {
11223 		verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
11224 		return -EINVAL;
11225 	}
11226 
11227 	if (check_lock && env->cur_state->active_rcu_lock) {
11228 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
11229 		return -EINVAL;
11230 	}
11231 
11232 	if (check_lock && env->cur_state->active_preempt_locks) {
11233 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
11234 		return -EINVAL;
11235 	}
11236 
11237 	return 0;
11238 }
11239 
11240 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
11241 				   struct bpf_reg_state *regs)
11242 {
11243 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
11244 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
11245 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
11246 	struct bpf_bprintf_data data = {};
11247 	int err, fmt_map_off, num_args;
11248 	u64 fmt_addr;
11249 	char *fmt;
11250 
11251 	/* data must be an array of u64 */
11252 	if (data_len_reg->var_off.value % 8)
11253 		return -EINVAL;
11254 	num_args = data_len_reg->var_off.value / 8;
11255 
11256 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
11257 	 * and map_direct_value_addr is set.
11258 	 */
11259 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
11260 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
11261 						  fmt_map_off);
11262 	if (err) {
11263 		verbose(env, "failed to retrieve map value address\n");
11264 		return -EFAULT;
11265 	}
11266 	fmt = (char *)(long)fmt_addr + fmt_map_off;
11267 
11268 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
11269 	 * can focus on validating the format specifiers.
11270 	 */
11271 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
11272 	if (err < 0)
11273 		verbose(env, "Invalid format string\n");
11274 
11275 	return err;
11276 }
11277 
11278 static int check_get_func_ip(struct bpf_verifier_env *env)
11279 {
11280 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11281 	int func_id = BPF_FUNC_get_func_ip;
11282 
11283 	if (type == BPF_PROG_TYPE_TRACING) {
11284 		if (!bpf_prog_has_trampoline(env->prog)) {
11285 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
11286 				func_id_name(func_id), func_id);
11287 			return -ENOTSUPP;
11288 		}
11289 		return 0;
11290 	} else if (type == BPF_PROG_TYPE_KPROBE) {
11291 		return 0;
11292 	}
11293 
11294 	verbose(env, "func %s#%d not supported for program type %d\n",
11295 		func_id_name(func_id), func_id, type);
11296 	return -ENOTSUPP;
11297 }
11298 
11299 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env)
11300 {
11301 	return &env->insn_aux_data[env->insn_idx];
11302 }
11303 
11304 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
11305 {
11306 	struct bpf_reg_state *regs = cur_regs(env);
11307 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
11308 	bool reg_is_null = register_is_null(reg);
11309 
11310 	if (reg_is_null)
11311 		mark_chain_precision(env, BPF_REG_4);
11312 
11313 	return reg_is_null;
11314 }
11315 
11316 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
11317 {
11318 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
11319 
11320 	if (!state->initialized) {
11321 		state->initialized = 1;
11322 		state->fit_for_inline = loop_flag_is_zero(env);
11323 		state->callback_subprogno = subprogno;
11324 		return;
11325 	}
11326 
11327 	if (!state->fit_for_inline)
11328 		return;
11329 
11330 	state->fit_for_inline = (loop_flag_is_zero(env) &&
11331 				 state->callback_subprogno == subprogno);
11332 }
11333 
11334 /* Returns whether or not the given map type can potentially elide
11335  * lookup return value nullness check. This is possible if the key
11336  * is statically known.
11337  */
11338 static bool can_elide_value_nullness(enum bpf_map_type type)
11339 {
11340 	switch (type) {
11341 	case BPF_MAP_TYPE_ARRAY:
11342 	case BPF_MAP_TYPE_PERCPU_ARRAY:
11343 		return true;
11344 	default:
11345 		return false;
11346 	}
11347 }
11348 
11349 static int get_helper_proto(struct bpf_verifier_env *env, int func_id,
11350 			    const struct bpf_func_proto **ptr)
11351 {
11352 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
11353 		return -ERANGE;
11354 
11355 	if (!env->ops->get_func_proto)
11356 		return -EINVAL;
11357 
11358 	*ptr = env->ops->get_func_proto(func_id, env->prog);
11359 	return *ptr && (*ptr)->func ? 0 : -EINVAL;
11360 }
11361 
11362 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11363 			     int *insn_idx_p)
11364 {
11365 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11366 	bool returns_cpu_specific_alloc_ptr = false;
11367 	const struct bpf_func_proto *fn = NULL;
11368 	enum bpf_return_type ret_type;
11369 	enum bpf_type_flag ret_flag;
11370 	struct bpf_reg_state *regs;
11371 	struct bpf_call_arg_meta meta;
11372 	int insn_idx = *insn_idx_p;
11373 	bool changes_data;
11374 	int i, err, func_id;
11375 
11376 	/* find function prototype */
11377 	func_id = insn->imm;
11378 	err = get_helper_proto(env, insn->imm, &fn);
11379 	if (err == -ERANGE) {
11380 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
11381 		return -EINVAL;
11382 	}
11383 
11384 	if (err) {
11385 		verbose(env, "program of this type cannot use helper %s#%d\n",
11386 			func_id_name(func_id), func_id);
11387 		return err;
11388 	}
11389 
11390 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
11391 	if (!env->prog->gpl_compatible && fn->gpl_only) {
11392 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
11393 		return -EINVAL;
11394 	}
11395 
11396 	if (fn->allowed && !fn->allowed(env->prog)) {
11397 		verbose(env, "helper call is not allowed in probe\n");
11398 		return -EINVAL;
11399 	}
11400 
11401 	if (!in_sleepable(env) && fn->might_sleep) {
11402 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
11403 		return -EINVAL;
11404 	}
11405 
11406 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
11407 	changes_data = bpf_helper_changes_pkt_data(func_id);
11408 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
11409 		verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id);
11410 		return -EFAULT;
11411 	}
11412 
11413 	memset(&meta, 0, sizeof(meta));
11414 	meta.pkt_access = fn->pkt_access;
11415 
11416 	err = check_func_proto(fn, func_id);
11417 	if (err) {
11418 		verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id);
11419 		return err;
11420 	}
11421 
11422 	if (env->cur_state->active_rcu_lock) {
11423 		if (fn->might_sleep) {
11424 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
11425 				func_id_name(func_id), func_id);
11426 			return -EINVAL;
11427 		}
11428 
11429 		if (in_sleepable(env) && is_storage_get_function(func_id))
11430 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11431 	}
11432 
11433 	if (env->cur_state->active_preempt_locks) {
11434 		if (fn->might_sleep) {
11435 			verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
11436 				func_id_name(func_id), func_id);
11437 			return -EINVAL;
11438 		}
11439 
11440 		if (in_sleepable(env) && is_storage_get_function(func_id))
11441 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11442 	}
11443 
11444 	if (env->cur_state->active_irq_id) {
11445 		if (fn->might_sleep) {
11446 			verbose(env, "sleepable helper %s#%d in IRQ-disabled region\n",
11447 				func_id_name(func_id), func_id);
11448 			return -EINVAL;
11449 		}
11450 
11451 		if (in_sleepable(env) && is_storage_get_function(func_id))
11452 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11453 	}
11454 
11455 	meta.func_id = func_id;
11456 	/* check args */
11457 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
11458 		err = check_func_arg(env, i, &meta, fn, insn_idx);
11459 		if (err)
11460 			return err;
11461 	}
11462 
11463 	err = record_func_map(env, &meta, func_id, insn_idx);
11464 	if (err)
11465 		return err;
11466 
11467 	err = record_func_key(env, &meta, func_id, insn_idx);
11468 	if (err)
11469 		return err;
11470 
11471 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
11472 	 * is inferred from register state.
11473 	 */
11474 	for (i = 0; i < meta.access_size; i++) {
11475 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
11476 				       BPF_WRITE, -1, false, false);
11477 		if (err)
11478 			return err;
11479 	}
11480 
11481 	regs = cur_regs(env);
11482 
11483 	if (meta.release_regno) {
11484 		err = -EINVAL;
11485 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
11486 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
11487 		 * is safe to do directly.
11488 		 */
11489 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
11490 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
11491 				verifier_bug(env, "CONST_PTR_TO_DYNPTR cannot be released");
11492 				return -EFAULT;
11493 			}
11494 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
11495 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
11496 			u32 ref_obj_id = meta.ref_obj_id;
11497 			bool in_rcu = in_rcu_cs(env);
11498 			struct bpf_func_state *state;
11499 			struct bpf_reg_state *reg;
11500 
11501 			err = release_reference_nomark(env->cur_state, ref_obj_id);
11502 			if (!err) {
11503 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11504 					if (reg->ref_obj_id == ref_obj_id) {
11505 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
11506 							reg->ref_obj_id = 0;
11507 							reg->type &= ~MEM_ALLOC;
11508 							reg->type |= MEM_RCU;
11509 						} else {
11510 							mark_reg_invalid(env, reg);
11511 						}
11512 					}
11513 				}));
11514 			}
11515 		} else if (meta.ref_obj_id) {
11516 			err = release_reference(env, meta.ref_obj_id);
11517 		} else if (register_is_null(&regs[meta.release_regno])) {
11518 			/* meta.ref_obj_id can only be 0 if register that is meant to be
11519 			 * released is NULL, which must be > R0.
11520 			 */
11521 			err = 0;
11522 		}
11523 		if (err) {
11524 			verbose(env, "func %s#%d reference has not been acquired before\n",
11525 				func_id_name(func_id), func_id);
11526 			return err;
11527 		}
11528 	}
11529 
11530 	switch (func_id) {
11531 	case BPF_FUNC_tail_call:
11532 		err = check_resource_leak(env, false, true, "tail_call");
11533 		if (err)
11534 			return err;
11535 		break;
11536 	case BPF_FUNC_get_local_storage:
11537 		/* check that flags argument in get_local_storage(map, flags) is 0,
11538 		 * this is required because get_local_storage() can't return an error.
11539 		 */
11540 		if (!register_is_null(&regs[BPF_REG_2])) {
11541 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
11542 			return -EINVAL;
11543 		}
11544 		break;
11545 	case BPF_FUNC_for_each_map_elem:
11546 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11547 					 set_map_elem_callback_state);
11548 		break;
11549 	case BPF_FUNC_timer_set_callback:
11550 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11551 					 set_timer_callback_state);
11552 		break;
11553 	case BPF_FUNC_find_vma:
11554 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11555 					 set_find_vma_callback_state);
11556 		break;
11557 	case BPF_FUNC_snprintf:
11558 		err = check_bpf_snprintf_call(env, regs);
11559 		break;
11560 	case BPF_FUNC_loop:
11561 		update_loop_inline_state(env, meta.subprogno);
11562 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
11563 		 * is finished, thus mark it precise.
11564 		 */
11565 		err = mark_chain_precision(env, BPF_REG_1);
11566 		if (err)
11567 			return err;
11568 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
11569 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11570 						 set_loop_callback_state);
11571 		} else {
11572 			cur_func(env)->callback_depth = 0;
11573 			if (env->log.level & BPF_LOG_LEVEL2)
11574 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
11575 					env->cur_state->curframe);
11576 		}
11577 		break;
11578 	case BPF_FUNC_dynptr_from_mem:
11579 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
11580 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
11581 				reg_type_str(env, regs[BPF_REG_1].type));
11582 			return -EACCES;
11583 		}
11584 		break;
11585 	case BPF_FUNC_set_retval:
11586 		if (prog_type == BPF_PROG_TYPE_LSM &&
11587 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
11588 			if (!env->prog->aux->attach_func_proto->type) {
11589 				/* Make sure programs that attach to void
11590 				 * hooks don't try to modify return value.
11591 				 */
11592 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
11593 				return -EINVAL;
11594 			}
11595 		}
11596 		break;
11597 	case BPF_FUNC_dynptr_data:
11598 	{
11599 		struct bpf_reg_state *reg;
11600 		int id, ref_obj_id;
11601 
11602 		reg = get_dynptr_arg_reg(env, fn, regs);
11603 		if (!reg)
11604 			return -EFAULT;
11605 
11606 
11607 		if (meta.dynptr_id) {
11608 			verifier_bug(env, "meta.dynptr_id already set");
11609 			return -EFAULT;
11610 		}
11611 		if (meta.ref_obj_id) {
11612 			verifier_bug(env, "meta.ref_obj_id already set");
11613 			return -EFAULT;
11614 		}
11615 
11616 		id = dynptr_id(env, reg);
11617 		if (id < 0) {
11618 			verifier_bug(env, "failed to obtain dynptr id");
11619 			return id;
11620 		}
11621 
11622 		ref_obj_id = dynptr_ref_obj_id(env, reg);
11623 		if (ref_obj_id < 0) {
11624 			verifier_bug(env, "failed to obtain dynptr ref_obj_id");
11625 			return ref_obj_id;
11626 		}
11627 
11628 		meta.dynptr_id = id;
11629 		meta.ref_obj_id = ref_obj_id;
11630 
11631 		break;
11632 	}
11633 	case BPF_FUNC_dynptr_write:
11634 	{
11635 		enum bpf_dynptr_type dynptr_type;
11636 		struct bpf_reg_state *reg;
11637 
11638 		reg = get_dynptr_arg_reg(env, fn, regs);
11639 		if (!reg)
11640 			return -EFAULT;
11641 
11642 		dynptr_type = dynptr_get_type(env, reg);
11643 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
11644 			return -EFAULT;
11645 
11646 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB ||
11647 		    dynptr_type == BPF_DYNPTR_TYPE_SKB_META)
11648 			/* this will trigger clear_all_pkt_pointers(), which will
11649 			 * invalidate all dynptr slices associated with the skb
11650 			 */
11651 			changes_data = true;
11652 
11653 		break;
11654 	}
11655 	case BPF_FUNC_per_cpu_ptr:
11656 	case BPF_FUNC_this_cpu_ptr:
11657 	{
11658 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
11659 		const struct btf_type *type;
11660 
11661 		if (reg->type & MEM_RCU) {
11662 			type = btf_type_by_id(reg->btf, reg->btf_id);
11663 			if (!type || !btf_type_is_struct(type)) {
11664 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
11665 				return -EFAULT;
11666 			}
11667 			returns_cpu_specific_alloc_ptr = true;
11668 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
11669 		}
11670 		break;
11671 	}
11672 	case BPF_FUNC_user_ringbuf_drain:
11673 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11674 					 set_user_ringbuf_callback_state);
11675 		break;
11676 	}
11677 
11678 	if (err)
11679 		return err;
11680 
11681 	/* reset caller saved regs */
11682 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
11683 		mark_reg_not_init(env, regs, caller_saved[i]);
11684 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11685 	}
11686 
11687 	/* helper call returns 64-bit value. */
11688 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
11689 
11690 	/* update return register (already marked as written above) */
11691 	ret_type = fn->ret_type;
11692 	ret_flag = type_flag(ret_type);
11693 
11694 	switch (base_type(ret_type)) {
11695 	case RET_INTEGER:
11696 		/* sets type to SCALAR_VALUE */
11697 		mark_reg_unknown(env, regs, BPF_REG_0);
11698 		break;
11699 	case RET_VOID:
11700 		regs[BPF_REG_0].type = NOT_INIT;
11701 		break;
11702 	case RET_PTR_TO_MAP_VALUE:
11703 		/* There is no offset yet applied, variable or fixed */
11704 		mark_reg_known_zero(env, regs, BPF_REG_0);
11705 		/* remember map_ptr, so that check_map_access()
11706 		 * can check 'value_size' boundary of memory access
11707 		 * to map element returned from bpf_map_lookup_elem()
11708 		 */
11709 		if (meta.map_ptr == NULL) {
11710 			verifier_bug(env, "unexpected null map_ptr");
11711 			return -EFAULT;
11712 		}
11713 
11714 		if (func_id == BPF_FUNC_map_lookup_elem &&
11715 		    can_elide_value_nullness(meta.map_ptr->map_type) &&
11716 		    meta.const_map_key >= 0 &&
11717 		    meta.const_map_key < meta.map_ptr->max_entries)
11718 			ret_flag &= ~PTR_MAYBE_NULL;
11719 
11720 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
11721 		regs[BPF_REG_0].map_uid = meta.map_uid;
11722 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
11723 		if (!type_may_be_null(ret_flag) &&
11724 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
11725 			regs[BPF_REG_0].id = ++env->id_gen;
11726 		}
11727 		break;
11728 	case RET_PTR_TO_SOCKET:
11729 		mark_reg_known_zero(env, regs, BPF_REG_0);
11730 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
11731 		break;
11732 	case RET_PTR_TO_SOCK_COMMON:
11733 		mark_reg_known_zero(env, regs, BPF_REG_0);
11734 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
11735 		break;
11736 	case RET_PTR_TO_TCP_SOCK:
11737 		mark_reg_known_zero(env, regs, BPF_REG_0);
11738 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
11739 		break;
11740 	case RET_PTR_TO_MEM:
11741 		mark_reg_known_zero(env, regs, BPF_REG_0);
11742 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11743 		regs[BPF_REG_0].mem_size = meta.mem_size;
11744 		break;
11745 	case RET_PTR_TO_MEM_OR_BTF_ID:
11746 	{
11747 		const struct btf_type *t;
11748 
11749 		mark_reg_known_zero(env, regs, BPF_REG_0);
11750 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
11751 		if (!btf_type_is_struct(t)) {
11752 			u32 tsize;
11753 			const struct btf_type *ret;
11754 			const char *tname;
11755 
11756 			/* resolve the type size of ksym. */
11757 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
11758 			if (IS_ERR(ret)) {
11759 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
11760 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
11761 					tname, PTR_ERR(ret));
11762 				return -EINVAL;
11763 			}
11764 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11765 			regs[BPF_REG_0].mem_size = tsize;
11766 		} else {
11767 			if (returns_cpu_specific_alloc_ptr) {
11768 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
11769 			} else {
11770 				/* MEM_RDONLY may be carried from ret_flag, but it
11771 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
11772 				 * it will confuse the check of PTR_TO_BTF_ID in
11773 				 * check_mem_access().
11774 				 */
11775 				ret_flag &= ~MEM_RDONLY;
11776 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11777 			}
11778 
11779 			regs[BPF_REG_0].btf = meta.ret_btf;
11780 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11781 		}
11782 		break;
11783 	}
11784 	case RET_PTR_TO_BTF_ID:
11785 	{
11786 		struct btf *ret_btf;
11787 		int ret_btf_id;
11788 
11789 		mark_reg_known_zero(env, regs, BPF_REG_0);
11790 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11791 		if (func_id == BPF_FUNC_kptr_xchg) {
11792 			ret_btf = meta.kptr_field->kptr.btf;
11793 			ret_btf_id = meta.kptr_field->kptr.btf_id;
11794 			if (!btf_is_kernel(ret_btf)) {
11795 				regs[BPF_REG_0].type |= MEM_ALLOC;
11796 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
11797 					regs[BPF_REG_0].type |= MEM_PERCPU;
11798 			}
11799 		} else {
11800 			if (fn->ret_btf_id == BPF_PTR_POISON) {
11801 				verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type",
11802 					     func_id_name(func_id));
11803 				return -EFAULT;
11804 			}
11805 			ret_btf = btf_vmlinux;
11806 			ret_btf_id = *fn->ret_btf_id;
11807 		}
11808 		if (ret_btf_id == 0) {
11809 			verbose(env, "invalid return type %u of func %s#%d\n",
11810 				base_type(ret_type), func_id_name(func_id),
11811 				func_id);
11812 			return -EINVAL;
11813 		}
11814 		regs[BPF_REG_0].btf = ret_btf;
11815 		regs[BPF_REG_0].btf_id = ret_btf_id;
11816 		break;
11817 	}
11818 	default:
11819 		verbose(env, "unknown return type %u of func %s#%d\n",
11820 			base_type(ret_type), func_id_name(func_id), func_id);
11821 		return -EINVAL;
11822 	}
11823 
11824 	if (type_may_be_null(regs[BPF_REG_0].type))
11825 		regs[BPF_REG_0].id = ++env->id_gen;
11826 
11827 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
11828 		verifier_bug(env, "func %s#%d sets ref_obj_id more than once",
11829 			     func_id_name(func_id), func_id);
11830 		return -EFAULT;
11831 	}
11832 
11833 	if (is_dynptr_ref_function(func_id))
11834 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
11835 
11836 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
11837 		/* For release_reference() */
11838 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11839 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
11840 		int id = acquire_reference(env, insn_idx);
11841 
11842 		if (id < 0)
11843 			return id;
11844 		/* For mark_ptr_or_null_reg() */
11845 		regs[BPF_REG_0].id = id;
11846 		/* For release_reference() */
11847 		regs[BPF_REG_0].ref_obj_id = id;
11848 	}
11849 
11850 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
11851 	if (err)
11852 		return err;
11853 
11854 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
11855 	if (err)
11856 		return err;
11857 
11858 	if ((func_id == BPF_FUNC_get_stack ||
11859 	     func_id == BPF_FUNC_get_task_stack) &&
11860 	    !env->prog->has_callchain_buf) {
11861 		const char *err_str;
11862 
11863 #ifdef CONFIG_PERF_EVENTS
11864 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
11865 		err_str = "cannot get callchain buffer for func %s#%d\n";
11866 #else
11867 		err = -ENOTSUPP;
11868 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
11869 #endif
11870 		if (err) {
11871 			verbose(env, err_str, func_id_name(func_id), func_id);
11872 			return err;
11873 		}
11874 
11875 		env->prog->has_callchain_buf = true;
11876 	}
11877 
11878 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
11879 		env->prog->call_get_stack = true;
11880 
11881 	if (func_id == BPF_FUNC_get_func_ip) {
11882 		if (check_get_func_ip(env))
11883 			return -ENOTSUPP;
11884 		env->prog->call_get_func_ip = true;
11885 	}
11886 
11887 	if (changes_data)
11888 		clear_all_pkt_pointers(env);
11889 	return 0;
11890 }
11891 
11892 /* mark_btf_func_reg_size() is used when the reg size is determined by
11893  * the BTF func_proto's return value size and argument.
11894  */
11895 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
11896 				     u32 regno, size_t reg_size)
11897 {
11898 	struct bpf_reg_state *reg = &regs[regno];
11899 
11900 	if (regno == BPF_REG_0) {
11901 		/* Function return value */
11902 		reg->subreg_def = reg_size == sizeof(u64) ?
11903 			DEF_NOT_SUBREG : env->insn_idx + 1;
11904 	} else if (reg_size == sizeof(u64)) {
11905 		/* Function argument */
11906 		mark_insn_zext(env, reg);
11907 	}
11908 }
11909 
11910 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
11911 				   size_t reg_size)
11912 {
11913 	return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size);
11914 }
11915 
11916 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
11917 {
11918 	return meta->kfunc_flags & KF_ACQUIRE;
11919 }
11920 
11921 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
11922 {
11923 	return meta->kfunc_flags & KF_RELEASE;
11924 }
11925 
11926 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
11927 {
11928 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
11929 }
11930 
11931 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
11932 {
11933 	return meta->kfunc_flags & KF_SLEEPABLE;
11934 }
11935 
11936 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
11937 {
11938 	return meta->kfunc_flags & KF_DESTRUCTIVE;
11939 }
11940 
11941 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
11942 {
11943 	return meta->kfunc_flags & KF_RCU;
11944 }
11945 
11946 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
11947 {
11948 	return meta->kfunc_flags & KF_RCU_PROTECTED;
11949 }
11950 
11951 static bool is_kfunc_arg_mem_size(const struct btf *btf,
11952 				  const struct btf_param *arg,
11953 				  const struct bpf_reg_state *reg)
11954 {
11955 	const struct btf_type *t;
11956 
11957 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11958 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11959 		return false;
11960 
11961 	return btf_param_match_suffix(btf, arg, "__sz");
11962 }
11963 
11964 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
11965 					const struct btf_param *arg,
11966 					const struct bpf_reg_state *reg)
11967 {
11968 	const struct btf_type *t;
11969 
11970 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11971 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11972 		return false;
11973 
11974 	return btf_param_match_suffix(btf, arg, "__szk");
11975 }
11976 
11977 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
11978 {
11979 	return btf_param_match_suffix(btf, arg, "__opt");
11980 }
11981 
11982 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
11983 {
11984 	return btf_param_match_suffix(btf, arg, "__k");
11985 }
11986 
11987 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
11988 {
11989 	return btf_param_match_suffix(btf, arg, "__ign");
11990 }
11991 
11992 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
11993 {
11994 	return btf_param_match_suffix(btf, arg, "__map");
11995 }
11996 
11997 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
11998 {
11999 	return btf_param_match_suffix(btf, arg, "__alloc");
12000 }
12001 
12002 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
12003 {
12004 	return btf_param_match_suffix(btf, arg, "__uninit");
12005 }
12006 
12007 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
12008 {
12009 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
12010 }
12011 
12012 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
12013 {
12014 	return btf_param_match_suffix(btf, arg, "__nullable");
12015 }
12016 
12017 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
12018 {
12019 	return btf_param_match_suffix(btf, arg, "__str");
12020 }
12021 
12022 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
12023 {
12024 	return btf_param_match_suffix(btf, arg, "__irq_flag");
12025 }
12026 
12027 static bool is_kfunc_arg_prog(const struct btf *btf, const struct btf_param *arg)
12028 {
12029 	return btf_param_match_suffix(btf, arg, "__prog");
12030 }
12031 
12032 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
12033 					  const struct btf_param *arg,
12034 					  const char *name)
12035 {
12036 	int len, target_len = strlen(name);
12037 	const char *param_name;
12038 
12039 	param_name = btf_name_by_offset(btf, arg->name_off);
12040 	if (str_is_empty(param_name))
12041 		return false;
12042 	len = strlen(param_name);
12043 	if (len != target_len)
12044 		return false;
12045 	if (strcmp(param_name, name))
12046 		return false;
12047 
12048 	return true;
12049 }
12050 
12051 enum {
12052 	KF_ARG_DYNPTR_ID,
12053 	KF_ARG_LIST_HEAD_ID,
12054 	KF_ARG_LIST_NODE_ID,
12055 	KF_ARG_RB_ROOT_ID,
12056 	KF_ARG_RB_NODE_ID,
12057 	KF_ARG_WORKQUEUE_ID,
12058 	KF_ARG_RES_SPIN_LOCK_ID,
12059 	KF_ARG_TASK_WORK_ID,
12060 };
12061 
12062 BTF_ID_LIST(kf_arg_btf_ids)
12063 BTF_ID(struct, bpf_dynptr)
12064 BTF_ID(struct, bpf_list_head)
12065 BTF_ID(struct, bpf_list_node)
12066 BTF_ID(struct, bpf_rb_root)
12067 BTF_ID(struct, bpf_rb_node)
12068 BTF_ID(struct, bpf_wq)
12069 BTF_ID(struct, bpf_res_spin_lock)
12070 BTF_ID(struct, bpf_task_work)
12071 
12072 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
12073 				    const struct btf_param *arg, int type)
12074 {
12075 	const struct btf_type *t;
12076 	u32 res_id;
12077 
12078 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12079 	if (!t)
12080 		return false;
12081 	if (!btf_type_is_ptr(t))
12082 		return false;
12083 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
12084 	if (!t)
12085 		return false;
12086 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
12087 }
12088 
12089 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
12090 {
12091 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
12092 }
12093 
12094 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
12095 {
12096 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
12097 }
12098 
12099 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
12100 {
12101 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
12102 }
12103 
12104 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
12105 {
12106 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
12107 }
12108 
12109 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
12110 {
12111 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
12112 }
12113 
12114 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
12115 {
12116 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
12117 }
12118 
12119 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg)
12120 {
12121 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID);
12122 }
12123 
12124 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg)
12125 {
12126 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID);
12127 }
12128 
12129 static bool is_rbtree_node_type(const struct btf_type *t)
12130 {
12131 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]);
12132 }
12133 
12134 static bool is_list_node_type(const struct btf_type *t)
12135 {
12136 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]);
12137 }
12138 
12139 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
12140 				  const struct btf_param *arg)
12141 {
12142 	const struct btf_type *t;
12143 
12144 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
12145 	if (!t)
12146 		return false;
12147 
12148 	return true;
12149 }
12150 
12151 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
12152 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
12153 					const struct btf *btf,
12154 					const struct btf_type *t, int rec)
12155 {
12156 	const struct btf_type *member_type;
12157 	const struct btf_member *member;
12158 	u32 i;
12159 
12160 	if (!btf_type_is_struct(t))
12161 		return false;
12162 
12163 	for_each_member(i, t, member) {
12164 		const struct btf_array *array;
12165 
12166 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
12167 		if (btf_type_is_struct(member_type)) {
12168 			if (rec >= 3) {
12169 				verbose(env, "max struct nesting depth exceeded\n");
12170 				return false;
12171 			}
12172 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
12173 				return false;
12174 			continue;
12175 		}
12176 		if (btf_type_is_array(member_type)) {
12177 			array = btf_array(member_type);
12178 			if (!array->nelems)
12179 				return false;
12180 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
12181 			if (!btf_type_is_scalar(member_type))
12182 				return false;
12183 			continue;
12184 		}
12185 		if (!btf_type_is_scalar(member_type))
12186 			return false;
12187 	}
12188 	return true;
12189 }
12190 
12191 enum kfunc_ptr_arg_type {
12192 	KF_ARG_PTR_TO_CTX,
12193 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
12194 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
12195 	KF_ARG_PTR_TO_DYNPTR,
12196 	KF_ARG_PTR_TO_ITER,
12197 	KF_ARG_PTR_TO_LIST_HEAD,
12198 	KF_ARG_PTR_TO_LIST_NODE,
12199 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
12200 	KF_ARG_PTR_TO_MEM,
12201 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
12202 	KF_ARG_PTR_TO_CALLBACK,
12203 	KF_ARG_PTR_TO_RB_ROOT,
12204 	KF_ARG_PTR_TO_RB_NODE,
12205 	KF_ARG_PTR_TO_NULL,
12206 	KF_ARG_PTR_TO_CONST_STR,
12207 	KF_ARG_PTR_TO_MAP,
12208 	KF_ARG_PTR_TO_WORKQUEUE,
12209 	KF_ARG_PTR_TO_IRQ_FLAG,
12210 	KF_ARG_PTR_TO_RES_SPIN_LOCK,
12211 	KF_ARG_PTR_TO_TASK_WORK,
12212 };
12213 
12214 enum special_kfunc_type {
12215 	KF_bpf_obj_new_impl,
12216 	KF_bpf_obj_drop_impl,
12217 	KF_bpf_refcount_acquire_impl,
12218 	KF_bpf_list_push_front_impl,
12219 	KF_bpf_list_push_back_impl,
12220 	KF_bpf_list_pop_front,
12221 	KF_bpf_list_pop_back,
12222 	KF_bpf_list_front,
12223 	KF_bpf_list_back,
12224 	KF_bpf_cast_to_kern_ctx,
12225 	KF_bpf_rdonly_cast,
12226 	KF_bpf_rcu_read_lock,
12227 	KF_bpf_rcu_read_unlock,
12228 	KF_bpf_rbtree_remove,
12229 	KF_bpf_rbtree_add_impl,
12230 	KF_bpf_rbtree_first,
12231 	KF_bpf_rbtree_root,
12232 	KF_bpf_rbtree_left,
12233 	KF_bpf_rbtree_right,
12234 	KF_bpf_dynptr_from_skb,
12235 	KF_bpf_dynptr_from_xdp,
12236 	KF_bpf_dynptr_from_skb_meta,
12237 	KF_bpf_xdp_pull_data,
12238 	KF_bpf_dynptr_slice,
12239 	KF_bpf_dynptr_slice_rdwr,
12240 	KF_bpf_dynptr_clone,
12241 	KF_bpf_percpu_obj_new_impl,
12242 	KF_bpf_percpu_obj_drop_impl,
12243 	KF_bpf_throw,
12244 	KF_bpf_wq_set_callback_impl,
12245 	KF_bpf_preempt_disable,
12246 	KF_bpf_preempt_enable,
12247 	KF_bpf_iter_css_task_new,
12248 	KF_bpf_session_cookie,
12249 	KF_bpf_get_kmem_cache,
12250 	KF_bpf_local_irq_save,
12251 	KF_bpf_local_irq_restore,
12252 	KF_bpf_iter_num_new,
12253 	KF_bpf_iter_num_next,
12254 	KF_bpf_iter_num_destroy,
12255 	KF_bpf_set_dentry_xattr,
12256 	KF_bpf_remove_dentry_xattr,
12257 	KF_bpf_res_spin_lock,
12258 	KF_bpf_res_spin_unlock,
12259 	KF_bpf_res_spin_lock_irqsave,
12260 	KF_bpf_res_spin_unlock_irqrestore,
12261 	KF___bpf_trap,
12262 	KF_bpf_task_work_schedule_signal,
12263 	KF_bpf_task_work_schedule_resume,
12264 };
12265 
12266 BTF_ID_LIST(special_kfunc_list)
12267 BTF_ID(func, bpf_obj_new_impl)
12268 BTF_ID(func, bpf_obj_drop_impl)
12269 BTF_ID(func, bpf_refcount_acquire_impl)
12270 BTF_ID(func, bpf_list_push_front_impl)
12271 BTF_ID(func, bpf_list_push_back_impl)
12272 BTF_ID(func, bpf_list_pop_front)
12273 BTF_ID(func, bpf_list_pop_back)
12274 BTF_ID(func, bpf_list_front)
12275 BTF_ID(func, bpf_list_back)
12276 BTF_ID(func, bpf_cast_to_kern_ctx)
12277 BTF_ID(func, bpf_rdonly_cast)
12278 BTF_ID(func, bpf_rcu_read_lock)
12279 BTF_ID(func, bpf_rcu_read_unlock)
12280 BTF_ID(func, bpf_rbtree_remove)
12281 BTF_ID(func, bpf_rbtree_add_impl)
12282 BTF_ID(func, bpf_rbtree_first)
12283 BTF_ID(func, bpf_rbtree_root)
12284 BTF_ID(func, bpf_rbtree_left)
12285 BTF_ID(func, bpf_rbtree_right)
12286 #ifdef CONFIG_NET
12287 BTF_ID(func, bpf_dynptr_from_skb)
12288 BTF_ID(func, bpf_dynptr_from_xdp)
12289 BTF_ID(func, bpf_dynptr_from_skb_meta)
12290 BTF_ID(func, bpf_xdp_pull_data)
12291 #else
12292 BTF_ID_UNUSED
12293 BTF_ID_UNUSED
12294 BTF_ID_UNUSED
12295 BTF_ID_UNUSED
12296 #endif
12297 BTF_ID(func, bpf_dynptr_slice)
12298 BTF_ID(func, bpf_dynptr_slice_rdwr)
12299 BTF_ID(func, bpf_dynptr_clone)
12300 BTF_ID(func, bpf_percpu_obj_new_impl)
12301 BTF_ID(func, bpf_percpu_obj_drop_impl)
12302 BTF_ID(func, bpf_throw)
12303 BTF_ID(func, bpf_wq_set_callback_impl)
12304 BTF_ID(func, bpf_preempt_disable)
12305 BTF_ID(func, bpf_preempt_enable)
12306 #ifdef CONFIG_CGROUPS
12307 BTF_ID(func, bpf_iter_css_task_new)
12308 #else
12309 BTF_ID_UNUSED
12310 #endif
12311 #ifdef CONFIG_BPF_EVENTS
12312 BTF_ID(func, bpf_session_cookie)
12313 #else
12314 BTF_ID_UNUSED
12315 #endif
12316 BTF_ID(func, bpf_get_kmem_cache)
12317 BTF_ID(func, bpf_local_irq_save)
12318 BTF_ID(func, bpf_local_irq_restore)
12319 BTF_ID(func, bpf_iter_num_new)
12320 BTF_ID(func, bpf_iter_num_next)
12321 BTF_ID(func, bpf_iter_num_destroy)
12322 #ifdef CONFIG_BPF_LSM
12323 BTF_ID(func, bpf_set_dentry_xattr)
12324 BTF_ID(func, bpf_remove_dentry_xattr)
12325 #else
12326 BTF_ID_UNUSED
12327 BTF_ID_UNUSED
12328 #endif
12329 BTF_ID(func, bpf_res_spin_lock)
12330 BTF_ID(func, bpf_res_spin_unlock)
12331 BTF_ID(func, bpf_res_spin_lock_irqsave)
12332 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
12333 BTF_ID(func, __bpf_trap)
12334 BTF_ID(func, bpf_task_work_schedule_signal)
12335 BTF_ID(func, bpf_task_work_schedule_resume)
12336 
12337 static bool is_task_work_add_kfunc(u32 func_id)
12338 {
12339 	return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal] ||
12340 	       func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume];
12341 }
12342 
12343 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
12344 {
12345 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
12346 	    meta->arg_owning_ref) {
12347 		return false;
12348 	}
12349 
12350 	return meta->kfunc_flags & KF_RET_NULL;
12351 }
12352 
12353 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
12354 {
12355 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
12356 }
12357 
12358 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
12359 {
12360 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
12361 }
12362 
12363 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
12364 {
12365 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
12366 }
12367 
12368 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
12369 {
12370 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
12371 }
12372 
12373 static bool is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta *meta)
12374 {
12375 	return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data];
12376 }
12377 
12378 static enum kfunc_ptr_arg_type
12379 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
12380 		       struct bpf_kfunc_call_arg_meta *meta,
12381 		       const struct btf_type *t, const struct btf_type *ref_t,
12382 		       const char *ref_tname, const struct btf_param *args,
12383 		       int argno, int nargs)
12384 {
12385 	u32 regno = argno + 1;
12386 	struct bpf_reg_state *regs = cur_regs(env);
12387 	struct bpf_reg_state *reg = &regs[regno];
12388 	bool arg_mem_size = false;
12389 
12390 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
12391 		return KF_ARG_PTR_TO_CTX;
12392 
12393 	/* In this function, we verify the kfunc's BTF as per the argument type,
12394 	 * leaving the rest of the verification with respect to the register
12395 	 * type to our caller. When a set of conditions hold in the BTF type of
12396 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
12397 	 */
12398 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
12399 		return KF_ARG_PTR_TO_CTX;
12400 
12401 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
12402 		return KF_ARG_PTR_TO_NULL;
12403 
12404 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
12405 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
12406 
12407 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
12408 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
12409 
12410 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
12411 		return KF_ARG_PTR_TO_DYNPTR;
12412 
12413 	if (is_kfunc_arg_iter(meta, argno, &args[argno]))
12414 		return KF_ARG_PTR_TO_ITER;
12415 
12416 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
12417 		return KF_ARG_PTR_TO_LIST_HEAD;
12418 
12419 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
12420 		return KF_ARG_PTR_TO_LIST_NODE;
12421 
12422 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
12423 		return KF_ARG_PTR_TO_RB_ROOT;
12424 
12425 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
12426 		return KF_ARG_PTR_TO_RB_NODE;
12427 
12428 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
12429 		return KF_ARG_PTR_TO_CONST_STR;
12430 
12431 	if (is_kfunc_arg_map(meta->btf, &args[argno]))
12432 		return KF_ARG_PTR_TO_MAP;
12433 
12434 	if (is_kfunc_arg_wq(meta->btf, &args[argno]))
12435 		return KF_ARG_PTR_TO_WORKQUEUE;
12436 
12437 	if (is_kfunc_arg_task_work(meta->btf, &args[argno]))
12438 		return KF_ARG_PTR_TO_TASK_WORK;
12439 
12440 	if (is_kfunc_arg_irq_flag(meta->btf, &args[argno]))
12441 		return KF_ARG_PTR_TO_IRQ_FLAG;
12442 
12443 	if (is_kfunc_arg_res_spin_lock(meta->btf, &args[argno]))
12444 		return KF_ARG_PTR_TO_RES_SPIN_LOCK;
12445 
12446 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
12447 		if (!btf_type_is_struct(ref_t)) {
12448 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
12449 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
12450 			return -EINVAL;
12451 		}
12452 		return KF_ARG_PTR_TO_BTF_ID;
12453 	}
12454 
12455 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
12456 		return KF_ARG_PTR_TO_CALLBACK;
12457 
12458 	if (argno + 1 < nargs &&
12459 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
12460 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
12461 		arg_mem_size = true;
12462 
12463 	/* This is the catch all argument type of register types supported by
12464 	 * check_helper_mem_access. However, we only allow when argument type is
12465 	 * pointer to scalar, or struct composed (recursively) of scalars. When
12466 	 * arg_mem_size is true, the pointer can be void *.
12467 	 */
12468 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
12469 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
12470 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
12471 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
12472 		return -EINVAL;
12473 	}
12474 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
12475 }
12476 
12477 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
12478 					struct bpf_reg_state *reg,
12479 					const struct btf_type *ref_t,
12480 					const char *ref_tname, u32 ref_id,
12481 					struct bpf_kfunc_call_arg_meta *meta,
12482 					int argno)
12483 {
12484 	const struct btf_type *reg_ref_t;
12485 	bool strict_type_match = false;
12486 	const struct btf *reg_btf;
12487 	const char *reg_ref_tname;
12488 	bool taking_projection;
12489 	bool struct_same;
12490 	u32 reg_ref_id;
12491 
12492 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
12493 		reg_btf = reg->btf;
12494 		reg_ref_id = reg->btf_id;
12495 	} else {
12496 		reg_btf = btf_vmlinux;
12497 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
12498 	}
12499 
12500 	/* Enforce strict type matching for calls to kfuncs that are acquiring
12501 	 * or releasing a reference, or are no-cast aliases. We do _not_
12502 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
12503 	 * as we want to enable BPF programs to pass types that are bitwise
12504 	 * equivalent without forcing them to explicitly cast with something
12505 	 * like bpf_cast_to_kern_ctx().
12506 	 *
12507 	 * For example, say we had a type like the following:
12508 	 *
12509 	 * struct bpf_cpumask {
12510 	 *	cpumask_t cpumask;
12511 	 *	refcount_t usage;
12512 	 * };
12513 	 *
12514 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
12515 	 * to a struct cpumask, so it would be safe to pass a struct
12516 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
12517 	 *
12518 	 * The philosophy here is similar to how we allow scalars of different
12519 	 * types to be passed to kfuncs as long as the size is the same. The
12520 	 * only difference here is that we're simply allowing
12521 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
12522 	 * resolve types.
12523 	 */
12524 	if ((is_kfunc_release(meta) && reg->ref_obj_id) ||
12525 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
12526 		strict_type_match = true;
12527 
12528 	WARN_ON_ONCE(is_kfunc_release(meta) &&
12529 		     (reg->off || !tnum_is_const(reg->var_off) ||
12530 		      reg->var_off.value));
12531 
12532 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
12533 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
12534 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
12535 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
12536 	 * actually use it -- it must cast to the underlying type. So we allow
12537 	 * caller to pass in the underlying type.
12538 	 */
12539 	taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
12540 	if (!taking_projection && !struct_same) {
12541 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
12542 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
12543 			btf_type_str(reg_ref_t), reg_ref_tname);
12544 		return -EINVAL;
12545 	}
12546 	return 0;
12547 }
12548 
12549 static int process_irq_flag(struct bpf_verifier_env *env, int regno,
12550 			     struct bpf_kfunc_call_arg_meta *meta)
12551 {
12552 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
12553 	int err, kfunc_class = IRQ_NATIVE_KFUNC;
12554 	bool irq_save;
12555 
12556 	if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] ||
12557 	    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) {
12558 		irq_save = true;
12559 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
12560 			kfunc_class = IRQ_LOCK_KFUNC;
12561 	} else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] ||
12562 		   meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) {
12563 		irq_save = false;
12564 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
12565 			kfunc_class = IRQ_LOCK_KFUNC;
12566 	} else {
12567 		verifier_bug(env, "unknown irq flags kfunc");
12568 		return -EFAULT;
12569 	}
12570 
12571 	if (irq_save) {
12572 		if (!is_irq_flag_reg_valid_uninit(env, reg)) {
12573 			verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1);
12574 			return -EINVAL;
12575 		}
12576 
12577 		err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false);
12578 		if (err)
12579 			return err;
12580 
12581 		err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class);
12582 		if (err)
12583 			return err;
12584 	} else {
12585 		err = is_irq_flag_reg_valid_init(env, reg);
12586 		if (err) {
12587 			verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1);
12588 			return err;
12589 		}
12590 
12591 		err = mark_irq_flag_read(env, reg);
12592 		if (err)
12593 			return err;
12594 
12595 		err = unmark_stack_slot_irq_flag(env, reg, kfunc_class);
12596 		if (err)
12597 			return err;
12598 	}
12599 	return 0;
12600 }
12601 
12602 
12603 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12604 {
12605 	struct btf_record *rec = reg_btf_record(reg);
12606 
12607 	if (!env->cur_state->active_locks) {
12608 		verifier_bug(env, "%s w/o active lock", __func__);
12609 		return -EFAULT;
12610 	}
12611 
12612 	if (type_flag(reg->type) & NON_OWN_REF) {
12613 		verifier_bug(env, "NON_OWN_REF already set");
12614 		return -EFAULT;
12615 	}
12616 
12617 	reg->type |= NON_OWN_REF;
12618 	if (rec->refcount_off >= 0)
12619 		reg->type |= MEM_RCU;
12620 
12621 	return 0;
12622 }
12623 
12624 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
12625 {
12626 	struct bpf_verifier_state *state = env->cur_state;
12627 	struct bpf_func_state *unused;
12628 	struct bpf_reg_state *reg;
12629 	int i;
12630 
12631 	if (!ref_obj_id) {
12632 		verifier_bug(env, "ref_obj_id is zero for owning -> non-owning conversion");
12633 		return -EFAULT;
12634 	}
12635 
12636 	for (i = 0; i < state->acquired_refs; i++) {
12637 		if (state->refs[i].id != ref_obj_id)
12638 			continue;
12639 
12640 		/* Clear ref_obj_id here so release_reference doesn't clobber
12641 		 * the whole reg
12642 		 */
12643 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
12644 			if (reg->ref_obj_id == ref_obj_id) {
12645 				reg->ref_obj_id = 0;
12646 				ref_set_non_owning(env, reg);
12647 			}
12648 		}));
12649 		return 0;
12650 	}
12651 
12652 	verifier_bug(env, "ref state missing for ref_obj_id");
12653 	return -EFAULT;
12654 }
12655 
12656 /* Implementation details:
12657  *
12658  * Each register points to some region of memory, which we define as an
12659  * allocation. Each allocation may embed a bpf_spin_lock which protects any
12660  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
12661  * allocation. The lock and the data it protects are colocated in the same
12662  * memory region.
12663  *
12664  * Hence, everytime a register holds a pointer value pointing to such
12665  * allocation, the verifier preserves a unique reg->id for it.
12666  *
12667  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
12668  * bpf_spin_lock is called.
12669  *
12670  * To enable this, lock state in the verifier captures two values:
12671  *	active_lock.ptr = Register's type specific pointer
12672  *	active_lock.id  = A unique ID for each register pointer value
12673  *
12674  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
12675  * supported register types.
12676  *
12677  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
12678  * allocated objects is the reg->btf pointer.
12679  *
12680  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
12681  * can establish the provenance of the map value statically for each distinct
12682  * lookup into such maps. They always contain a single map value hence unique
12683  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
12684  *
12685  * So, in case of global variables, they use array maps with max_entries = 1,
12686  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
12687  * into the same map value as max_entries is 1, as described above).
12688  *
12689  * In case of inner map lookups, the inner map pointer has same map_ptr as the
12690  * outer map pointer (in verifier context), but each lookup into an inner map
12691  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
12692  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
12693  * will get different reg->id assigned to each lookup, hence different
12694  * active_lock.id.
12695  *
12696  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
12697  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
12698  * returned from bpf_obj_new. Each allocation receives a new reg->id.
12699  */
12700 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12701 {
12702 	struct bpf_reference_state *s;
12703 	void *ptr;
12704 	u32 id;
12705 
12706 	switch ((int)reg->type) {
12707 	case PTR_TO_MAP_VALUE:
12708 		ptr = reg->map_ptr;
12709 		break;
12710 	case PTR_TO_BTF_ID | MEM_ALLOC:
12711 		ptr = reg->btf;
12712 		break;
12713 	default:
12714 		verifier_bug(env, "unknown reg type for lock check");
12715 		return -EFAULT;
12716 	}
12717 	id = reg->id;
12718 
12719 	if (!env->cur_state->active_locks)
12720 		return -EINVAL;
12721 	s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr);
12722 	if (!s) {
12723 		verbose(env, "held lock and object are not in the same allocation\n");
12724 		return -EINVAL;
12725 	}
12726 	return 0;
12727 }
12728 
12729 static bool is_bpf_list_api_kfunc(u32 btf_id)
12730 {
12731 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12732 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12733 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12734 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back] ||
12735 	       btf_id == special_kfunc_list[KF_bpf_list_front] ||
12736 	       btf_id == special_kfunc_list[KF_bpf_list_back];
12737 }
12738 
12739 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
12740 {
12741 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12742 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12743 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first] ||
12744 	       btf_id == special_kfunc_list[KF_bpf_rbtree_root] ||
12745 	       btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12746 	       btf_id == special_kfunc_list[KF_bpf_rbtree_right];
12747 }
12748 
12749 static bool is_bpf_iter_num_api_kfunc(u32 btf_id)
12750 {
12751 	return btf_id == special_kfunc_list[KF_bpf_iter_num_new] ||
12752 	       btf_id == special_kfunc_list[KF_bpf_iter_num_next] ||
12753 	       btf_id == special_kfunc_list[KF_bpf_iter_num_destroy];
12754 }
12755 
12756 static bool is_bpf_graph_api_kfunc(u32 btf_id)
12757 {
12758 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
12759 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
12760 }
12761 
12762 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id)
12763 {
12764 	return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
12765 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
12766 	       btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
12767 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore];
12768 }
12769 
12770 static bool kfunc_spin_allowed(u32 btf_id)
12771 {
12772 	return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) ||
12773 	       is_bpf_res_spin_lock_kfunc(btf_id);
12774 }
12775 
12776 static bool is_sync_callback_calling_kfunc(u32 btf_id)
12777 {
12778 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
12779 }
12780 
12781 static bool is_async_callback_calling_kfunc(u32 btf_id)
12782 {
12783 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl] ||
12784 	       is_task_work_add_kfunc(btf_id);
12785 }
12786 
12787 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
12788 {
12789 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
12790 	       insn->imm == special_kfunc_list[KF_bpf_throw];
12791 }
12792 
12793 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
12794 {
12795 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
12796 }
12797 
12798 static bool is_callback_calling_kfunc(u32 btf_id)
12799 {
12800 	return is_sync_callback_calling_kfunc(btf_id) ||
12801 	       is_async_callback_calling_kfunc(btf_id);
12802 }
12803 
12804 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
12805 {
12806 	return is_bpf_rbtree_api_kfunc(btf_id);
12807 }
12808 
12809 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
12810 					  enum btf_field_type head_field_type,
12811 					  u32 kfunc_btf_id)
12812 {
12813 	bool ret;
12814 
12815 	switch (head_field_type) {
12816 	case BPF_LIST_HEAD:
12817 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
12818 		break;
12819 	case BPF_RB_ROOT:
12820 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
12821 		break;
12822 	default:
12823 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
12824 			btf_field_type_name(head_field_type));
12825 		return false;
12826 	}
12827 
12828 	if (!ret)
12829 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
12830 			btf_field_type_name(head_field_type));
12831 	return ret;
12832 }
12833 
12834 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
12835 					  enum btf_field_type node_field_type,
12836 					  u32 kfunc_btf_id)
12837 {
12838 	bool ret;
12839 
12840 	switch (node_field_type) {
12841 	case BPF_LIST_NODE:
12842 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12843 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
12844 		break;
12845 	case BPF_RB_NODE:
12846 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12847 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12848 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12849 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
12850 		break;
12851 	default:
12852 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
12853 			btf_field_type_name(node_field_type));
12854 		return false;
12855 	}
12856 
12857 	if (!ret)
12858 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
12859 			btf_field_type_name(node_field_type));
12860 	return ret;
12861 }
12862 
12863 static int
12864 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
12865 				   struct bpf_reg_state *reg, u32 regno,
12866 				   struct bpf_kfunc_call_arg_meta *meta,
12867 				   enum btf_field_type head_field_type,
12868 				   struct btf_field **head_field)
12869 {
12870 	const char *head_type_name;
12871 	struct btf_field *field;
12872 	struct btf_record *rec;
12873 	u32 head_off;
12874 
12875 	if (meta->btf != btf_vmlinux) {
12876 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
12877 		return -EFAULT;
12878 	}
12879 
12880 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
12881 		return -EFAULT;
12882 
12883 	head_type_name = btf_field_type_name(head_field_type);
12884 	if (!tnum_is_const(reg->var_off)) {
12885 		verbose(env,
12886 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
12887 			regno, head_type_name);
12888 		return -EINVAL;
12889 	}
12890 
12891 	rec = reg_btf_record(reg);
12892 	head_off = reg->off + reg->var_off.value;
12893 	field = btf_record_find(rec, head_off, head_field_type);
12894 	if (!field) {
12895 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
12896 		return -EINVAL;
12897 	}
12898 
12899 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
12900 	if (check_reg_allocation_locked(env, reg)) {
12901 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
12902 			rec->spin_lock_off, head_type_name);
12903 		return -EINVAL;
12904 	}
12905 
12906 	if (*head_field) {
12907 		verifier_bug(env, "repeating %s arg", head_type_name);
12908 		return -EFAULT;
12909 	}
12910 	*head_field = field;
12911 	return 0;
12912 }
12913 
12914 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
12915 					   struct bpf_reg_state *reg, u32 regno,
12916 					   struct bpf_kfunc_call_arg_meta *meta)
12917 {
12918 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
12919 							  &meta->arg_list_head.field);
12920 }
12921 
12922 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
12923 					     struct bpf_reg_state *reg, u32 regno,
12924 					     struct bpf_kfunc_call_arg_meta *meta)
12925 {
12926 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
12927 							  &meta->arg_rbtree_root.field);
12928 }
12929 
12930 static int
12931 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
12932 				   struct bpf_reg_state *reg, u32 regno,
12933 				   struct bpf_kfunc_call_arg_meta *meta,
12934 				   enum btf_field_type head_field_type,
12935 				   enum btf_field_type node_field_type,
12936 				   struct btf_field **node_field)
12937 {
12938 	const char *node_type_name;
12939 	const struct btf_type *et, *t;
12940 	struct btf_field *field;
12941 	u32 node_off;
12942 
12943 	if (meta->btf != btf_vmlinux) {
12944 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
12945 		return -EFAULT;
12946 	}
12947 
12948 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
12949 		return -EFAULT;
12950 
12951 	node_type_name = btf_field_type_name(node_field_type);
12952 	if (!tnum_is_const(reg->var_off)) {
12953 		verbose(env,
12954 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
12955 			regno, node_type_name);
12956 		return -EINVAL;
12957 	}
12958 
12959 	node_off = reg->off + reg->var_off.value;
12960 	field = reg_find_field_offset(reg, node_off, node_field_type);
12961 	if (!field) {
12962 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
12963 		return -EINVAL;
12964 	}
12965 
12966 	field = *node_field;
12967 
12968 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
12969 	t = btf_type_by_id(reg->btf, reg->btf_id);
12970 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
12971 				  field->graph_root.value_btf_id, true)) {
12972 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
12973 			"in struct %s, but arg is at offset=%d in struct %s\n",
12974 			btf_field_type_name(head_field_type),
12975 			btf_field_type_name(node_field_type),
12976 			field->graph_root.node_offset,
12977 			btf_name_by_offset(field->graph_root.btf, et->name_off),
12978 			node_off, btf_name_by_offset(reg->btf, t->name_off));
12979 		return -EINVAL;
12980 	}
12981 	meta->arg_btf = reg->btf;
12982 	meta->arg_btf_id = reg->btf_id;
12983 
12984 	if (node_off != field->graph_root.node_offset) {
12985 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
12986 			node_off, btf_field_type_name(node_field_type),
12987 			field->graph_root.node_offset,
12988 			btf_name_by_offset(field->graph_root.btf, et->name_off));
12989 		return -EINVAL;
12990 	}
12991 
12992 	return 0;
12993 }
12994 
12995 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
12996 					   struct bpf_reg_state *reg, u32 regno,
12997 					   struct bpf_kfunc_call_arg_meta *meta)
12998 {
12999 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
13000 						  BPF_LIST_HEAD, BPF_LIST_NODE,
13001 						  &meta->arg_list_head.field);
13002 }
13003 
13004 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
13005 					     struct bpf_reg_state *reg, u32 regno,
13006 					     struct bpf_kfunc_call_arg_meta *meta)
13007 {
13008 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
13009 						  BPF_RB_ROOT, BPF_RB_NODE,
13010 						  &meta->arg_rbtree_root.field);
13011 }
13012 
13013 /*
13014  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
13015  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
13016  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
13017  * them can only be attached to some specific hook points.
13018  */
13019 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
13020 {
13021 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
13022 
13023 	switch (prog_type) {
13024 	case BPF_PROG_TYPE_LSM:
13025 		return true;
13026 	case BPF_PROG_TYPE_TRACING:
13027 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
13028 			return true;
13029 		fallthrough;
13030 	default:
13031 		return in_sleepable(env);
13032 	}
13033 }
13034 
13035 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13036 			    int insn_idx)
13037 {
13038 	const char *func_name = meta->func_name, *ref_tname;
13039 	const struct btf *btf = meta->btf;
13040 	const struct btf_param *args;
13041 	struct btf_record *rec;
13042 	u32 i, nargs;
13043 	int ret;
13044 
13045 	args = (const struct btf_param *)(meta->func_proto + 1);
13046 	nargs = btf_type_vlen(meta->func_proto);
13047 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
13048 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
13049 			MAX_BPF_FUNC_REG_ARGS);
13050 		return -EINVAL;
13051 	}
13052 
13053 	/* Check that BTF function arguments match actual types that the
13054 	 * verifier sees.
13055 	 */
13056 	for (i = 0; i < nargs; i++) {
13057 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
13058 		const struct btf_type *t, *ref_t, *resolve_ret;
13059 		enum bpf_arg_type arg_type = ARG_DONTCARE;
13060 		u32 regno = i + 1, ref_id, type_size;
13061 		bool is_ret_buf_sz = false;
13062 		int kf_arg_type;
13063 
13064 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
13065 
13066 		if (is_kfunc_arg_ignore(btf, &args[i]))
13067 			continue;
13068 
13069 		if (is_kfunc_arg_prog(btf, &args[i])) {
13070 			/* Used to reject repeated use of __prog. */
13071 			if (meta->arg_prog) {
13072 				verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc");
13073 				return -EFAULT;
13074 			}
13075 			meta->arg_prog = true;
13076 			cur_aux(env)->arg_prog = regno;
13077 			continue;
13078 		}
13079 
13080 		if (btf_type_is_scalar(t)) {
13081 			if (reg->type != SCALAR_VALUE) {
13082 				verbose(env, "R%d is not a scalar\n", regno);
13083 				return -EINVAL;
13084 			}
13085 
13086 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
13087 				if (meta->arg_constant.found) {
13088 					verifier_bug(env, "only one constant argument permitted");
13089 					return -EFAULT;
13090 				}
13091 				if (!tnum_is_const(reg->var_off)) {
13092 					verbose(env, "R%d must be a known constant\n", regno);
13093 					return -EINVAL;
13094 				}
13095 				ret = mark_chain_precision(env, regno);
13096 				if (ret < 0)
13097 					return ret;
13098 				meta->arg_constant.found = true;
13099 				meta->arg_constant.value = reg->var_off.value;
13100 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
13101 				meta->r0_rdonly = true;
13102 				is_ret_buf_sz = true;
13103 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
13104 				is_ret_buf_sz = true;
13105 			}
13106 
13107 			if (is_ret_buf_sz) {
13108 				if (meta->r0_size) {
13109 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
13110 					return -EINVAL;
13111 				}
13112 
13113 				if (!tnum_is_const(reg->var_off)) {
13114 					verbose(env, "R%d is not a const\n", regno);
13115 					return -EINVAL;
13116 				}
13117 
13118 				meta->r0_size = reg->var_off.value;
13119 				ret = mark_chain_precision(env, regno);
13120 				if (ret)
13121 					return ret;
13122 			}
13123 			continue;
13124 		}
13125 
13126 		if (!btf_type_is_ptr(t)) {
13127 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
13128 			return -EINVAL;
13129 		}
13130 
13131 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
13132 		    (register_is_null(reg) || type_may_be_null(reg->type)) &&
13133 			!is_kfunc_arg_nullable(meta->btf, &args[i])) {
13134 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
13135 			return -EACCES;
13136 		}
13137 
13138 		if (reg->ref_obj_id) {
13139 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
13140 				verifier_bug(env, "more than one arg with ref_obj_id R%d %u %u",
13141 					     regno, reg->ref_obj_id,
13142 					     meta->ref_obj_id);
13143 				return -EFAULT;
13144 			}
13145 			meta->ref_obj_id = reg->ref_obj_id;
13146 			if (is_kfunc_release(meta))
13147 				meta->release_regno = regno;
13148 		}
13149 
13150 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
13151 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13152 
13153 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
13154 		if (kf_arg_type < 0)
13155 			return kf_arg_type;
13156 
13157 		switch (kf_arg_type) {
13158 		case KF_ARG_PTR_TO_NULL:
13159 			continue;
13160 		case KF_ARG_PTR_TO_MAP:
13161 			if (!reg->map_ptr) {
13162 				verbose(env, "pointer in R%d isn't map pointer\n", regno);
13163 				return -EINVAL;
13164 			}
13165 			if (meta->map.ptr && (reg->map_ptr->record->wq_off >= 0 ||
13166 					      reg->map_ptr->record->task_work_off >= 0)) {
13167 				/* Use map_uid (which is unique id of inner map) to reject:
13168 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
13169 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
13170 				 * if (inner_map1 && inner_map2) {
13171 				 *     wq = bpf_map_lookup_elem(inner_map1);
13172 				 *     if (wq)
13173 				 *         // mismatch would have been allowed
13174 				 *         bpf_wq_init(wq, inner_map2);
13175 				 * }
13176 				 *
13177 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
13178 				 */
13179 				if (meta->map.ptr != reg->map_ptr ||
13180 				    meta->map.uid != reg->map_uid) {
13181 					if (reg->map_ptr->record->task_work_off >= 0) {
13182 						verbose(env,
13183 							"bpf_task_work pointer in R2 map_uid=%d doesn't match map pointer in R3 map_uid=%d\n",
13184 							meta->map.uid, reg->map_uid);
13185 						return -EINVAL;
13186 					}
13187 					verbose(env,
13188 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
13189 						meta->map.uid, reg->map_uid);
13190 					return -EINVAL;
13191 				}
13192 			}
13193 			meta->map.ptr = reg->map_ptr;
13194 			meta->map.uid = reg->map_uid;
13195 			fallthrough;
13196 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13197 		case KF_ARG_PTR_TO_BTF_ID:
13198 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
13199 				break;
13200 
13201 			if (!is_trusted_reg(reg)) {
13202 				if (!is_kfunc_rcu(meta)) {
13203 					verbose(env, "R%d must be referenced or trusted\n", regno);
13204 					return -EINVAL;
13205 				}
13206 				if (!is_rcu_reg(reg)) {
13207 					verbose(env, "R%d must be a rcu pointer\n", regno);
13208 					return -EINVAL;
13209 				}
13210 			}
13211 			fallthrough;
13212 		case KF_ARG_PTR_TO_CTX:
13213 		case KF_ARG_PTR_TO_DYNPTR:
13214 		case KF_ARG_PTR_TO_ITER:
13215 		case KF_ARG_PTR_TO_LIST_HEAD:
13216 		case KF_ARG_PTR_TO_LIST_NODE:
13217 		case KF_ARG_PTR_TO_RB_ROOT:
13218 		case KF_ARG_PTR_TO_RB_NODE:
13219 		case KF_ARG_PTR_TO_MEM:
13220 		case KF_ARG_PTR_TO_MEM_SIZE:
13221 		case KF_ARG_PTR_TO_CALLBACK:
13222 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13223 		case KF_ARG_PTR_TO_CONST_STR:
13224 		case KF_ARG_PTR_TO_WORKQUEUE:
13225 		case KF_ARG_PTR_TO_TASK_WORK:
13226 		case KF_ARG_PTR_TO_IRQ_FLAG:
13227 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13228 			break;
13229 		default:
13230 			verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type);
13231 			return -EFAULT;
13232 		}
13233 
13234 		if (is_kfunc_release(meta) && reg->ref_obj_id)
13235 			arg_type |= OBJ_RELEASE;
13236 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
13237 		if (ret < 0)
13238 			return ret;
13239 
13240 		switch (kf_arg_type) {
13241 		case KF_ARG_PTR_TO_CTX:
13242 			if (reg->type != PTR_TO_CTX) {
13243 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n",
13244 					i, reg_type_str(env, reg->type));
13245 				return -EINVAL;
13246 			}
13247 
13248 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13249 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
13250 				if (ret < 0)
13251 					return -EINVAL;
13252 				meta->ret_btf_id  = ret;
13253 			}
13254 			break;
13255 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13256 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
13257 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
13258 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
13259 					return -EINVAL;
13260 				}
13261 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
13262 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
13263 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
13264 					return -EINVAL;
13265 				}
13266 			} else {
13267 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13268 				return -EINVAL;
13269 			}
13270 			if (!reg->ref_obj_id) {
13271 				verbose(env, "allocated object must be referenced\n");
13272 				return -EINVAL;
13273 			}
13274 			if (meta->btf == btf_vmlinux) {
13275 				meta->arg_btf = reg->btf;
13276 				meta->arg_btf_id = reg->btf_id;
13277 			}
13278 			break;
13279 		case KF_ARG_PTR_TO_DYNPTR:
13280 		{
13281 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
13282 			int clone_ref_obj_id = 0;
13283 
13284 			if (reg->type == CONST_PTR_TO_DYNPTR)
13285 				dynptr_arg_type |= MEM_RDONLY;
13286 
13287 			if (is_kfunc_arg_uninit(btf, &args[i]))
13288 				dynptr_arg_type |= MEM_UNINIT;
13289 
13290 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
13291 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
13292 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
13293 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
13294 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) {
13295 				dynptr_arg_type |= DYNPTR_TYPE_SKB_META;
13296 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
13297 				   (dynptr_arg_type & MEM_UNINIT)) {
13298 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
13299 
13300 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
13301 					verifier_bug(env, "no dynptr type for parent of clone");
13302 					return -EFAULT;
13303 				}
13304 
13305 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
13306 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
13307 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
13308 					verifier_bug(env, "missing ref obj id for parent of clone");
13309 					return -EFAULT;
13310 				}
13311 			}
13312 
13313 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
13314 			if (ret < 0)
13315 				return ret;
13316 
13317 			if (!(dynptr_arg_type & MEM_UNINIT)) {
13318 				int id = dynptr_id(env, reg);
13319 
13320 				if (id < 0) {
13321 					verifier_bug(env, "failed to obtain dynptr id");
13322 					return id;
13323 				}
13324 				meta->initialized_dynptr.id = id;
13325 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
13326 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
13327 			}
13328 
13329 			break;
13330 		}
13331 		case KF_ARG_PTR_TO_ITER:
13332 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
13333 				if (!check_css_task_iter_allowlist(env)) {
13334 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
13335 					return -EINVAL;
13336 				}
13337 			}
13338 			ret = process_iter_arg(env, regno, insn_idx, meta);
13339 			if (ret < 0)
13340 				return ret;
13341 			break;
13342 		case KF_ARG_PTR_TO_LIST_HEAD:
13343 			if (reg->type != PTR_TO_MAP_VALUE &&
13344 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13345 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13346 				return -EINVAL;
13347 			}
13348 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13349 				verbose(env, "allocated object must be referenced\n");
13350 				return -EINVAL;
13351 			}
13352 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
13353 			if (ret < 0)
13354 				return ret;
13355 			break;
13356 		case KF_ARG_PTR_TO_RB_ROOT:
13357 			if (reg->type != PTR_TO_MAP_VALUE &&
13358 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13359 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13360 				return -EINVAL;
13361 			}
13362 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13363 				verbose(env, "allocated object must be referenced\n");
13364 				return -EINVAL;
13365 			}
13366 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
13367 			if (ret < 0)
13368 				return ret;
13369 			break;
13370 		case KF_ARG_PTR_TO_LIST_NODE:
13371 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13372 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13373 				return -EINVAL;
13374 			}
13375 			if (!reg->ref_obj_id) {
13376 				verbose(env, "allocated object must be referenced\n");
13377 				return -EINVAL;
13378 			}
13379 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
13380 			if (ret < 0)
13381 				return ret;
13382 			break;
13383 		case KF_ARG_PTR_TO_RB_NODE:
13384 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13385 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13386 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
13387 					return -EINVAL;
13388 				}
13389 				if (!reg->ref_obj_id) {
13390 					verbose(env, "allocated object must be referenced\n");
13391 					return -EINVAL;
13392 				}
13393 			} else {
13394 				if (!type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) {
13395 					verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name);
13396 					return -EINVAL;
13397 				}
13398 				if (in_rbtree_lock_required_cb(env)) {
13399 					verbose(env, "%s not allowed in rbtree cb\n", func_name);
13400 					return -EINVAL;
13401 				}
13402 			}
13403 
13404 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
13405 			if (ret < 0)
13406 				return ret;
13407 			break;
13408 		case KF_ARG_PTR_TO_MAP:
13409 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
13410 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
13411 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
13412 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13413 			fallthrough;
13414 		case KF_ARG_PTR_TO_BTF_ID:
13415 			/* Only base_type is checked, further checks are done here */
13416 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
13417 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
13418 			    !reg2btf_ids[base_type(reg->type)]) {
13419 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
13420 				verbose(env, "expected %s or socket\n",
13421 					reg_type_str(env, base_type(reg->type) |
13422 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
13423 				return -EINVAL;
13424 			}
13425 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
13426 			if (ret < 0)
13427 				return ret;
13428 			break;
13429 		case KF_ARG_PTR_TO_MEM:
13430 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
13431 			if (IS_ERR(resolve_ret)) {
13432 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
13433 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
13434 				return -EINVAL;
13435 			}
13436 			ret = check_mem_reg(env, reg, regno, type_size);
13437 			if (ret < 0)
13438 				return ret;
13439 			break;
13440 		case KF_ARG_PTR_TO_MEM_SIZE:
13441 		{
13442 			struct bpf_reg_state *buff_reg = &regs[regno];
13443 			const struct btf_param *buff_arg = &args[i];
13444 			struct bpf_reg_state *size_reg = &regs[regno + 1];
13445 			const struct btf_param *size_arg = &args[i + 1];
13446 
13447 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
13448 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
13449 				if (ret < 0) {
13450 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
13451 					return ret;
13452 				}
13453 			}
13454 
13455 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
13456 				if (meta->arg_constant.found) {
13457 					verifier_bug(env, "only one constant argument permitted");
13458 					return -EFAULT;
13459 				}
13460 				if (!tnum_is_const(size_reg->var_off)) {
13461 					verbose(env, "R%d must be a known constant\n", regno + 1);
13462 					return -EINVAL;
13463 				}
13464 				meta->arg_constant.found = true;
13465 				meta->arg_constant.value = size_reg->var_off.value;
13466 			}
13467 
13468 			/* Skip next '__sz' or '__szk' argument */
13469 			i++;
13470 			break;
13471 		}
13472 		case KF_ARG_PTR_TO_CALLBACK:
13473 			if (reg->type != PTR_TO_FUNC) {
13474 				verbose(env, "arg%d expected pointer to func\n", i);
13475 				return -EINVAL;
13476 			}
13477 			meta->subprogno = reg->subprogno;
13478 			break;
13479 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13480 			if (!type_is_ptr_alloc_obj(reg->type)) {
13481 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
13482 				return -EINVAL;
13483 			}
13484 			if (!type_is_non_owning_ref(reg->type))
13485 				meta->arg_owning_ref = true;
13486 
13487 			rec = reg_btf_record(reg);
13488 			if (!rec) {
13489 				verifier_bug(env, "Couldn't find btf_record");
13490 				return -EFAULT;
13491 			}
13492 
13493 			if (rec->refcount_off < 0) {
13494 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
13495 				return -EINVAL;
13496 			}
13497 
13498 			meta->arg_btf = reg->btf;
13499 			meta->arg_btf_id = reg->btf_id;
13500 			break;
13501 		case KF_ARG_PTR_TO_CONST_STR:
13502 			if (reg->type != PTR_TO_MAP_VALUE) {
13503 				verbose(env, "arg#%d doesn't point to a const string\n", i);
13504 				return -EINVAL;
13505 			}
13506 			ret = check_reg_const_str(env, reg, regno);
13507 			if (ret)
13508 				return ret;
13509 			break;
13510 		case KF_ARG_PTR_TO_WORKQUEUE:
13511 			if (reg->type != PTR_TO_MAP_VALUE) {
13512 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13513 				return -EINVAL;
13514 			}
13515 			ret = process_wq_func(env, regno, meta);
13516 			if (ret < 0)
13517 				return ret;
13518 			break;
13519 		case KF_ARG_PTR_TO_TASK_WORK:
13520 			if (reg->type != PTR_TO_MAP_VALUE) {
13521 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13522 				return -EINVAL;
13523 			}
13524 			ret = process_task_work_func(env, regno, meta);
13525 			if (ret < 0)
13526 				return ret;
13527 			break;
13528 		case KF_ARG_PTR_TO_IRQ_FLAG:
13529 			if (reg->type != PTR_TO_STACK) {
13530 				verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i);
13531 				return -EINVAL;
13532 			}
13533 			ret = process_irq_flag(env, regno, meta);
13534 			if (ret < 0)
13535 				return ret;
13536 			break;
13537 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13538 		{
13539 			int flags = PROCESS_RES_LOCK;
13540 
13541 			if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13542 				verbose(env, "arg#%d doesn't point to map value or allocated object\n", i);
13543 				return -EINVAL;
13544 			}
13545 
13546 			if (!is_bpf_res_spin_lock_kfunc(meta->func_id))
13547 				return -EFAULT;
13548 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13549 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
13550 				flags |= PROCESS_SPIN_LOCK;
13551 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
13552 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
13553 				flags |= PROCESS_LOCK_IRQ;
13554 			ret = process_spin_lock(env, regno, flags);
13555 			if (ret < 0)
13556 				return ret;
13557 			break;
13558 		}
13559 		}
13560 	}
13561 
13562 	if (is_kfunc_release(meta) && !meta->release_regno) {
13563 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
13564 			func_name);
13565 		return -EINVAL;
13566 	}
13567 
13568 	return 0;
13569 }
13570 
13571 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
13572 			    struct bpf_insn *insn,
13573 			    struct bpf_kfunc_call_arg_meta *meta,
13574 			    const char **kfunc_name)
13575 {
13576 	const struct btf_type *func, *func_proto;
13577 	u32 func_id, *kfunc_flags;
13578 	const char *func_name;
13579 	struct btf *desc_btf;
13580 
13581 	if (kfunc_name)
13582 		*kfunc_name = NULL;
13583 
13584 	if (!insn->imm)
13585 		return -EINVAL;
13586 
13587 	desc_btf = find_kfunc_desc_btf(env, insn->off);
13588 	if (IS_ERR(desc_btf))
13589 		return PTR_ERR(desc_btf);
13590 
13591 	func_id = insn->imm;
13592 	func = btf_type_by_id(desc_btf, func_id);
13593 	func_name = btf_name_by_offset(desc_btf, func->name_off);
13594 	if (kfunc_name)
13595 		*kfunc_name = func_name;
13596 	func_proto = btf_type_by_id(desc_btf, func->type);
13597 
13598 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
13599 	if (!kfunc_flags) {
13600 		return -EACCES;
13601 	}
13602 
13603 	memset(meta, 0, sizeof(*meta));
13604 	meta->btf = desc_btf;
13605 	meta->func_id = func_id;
13606 	meta->kfunc_flags = *kfunc_flags;
13607 	meta->func_proto = func_proto;
13608 	meta->func_name = func_name;
13609 
13610 	return 0;
13611 }
13612 
13613 /* check special kfuncs and return:
13614  *  1  - not fall-through to 'else' branch, continue verification
13615  *  0  - fall-through to 'else' branch
13616  * < 0 - not fall-through to 'else' branch, return error
13617  */
13618 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13619 			       struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
13620 			       const struct btf_type *ptr_type, struct btf *desc_btf)
13621 {
13622 	const struct btf_type *ret_t;
13623 	int err = 0;
13624 
13625 	if (meta->btf != btf_vmlinux)
13626 		return 0;
13627 
13628 	if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
13629 	    meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13630 		struct btf_struct_meta *struct_meta;
13631 		struct btf *ret_btf;
13632 		u32 ret_btf_id;
13633 
13634 		if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
13635 			return -ENOMEM;
13636 
13637 		if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) {
13638 			verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
13639 			return -EINVAL;
13640 		}
13641 
13642 		ret_btf = env->prog->aux->btf;
13643 		ret_btf_id = meta->arg_constant.value;
13644 
13645 		/* This may be NULL due to user not supplying a BTF */
13646 		if (!ret_btf) {
13647 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
13648 			return -EINVAL;
13649 		}
13650 
13651 		ret_t = btf_type_by_id(ret_btf, ret_btf_id);
13652 		if (!ret_t || !__btf_type_is_struct(ret_t)) {
13653 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
13654 			return -EINVAL;
13655 		}
13656 
13657 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13658 			if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
13659 				verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
13660 					ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
13661 				return -EINVAL;
13662 			}
13663 
13664 			if (!bpf_global_percpu_ma_set) {
13665 				mutex_lock(&bpf_percpu_ma_lock);
13666 				if (!bpf_global_percpu_ma_set) {
13667 					/* Charge memory allocated with bpf_global_percpu_ma to
13668 					 * root memcg. The obj_cgroup for root memcg is NULL.
13669 					 */
13670 					err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
13671 					if (!err)
13672 						bpf_global_percpu_ma_set = true;
13673 				}
13674 				mutex_unlock(&bpf_percpu_ma_lock);
13675 				if (err)
13676 					return err;
13677 			}
13678 
13679 			mutex_lock(&bpf_percpu_ma_lock);
13680 			err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
13681 			mutex_unlock(&bpf_percpu_ma_lock);
13682 			if (err)
13683 				return err;
13684 		}
13685 
13686 		struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
13687 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13688 			if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
13689 				verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
13690 				return -EINVAL;
13691 			}
13692 
13693 			if (struct_meta) {
13694 				verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
13695 				return -EINVAL;
13696 			}
13697 		}
13698 
13699 		mark_reg_known_zero(env, regs, BPF_REG_0);
13700 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13701 		regs[BPF_REG_0].btf = ret_btf;
13702 		regs[BPF_REG_0].btf_id = ret_btf_id;
13703 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
13704 			regs[BPF_REG_0].type |= MEM_PERCPU;
13705 
13706 		insn_aux->obj_new_size = ret_t->size;
13707 		insn_aux->kptr_struct_meta = struct_meta;
13708 	} else if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
13709 		mark_reg_known_zero(env, regs, BPF_REG_0);
13710 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13711 		regs[BPF_REG_0].btf = meta->arg_btf;
13712 		regs[BPF_REG_0].btf_id = meta->arg_btf_id;
13713 
13714 		insn_aux->kptr_struct_meta =
13715 			btf_find_struct_meta(meta->arg_btf,
13716 					     meta->arg_btf_id);
13717 	} else if (is_list_node_type(ptr_type)) {
13718 		struct btf_field *field = meta->arg_list_head.field;
13719 
13720 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13721 	} else if (is_rbtree_node_type(ptr_type)) {
13722 		struct btf_field *field = meta->arg_rbtree_root.field;
13723 
13724 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13725 	} else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13726 		mark_reg_known_zero(env, regs, BPF_REG_0);
13727 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
13728 		regs[BPF_REG_0].btf = desc_btf;
13729 		regs[BPF_REG_0].btf_id = meta->ret_btf_id;
13730 	} else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
13731 		ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value);
13732 		if (!ret_t) {
13733 			verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n",
13734 				meta->arg_constant.value);
13735 			return -EINVAL;
13736 		} else if (btf_type_is_struct(ret_t)) {
13737 			mark_reg_known_zero(env, regs, BPF_REG_0);
13738 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
13739 			regs[BPF_REG_0].btf = desc_btf;
13740 			regs[BPF_REG_0].btf_id = meta->arg_constant.value;
13741 		} else if (btf_type_is_void(ret_t)) {
13742 			mark_reg_known_zero(env, regs, BPF_REG_0);
13743 			regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
13744 			regs[BPF_REG_0].mem_size = 0;
13745 		} else {
13746 			verbose(env,
13747 				"kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n");
13748 			return -EINVAL;
13749 		}
13750 	} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
13751 		   meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
13752 		enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->initialized_dynptr.type);
13753 
13754 		mark_reg_known_zero(env, regs, BPF_REG_0);
13755 
13756 		if (!meta->arg_constant.found) {
13757 			verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size");
13758 			return -EFAULT;
13759 		}
13760 
13761 		regs[BPF_REG_0].mem_size = meta->arg_constant.value;
13762 
13763 		/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
13764 		regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
13765 
13766 		if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
13767 			regs[BPF_REG_0].type |= MEM_RDONLY;
13768 		} else {
13769 			/* this will set env->seen_direct_write to true */
13770 			if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
13771 				verbose(env, "the prog does not allow writes to packet data\n");
13772 				return -EINVAL;
13773 			}
13774 		}
13775 
13776 		if (!meta->initialized_dynptr.id) {
13777 			verifier_bug(env, "no dynptr id");
13778 			return -EFAULT;
13779 		}
13780 		regs[BPF_REG_0].dynptr_id = meta->initialized_dynptr.id;
13781 
13782 		/* we don't need to set BPF_REG_0's ref obj id
13783 		 * because packet slices are not refcounted (see
13784 		 * dynptr_type_refcounted)
13785 		 */
13786 	} else {
13787 		return 0;
13788 	}
13789 
13790 	return 1;
13791 }
13792 
13793 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
13794 
13795 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
13796 			    int *insn_idx_p)
13797 {
13798 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
13799 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
13800 	struct bpf_reg_state *regs = cur_regs(env);
13801 	const char *func_name, *ptr_type_name;
13802 	const struct btf_type *t, *ptr_type;
13803 	struct bpf_kfunc_call_arg_meta meta;
13804 	struct bpf_insn_aux_data *insn_aux;
13805 	int err, insn_idx = *insn_idx_p;
13806 	const struct btf_param *args;
13807 	struct btf *desc_btf;
13808 
13809 	/* skip for now, but return error when we find this in fixup_kfunc_call */
13810 	if (!insn->imm)
13811 		return 0;
13812 
13813 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
13814 	if (err == -EACCES && func_name)
13815 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
13816 	if (err)
13817 		return err;
13818 	desc_btf = meta.btf;
13819 	insn_aux = &env->insn_aux_data[insn_idx];
13820 
13821 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
13822 
13823 	if (!insn->off &&
13824 	    (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
13825 	     insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
13826 		struct bpf_verifier_state *branch;
13827 		struct bpf_reg_state *regs;
13828 
13829 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
13830 		if (!branch) {
13831 			verbose(env, "failed to push state for failed lock acquisition\n");
13832 			return -ENOMEM;
13833 		}
13834 
13835 		regs = branch->frame[branch->curframe]->regs;
13836 
13837 		/* Clear r0-r5 registers in forked state */
13838 		for (i = 0; i < CALLER_SAVED_REGS; i++)
13839 			mark_reg_not_init(env, regs, caller_saved[i]);
13840 
13841 		mark_reg_unknown(env, regs, BPF_REG_0);
13842 		err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1);
13843 		if (err) {
13844 			verbose(env, "failed to mark s32 range for retval in forked state for lock\n");
13845 			return err;
13846 		}
13847 		__mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32));
13848 	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
13849 		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
13850 		return -EFAULT;
13851 	}
13852 
13853 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
13854 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
13855 		return -EACCES;
13856 	}
13857 
13858 	sleepable = is_kfunc_sleepable(&meta);
13859 	if (sleepable && !in_sleepable(env)) {
13860 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
13861 		return -EACCES;
13862 	}
13863 
13864 	/* Check the arguments */
13865 	err = check_kfunc_args(env, &meta, insn_idx);
13866 	if (err < 0)
13867 		return err;
13868 
13869 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13870 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13871 					 set_rbtree_add_callback_state);
13872 		if (err) {
13873 			verbose(env, "kfunc %s#%d failed callback verification\n",
13874 				func_name, meta.func_id);
13875 			return err;
13876 		}
13877 	}
13878 
13879 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
13880 		meta.r0_size = sizeof(u64);
13881 		meta.r0_rdonly = false;
13882 	}
13883 
13884 	if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
13885 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13886 					 set_timer_callback_state);
13887 		if (err) {
13888 			verbose(env, "kfunc %s#%d failed callback verification\n",
13889 				func_name, meta.func_id);
13890 			return err;
13891 		}
13892 	}
13893 
13894 	if (is_task_work_add_kfunc(meta.func_id)) {
13895 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13896 					 set_task_work_schedule_callback_state);
13897 		if (err) {
13898 			verbose(env, "kfunc %s#%d failed callback verification\n",
13899 				func_name, meta.func_id);
13900 			return err;
13901 		}
13902 	}
13903 
13904 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
13905 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
13906 
13907 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
13908 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
13909 
13910 	if (env->cur_state->active_rcu_lock) {
13911 		struct bpf_func_state *state;
13912 		struct bpf_reg_state *reg;
13913 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
13914 
13915 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
13916 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
13917 			return -EACCES;
13918 		}
13919 
13920 		if (rcu_lock) {
13921 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
13922 			return -EINVAL;
13923 		} else if (rcu_unlock) {
13924 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
13925 				if (reg->type & MEM_RCU) {
13926 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
13927 					reg->type |= PTR_UNTRUSTED;
13928 				}
13929 			}));
13930 			env->cur_state->active_rcu_lock = false;
13931 		} else if (sleepable) {
13932 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
13933 			return -EACCES;
13934 		}
13935 	} else if (rcu_lock) {
13936 		env->cur_state->active_rcu_lock = true;
13937 	} else if (rcu_unlock) {
13938 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
13939 		return -EINVAL;
13940 	}
13941 
13942 	if (env->cur_state->active_preempt_locks) {
13943 		if (preempt_disable) {
13944 			env->cur_state->active_preempt_locks++;
13945 		} else if (preempt_enable) {
13946 			env->cur_state->active_preempt_locks--;
13947 		} else if (sleepable) {
13948 			verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
13949 			return -EACCES;
13950 		}
13951 	} else if (preempt_disable) {
13952 		env->cur_state->active_preempt_locks++;
13953 	} else if (preempt_enable) {
13954 		verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
13955 		return -EINVAL;
13956 	}
13957 
13958 	if (env->cur_state->active_irq_id && sleepable) {
13959 		verbose(env, "kernel func %s is sleepable within IRQ-disabled region\n", func_name);
13960 		return -EACCES;
13961 	}
13962 
13963 	if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) {
13964 		verbose(env, "kernel func %s requires RCU critical section protection\n", func_name);
13965 		return -EACCES;
13966 	}
13967 
13968 	/* In case of release function, we get register number of refcounted
13969 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
13970 	 */
13971 	if (meta.release_regno) {
13972 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
13973 		if (err) {
13974 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
13975 				func_name, meta.func_id);
13976 			return err;
13977 		}
13978 	}
13979 
13980 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
13981 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
13982 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13983 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
13984 		insn_aux->insert_off = regs[BPF_REG_2].off;
13985 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
13986 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
13987 		if (err) {
13988 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
13989 				func_name, meta.func_id);
13990 			return err;
13991 		}
13992 
13993 		err = release_reference(env, release_ref_obj_id);
13994 		if (err) {
13995 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
13996 				func_name, meta.func_id);
13997 			return err;
13998 		}
13999 	}
14000 
14001 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
14002 		if (!bpf_jit_supports_exceptions()) {
14003 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
14004 				func_name, meta.func_id);
14005 			return -ENOTSUPP;
14006 		}
14007 		env->seen_exception = true;
14008 
14009 		/* In the case of the default callback, the cookie value passed
14010 		 * to bpf_throw becomes the return value of the program.
14011 		 */
14012 		if (!env->exception_callback_subprog) {
14013 			err = check_return_code(env, BPF_REG_1, "R1");
14014 			if (err < 0)
14015 				return err;
14016 		}
14017 	}
14018 
14019 	for (i = 0; i < CALLER_SAVED_REGS; i++)
14020 		mark_reg_not_init(env, regs, caller_saved[i]);
14021 
14022 	/* Check return type */
14023 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
14024 
14025 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
14026 		/* Only exception is bpf_obj_new_impl */
14027 		if (meta.btf != btf_vmlinux ||
14028 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
14029 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
14030 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
14031 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
14032 			return -EINVAL;
14033 		}
14034 	}
14035 
14036 	if (btf_type_is_scalar(t)) {
14037 		mark_reg_unknown(env, regs, BPF_REG_0);
14038 		if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
14039 		    meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
14040 			__mark_reg_const_zero(env, &regs[BPF_REG_0]);
14041 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
14042 	} else if (btf_type_is_ptr(t)) {
14043 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
14044 		err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
14045 		if (err) {
14046 			if (err < 0)
14047 				return err;
14048 		} else if (btf_type_is_void(ptr_type)) {
14049 			/* kfunc returning 'void *' is equivalent to returning scalar */
14050 			mark_reg_unknown(env, regs, BPF_REG_0);
14051 		} else if (!__btf_type_is_struct(ptr_type)) {
14052 			if (!meta.r0_size) {
14053 				__u32 sz;
14054 
14055 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
14056 					meta.r0_size = sz;
14057 					meta.r0_rdonly = true;
14058 				}
14059 			}
14060 			if (!meta.r0_size) {
14061 				ptr_type_name = btf_name_by_offset(desc_btf,
14062 								   ptr_type->name_off);
14063 				verbose(env,
14064 					"kernel function %s returns pointer type %s %s is not supported\n",
14065 					func_name,
14066 					btf_type_str(ptr_type),
14067 					ptr_type_name);
14068 				return -EINVAL;
14069 			}
14070 
14071 			mark_reg_known_zero(env, regs, BPF_REG_0);
14072 			regs[BPF_REG_0].type = PTR_TO_MEM;
14073 			regs[BPF_REG_0].mem_size = meta.r0_size;
14074 
14075 			if (meta.r0_rdonly)
14076 				regs[BPF_REG_0].type |= MEM_RDONLY;
14077 
14078 			/* Ensures we don't access the memory after a release_reference() */
14079 			if (meta.ref_obj_id)
14080 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
14081 
14082 			if (is_kfunc_rcu_protected(&meta))
14083 				regs[BPF_REG_0].type |= MEM_RCU;
14084 		} else {
14085 			mark_reg_known_zero(env, regs, BPF_REG_0);
14086 			regs[BPF_REG_0].btf = desc_btf;
14087 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
14088 			regs[BPF_REG_0].btf_id = ptr_type_id;
14089 
14090 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
14091 				regs[BPF_REG_0].type |= PTR_UNTRUSTED;
14092 			else if (is_kfunc_rcu_protected(&meta))
14093 				regs[BPF_REG_0].type |= MEM_RCU;
14094 
14095 			if (is_iter_next_kfunc(&meta)) {
14096 				struct bpf_reg_state *cur_iter;
14097 
14098 				cur_iter = get_iter_from_state(env->cur_state, &meta);
14099 
14100 				if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
14101 					regs[BPF_REG_0].type |= MEM_RCU;
14102 				else
14103 					regs[BPF_REG_0].type |= PTR_TRUSTED;
14104 			}
14105 		}
14106 
14107 		if (is_kfunc_ret_null(&meta)) {
14108 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
14109 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
14110 			regs[BPF_REG_0].id = ++env->id_gen;
14111 		}
14112 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
14113 		if (is_kfunc_acquire(&meta)) {
14114 			int id = acquire_reference(env, insn_idx);
14115 
14116 			if (id < 0)
14117 				return id;
14118 			if (is_kfunc_ret_null(&meta))
14119 				regs[BPF_REG_0].id = id;
14120 			regs[BPF_REG_0].ref_obj_id = id;
14121 		} else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
14122 			ref_set_non_owning(env, &regs[BPF_REG_0]);
14123 		}
14124 
14125 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
14126 			regs[BPF_REG_0].id = ++env->id_gen;
14127 	} else if (btf_type_is_void(t)) {
14128 		if (meta.btf == btf_vmlinux) {
14129 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
14130 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
14131 				insn_aux->kptr_struct_meta =
14132 					btf_find_struct_meta(meta.arg_btf,
14133 							     meta.arg_btf_id);
14134 			}
14135 		}
14136 	}
14137 
14138 	if (is_kfunc_pkt_changing(&meta))
14139 		clear_all_pkt_pointers(env);
14140 
14141 	nargs = btf_type_vlen(meta.func_proto);
14142 	args = (const struct btf_param *)(meta.func_proto + 1);
14143 	for (i = 0; i < nargs; i++) {
14144 		u32 regno = i + 1;
14145 
14146 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
14147 		if (btf_type_is_ptr(t))
14148 			mark_btf_func_reg_size(env, regno, sizeof(void *));
14149 		else
14150 			/* scalar. ensured by btf_check_kfunc_arg_match() */
14151 			mark_btf_func_reg_size(env, regno, t->size);
14152 	}
14153 
14154 	if (is_iter_next_kfunc(&meta)) {
14155 		err = process_iter_next_call(env, insn_idx, &meta);
14156 		if (err)
14157 			return err;
14158 	}
14159 
14160 	return 0;
14161 }
14162 
14163 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
14164 				  const struct bpf_reg_state *reg,
14165 				  enum bpf_reg_type type)
14166 {
14167 	bool known = tnum_is_const(reg->var_off);
14168 	s64 val = reg->var_off.value;
14169 	s64 smin = reg->smin_value;
14170 
14171 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
14172 		verbose(env, "math between %s pointer and %lld is not allowed\n",
14173 			reg_type_str(env, type), val);
14174 		return false;
14175 	}
14176 
14177 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
14178 		verbose(env, "%s pointer offset %d is not allowed\n",
14179 			reg_type_str(env, type), reg->off);
14180 		return false;
14181 	}
14182 
14183 	if (smin == S64_MIN) {
14184 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
14185 			reg_type_str(env, type));
14186 		return false;
14187 	}
14188 
14189 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
14190 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
14191 			smin, reg_type_str(env, type));
14192 		return false;
14193 	}
14194 
14195 	return true;
14196 }
14197 
14198 enum {
14199 	REASON_BOUNDS	= -1,
14200 	REASON_TYPE	= -2,
14201 	REASON_PATHS	= -3,
14202 	REASON_LIMIT	= -4,
14203 	REASON_STACK	= -5,
14204 };
14205 
14206 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
14207 			      u32 *alu_limit, bool mask_to_left)
14208 {
14209 	u32 max = 0, ptr_limit = 0;
14210 
14211 	switch (ptr_reg->type) {
14212 	case PTR_TO_STACK:
14213 		/* Offset 0 is out-of-bounds, but acceptable start for the
14214 		 * left direction, see BPF_REG_FP. Also, unknown scalar
14215 		 * offset where we would need to deal with min/max bounds is
14216 		 * currently prohibited for unprivileged.
14217 		 */
14218 		max = MAX_BPF_STACK + mask_to_left;
14219 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
14220 		break;
14221 	case PTR_TO_MAP_VALUE:
14222 		max = ptr_reg->map_ptr->value_size;
14223 		ptr_limit = (mask_to_left ?
14224 			     ptr_reg->smin_value :
14225 			     ptr_reg->umax_value) + ptr_reg->off;
14226 		break;
14227 	default:
14228 		return REASON_TYPE;
14229 	}
14230 
14231 	if (ptr_limit >= max)
14232 		return REASON_LIMIT;
14233 	*alu_limit = ptr_limit;
14234 	return 0;
14235 }
14236 
14237 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
14238 				    const struct bpf_insn *insn)
14239 {
14240 	return env->bypass_spec_v1 ||
14241 		BPF_SRC(insn->code) == BPF_K ||
14242 		cur_aux(env)->nospec;
14243 }
14244 
14245 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
14246 				       u32 alu_state, u32 alu_limit)
14247 {
14248 	/* If we arrived here from different branches with different
14249 	 * state or limits to sanitize, then this won't work.
14250 	 */
14251 	if (aux->alu_state &&
14252 	    (aux->alu_state != alu_state ||
14253 	     aux->alu_limit != alu_limit))
14254 		return REASON_PATHS;
14255 
14256 	/* Corresponding fixup done in do_misc_fixups(). */
14257 	aux->alu_state = alu_state;
14258 	aux->alu_limit = alu_limit;
14259 	return 0;
14260 }
14261 
14262 static int sanitize_val_alu(struct bpf_verifier_env *env,
14263 			    struct bpf_insn *insn)
14264 {
14265 	struct bpf_insn_aux_data *aux = cur_aux(env);
14266 
14267 	if (can_skip_alu_sanitation(env, insn))
14268 		return 0;
14269 
14270 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
14271 }
14272 
14273 static bool sanitize_needed(u8 opcode)
14274 {
14275 	return opcode == BPF_ADD || opcode == BPF_SUB;
14276 }
14277 
14278 struct bpf_sanitize_info {
14279 	struct bpf_insn_aux_data aux;
14280 	bool mask_to_left;
14281 };
14282 
14283 static struct bpf_verifier_state *
14284 sanitize_speculative_path(struct bpf_verifier_env *env,
14285 			  const struct bpf_insn *insn,
14286 			  u32 next_idx, u32 curr_idx)
14287 {
14288 	struct bpf_verifier_state *branch;
14289 	struct bpf_reg_state *regs;
14290 
14291 	branch = push_stack(env, next_idx, curr_idx, true);
14292 	if (branch && insn) {
14293 		regs = branch->frame[branch->curframe]->regs;
14294 		if (BPF_SRC(insn->code) == BPF_K) {
14295 			mark_reg_unknown(env, regs, insn->dst_reg);
14296 		} else if (BPF_SRC(insn->code) == BPF_X) {
14297 			mark_reg_unknown(env, regs, insn->dst_reg);
14298 			mark_reg_unknown(env, regs, insn->src_reg);
14299 		}
14300 	}
14301 	return branch;
14302 }
14303 
14304 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
14305 			    struct bpf_insn *insn,
14306 			    const struct bpf_reg_state *ptr_reg,
14307 			    const struct bpf_reg_state *off_reg,
14308 			    struct bpf_reg_state *dst_reg,
14309 			    struct bpf_sanitize_info *info,
14310 			    const bool commit_window)
14311 {
14312 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
14313 	struct bpf_verifier_state *vstate = env->cur_state;
14314 	bool off_is_imm = tnum_is_const(off_reg->var_off);
14315 	bool off_is_neg = off_reg->smin_value < 0;
14316 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
14317 	u8 opcode = BPF_OP(insn->code);
14318 	u32 alu_state, alu_limit;
14319 	struct bpf_reg_state tmp;
14320 	bool ret;
14321 	int err;
14322 
14323 	if (can_skip_alu_sanitation(env, insn))
14324 		return 0;
14325 
14326 	/* We already marked aux for masking from non-speculative
14327 	 * paths, thus we got here in the first place. We only care
14328 	 * to explore bad access from here.
14329 	 */
14330 	if (vstate->speculative)
14331 		goto do_sim;
14332 
14333 	if (!commit_window) {
14334 		if (!tnum_is_const(off_reg->var_off) &&
14335 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
14336 			return REASON_BOUNDS;
14337 
14338 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
14339 				     (opcode == BPF_SUB && !off_is_neg);
14340 	}
14341 
14342 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
14343 	if (err < 0)
14344 		return err;
14345 
14346 	if (commit_window) {
14347 		/* In commit phase we narrow the masking window based on
14348 		 * the observed pointer move after the simulated operation.
14349 		 */
14350 		alu_state = info->aux.alu_state;
14351 		alu_limit = abs(info->aux.alu_limit - alu_limit);
14352 	} else {
14353 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
14354 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
14355 		alu_state |= ptr_is_dst_reg ?
14356 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
14357 
14358 		/* Limit pruning on unknown scalars to enable deep search for
14359 		 * potential masking differences from other program paths.
14360 		 */
14361 		if (!off_is_imm)
14362 			env->explore_alu_limits = true;
14363 	}
14364 
14365 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
14366 	if (err < 0)
14367 		return err;
14368 do_sim:
14369 	/* If we're in commit phase, we're done here given we already
14370 	 * pushed the truncated dst_reg into the speculative verification
14371 	 * stack.
14372 	 *
14373 	 * Also, when register is a known constant, we rewrite register-based
14374 	 * operation to immediate-based, and thus do not need masking (and as
14375 	 * a consequence, do not need to simulate the zero-truncation either).
14376 	 */
14377 	if (commit_window || off_is_imm)
14378 		return 0;
14379 
14380 	/* Simulate and find potential out-of-bounds access under
14381 	 * speculative execution from truncation as a result of
14382 	 * masking when off was not within expected range. If off
14383 	 * sits in dst, then we temporarily need to move ptr there
14384 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
14385 	 * for cases where we use K-based arithmetic in one direction
14386 	 * and truncated reg-based in the other in order to explore
14387 	 * bad access.
14388 	 */
14389 	if (!ptr_is_dst_reg) {
14390 		tmp = *dst_reg;
14391 		copy_register_state(dst_reg, ptr_reg);
14392 	}
14393 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
14394 					env->insn_idx);
14395 	if (!ptr_is_dst_reg && ret)
14396 		*dst_reg = tmp;
14397 	return !ret ? REASON_STACK : 0;
14398 }
14399 
14400 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
14401 {
14402 	struct bpf_verifier_state *vstate = env->cur_state;
14403 
14404 	/* If we simulate paths under speculation, we don't update the
14405 	 * insn as 'seen' such that when we verify unreachable paths in
14406 	 * the non-speculative domain, sanitize_dead_code() can still
14407 	 * rewrite/sanitize them.
14408 	 */
14409 	if (!vstate->speculative)
14410 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
14411 }
14412 
14413 static int sanitize_err(struct bpf_verifier_env *env,
14414 			const struct bpf_insn *insn, int reason,
14415 			const struct bpf_reg_state *off_reg,
14416 			const struct bpf_reg_state *dst_reg)
14417 {
14418 	static const char *err = "pointer arithmetic with it prohibited for !root";
14419 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
14420 	u32 dst = insn->dst_reg, src = insn->src_reg;
14421 
14422 	switch (reason) {
14423 	case REASON_BOUNDS:
14424 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
14425 			off_reg == dst_reg ? dst : src, err);
14426 		break;
14427 	case REASON_TYPE:
14428 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
14429 			off_reg == dst_reg ? src : dst, err);
14430 		break;
14431 	case REASON_PATHS:
14432 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
14433 			dst, op, err);
14434 		break;
14435 	case REASON_LIMIT:
14436 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
14437 			dst, op, err);
14438 		break;
14439 	case REASON_STACK:
14440 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
14441 			dst, err);
14442 		return -ENOMEM;
14443 	default:
14444 		verifier_bug(env, "unknown reason (%d)", reason);
14445 		break;
14446 	}
14447 
14448 	return -EACCES;
14449 }
14450 
14451 /* check that stack access falls within stack limits and that 'reg' doesn't
14452  * have a variable offset.
14453  *
14454  * Variable offset is prohibited for unprivileged mode for simplicity since it
14455  * requires corresponding support in Spectre masking for stack ALU.  See also
14456  * retrieve_ptr_limit().
14457  *
14458  *
14459  * 'off' includes 'reg->off'.
14460  */
14461 static int check_stack_access_for_ptr_arithmetic(
14462 				struct bpf_verifier_env *env,
14463 				int regno,
14464 				const struct bpf_reg_state *reg,
14465 				int off)
14466 {
14467 	if (!tnum_is_const(reg->var_off)) {
14468 		char tn_buf[48];
14469 
14470 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
14471 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
14472 			regno, tn_buf, off);
14473 		return -EACCES;
14474 	}
14475 
14476 	if (off >= 0 || off < -MAX_BPF_STACK) {
14477 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
14478 			"prohibited for !root; off=%d\n", regno, off);
14479 		return -EACCES;
14480 	}
14481 
14482 	return 0;
14483 }
14484 
14485 static int sanitize_check_bounds(struct bpf_verifier_env *env,
14486 				 const struct bpf_insn *insn,
14487 				 const struct bpf_reg_state *dst_reg)
14488 {
14489 	u32 dst = insn->dst_reg;
14490 
14491 	/* For unprivileged we require that resulting offset must be in bounds
14492 	 * in order to be able to sanitize access later on.
14493 	 */
14494 	if (env->bypass_spec_v1)
14495 		return 0;
14496 
14497 	switch (dst_reg->type) {
14498 	case PTR_TO_STACK:
14499 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
14500 					dst_reg->off + dst_reg->var_off.value))
14501 			return -EACCES;
14502 		break;
14503 	case PTR_TO_MAP_VALUE:
14504 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
14505 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
14506 				"prohibited for !root\n", dst);
14507 			return -EACCES;
14508 		}
14509 		break;
14510 	default:
14511 		return -EOPNOTSUPP;
14512 	}
14513 
14514 	return 0;
14515 }
14516 
14517 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
14518  * Caller should also handle BPF_MOV case separately.
14519  * If we return -EACCES, caller may want to try again treating pointer as a
14520  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
14521  */
14522 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
14523 				   struct bpf_insn *insn,
14524 				   const struct bpf_reg_state *ptr_reg,
14525 				   const struct bpf_reg_state *off_reg)
14526 {
14527 	struct bpf_verifier_state *vstate = env->cur_state;
14528 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14529 	struct bpf_reg_state *regs = state->regs, *dst_reg;
14530 	bool known = tnum_is_const(off_reg->var_off);
14531 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
14532 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
14533 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
14534 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
14535 	struct bpf_sanitize_info info = {};
14536 	u8 opcode = BPF_OP(insn->code);
14537 	u32 dst = insn->dst_reg;
14538 	int ret, bounds_ret;
14539 
14540 	dst_reg = &regs[dst];
14541 
14542 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
14543 	    smin_val > smax_val || umin_val > umax_val) {
14544 		/* Taint dst register if offset had invalid bounds derived from
14545 		 * e.g. dead branches.
14546 		 */
14547 		__mark_reg_unknown(env, dst_reg);
14548 		return 0;
14549 	}
14550 
14551 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
14552 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
14553 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14554 			__mark_reg_unknown(env, dst_reg);
14555 			return 0;
14556 		}
14557 
14558 		verbose(env,
14559 			"R%d 32-bit pointer arithmetic prohibited\n",
14560 			dst);
14561 		return -EACCES;
14562 	}
14563 
14564 	if (ptr_reg->type & PTR_MAYBE_NULL) {
14565 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
14566 			dst, reg_type_str(env, ptr_reg->type));
14567 		return -EACCES;
14568 	}
14569 
14570 	/*
14571 	 * Accesses to untrusted PTR_TO_MEM are done through probe
14572 	 * instructions, hence no need to track offsets.
14573 	 */
14574 	if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED))
14575 		return 0;
14576 
14577 	switch (base_type(ptr_reg->type)) {
14578 	case PTR_TO_CTX:
14579 	case PTR_TO_MAP_VALUE:
14580 	case PTR_TO_MAP_KEY:
14581 	case PTR_TO_STACK:
14582 	case PTR_TO_PACKET_META:
14583 	case PTR_TO_PACKET:
14584 	case PTR_TO_TP_BUFFER:
14585 	case PTR_TO_BTF_ID:
14586 	case PTR_TO_MEM:
14587 	case PTR_TO_BUF:
14588 	case PTR_TO_FUNC:
14589 	case CONST_PTR_TO_DYNPTR:
14590 		break;
14591 	case PTR_TO_FLOW_KEYS:
14592 		if (known)
14593 			break;
14594 		fallthrough;
14595 	case CONST_PTR_TO_MAP:
14596 		/* smin_val represents the known value */
14597 		if (known && smin_val == 0 && opcode == BPF_ADD)
14598 			break;
14599 		fallthrough;
14600 	default:
14601 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
14602 			dst, reg_type_str(env, ptr_reg->type));
14603 		return -EACCES;
14604 	}
14605 
14606 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
14607 	 * The id may be overwritten later if we create a new variable offset.
14608 	 */
14609 	dst_reg->type = ptr_reg->type;
14610 	dst_reg->id = ptr_reg->id;
14611 
14612 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
14613 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
14614 		return -EINVAL;
14615 
14616 	/* pointer types do not carry 32-bit bounds at the moment. */
14617 	__mark_reg32_unbounded(dst_reg);
14618 
14619 	if (sanitize_needed(opcode)) {
14620 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
14621 				       &info, false);
14622 		if (ret < 0)
14623 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14624 	}
14625 
14626 	switch (opcode) {
14627 	case BPF_ADD:
14628 		/* We can take a fixed offset as long as it doesn't overflow
14629 		 * the s32 'off' field
14630 		 */
14631 		if (known && (ptr_reg->off + smin_val ==
14632 			      (s64)(s32)(ptr_reg->off + smin_val))) {
14633 			/* pointer += K.  Accumulate it into fixed offset */
14634 			dst_reg->smin_value = smin_ptr;
14635 			dst_reg->smax_value = smax_ptr;
14636 			dst_reg->umin_value = umin_ptr;
14637 			dst_reg->umax_value = umax_ptr;
14638 			dst_reg->var_off = ptr_reg->var_off;
14639 			dst_reg->off = ptr_reg->off + smin_val;
14640 			dst_reg->raw = ptr_reg->raw;
14641 			break;
14642 		}
14643 		/* A new variable offset is created.  Note that off_reg->off
14644 		 * == 0, since it's a scalar.
14645 		 * dst_reg gets the pointer type and since some positive
14646 		 * integer value was added to the pointer, give it a new 'id'
14647 		 * if it's a PTR_TO_PACKET.
14648 		 * this creates a new 'base' pointer, off_reg (variable) gets
14649 		 * added into the variable offset, and we copy the fixed offset
14650 		 * from ptr_reg.
14651 		 */
14652 		if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
14653 		    check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
14654 			dst_reg->smin_value = S64_MIN;
14655 			dst_reg->smax_value = S64_MAX;
14656 		}
14657 		if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
14658 		    check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
14659 			dst_reg->umin_value = 0;
14660 			dst_reg->umax_value = U64_MAX;
14661 		}
14662 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
14663 		dst_reg->off = ptr_reg->off;
14664 		dst_reg->raw = ptr_reg->raw;
14665 		if (reg_is_pkt_pointer(ptr_reg)) {
14666 			dst_reg->id = ++env->id_gen;
14667 			/* something was added to pkt_ptr, set range to zero */
14668 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14669 		}
14670 		break;
14671 	case BPF_SUB:
14672 		if (dst_reg == off_reg) {
14673 			/* scalar -= pointer.  Creates an unknown scalar */
14674 			verbose(env, "R%d tried to subtract pointer from scalar\n",
14675 				dst);
14676 			return -EACCES;
14677 		}
14678 		/* We don't allow subtraction from FP, because (according to
14679 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
14680 		 * be able to deal with it.
14681 		 */
14682 		if (ptr_reg->type == PTR_TO_STACK) {
14683 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
14684 				dst);
14685 			return -EACCES;
14686 		}
14687 		if (known && (ptr_reg->off - smin_val ==
14688 			      (s64)(s32)(ptr_reg->off - smin_val))) {
14689 			/* pointer -= K.  Subtract it from fixed offset */
14690 			dst_reg->smin_value = smin_ptr;
14691 			dst_reg->smax_value = smax_ptr;
14692 			dst_reg->umin_value = umin_ptr;
14693 			dst_reg->umax_value = umax_ptr;
14694 			dst_reg->var_off = ptr_reg->var_off;
14695 			dst_reg->id = ptr_reg->id;
14696 			dst_reg->off = ptr_reg->off - smin_val;
14697 			dst_reg->raw = ptr_reg->raw;
14698 			break;
14699 		}
14700 		/* A new variable offset is created.  If the subtrahend is known
14701 		 * nonnegative, then any reg->range we had before is still good.
14702 		 */
14703 		if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
14704 		    check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
14705 			/* Overflow possible, we know nothing */
14706 			dst_reg->smin_value = S64_MIN;
14707 			dst_reg->smax_value = S64_MAX;
14708 		}
14709 		if (umin_ptr < umax_val) {
14710 			/* Overflow possible, we know nothing */
14711 			dst_reg->umin_value = 0;
14712 			dst_reg->umax_value = U64_MAX;
14713 		} else {
14714 			/* Cannot overflow (as long as bounds are consistent) */
14715 			dst_reg->umin_value = umin_ptr - umax_val;
14716 			dst_reg->umax_value = umax_ptr - umin_val;
14717 		}
14718 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
14719 		dst_reg->off = ptr_reg->off;
14720 		dst_reg->raw = ptr_reg->raw;
14721 		if (reg_is_pkt_pointer(ptr_reg)) {
14722 			dst_reg->id = ++env->id_gen;
14723 			/* something was added to pkt_ptr, set range to zero */
14724 			if (smin_val < 0)
14725 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14726 		}
14727 		break;
14728 	case BPF_AND:
14729 	case BPF_OR:
14730 	case BPF_XOR:
14731 		/* bitwise ops on pointers are troublesome, prohibit. */
14732 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
14733 			dst, bpf_alu_string[opcode >> 4]);
14734 		return -EACCES;
14735 	default:
14736 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
14737 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
14738 			dst, bpf_alu_string[opcode >> 4]);
14739 		return -EACCES;
14740 	}
14741 
14742 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
14743 		return -EINVAL;
14744 	reg_bounds_sync(dst_reg);
14745 	bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
14746 	if (bounds_ret == -EACCES)
14747 		return bounds_ret;
14748 	if (sanitize_needed(opcode)) {
14749 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
14750 				       &info, true);
14751 		if (verifier_bug_if(!can_skip_alu_sanitation(env, insn)
14752 				    && !env->cur_state->speculative
14753 				    && bounds_ret
14754 				    && !ret,
14755 				    env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) {
14756 			return -EFAULT;
14757 		}
14758 		if (ret < 0)
14759 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14760 	}
14761 
14762 	return 0;
14763 }
14764 
14765 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
14766 				 struct bpf_reg_state *src_reg)
14767 {
14768 	s32 *dst_smin = &dst_reg->s32_min_value;
14769 	s32 *dst_smax = &dst_reg->s32_max_value;
14770 	u32 *dst_umin = &dst_reg->u32_min_value;
14771 	u32 *dst_umax = &dst_reg->u32_max_value;
14772 	u32 umin_val = src_reg->u32_min_value;
14773 	u32 umax_val = src_reg->u32_max_value;
14774 	bool min_overflow, max_overflow;
14775 
14776 	if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
14777 	    check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
14778 		*dst_smin = S32_MIN;
14779 		*dst_smax = S32_MAX;
14780 	}
14781 
14782 	/* If either all additions overflow or no additions overflow, then
14783 	 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
14784 	 * dst_umax + src_umax. Otherwise (some additions overflow), set
14785 	 * the output bounds to unbounded.
14786 	 */
14787 	min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
14788 	max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
14789 
14790 	if (!min_overflow && max_overflow) {
14791 		*dst_umin = 0;
14792 		*dst_umax = U32_MAX;
14793 	}
14794 }
14795 
14796 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
14797 			       struct bpf_reg_state *src_reg)
14798 {
14799 	s64 *dst_smin = &dst_reg->smin_value;
14800 	s64 *dst_smax = &dst_reg->smax_value;
14801 	u64 *dst_umin = &dst_reg->umin_value;
14802 	u64 *dst_umax = &dst_reg->umax_value;
14803 	u64 umin_val = src_reg->umin_value;
14804 	u64 umax_val = src_reg->umax_value;
14805 	bool min_overflow, max_overflow;
14806 
14807 	if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
14808 	    check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
14809 		*dst_smin = S64_MIN;
14810 		*dst_smax = S64_MAX;
14811 	}
14812 
14813 	/* If either all additions overflow or no additions overflow, then
14814 	 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
14815 	 * dst_umax + src_umax. Otherwise (some additions overflow), set
14816 	 * the output bounds to unbounded.
14817 	 */
14818 	min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
14819 	max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
14820 
14821 	if (!min_overflow && max_overflow) {
14822 		*dst_umin = 0;
14823 		*dst_umax = U64_MAX;
14824 	}
14825 }
14826 
14827 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
14828 				 struct bpf_reg_state *src_reg)
14829 {
14830 	s32 *dst_smin = &dst_reg->s32_min_value;
14831 	s32 *dst_smax = &dst_reg->s32_max_value;
14832 	u32 *dst_umin = &dst_reg->u32_min_value;
14833 	u32 *dst_umax = &dst_reg->u32_max_value;
14834 	u32 umin_val = src_reg->u32_min_value;
14835 	u32 umax_val = src_reg->u32_max_value;
14836 	bool min_underflow, max_underflow;
14837 
14838 	if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
14839 	    check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
14840 		/* Overflow possible, we know nothing */
14841 		*dst_smin = S32_MIN;
14842 		*dst_smax = S32_MAX;
14843 	}
14844 
14845 	/* If either all subtractions underflow or no subtractions
14846 	 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
14847 	 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
14848 	 * underflow), set the output bounds to unbounded.
14849 	 */
14850 	min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
14851 	max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
14852 
14853 	if (min_underflow && !max_underflow) {
14854 		*dst_umin = 0;
14855 		*dst_umax = U32_MAX;
14856 	}
14857 }
14858 
14859 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
14860 			       struct bpf_reg_state *src_reg)
14861 {
14862 	s64 *dst_smin = &dst_reg->smin_value;
14863 	s64 *dst_smax = &dst_reg->smax_value;
14864 	u64 *dst_umin = &dst_reg->umin_value;
14865 	u64 *dst_umax = &dst_reg->umax_value;
14866 	u64 umin_val = src_reg->umin_value;
14867 	u64 umax_val = src_reg->umax_value;
14868 	bool min_underflow, max_underflow;
14869 
14870 	if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
14871 	    check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
14872 		/* Overflow possible, we know nothing */
14873 		*dst_smin = S64_MIN;
14874 		*dst_smax = S64_MAX;
14875 	}
14876 
14877 	/* If either all subtractions underflow or no subtractions
14878 	 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
14879 	 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
14880 	 * underflow), set the output bounds to unbounded.
14881 	 */
14882 	min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
14883 	max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
14884 
14885 	if (min_underflow && !max_underflow) {
14886 		*dst_umin = 0;
14887 		*dst_umax = U64_MAX;
14888 	}
14889 }
14890 
14891 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
14892 				 struct bpf_reg_state *src_reg)
14893 {
14894 	s32 *dst_smin = &dst_reg->s32_min_value;
14895 	s32 *dst_smax = &dst_reg->s32_max_value;
14896 	u32 *dst_umin = &dst_reg->u32_min_value;
14897 	u32 *dst_umax = &dst_reg->u32_max_value;
14898 	s32 tmp_prod[4];
14899 
14900 	if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) ||
14901 	    check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) {
14902 		/* Overflow possible, we know nothing */
14903 		*dst_umin = 0;
14904 		*dst_umax = U32_MAX;
14905 	}
14906 	if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) ||
14907 	    check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) ||
14908 	    check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) ||
14909 	    check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) {
14910 		/* Overflow possible, we know nothing */
14911 		*dst_smin = S32_MIN;
14912 		*dst_smax = S32_MAX;
14913 	} else {
14914 		*dst_smin = min_array(tmp_prod, 4);
14915 		*dst_smax = max_array(tmp_prod, 4);
14916 	}
14917 }
14918 
14919 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
14920 			       struct bpf_reg_state *src_reg)
14921 {
14922 	s64 *dst_smin = &dst_reg->smin_value;
14923 	s64 *dst_smax = &dst_reg->smax_value;
14924 	u64 *dst_umin = &dst_reg->umin_value;
14925 	u64 *dst_umax = &dst_reg->umax_value;
14926 	s64 tmp_prod[4];
14927 
14928 	if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) ||
14929 	    check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) {
14930 		/* Overflow possible, we know nothing */
14931 		*dst_umin = 0;
14932 		*dst_umax = U64_MAX;
14933 	}
14934 	if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) ||
14935 	    check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) ||
14936 	    check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) ||
14937 	    check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) {
14938 		/* Overflow possible, we know nothing */
14939 		*dst_smin = S64_MIN;
14940 		*dst_smax = S64_MAX;
14941 	} else {
14942 		*dst_smin = min_array(tmp_prod, 4);
14943 		*dst_smax = max_array(tmp_prod, 4);
14944 	}
14945 }
14946 
14947 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
14948 				 struct bpf_reg_state *src_reg)
14949 {
14950 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14951 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14952 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14953 	u32 umax_val = src_reg->u32_max_value;
14954 
14955 	if (src_known && dst_known) {
14956 		__mark_reg32_known(dst_reg, var32_off.value);
14957 		return;
14958 	}
14959 
14960 	/* We get our minimum from the var_off, since that's inherently
14961 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14962 	 */
14963 	dst_reg->u32_min_value = var32_off.value;
14964 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
14965 
14966 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
14967 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
14968 	 */
14969 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
14970 		dst_reg->s32_min_value = dst_reg->u32_min_value;
14971 		dst_reg->s32_max_value = dst_reg->u32_max_value;
14972 	} else {
14973 		dst_reg->s32_min_value = S32_MIN;
14974 		dst_reg->s32_max_value = S32_MAX;
14975 	}
14976 }
14977 
14978 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
14979 			       struct bpf_reg_state *src_reg)
14980 {
14981 	bool src_known = tnum_is_const(src_reg->var_off);
14982 	bool dst_known = tnum_is_const(dst_reg->var_off);
14983 	u64 umax_val = src_reg->umax_value;
14984 
14985 	if (src_known && dst_known) {
14986 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14987 		return;
14988 	}
14989 
14990 	/* We get our minimum from the var_off, since that's inherently
14991 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14992 	 */
14993 	dst_reg->umin_value = dst_reg->var_off.value;
14994 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
14995 
14996 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
14997 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
14998 	 */
14999 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15000 		dst_reg->smin_value = dst_reg->umin_value;
15001 		dst_reg->smax_value = dst_reg->umax_value;
15002 	} else {
15003 		dst_reg->smin_value = S64_MIN;
15004 		dst_reg->smax_value = S64_MAX;
15005 	}
15006 	/* We may learn something more from the var_off */
15007 	__update_reg_bounds(dst_reg);
15008 }
15009 
15010 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
15011 				struct bpf_reg_state *src_reg)
15012 {
15013 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15014 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15015 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15016 	u32 umin_val = src_reg->u32_min_value;
15017 
15018 	if (src_known && dst_known) {
15019 		__mark_reg32_known(dst_reg, var32_off.value);
15020 		return;
15021 	}
15022 
15023 	/* We get our maximum from the var_off, and our minimum is the
15024 	 * maximum of the operands' minima
15025 	 */
15026 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
15027 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15028 
15029 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15030 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15031 	 */
15032 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15033 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15034 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15035 	} else {
15036 		dst_reg->s32_min_value = S32_MIN;
15037 		dst_reg->s32_max_value = S32_MAX;
15038 	}
15039 }
15040 
15041 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
15042 			      struct bpf_reg_state *src_reg)
15043 {
15044 	bool src_known = tnum_is_const(src_reg->var_off);
15045 	bool dst_known = tnum_is_const(dst_reg->var_off);
15046 	u64 umin_val = src_reg->umin_value;
15047 
15048 	if (src_known && dst_known) {
15049 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15050 		return;
15051 	}
15052 
15053 	/* We get our maximum from the var_off, and our minimum is the
15054 	 * maximum of the operands' minima
15055 	 */
15056 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
15057 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15058 
15059 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15060 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15061 	 */
15062 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15063 		dst_reg->smin_value = dst_reg->umin_value;
15064 		dst_reg->smax_value = dst_reg->umax_value;
15065 	} else {
15066 		dst_reg->smin_value = S64_MIN;
15067 		dst_reg->smax_value = S64_MAX;
15068 	}
15069 	/* We may learn something more from the var_off */
15070 	__update_reg_bounds(dst_reg);
15071 }
15072 
15073 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
15074 				 struct bpf_reg_state *src_reg)
15075 {
15076 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15077 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15078 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15079 
15080 	if (src_known && dst_known) {
15081 		__mark_reg32_known(dst_reg, var32_off.value);
15082 		return;
15083 	}
15084 
15085 	/* We get both minimum and maximum from the var32_off. */
15086 	dst_reg->u32_min_value = var32_off.value;
15087 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15088 
15089 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15090 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15091 	 */
15092 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15093 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15094 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15095 	} else {
15096 		dst_reg->s32_min_value = S32_MIN;
15097 		dst_reg->s32_max_value = S32_MAX;
15098 	}
15099 }
15100 
15101 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
15102 			       struct bpf_reg_state *src_reg)
15103 {
15104 	bool src_known = tnum_is_const(src_reg->var_off);
15105 	bool dst_known = tnum_is_const(dst_reg->var_off);
15106 
15107 	if (src_known && dst_known) {
15108 		/* dst_reg->var_off.value has been updated earlier */
15109 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15110 		return;
15111 	}
15112 
15113 	/* We get both minimum and maximum from the var_off. */
15114 	dst_reg->umin_value = dst_reg->var_off.value;
15115 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15116 
15117 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15118 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15119 	 */
15120 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15121 		dst_reg->smin_value = dst_reg->umin_value;
15122 		dst_reg->smax_value = dst_reg->umax_value;
15123 	} else {
15124 		dst_reg->smin_value = S64_MIN;
15125 		dst_reg->smax_value = S64_MAX;
15126 	}
15127 
15128 	__update_reg_bounds(dst_reg);
15129 }
15130 
15131 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15132 				   u64 umin_val, u64 umax_val)
15133 {
15134 	/* We lose all sign bit information (except what we can pick
15135 	 * up from var_off)
15136 	 */
15137 	dst_reg->s32_min_value = S32_MIN;
15138 	dst_reg->s32_max_value = S32_MAX;
15139 	/* If we might shift our top bit out, then we know nothing */
15140 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
15141 		dst_reg->u32_min_value = 0;
15142 		dst_reg->u32_max_value = U32_MAX;
15143 	} else {
15144 		dst_reg->u32_min_value <<= umin_val;
15145 		dst_reg->u32_max_value <<= umax_val;
15146 	}
15147 }
15148 
15149 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15150 				 struct bpf_reg_state *src_reg)
15151 {
15152 	u32 umax_val = src_reg->u32_max_value;
15153 	u32 umin_val = src_reg->u32_min_value;
15154 	/* u32 alu operation will zext upper bits */
15155 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15156 
15157 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15158 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
15159 	/* Not required but being careful mark reg64 bounds as unknown so
15160 	 * that we are forced to pick them up from tnum and zext later and
15161 	 * if some path skips this step we are still safe.
15162 	 */
15163 	__mark_reg64_unbounded(dst_reg);
15164 	__update_reg32_bounds(dst_reg);
15165 }
15166 
15167 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
15168 				   u64 umin_val, u64 umax_val)
15169 {
15170 	/* Special case <<32 because it is a common compiler pattern to sign
15171 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
15172 	 * positive we know this shift will also be positive so we can track
15173 	 * bounds correctly. Otherwise we lose all sign bit information except
15174 	 * what we can pick up from var_off. Perhaps we can generalize this
15175 	 * later to shifts of any length.
15176 	 */
15177 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
15178 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
15179 	else
15180 		dst_reg->smax_value = S64_MAX;
15181 
15182 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
15183 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
15184 	else
15185 		dst_reg->smin_value = S64_MIN;
15186 
15187 	/* If we might shift our top bit out, then we know nothing */
15188 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
15189 		dst_reg->umin_value = 0;
15190 		dst_reg->umax_value = U64_MAX;
15191 	} else {
15192 		dst_reg->umin_value <<= umin_val;
15193 		dst_reg->umax_value <<= umax_val;
15194 	}
15195 }
15196 
15197 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
15198 			       struct bpf_reg_state *src_reg)
15199 {
15200 	u64 umax_val = src_reg->umax_value;
15201 	u64 umin_val = src_reg->umin_value;
15202 
15203 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
15204 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
15205 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15206 
15207 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
15208 	/* We may learn something more from the var_off */
15209 	__update_reg_bounds(dst_reg);
15210 }
15211 
15212 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
15213 				 struct bpf_reg_state *src_reg)
15214 {
15215 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15216 	u32 umax_val = src_reg->u32_max_value;
15217 	u32 umin_val = src_reg->u32_min_value;
15218 
15219 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15220 	 * be negative, then either:
15221 	 * 1) src_reg might be zero, so the sign bit of the result is
15222 	 *    unknown, so we lose our signed bounds
15223 	 * 2) it's known negative, thus the unsigned bounds capture the
15224 	 *    signed bounds
15225 	 * 3) the signed bounds cross zero, so they tell us nothing
15226 	 *    about the result
15227 	 * If the value in dst_reg is known nonnegative, then again the
15228 	 * unsigned bounds capture the signed bounds.
15229 	 * Thus, in all cases it suffices to blow away our signed bounds
15230 	 * and rely on inferring new ones from the unsigned bounds and
15231 	 * var_off of the result.
15232 	 */
15233 	dst_reg->s32_min_value = S32_MIN;
15234 	dst_reg->s32_max_value = S32_MAX;
15235 
15236 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
15237 	dst_reg->u32_min_value >>= umax_val;
15238 	dst_reg->u32_max_value >>= umin_val;
15239 
15240 	__mark_reg64_unbounded(dst_reg);
15241 	__update_reg32_bounds(dst_reg);
15242 }
15243 
15244 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
15245 			       struct bpf_reg_state *src_reg)
15246 {
15247 	u64 umax_val = src_reg->umax_value;
15248 	u64 umin_val = src_reg->umin_value;
15249 
15250 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15251 	 * be negative, then either:
15252 	 * 1) src_reg might be zero, so the sign bit of the result is
15253 	 *    unknown, so we lose our signed bounds
15254 	 * 2) it's known negative, thus the unsigned bounds capture the
15255 	 *    signed bounds
15256 	 * 3) the signed bounds cross zero, so they tell us nothing
15257 	 *    about the result
15258 	 * If the value in dst_reg is known nonnegative, then again the
15259 	 * unsigned bounds capture the signed bounds.
15260 	 * Thus, in all cases it suffices to blow away our signed bounds
15261 	 * and rely on inferring new ones from the unsigned bounds and
15262 	 * var_off of the result.
15263 	 */
15264 	dst_reg->smin_value = S64_MIN;
15265 	dst_reg->smax_value = S64_MAX;
15266 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
15267 	dst_reg->umin_value >>= umax_val;
15268 	dst_reg->umax_value >>= umin_val;
15269 
15270 	/* Its not easy to operate on alu32 bounds here because it depends
15271 	 * on bits being shifted in. Take easy way out and mark unbounded
15272 	 * so we can recalculate later from tnum.
15273 	 */
15274 	__mark_reg32_unbounded(dst_reg);
15275 	__update_reg_bounds(dst_reg);
15276 }
15277 
15278 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
15279 				  struct bpf_reg_state *src_reg)
15280 {
15281 	u64 umin_val = src_reg->u32_min_value;
15282 
15283 	/* Upon reaching here, src_known is true and
15284 	 * umax_val is equal to umin_val.
15285 	 */
15286 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
15287 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
15288 
15289 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
15290 
15291 	/* blow away the dst_reg umin_value/umax_value and rely on
15292 	 * dst_reg var_off to refine the result.
15293 	 */
15294 	dst_reg->u32_min_value = 0;
15295 	dst_reg->u32_max_value = U32_MAX;
15296 
15297 	__mark_reg64_unbounded(dst_reg);
15298 	__update_reg32_bounds(dst_reg);
15299 }
15300 
15301 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
15302 				struct bpf_reg_state *src_reg)
15303 {
15304 	u64 umin_val = src_reg->umin_value;
15305 
15306 	/* Upon reaching here, src_known is true and umax_val is equal
15307 	 * to umin_val.
15308 	 */
15309 	dst_reg->smin_value >>= umin_val;
15310 	dst_reg->smax_value >>= umin_val;
15311 
15312 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
15313 
15314 	/* blow away the dst_reg umin_value/umax_value and rely on
15315 	 * dst_reg var_off to refine the result.
15316 	 */
15317 	dst_reg->umin_value = 0;
15318 	dst_reg->umax_value = U64_MAX;
15319 
15320 	/* Its not easy to operate on alu32 bounds here because it depends
15321 	 * on bits being shifted in from upper 32-bits. Take easy way out
15322 	 * and mark unbounded so we can recalculate later from tnum.
15323 	 */
15324 	__mark_reg32_unbounded(dst_reg);
15325 	__update_reg_bounds(dst_reg);
15326 }
15327 
15328 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
15329 					     const struct bpf_reg_state *src_reg)
15330 {
15331 	bool src_is_const = false;
15332 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
15333 
15334 	if (insn_bitness == 32) {
15335 		if (tnum_subreg_is_const(src_reg->var_off)
15336 		    && src_reg->s32_min_value == src_reg->s32_max_value
15337 		    && src_reg->u32_min_value == src_reg->u32_max_value)
15338 			src_is_const = true;
15339 	} else {
15340 		if (tnum_is_const(src_reg->var_off)
15341 		    && src_reg->smin_value == src_reg->smax_value
15342 		    && src_reg->umin_value == src_reg->umax_value)
15343 			src_is_const = true;
15344 	}
15345 
15346 	switch (BPF_OP(insn->code)) {
15347 	case BPF_ADD:
15348 	case BPF_SUB:
15349 	case BPF_NEG:
15350 	case BPF_AND:
15351 	case BPF_XOR:
15352 	case BPF_OR:
15353 	case BPF_MUL:
15354 		return true;
15355 
15356 	/* Shift operators range is only computable if shift dimension operand
15357 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
15358 	 * includes shifts by a negative number.
15359 	 */
15360 	case BPF_LSH:
15361 	case BPF_RSH:
15362 	case BPF_ARSH:
15363 		return (src_is_const && src_reg->umax_value < insn_bitness);
15364 	default:
15365 		return false;
15366 	}
15367 }
15368 
15369 /* WARNING: This function does calculations on 64-bit values, but the actual
15370  * execution may occur on 32-bit values. Therefore, things like bitshifts
15371  * need extra checks in the 32-bit case.
15372  */
15373 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
15374 				      struct bpf_insn *insn,
15375 				      struct bpf_reg_state *dst_reg,
15376 				      struct bpf_reg_state src_reg)
15377 {
15378 	u8 opcode = BPF_OP(insn->code);
15379 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15380 	int ret;
15381 
15382 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
15383 		__mark_reg_unknown(env, dst_reg);
15384 		return 0;
15385 	}
15386 
15387 	if (sanitize_needed(opcode)) {
15388 		ret = sanitize_val_alu(env, insn);
15389 		if (ret < 0)
15390 			return sanitize_err(env, insn, ret, NULL, NULL);
15391 	}
15392 
15393 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
15394 	 * There are two classes of instructions: The first class we track both
15395 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
15396 	 * greatest amount of precision when alu operations are mixed with jmp32
15397 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
15398 	 * and BPF_OR. This is possible because these ops have fairly easy to
15399 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
15400 	 * See alu32 verifier tests for examples. The second class of
15401 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
15402 	 * with regards to tracking sign/unsigned bounds because the bits may
15403 	 * cross subreg boundaries in the alu64 case. When this happens we mark
15404 	 * the reg unbounded in the subreg bound space and use the resulting
15405 	 * tnum to calculate an approximation of the sign/unsigned bounds.
15406 	 */
15407 	switch (opcode) {
15408 	case BPF_ADD:
15409 		scalar32_min_max_add(dst_reg, &src_reg);
15410 		scalar_min_max_add(dst_reg, &src_reg);
15411 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
15412 		break;
15413 	case BPF_SUB:
15414 		scalar32_min_max_sub(dst_reg, &src_reg);
15415 		scalar_min_max_sub(dst_reg, &src_reg);
15416 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
15417 		break;
15418 	case BPF_NEG:
15419 		env->fake_reg[0] = *dst_reg;
15420 		__mark_reg_known(dst_reg, 0);
15421 		scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
15422 		scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
15423 		dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
15424 		break;
15425 	case BPF_MUL:
15426 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
15427 		scalar32_min_max_mul(dst_reg, &src_reg);
15428 		scalar_min_max_mul(dst_reg, &src_reg);
15429 		break;
15430 	case BPF_AND:
15431 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
15432 		scalar32_min_max_and(dst_reg, &src_reg);
15433 		scalar_min_max_and(dst_reg, &src_reg);
15434 		break;
15435 	case BPF_OR:
15436 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
15437 		scalar32_min_max_or(dst_reg, &src_reg);
15438 		scalar_min_max_or(dst_reg, &src_reg);
15439 		break;
15440 	case BPF_XOR:
15441 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
15442 		scalar32_min_max_xor(dst_reg, &src_reg);
15443 		scalar_min_max_xor(dst_reg, &src_reg);
15444 		break;
15445 	case BPF_LSH:
15446 		if (alu32)
15447 			scalar32_min_max_lsh(dst_reg, &src_reg);
15448 		else
15449 			scalar_min_max_lsh(dst_reg, &src_reg);
15450 		break;
15451 	case BPF_RSH:
15452 		if (alu32)
15453 			scalar32_min_max_rsh(dst_reg, &src_reg);
15454 		else
15455 			scalar_min_max_rsh(dst_reg, &src_reg);
15456 		break;
15457 	case BPF_ARSH:
15458 		if (alu32)
15459 			scalar32_min_max_arsh(dst_reg, &src_reg);
15460 		else
15461 			scalar_min_max_arsh(dst_reg, &src_reg);
15462 		break;
15463 	default:
15464 		break;
15465 	}
15466 
15467 	/* ALU32 ops are zero extended into 64bit register */
15468 	if (alu32)
15469 		zext_32_to_64(dst_reg);
15470 	reg_bounds_sync(dst_reg);
15471 	return 0;
15472 }
15473 
15474 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
15475  * and var_off.
15476  */
15477 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
15478 				   struct bpf_insn *insn)
15479 {
15480 	struct bpf_verifier_state *vstate = env->cur_state;
15481 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
15482 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
15483 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
15484 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15485 	u8 opcode = BPF_OP(insn->code);
15486 	int err;
15487 
15488 	dst_reg = &regs[insn->dst_reg];
15489 	src_reg = NULL;
15490 
15491 	if (dst_reg->type == PTR_TO_ARENA) {
15492 		struct bpf_insn_aux_data *aux = cur_aux(env);
15493 
15494 		if (BPF_CLASS(insn->code) == BPF_ALU64)
15495 			/*
15496 			 * 32-bit operations zero upper bits automatically.
15497 			 * 64-bit operations need to be converted to 32.
15498 			 */
15499 			aux->needs_zext = true;
15500 
15501 		/* Any arithmetic operations are allowed on arena pointers */
15502 		return 0;
15503 	}
15504 
15505 	if (dst_reg->type != SCALAR_VALUE)
15506 		ptr_reg = dst_reg;
15507 
15508 	if (BPF_SRC(insn->code) == BPF_X) {
15509 		src_reg = &regs[insn->src_reg];
15510 		if (src_reg->type != SCALAR_VALUE) {
15511 			if (dst_reg->type != SCALAR_VALUE) {
15512 				/* Combining two pointers by any ALU op yields
15513 				 * an arbitrary scalar. Disallow all math except
15514 				 * pointer subtraction
15515 				 */
15516 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
15517 					mark_reg_unknown(env, regs, insn->dst_reg);
15518 					return 0;
15519 				}
15520 				verbose(env, "R%d pointer %s pointer prohibited\n",
15521 					insn->dst_reg,
15522 					bpf_alu_string[opcode >> 4]);
15523 				return -EACCES;
15524 			} else {
15525 				/* scalar += pointer
15526 				 * This is legal, but we have to reverse our
15527 				 * src/dest handling in computing the range
15528 				 */
15529 				err = mark_chain_precision(env, insn->dst_reg);
15530 				if (err)
15531 					return err;
15532 				return adjust_ptr_min_max_vals(env, insn,
15533 							       src_reg, dst_reg);
15534 			}
15535 		} else if (ptr_reg) {
15536 			/* pointer += scalar */
15537 			err = mark_chain_precision(env, insn->src_reg);
15538 			if (err)
15539 				return err;
15540 			return adjust_ptr_min_max_vals(env, insn,
15541 						       dst_reg, src_reg);
15542 		} else if (dst_reg->precise) {
15543 			/* if dst_reg is precise, src_reg should be precise as well */
15544 			err = mark_chain_precision(env, insn->src_reg);
15545 			if (err)
15546 				return err;
15547 		}
15548 	} else {
15549 		/* Pretend the src is a reg with a known value, since we only
15550 		 * need to be able to read from this state.
15551 		 */
15552 		off_reg.type = SCALAR_VALUE;
15553 		__mark_reg_known(&off_reg, insn->imm);
15554 		src_reg = &off_reg;
15555 		if (ptr_reg) /* pointer += K */
15556 			return adjust_ptr_min_max_vals(env, insn,
15557 						       ptr_reg, src_reg);
15558 	}
15559 
15560 	/* Got here implies adding two SCALAR_VALUEs */
15561 	if (WARN_ON_ONCE(ptr_reg)) {
15562 		print_verifier_state(env, vstate, vstate->curframe, true);
15563 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
15564 		return -EFAULT;
15565 	}
15566 	if (WARN_ON(!src_reg)) {
15567 		print_verifier_state(env, vstate, vstate->curframe, true);
15568 		verbose(env, "verifier internal error: no src_reg\n");
15569 		return -EFAULT;
15570 	}
15571 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
15572 	if (err)
15573 		return err;
15574 	/*
15575 	 * Compilers can generate the code
15576 	 * r1 = r2
15577 	 * r1 += 0x1
15578 	 * if r2 < 1000 goto ...
15579 	 * use r1 in memory access
15580 	 * So for 64-bit alu remember constant delta between r2 and r1 and
15581 	 * update r1 after 'if' condition.
15582 	 */
15583 	if (env->bpf_capable &&
15584 	    BPF_OP(insn->code) == BPF_ADD && !alu32 &&
15585 	    dst_reg->id && is_reg_const(src_reg, false)) {
15586 		u64 val = reg_const_value(src_reg, false);
15587 
15588 		if ((dst_reg->id & BPF_ADD_CONST) ||
15589 		    /* prevent overflow in sync_linked_regs() later */
15590 		    val > (u32)S32_MAX) {
15591 			/*
15592 			 * If the register already went through rX += val
15593 			 * we cannot accumulate another val into rx->off.
15594 			 */
15595 			dst_reg->off = 0;
15596 			dst_reg->id = 0;
15597 		} else {
15598 			dst_reg->id |= BPF_ADD_CONST;
15599 			dst_reg->off = val;
15600 		}
15601 	} else {
15602 		/*
15603 		 * Make sure ID is cleared otherwise dst_reg min/max could be
15604 		 * incorrectly propagated into other registers by sync_linked_regs()
15605 		 */
15606 		dst_reg->id = 0;
15607 	}
15608 	return 0;
15609 }
15610 
15611 /* check validity of 32-bit and 64-bit arithmetic operations */
15612 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
15613 {
15614 	struct bpf_reg_state *regs = cur_regs(env);
15615 	u8 opcode = BPF_OP(insn->code);
15616 	int err;
15617 
15618 	if (opcode == BPF_END || opcode == BPF_NEG) {
15619 		if (opcode == BPF_NEG) {
15620 			if (BPF_SRC(insn->code) != BPF_K ||
15621 			    insn->src_reg != BPF_REG_0 ||
15622 			    insn->off != 0 || insn->imm != 0) {
15623 				verbose(env, "BPF_NEG uses reserved fields\n");
15624 				return -EINVAL;
15625 			}
15626 		} else {
15627 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
15628 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
15629 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
15630 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
15631 				verbose(env, "BPF_END uses reserved fields\n");
15632 				return -EINVAL;
15633 			}
15634 		}
15635 
15636 		/* check src operand */
15637 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15638 		if (err)
15639 			return err;
15640 
15641 		if (is_pointer_value(env, insn->dst_reg)) {
15642 			verbose(env, "R%d pointer arithmetic prohibited\n",
15643 				insn->dst_reg);
15644 			return -EACCES;
15645 		}
15646 
15647 		/* check dest operand */
15648 		if (opcode == BPF_NEG &&
15649 		    regs[insn->dst_reg].type == SCALAR_VALUE) {
15650 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15651 			err = err ?: adjust_scalar_min_max_vals(env, insn,
15652 							 &regs[insn->dst_reg],
15653 							 regs[insn->dst_reg]);
15654 		} else {
15655 			err = check_reg_arg(env, insn->dst_reg, DST_OP);
15656 		}
15657 		if (err)
15658 			return err;
15659 
15660 	} else if (opcode == BPF_MOV) {
15661 
15662 		if (BPF_SRC(insn->code) == BPF_X) {
15663 			if (BPF_CLASS(insn->code) == BPF_ALU) {
15664 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
15665 				    insn->imm) {
15666 					verbose(env, "BPF_MOV uses reserved fields\n");
15667 					return -EINVAL;
15668 				}
15669 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
15670 				if (insn->imm != 1 && insn->imm != 1u << 16) {
15671 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
15672 					return -EINVAL;
15673 				}
15674 				if (!env->prog->aux->arena) {
15675 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
15676 					return -EINVAL;
15677 				}
15678 			} else {
15679 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
15680 				     insn->off != 32) || insn->imm) {
15681 					verbose(env, "BPF_MOV uses reserved fields\n");
15682 					return -EINVAL;
15683 				}
15684 			}
15685 
15686 			/* check src operand */
15687 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15688 			if (err)
15689 				return err;
15690 		} else {
15691 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
15692 				verbose(env, "BPF_MOV uses reserved fields\n");
15693 				return -EINVAL;
15694 			}
15695 		}
15696 
15697 		/* check dest operand, mark as required later */
15698 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15699 		if (err)
15700 			return err;
15701 
15702 		if (BPF_SRC(insn->code) == BPF_X) {
15703 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
15704 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
15705 
15706 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15707 				if (insn->imm) {
15708 					/* off == BPF_ADDR_SPACE_CAST */
15709 					mark_reg_unknown(env, regs, insn->dst_reg);
15710 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
15711 						dst_reg->type = PTR_TO_ARENA;
15712 						/* PTR_TO_ARENA is 32-bit */
15713 						dst_reg->subreg_def = env->insn_idx + 1;
15714 					}
15715 				} else if (insn->off == 0) {
15716 					/* case: R1 = R2
15717 					 * copy register state to dest reg
15718 					 */
15719 					assign_scalar_id_before_mov(env, src_reg);
15720 					copy_register_state(dst_reg, src_reg);
15721 					dst_reg->subreg_def = DEF_NOT_SUBREG;
15722 				} else {
15723 					/* case: R1 = (s8, s16 s32)R2 */
15724 					if (is_pointer_value(env, insn->src_reg)) {
15725 						verbose(env,
15726 							"R%d sign-extension part of pointer\n",
15727 							insn->src_reg);
15728 						return -EACCES;
15729 					} else if (src_reg->type == SCALAR_VALUE) {
15730 						bool no_sext;
15731 
15732 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15733 						if (no_sext)
15734 							assign_scalar_id_before_mov(env, src_reg);
15735 						copy_register_state(dst_reg, src_reg);
15736 						if (!no_sext)
15737 							dst_reg->id = 0;
15738 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
15739 						dst_reg->subreg_def = DEF_NOT_SUBREG;
15740 					} else {
15741 						mark_reg_unknown(env, regs, insn->dst_reg);
15742 					}
15743 				}
15744 			} else {
15745 				/* R1 = (u32) R2 */
15746 				if (is_pointer_value(env, insn->src_reg)) {
15747 					verbose(env,
15748 						"R%d partial copy of pointer\n",
15749 						insn->src_reg);
15750 					return -EACCES;
15751 				} else if (src_reg->type == SCALAR_VALUE) {
15752 					if (insn->off == 0) {
15753 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
15754 
15755 						if (is_src_reg_u32)
15756 							assign_scalar_id_before_mov(env, src_reg);
15757 						copy_register_state(dst_reg, src_reg);
15758 						/* Make sure ID is cleared if src_reg is not in u32
15759 						 * range otherwise dst_reg min/max could be incorrectly
15760 						 * propagated into src_reg by sync_linked_regs()
15761 						 */
15762 						if (!is_src_reg_u32)
15763 							dst_reg->id = 0;
15764 						dst_reg->subreg_def = env->insn_idx + 1;
15765 					} else {
15766 						/* case: W1 = (s8, s16)W2 */
15767 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15768 
15769 						if (no_sext)
15770 							assign_scalar_id_before_mov(env, src_reg);
15771 						copy_register_state(dst_reg, src_reg);
15772 						if (!no_sext)
15773 							dst_reg->id = 0;
15774 						dst_reg->subreg_def = env->insn_idx + 1;
15775 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
15776 					}
15777 				} else {
15778 					mark_reg_unknown(env, regs,
15779 							 insn->dst_reg);
15780 				}
15781 				zext_32_to_64(dst_reg);
15782 				reg_bounds_sync(dst_reg);
15783 			}
15784 		} else {
15785 			/* case: R = imm
15786 			 * remember the value we stored into this reg
15787 			 */
15788 			/* clear any state __mark_reg_known doesn't set */
15789 			mark_reg_unknown(env, regs, insn->dst_reg);
15790 			regs[insn->dst_reg].type = SCALAR_VALUE;
15791 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15792 				__mark_reg_known(regs + insn->dst_reg,
15793 						 insn->imm);
15794 			} else {
15795 				__mark_reg_known(regs + insn->dst_reg,
15796 						 (u32)insn->imm);
15797 			}
15798 		}
15799 
15800 	} else if (opcode > BPF_END) {
15801 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
15802 		return -EINVAL;
15803 
15804 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
15805 
15806 		if (BPF_SRC(insn->code) == BPF_X) {
15807 			if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) ||
15808 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15809 				verbose(env, "BPF_ALU uses reserved fields\n");
15810 				return -EINVAL;
15811 			}
15812 			/* check src1 operand */
15813 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15814 			if (err)
15815 				return err;
15816 		} else {
15817 			if (insn->src_reg != BPF_REG_0 || (insn->off != 0 && insn->off != 1) ||
15818 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15819 				verbose(env, "BPF_ALU uses reserved fields\n");
15820 				return -EINVAL;
15821 			}
15822 		}
15823 
15824 		/* check src2 operand */
15825 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15826 		if (err)
15827 			return err;
15828 
15829 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
15830 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
15831 			verbose(env, "div by zero\n");
15832 			return -EINVAL;
15833 		}
15834 
15835 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
15836 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
15837 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
15838 
15839 			if (insn->imm < 0 || insn->imm >= size) {
15840 				verbose(env, "invalid shift %d\n", insn->imm);
15841 				return -EINVAL;
15842 			}
15843 		}
15844 
15845 		/* check dest operand */
15846 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15847 		err = err ?: adjust_reg_min_max_vals(env, insn);
15848 		if (err)
15849 			return err;
15850 	}
15851 
15852 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
15853 }
15854 
15855 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
15856 				   struct bpf_reg_state *dst_reg,
15857 				   enum bpf_reg_type type,
15858 				   bool range_right_open)
15859 {
15860 	struct bpf_func_state *state;
15861 	struct bpf_reg_state *reg;
15862 	int new_range;
15863 
15864 	if (dst_reg->off < 0 ||
15865 	    (dst_reg->off == 0 && range_right_open))
15866 		/* This doesn't give us any range */
15867 		return;
15868 
15869 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
15870 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
15871 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
15872 		 * than pkt_end, but that's because it's also less than pkt.
15873 		 */
15874 		return;
15875 
15876 	new_range = dst_reg->off;
15877 	if (range_right_open)
15878 		new_range++;
15879 
15880 	/* Examples for register markings:
15881 	 *
15882 	 * pkt_data in dst register:
15883 	 *
15884 	 *   r2 = r3;
15885 	 *   r2 += 8;
15886 	 *   if (r2 > pkt_end) goto <handle exception>
15887 	 *   <access okay>
15888 	 *
15889 	 *   r2 = r3;
15890 	 *   r2 += 8;
15891 	 *   if (r2 < pkt_end) goto <access okay>
15892 	 *   <handle exception>
15893 	 *
15894 	 *   Where:
15895 	 *     r2 == dst_reg, pkt_end == src_reg
15896 	 *     r2=pkt(id=n,off=8,r=0)
15897 	 *     r3=pkt(id=n,off=0,r=0)
15898 	 *
15899 	 * pkt_data in src register:
15900 	 *
15901 	 *   r2 = r3;
15902 	 *   r2 += 8;
15903 	 *   if (pkt_end >= r2) goto <access okay>
15904 	 *   <handle exception>
15905 	 *
15906 	 *   r2 = r3;
15907 	 *   r2 += 8;
15908 	 *   if (pkt_end <= r2) goto <handle exception>
15909 	 *   <access okay>
15910 	 *
15911 	 *   Where:
15912 	 *     pkt_end == dst_reg, r2 == src_reg
15913 	 *     r2=pkt(id=n,off=8,r=0)
15914 	 *     r3=pkt(id=n,off=0,r=0)
15915 	 *
15916 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
15917 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
15918 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
15919 	 * the check.
15920 	 */
15921 
15922 	/* If our ids match, then we must have the same max_value.  And we
15923 	 * don't care about the other reg's fixed offset, since if it's too big
15924 	 * the range won't allow anything.
15925 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
15926 	 */
15927 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15928 		if (reg->type == type && reg->id == dst_reg->id)
15929 			/* keep the maximum range already checked */
15930 			reg->range = max(reg->range, new_range);
15931 	}));
15932 }
15933 
15934 /*
15935  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
15936  */
15937 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15938 				  u8 opcode, bool is_jmp32)
15939 {
15940 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
15941 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
15942 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
15943 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
15944 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
15945 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
15946 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
15947 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
15948 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
15949 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
15950 
15951 	switch (opcode) {
15952 	case BPF_JEQ:
15953 		/* constants, umin/umax and smin/smax checks would be
15954 		 * redundant in this case because they all should match
15955 		 */
15956 		if (tnum_is_const(t1) && tnum_is_const(t2))
15957 			return t1.value == t2.value;
15958 		if (!tnum_overlap(t1, t2))
15959 			return 0;
15960 		/* non-overlapping ranges */
15961 		if (umin1 > umax2 || umax1 < umin2)
15962 			return 0;
15963 		if (smin1 > smax2 || smax1 < smin2)
15964 			return 0;
15965 		if (!is_jmp32) {
15966 			/* if 64-bit ranges are inconclusive, see if we can
15967 			 * utilize 32-bit subrange knowledge to eliminate
15968 			 * branches that can't be taken a priori
15969 			 */
15970 			if (reg1->u32_min_value > reg2->u32_max_value ||
15971 			    reg1->u32_max_value < reg2->u32_min_value)
15972 				return 0;
15973 			if (reg1->s32_min_value > reg2->s32_max_value ||
15974 			    reg1->s32_max_value < reg2->s32_min_value)
15975 				return 0;
15976 		}
15977 		break;
15978 	case BPF_JNE:
15979 		/* constants, umin/umax and smin/smax checks would be
15980 		 * redundant in this case because they all should match
15981 		 */
15982 		if (tnum_is_const(t1) && tnum_is_const(t2))
15983 			return t1.value != t2.value;
15984 		if (!tnum_overlap(t1, t2))
15985 			return 1;
15986 		/* non-overlapping ranges */
15987 		if (umin1 > umax2 || umax1 < umin2)
15988 			return 1;
15989 		if (smin1 > smax2 || smax1 < smin2)
15990 			return 1;
15991 		if (!is_jmp32) {
15992 			/* if 64-bit ranges are inconclusive, see if we can
15993 			 * utilize 32-bit subrange knowledge to eliminate
15994 			 * branches that can't be taken a priori
15995 			 */
15996 			if (reg1->u32_min_value > reg2->u32_max_value ||
15997 			    reg1->u32_max_value < reg2->u32_min_value)
15998 				return 1;
15999 			if (reg1->s32_min_value > reg2->s32_max_value ||
16000 			    reg1->s32_max_value < reg2->s32_min_value)
16001 				return 1;
16002 		}
16003 		break;
16004 	case BPF_JSET:
16005 		if (!is_reg_const(reg2, is_jmp32)) {
16006 			swap(reg1, reg2);
16007 			swap(t1, t2);
16008 		}
16009 		if (!is_reg_const(reg2, is_jmp32))
16010 			return -1;
16011 		if ((~t1.mask & t1.value) & t2.value)
16012 			return 1;
16013 		if (!((t1.mask | t1.value) & t2.value))
16014 			return 0;
16015 		break;
16016 	case BPF_JGT:
16017 		if (umin1 > umax2)
16018 			return 1;
16019 		else if (umax1 <= umin2)
16020 			return 0;
16021 		break;
16022 	case BPF_JSGT:
16023 		if (smin1 > smax2)
16024 			return 1;
16025 		else if (smax1 <= smin2)
16026 			return 0;
16027 		break;
16028 	case BPF_JLT:
16029 		if (umax1 < umin2)
16030 			return 1;
16031 		else if (umin1 >= umax2)
16032 			return 0;
16033 		break;
16034 	case BPF_JSLT:
16035 		if (smax1 < smin2)
16036 			return 1;
16037 		else if (smin1 >= smax2)
16038 			return 0;
16039 		break;
16040 	case BPF_JGE:
16041 		if (umin1 >= umax2)
16042 			return 1;
16043 		else if (umax1 < umin2)
16044 			return 0;
16045 		break;
16046 	case BPF_JSGE:
16047 		if (smin1 >= smax2)
16048 			return 1;
16049 		else if (smax1 < smin2)
16050 			return 0;
16051 		break;
16052 	case BPF_JLE:
16053 		if (umax1 <= umin2)
16054 			return 1;
16055 		else if (umin1 > umax2)
16056 			return 0;
16057 		break;
16058 	case BPF_JSLE:
16059 		if (smax1 <= smin2)
16060 			return 1;
16061 		else if (smin1 > smax2)
16062 			return 0;
16063 		break;
16064 	}
16065 
16066 	return -1;
16067 }
16068 
16069 static int flip_opcode(u32 opcode)
16070 {
16071 	/* How can we transform "a <op> b" into "b <op> a"? */
16072 	static const u8 opcode_flip[16] = {
16073 		/* these stay the same */
16074 		[BPF_JEQ  >> 4] = BPF_JEQ,
16075 		[BPF_JNE  >> 4] = BPF_JNE,
16076 		[BPF_JSET >> 4] = BPF_JSET,
16077 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
16078 		[BPF_JGE  >> 4] = BPF_JLE,
16079 		[BPF_JGT  >> 4] = BPF_JLT,
16080 		[BPF_JLE  >> 4] = BPF_JGE,
16081 		[BPF_JLT  >> 4] = BPF_JGT,
16082 		[BPF_JSGE >> 4] = BPF_JSLE,
16083 		[BPF_JSGT >> 4] = BPF_JSLT,
16084 		[BPF_JSLE >> 4] = BPF_JSGE,
16085 		[BPF_JSLT >> 4] = BPF_JSGT
16086 	};
16087 	return opcode_flip[opcode >> 4];
16088 }
16089 
16090 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
16091 				   struct bpf_reg_state *src_reg,
16092 				   u8 opcode)
16093 {
16094 	struct bpf_reg_state *pkt;
16095 
16096 	if (src_reg->type == PTR_TO_PACKET_END) {
16097 		pkt = dst_reg;
16098 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
16099 		pkt = src_reg;
16100 		opcode = flip_opcode(opcode);
16101 	} else {
16102 		return -1;
16103 	}
16104 
16105 	if (pkt->range >= 0)
16106 		return -1;
16107 
16108 	switch (opcode) {
16109 	case BPF_JLE:
16110 		/* pkt <= pkt_end */
16111 		fallthrough;
16112 	case BPF_JGT:
16113 		/* pkt > pkt_end */
16114 		if (pkt->range == BEYOND_PKT_END)
16115 			/* pkt has at last one extra byte beyond pkt_end */
16116 			return opcode == BPF_JGT;
16117 		break;
16118 	case BPF_JLT:
16119 		/* pkt < pkt_end */
16120 		fallthrough;
16121 	case BPF_JGE:
16122 		/* pkt >= pkt_end */
16123 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
16124 			return opcode == BPF_JGE;
16125 		break;
16126 	}
16127 	return -1;
16128 }
16129 
16130 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
16131  * and return:
16132  *  1 - branch will be taken and "goto target" will be executed
16133  *  0 - branch will not be taken and fall-through to next insn
16134  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
16135  *      range [0,10]
16136  */
16137 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16138 			   u8 opcode, bool is_jmp32)
16139 {
16140 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
16141 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
16142 
16143 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
16144 		u64 val;
16145 
16146 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
16147 		if (!is_reg_const(reg2, is_jmp32)) {
16148 			opcode = flip_opcode(opcode);
16149 			swap(reg1, reg2);
16150 		}
16151 		/* and ensure that reg2 is a constant */
16152 		if (!is_reg_const(reg2, is_jmp32))
16153 			return -1;
16154 
16155 		if (!reg_not_null(reg1))
16156 			return -1;
16157 
16158 		/* If pointer is valid tests against zero will fail so we can
16159 		 * use this to direct branch taken.
16160 		 */
16161 		val = reg_const_value(reg2, is_jmp32);
16162 		if (val != 0)
16163 			return -1;
16164 
16165 		switch (opcode) {
16166 		case BPF_JEQ:
16167 			return 0;
16168 		case BPF_JNE:
16169 			return 1;
16170 		default:
16171 			return -1;
16172 		}
16173 	}
16174 
16175 	/* now deal with two scalars, but not necessarily constants */
16176 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
16177 }
16178 
16179 /* Opcode that corresponds to a *false* branch condition.
16180  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
16181  */
16182 static u8 rev_opcode(u8 opcode)
16183 {
16184 	switch (opcode) {
16185 	case BPF_JEQ:		return BPF_JNE;
16186 	case BPF_JNE:		return BPF_JEQ;
16187 	/* JSET doesn't have it's reverse opcode in BPF, so add
16188 	 * BPF_X flag to denote the reverse of that operation
16189 	 */
16190 	case BPF_JSET:		return BPF_JSET | BPF_X;
16191 	case BPF_JSET | BPF_X:	return BPF_JSET;
16192 	case BPF_JGE:		return BPF_JLT;
16193 	case BPF_JGT:		return BPF_JLE;
16194 	case BPF_JLE:		return BPF_JGT;
16195 	case BPF_JLT:		return BPF_JGE;
16196 	case BPF_JSGE:		return BPF_JSLT;
16197 	case BPF_JSGT:		return BPF_JSLE;
16198 	case BPF_JSLE:		return BPF_JSGT;
16199 	case BPF_JSLT:		return BPF_JSGE;
16200 	default:		return 0;
16201 	}
16202 }
16203 
16204 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
16205 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16206 				u8 opcode, bool is_jmp32)
16207 {
16208 	struct tnum t;
16209 	u64 val;
16210 
16211 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
16212 	switch (opcode) {
16213 	case BPF_JGE:
16214 	case BPF_JGT:
16215 	case BPF_JSGE:
16216 	case BPF_JSGT:
16217 		opcode = flip_opcode(opcode);
16218 		swap(reg1, reg2);
16219 		break;
16220 	default:
16221 		break;
16222 	}
16223 
16224 	switch (opcode) {
16225 	case BPF_JEQ:
16226 		if (is_jmp32) {
16227 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16228 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16229 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16230 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16231 			reg2->u32_min_value = reg1->u32_min_value;
16232 			reg2->u32_max_value = reg1->u32_max_value;
16233 			reg2->s32_min_value = reg1->s32_min_value;
16234 			reg2->s32_max_value = reg1->s32_max_value;
16235 
16236 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
16237 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16238 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
16239 		} else {
16240 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
16241 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16242 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
16243 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16244 			reg2->umin_value = reg1->umin_value;
16245 			reg2->umax_value = reg1->umax_value;
16246 			reg2->smin_value = reg1->smin_value;
16247 			reg2->smax_value = reg1->smax_value;
16248 
16249 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
16250 			reg2->var_off = reg1->var_off;
16251 		}
16252 		break;
16253 	case BPF_JNE:
16254 		if (!is_reg_const(reg2, is_jmp32))
16255 			swap(reg1, reg2);
16256 		if (!is_reg_const(reg2, is_jmp32))
16257 			break;
16258 
16259 		/* try to recompute the bound of reg1 if reg2 is a const and
16260 		 * is exactly the edge of reg1.
16261 		 */
16262 		val = reg_const_value(reg2, is_jmp32);
16263 		if (is_jmp32) {
16264 			/* u32_min_value is not equal to 0xffffffff at this point,
16265 			 * because otherwise u32_max_value is 0xffffffff as well,
16266 			 * in such a case both reg1 and reg2 would be constants,
16267 			 * jump would be predicted and reg_set_min_max() won't
16268 			 * be called.
16269 			 *
16270 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
16271 			 * below.
16272 			 */
16273 			if (reg1->u32_min_value == (u32)val)
16274 				reg1->u32_min_value++;
16275 			if (reg1->u32_max_value == (u32)val)
16276 				reg1->u32_max_value--;
16277 			if (reg1->s32_min_value == (s32)val)
16278 				reg1->s32_min_value++;
16279 			if (reg1->s32_max_value == (s32)val)
16280 				reg1->s32_max_value--;
16281 		} else {
16282 			if (reg1->umin_value == (u64)val)
16283 				reg1->umin_value++;
16284 			if (reg1->umax_value == (u64)val)
16285 				reg1->umax_value--;
16286 			if (reg1->smin_value == (s64)val)
16287 				reg1->smin_value++;
16288 			if (reg1->smax_value == (s64)val)
16289 				reg1->smax_value--;
16290 		}
16291 		break;
16292 	case BPF_JSET:
16293 		if (!is_reg_const(reg2, is_jmp32))
16294 			swap(reg1, reg2);
16295 		if (!is_reg_const(reg2, is_jmp32))
16296 			break;
16297 		val = reg_const_value(reg2, is_jmp32);
16298 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
16299 		 * requires single bit to learn something useful. E.g., if we
16300 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
16301 		 * are actually set? We can learn something definite only if
16302 		 * it's a single-bit value to begin with.
16303 		 *
16304 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
16305 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
16306 		 * bit 1 is set, which we can readily use in adjustments.
16307 		 */
16308 		if (!is_power_of_2(val))
16309 			break;
16310 		if (is_jmp32) {
16311 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
16312 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16313 		} else {
16314 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
16315 		}
16316 		break;
16317 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
16318 		if (!is_reg_const(reg2, is_jmp32))
16319 			swap(reg1, reg2);
16320 		if (!is_reg_const(reg2, is_jmp32))
16321 			break;
16322 		val = reg_const_value(reg2, is_jmp32);
16323 		/* Forget the ranges before narrowing tnums, to avoid invariant
16324 		 * violations if we're on a dead branch.
16325 		 */
16326 		__mark_reg_unbounded(reg1);
16327 		if (is_jmp32) {
16328 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
16329 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16330 		} else {
16331 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
16332 		}
16333 		break;
16334 	case BPF_JLE:
16335 		if (is_jmp32) {
16336 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16337 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16338 		} else {
16339 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16340 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
16341 		}
16342 		break;
16343 	case BPF_JLT:
16344 		if (is_jmp32) {
16345 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
16346 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
16347 		} else {
16348 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
16349 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
16350 		}
16351 		break;
16352 	case BPF_JSLE:
16353 		if (is_jmp32) {
16354 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16355 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16356 		} else {
16357 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16358 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
16359 		}
16360 		break;
16361 	case BPF_JSLT:
16362 		if (is_jmp32) {
16363 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
16364 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
16365 		} else {
16366 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
16367 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
16368 		}
16369 		break;
16370 	default:
16371 		return;
16372 	}
16373 }
16374 
16375 /* Adjusts the register min/max values in the case that the dst_reg and
16376  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
16377  * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
16378  * Technically we can do similar adjustments for pointers to the same object,
16379  * but we don't support that right now.
16380  */
16381 static int reg_set_min_max(struct bpf_verifier_env *env,
16382 			   struct bpf_reg_state *true_reg1,
16383 			   struct bpf_reg_state *true_reg2,
16384 			   struct bpf_reg_state *false_reg1,
16385 			   struct bpf_reg_state *false_reg2,
16386 			   u8 opcode, bool is_jmp32)
16387 {
16388 	int err;
16389 
16390 	/* If either register is a pointer, we can't learn anything about its
16391 	 * variable offset from the compare (unless they were a pointer into
16392 	 * the same object, but we don't bother with that).
16393 	 */
16394 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
16395 		return 0;
16396 
16397 	/* fallthrough (FALSE) branch */
16398 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
16399 	reg_bounds_sync(false_reg1);
16400 	reg_bounds_sync(false_reg2);
16401 
16402 	/* jump (TRUE) branch */
16403 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
16404 	reg_bounds_sync(true_reg1);
16405 	reg_bounds_sync(true_reg2);
16406 
16407 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
16408 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
16409 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
16410 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
16411 	return err;
16412 }
16413 
16414 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
16415 				 struct bpf_reg_state *reg, u32 id,
16416 				 bool is_null)
16417 {
16418 	if (type_may_be_null(reg->type) && reg->id == id &&
16419 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
16420 		/* Old offset (both fixed and variable parts) should have been
16421 		 * known-zero, because we don't allow pointer arithmetic on
16422 		 * pointers that might be NULL. If we see this happening, don't
16423 		 * convert the register.
16424 		 *
16425 		 * But in some cases, some helpers that return local kptrs
16426 		 * advance offset for the returned pointer. In those cases, it
16427 		 * is fine to expect to see reg->off.
16428 		 */
16429 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
16430 			return;
16431 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
16432 		    WARN_ON_ONCE(reg->off))
16433 			return;
16434 
16435 		if (is_null) {
16436 			reg->type = SCALAR_VALUE;
16437 			/* We don't need id and ref_obj_id from this point
16438 			 * onwards anymore, thus we should better reset it,
16439 			 * so that state pruning has chances to take effect.
16440 			 */
16441 			reg->id = 0;
16442 			reg->ref_obj_id = 0;
16443 
16444 			return;
16445 		}
16446 
16447 		mark_ptr_not_null_reg(reg);
16448 
16449 		if (!reg_may_point_to_spin_lock(reg)) {
16450 			/* For not-NULL ptr, reg->ref_obj_id will be reset
16451 			 * in release_reference().
16452 			 *
16453 			 * reg->id is still used by spin_lock ptr. Other
16454 			 * than spin_lock ptr type, reg->id can be reset.
16455 			 */
16456 			reg->id = 0;
16457 		}
16458 	}
16459 }
16460 
16461 /* The logic is similar to find_good_pkt_pointers(), both could eventually
16462  * be folded together at some point.
16463  */
16464 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
16465 				  bool is_null)
16466 {
16467 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
16468 	struct bpf_reg_state *regs = state->regs, *reg;
16469 	u32 ref_obj_id = regs[regno].ref_obj_id;
16470 	u32 id = regs[regno].id;
16471 
16472 	if (ref_obj_id && ref_obj_id == id && is_null)
16473 		/* regs[regno] is in the " == NULL" branch.
16474 		 * No one could have freed the reference state before
16475 		 * doing the NULL check.
16476 		 */
16477 		WARN_ON_ONCE(release_reference_nomark(vstate, id));
16478 
16479 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
16480 		mark_ptr_or_null_reg(state, reg, id, is_null);
16481 	}));
16482 }
16483 
16484 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
16485 				   struct bpf_reg_state *dst_reg,
16486 				   struct bpf_reg_state *src_reg,
16487 				   struct bpf_verifier_state *this_branch,
16488 				   struct bpf_verifier_state *other_branch)
16489 {
16490 	if (BPF_SRC(insn->code) != BPF_X)
16491 		return false;
16492 
16493 	/* Pointers are always 64-bit. */
16494 	if (BPF_CLASS(insn->code) == BPF_JMP32)
16495 		return false;
16496 
16497 	switch (BPF_OP(insn->code)) {
16498 	case BPF_JGT:
16499 		if ((dst_reg->type == PTR_TO_PACKET &&
16500 		     src_reg->type == PTR_TO_PACKET_END) ||
16501 		    (dst_reg->type == PTR_TO_PACKET_META &&
16502 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16503 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
16504 			find_good_pkt_pointers(this_branch, dst_reg,
16505 					       dst_reg->type, false);
16506 			mark_pkt_end(other_branch, insn->dst_reg, true);
16507 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16508 			    src_reg->type == PTR_TO_PACKET) ||
16509 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16510 			    src_reg->type == PTR_TO_PACKET_META)) {
16511 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
16512 			find_good_pkt_pointers(other_branch, src_reg,
16513 					       src_reg->type, true);
16514 			mark_pkt_end(this_branch, insn->src_reg, false);
16515 		} else {
16516 			return false;
16517 		}
16518 		break;
16519 	case BPF_JLT:
16520 		if ((dst_reg->type == PTR_TO_PACKET &&
16521 		     src_reg->type == PTR_TO_PACKET_END) ||
16522 		    (dst_reg->type == PTR_TO_PACKET_META &&
16523 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16524 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
16525 			find_good_pkt_pointers(other_branch, dst_reg,
16526 					       dst_reg->type, true);
16527 			mark_pkt_end(this_branch, insn->dst_reg, false);
16528 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16529 			    src_reg->type == PTR_TO_PACKET) ||
16530 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16531 			    src_reg->type == PTR_TO_PACKET_META)) {
16532 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
16533 			find_good_pkt_pointers(this_branch, src_reg,
16534 					       src_reg->type, false);
16535 			mark_pkt_end(other_branch, insn->src_reg, true);
16536 		} else {
16537 			return false;
16538 		}
16539 		break;
16540 	case BPF_JGE:
16541 		if ((dst_reg->type == PTR_TO_PACKET &&
16542 		     src_reg->type == PTR_TO_PACKET_END) ||
16543 		    (dst_reg->type == PTR_TO_PACKET_META &&
16544 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16545 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
16546 			find_good_pkt_pointers(this_branch, dst_reg,
16547 					       dst_reg->type, true);
16548 			mark_pkt_end(other_branch, insn->dst_reg, false);
16549 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16550 			    src_reg->type == PTR_TO_PACKET) ||
16551 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16552 			    src_reg->type == PTR_TO_PACKET_META)) {
16553 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
16554 			find_good_pkt_pointers(other_branch, src_reg,
16555 					       src_reg->type, false);
16556 			mark_pkt_end(this_branch, insn->src_reg, true);
16557 		} else {
16558 			return false;
16559 		}
16560 		break;
16561 	case BPF_JLE:
16562 		if ((dst_reg->type == PTR_TO_PACKET &&
16563 		     src_reg->type == PTR_TO_PACKET_END) ||
16564 		    (dst_reg->type == PTR_TO_PACKET_META &&
16565 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16566 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
16567 			find_good_pkt_pointers(other_branch, dst_reg,
16568 					       dst_reg->type, false);
16569 			mark_pkt_end(this_branch, insn->dst_reg, true);
16570 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16571 			    src_reg->type == PTR_TO_PACKET) ||
16572 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16573 			    src_reg->type == PTR_TO_PACKET_META)) {
16574 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
16575 			find_good_pkt_pointers(this_branch, src_reg,
16576 					       src_reg->type, true);
16577 			mark_pkt_end(other_branch, insn->src_reg, false);
16578 		} else {
16579 			return false;
16580 		}
16581 		break;
16582 	default:
16583 		return false;
16584 	}
16585 
16586 	return true;
16587 }
16588 
16589 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
16590 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
16591 {
16592 	struct linked_reg *e;
16593 
16594 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
16595 		return;
16596 
16597 	e = linked_regs_push(reg_set);
16598 	if (e) {
16599 		e->frameno = frameno;
16600 		e->is_reg = is_reg;
16601 		e->regno = spi_or_reg;
16602 	} else {
16603 		reg->id = 0;
16604 	}
16605 }
16606 
16607 /* For all R being scalar registers or spilled scalar registers
16608  * in verifier state, save R in linked_regs if R->id == id.
16609  * If there are too many Rs sharing same id, reset id for leftover Rs.
16610  */
16611 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id,
16612 				struct linked_regs *linked_regs)
16613 {
16614 	struct bpf_func_state *func;
16615 	struct bpf_reg_state *reg;
16616 	int i, j;
16617 
16618 	id = id & ~BPF_ADD_CONST;
16619 	for (i = vstate->curframe; i >= 0; i--) {
16620 		func = vstate->frame[i];
16621 		for (j = 0; j < BPF_REG_FP; j++) {
16622 			reg = &func->regs[j];
16623 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
16624 		}
16625 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
16626 			if (!is_spilled_reg(&func->stack[j]))
16627 				continue;
16628 			reg = &func->stack[j].spilled_ptr;
16629 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
16630 		}
16631 	}
16632 }
16633 
16634 /* For all R in linked_regs, copy known_reg range into R
16635  * if R->id == known_reg->id.
16636  */
16637 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg,
16638 			     struct linked_regs *linked_regs)
16639 {
16640 	struct bpf_reg_state fake_reg;
16641 	struct bpf_reg_state *reg;
16642 	struct linked_reg *e;
16643 	int i;
16644 
16645 	for (i = 0; i < linked_regs->cnt; ++i) {
16646 		e = &linked_regs->entries[i];
16647 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
16648 				: &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
16649 		if (reg->type != SCALAR_VALUE || reg == known_reg)
16650 			continue;
16651 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
16652 			continue;
16653 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
16654 		    reg->off == known_reg->off) {
16655 			s32 saved_subreg_def = reg->subreg_def;
16656 
16657 			copy_register_state(reg, known_reg);
16658 			reg->subreg_def = saved_subreg_def;
16659 		} else {
16660 			s32 saved_subreg_def = reg->subreg_def;
16661 			s32 saved_off = reg->off;
16662 
16663 			fake_reg.type = SCALAR_VALUE;
16664 			__mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off);
16665 
16666 			/* reg = known_reg; reg += delta */
16667 			copy_register_state(reg, known_reg);
16668 			/*
16669 			 * Must preserve off, id and add_const flag,
16670 			 * otherwise another sync_linked_regs() will be incorrect.
16671 			 */
16672 			reg->off = saved_off;
16673 			reg->subreg_def = saved_subreg_def;
16674 
16675 			scalar32_min_max_add(reg, &fake_reg);
16676 			scalar_min_max_add(reg, &fake_reg);
16677 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
16678 		}
16679 	}
16680 }
16681 
16682 static int check_cond_jmp_op(struct bpf_verifier_env *env,
16683 			     struct bpf_insn *insn, int *insn_idx)
16684 {
16685 	struct bpf_verifier_state *this_branch = env->cur_state;
16686 	struct bpf_verifier_state *other_branch;
16687 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
16688 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
16689 	struct bpf_reg_state *eq_branch_regs;
16690 	struct linked_regs linked_regs = {};
16691 	u8 opcode = BPF_OP(insn->code);
16692 	int insn_flags = 0;
16693 	bool is_jmp32;
16694 	int pred = -1;
16695 	int err;
16696 
16697 	/* Only conditional jumps are expected to reach here. */
16698 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
16699 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
16700 		return -EINVAL;
16701 	}
16702 
16703 	if (opcode == BPF_JCOND) {
16704 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
16705 		int idx = *insn_idx;
16706 
16707 		if (insn->code != (BPF_JMP | BPF_JCOND) ||
16708 		    insn->src_reg != BPF_MAY_GOTO ||
16709 		    insn->dst_reg || insn->imm) {
16710 			verbose(env, "invalid may_goto imm %d\n", insn->imm);
16711 			return -EINVAL;
16712 		}
16713 		prev_st = find_prev_entry(env, cur_st->parent, idx);
16714 
16715 		/* branch out 'fallthrough' insn as a new state to explore */
16716 		queued_st = push_stack(env, idx + 1, idx, false);
16717 		if (!queued_st)
16718 			return -ENOMEM;
16719 
16720 		queued_st->may_goto_depth++;
16721 		if (prev_st)
16722 			widen_imprecise_scalars(env, prev_st, queued_st);
16723 		*insn_idx += insn->off;
16724 		return 0;
16725 	}
16726 
16727 	/* check src2 operand */
16728 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16729 	if (err)
16730 		return err;
16731 
16732 	dst_reg = &regs[insn->dst_reg];
16733 	if (BPF_SRC(insn->code) == BPF_X) {
16734 		if (insn->imm != 0) {
16735 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16736 			return -EINVAL;
16737 		}
16738 
16739 		/* check src1 operand */
16740 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
16741 		if (err)
16742 			return err;
16743 
16744 		src_reg = &regs[insn->src_reg];
16745 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
16746 		    is_pointer_value(env, insn->src_reg)) {
16747 			verbose(env, "R%d pointer comparison prohibited\n",
16748 				insn->src_reg);
16749 			return -EACCES;
16750 		}
16751 
16752 		if (src_reg->type == PTR_TO_STACK)
16753 			insn_flags |= INSN_F_SRC_REG_STACK;
16754 		if (dst_reg->type == PTR_TO_STACK)
16755 			insn_flags |= INSN_F_DST_REG_STACK;
16756 	} else {
16757 		if (insn->src_reg != BPF_REG_0) {
16758 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16759 			return -EINVAL;
16760 		}
16761 		src_reg = &env->fake_reg[0];
16762 		memset(src_reg, 0, sizeof(*src_reg));
16763 		src_reg->type = SCALAR_VALUE;
16764 		__mark_reg_known(src_reg, insn->imm);
16765 
16766 		if (dst_reg->type == PTR_TO_STACK)
16767 			insn_flags |= INSN_F_DST_REG_STACK;
16768 	}
16769 
16770 	if (insn_flags) {
16771 		err = push_jmp_history(env, this_branch, insn_flags, 0);
16772 		if (err)
16773 			return err;
16774 	}
16775 
16776 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
16777 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
16778 	if (pred >= 0) {
16779 		/* If we get here with a dst_reg pointer type it is because
16780 		 * above is_branch_taken() special cased the 0 comparison.
16781 		 */
16782 		if (!__is_pointer_value(false, dst_reg))
16783 			err = mark_chain_precision(env, insn->dst_reg);
16784 		if (BPF_SRC(insn->code) == BPF_X && !err &&
16785 		    !__is_pointer_value(false, src_reg))
16786 			err = mark_chain_precision(env, insn->src_reg);
16787 		if (err)
16788 			return err;
16789 	}
16790 
16791 	if (pred == 1) {
16792 		/* Only follow the goto, ignore fall-through. If needed, push
16793 		 * the fall-through branch for simulation under speculative
16794 		 * execution.
16795 		 */
16796 		if (!env->bypass_spec_v1 &&
16797 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
16798 					       *insn_idx))
16799 			return -EFAULT;
16800 		if (env->log.level & BPF_LOG_LEVEL)
16801 			print_insn_state(env, this_branch, this_branch->curframe);
16802 		*insn_idx += insn->off;
16803 		return 0;
16804 	} else if (pred == 0) {
16805 		/* Only follow the fall-through branch, since that's where the
16806 		 * program will go. If needed, push the goto branch for
16807 		 * simulation under speculative execution.
16808 		 */
16809 		if (!env->bypass_spec_v1 &&
16810 		    !sanitize_speculative_path(env, insn,
16811 					       *insn_idx + insn->off + 1,
16812 					       *insn_idx))
16813 			return -EFAULT;
16814 		if (env->log.level & BPF_LOG_LEVEL)
16815 			print_insn_state(env, this_branch, this_branch->curframe);
16816 		return 0;
16817 	}
16818 
16819 	/* Push scalar registers sharing same ID to jump history,
16820 	 * do this before creating 'other_branch', so that both
16821 	 * 'this_branch' and 'other_branch' share this history
16822 	 * if parent state is created.
16823 	 */
16824 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
16825 		collect_linked_regs(this_branch, src_reg->id, &linked_regs);
16826 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
16827 		collect_linked_regs(this_branch, dst_reg->id, &linked_regs);
16828 	if (linked_regs.cnt > 1) {
16829 		err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs));
16830 		if (err)
16831 			return err;
16832 	}
16833 
16834 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
16835 				  false);
16836 	if (!other_branch)
16837 		return -EFAULT;
16838 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
16839 
16840 	if (BPF_SRC(insn->code) == BPF_X) {
16841 		err = reg_set_min_max(env,
16842 				      &other_branch_regs[insn->dst_reg],
16843 				      &other_branch_regs[insn->src_reg],
16844 				      dst_reg, src_reg, opcode, is_jmp32);
16845 	} else /* BPF_SRC(insn->code) == BPF_K */ {
16846 		/* reg_set_min_max() can mangle the fake_reg. Make a copy
16847 		 * so that these are two different memory locations. The
16848 		 * src_reg is not used beyond here in context of K.
16849 		 */
16850 		memcpy(&env->fake_reg[1], &env->fake_reg[0],
16851 		       sizeof(env->fake_reg[0]));
16852 		err = reg_set_min_max(env,
16853 				      &other_branch_regs[insn->dst_reg],
16854 				      &env->fake_reg[0],
16855 				      dst_reg, &env->fake_reg[1],
16856 				      opcode, is_jmp32);
16857 	}
16858 	if (err)
16859 		return err;
16860 
16861 	if (BPF_SRC(insn->code) == BPF_X &&
16862 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
16863 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
16864 		sync_linked_regs(this_branch, src_reg, &linked_regs);
16865 		sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs);
16866 	}
16867 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
16868 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
16869 		sync_linked_regs(this_branch, dst_reg, &linked_regs);
16870 		sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs);
16871 	}
16872 
16873 	/* if one pointer register is compared to another pointer
16874 	 * register check if PTR_MAYBE_NULL could be lifted.
16875 	 * E.g. register A - maybe null
16876 	 *      register B - not null
16877 	 * for JNE A, B, ... - A is not null in the false branch;
16878 	 * for JEQ A, B, ... - A is not null in the true branch.
16879 	 *
16880 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
16881 	 * not need to be null checked by the BPF program, i.e.,
16882 	 * could be null even without PTR_MAYBE_NULL marking, so
16883 	 * only propagate nullness when neither reg is that type.
16884 	 */
16885 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
16886 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
16887 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
16888 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
16889 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
16890 		eq_branch_regs = NULL;
16891 		switch (opcode) {
16892 		case BPF_JEQ:
16893 			eq_branch_regs = other_branch_regs;
16894 			break;
16895 		case BPF_JNE:
16896 			eq_branch_regs = regs;
16897 			break;
16898 		default:
16899 			/* do nothing */
16900 			break;
16901 		}
16902 		if (eq_branch_regs) {
16903 			if (type_may_be_null(src_reg->type))
16904 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
16905 			else
16906 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
16907 		}
16908 	}
16909 
16910 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
16911 	 * NOTE: these optimizations below are related with pointer comparison
16912 	 *       which will never be JMP32.
16913 	 */
16914 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
16915 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
16916 	    type_may_be_null(dst_reg->type)) {
16917 		/* Mark all identical registers in each branch as either
16918 		 * safe or unknown depending R == 0 or R != 0 conditional.
16919 		 */
16920 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
16921 				      opcode == BPF_JNE);
16922 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
16923 				      opcode == BPF_JEQ);
16924 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
16925 					   this_branch, other_branch) &&
16926 		   is_pointer_value(env, insn->dst_reg)) {
16927 		verbose(env, "R%d pointer comparison prohibited\n",
16928 			insn->dst_reg);
16929 		return -EACCES;
16930 	}
16931 	if (env->log.level & BPF_LOG_LEVEL)
16932 		print_insn_state(env, this_branch, this_branch->curframe);
16933 	return 0;
16934 }
16935 
16936 /* verify BPF_LD_IMM64 instruction */
16937 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
16938 {
16939 	struct bpf_insn_aux_data *aux = cur_aux(env);
16940 	struct bpf_reg_state *regs = cur_regs(env);
16941 	struct bpf_reg_state *dst_reg;
16942 	struct bpf_map *map;
16943 	int err;
16944 
16945 	if (BPF_SIZE(insn->code) != BPF_DW) {
16946 		verbose(env, "invalid BPF_LD_IMM insn\n");
16947 		return -EINVAL;
16948 	}
16949 	if (insn->off != 0) {
16950 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
16951 		return -EINVAL;
16952 	}
16953 
16954 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
16955 	if (err)
16956 		return err;
16957 
16958 	dst_reg = &regs[insn->dst_reg];
16959 	if (insn->src_reg == 0) {
16960 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
16961 
16962 		dst_reg->type = SCALAR_VALUE;
16963 		__mark_reg_known(&regs[insn->dst_reg], imm);
16964 		return 0;
16965 	}
16966 
16967 	/* All special src_reg cases are listed below. From this point onwards
16968 	 * we either succeed and assign a corresponding dst_reg->type after
16969 	 * zeroing the offset, or fail and reject the program.
16970 	 */
16971 	mark_reg_known_zero(env, regs, insn->dst_reg);
16972 
16973 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
16974 		dst_reg->type = aux->btf_var.reg_type;
16975 		switch (base_type(dst_reg->type)) {
16976 		case PTR_TO_MEM:
16977 			dst_reg->mem_size = aux->btf_var.mem_size;
16978 			break;
16979 		case PTR_TO_BTF_ID:
16980 			dst_reg->btf = aux->btf_var.btf;
16981 			dst_reg->btf_id = aux->btf_var.btf_id;
16982 			break;
16983 		default:
16984 			verifier_bug(env, "pseudo btf id: unexpected dst reg type");
16985 			return -EFAULT;
16986 		}
16987 		return 0;
16988 	}
16989 
16990 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
16991 		struct bpf_prog_aux *aux = env->prog->aux;
16992 		u32 subprogno = find_subprog(env,
16993 					     env->insn_idx + insn->imm + 1);
16994 
16995 		if (!aux->func_info) {
16996 			verbose(env, "missing btf func_info\n");
16997 			return -EINVAL;
16998 		}
16999 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
17000 			verbose(env, "callback function not static\n");
17001 			return -EINVAL;
17002 		}
17003 
17004 		dst_reg->type = PTR_TO_FUNC;
17005 		dst_reg->subprogno = subprogno;
17006 		return 0;
17007 	}
17008 
17009 	map = env->used_maps[aux->map_index];
17010 	dst_reg->map_ptr = map;
17011 
17012 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
17013 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
17014 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
17015 			__mark_reg_unknown(env, dst_reg);
17016 			return 0;
17017 		}
17018 		dst_reg->type = PTR_TO_MAP_VALUE;
17019 		dst_reg->off = aux->map_off;
17020 		WARN_ON_ONCE(map->max_entries != 1);
17021 		/* We want reg->id to be same (0) as map_value is not distinct */
17022 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
17023 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
17024 		dst_reg->type = CONST_PTR_TO_MAP;
17025 	} else {
17026 		verifier_bug(env, "unexpected src reg value for ldimm64");
17027 		return -EFAULT;
17028 	}
17029 
17030 	return 0;
17031 }
17032 
17033 static bool may_access_skb(enum bpf_prog_type type)
17034 {
17035 	switch (type) {
17036 	case BPF_PROG_TYPE_SOCKET_FILTER:
17037 	case BPF_PROG_TYPE_SCHED_CLS:
17038 	case BPF_PROG_TYPE_SCHED_ACT:
17039 		return true;
17040 	default:
17041 		return false;
17042 	}
17043 }
17044 
17045 /* verify safety of LD_ABS|LD_IND instructions:
17046  * - they can only appear in the programs where ctx == skb
17047  * - since they are wrappers of function calls, they scratch R1-R5 registers,
17048  *   preserve R6-R9, and store return value into R0
17049  *
17050  * Implicit input:
17051  *   ctx == skb == R6 == CTX
17052  *
17053  * Explicit input:
17054  *   SRC == any register
17055  *   IMM == 32-bit immediate
17056  *
17057  * Output:
17058  *   R0 - 8/16/32-bit skb data converted to cpu endianness
17059  */
17060 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
17061 {
17062 	struct bpf_reg_state *regs = cur_regs(env);
17063 	static const int ctx_reg = BPF_REG_6;
17064 	u8 mode = BPF_MODE(insn->code);
17065 	int i, err;
17066 
17067 	if (!may_access_skb(resolve_prog_type(env->prog))) {
17068 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
17069 		return -EINVAL;
17070 	}
17071 
17072 	if (!env->ops->gen_ld_abs) {
17073 		verifier_bug(env, "gen_ld_abs is null");
17074 		return -EFAULT;
17075 	}
17076 
17077 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
17078 	    BPF_SIZE(insn->code) == BPF_DW ||
17079 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
17080 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
17081 		return -EINVAL;
17082 	}
17083 
17084 	/* check whether implicit source operand (register R6) is readable */
17085 	err = check_reg_arg(env, ctx_reg, SRC_OP);
17086 	if (err)
17087 		return err;
17088 
17089 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
17090 	 * gen_ld_abs() may terminate the program at runtime, leading to
17091 	 * reference leak.
17092 	 */
17093 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
17094 	if (err)
17095 		return err;
17096 
17097 	if (regs[ctx_reg].type != PTR_TO_CTX) {
17098 		verbose(env,
17099 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
17100 		return -EINVAL;
17101 	}
17102 
17103 	if (mode == BPF_IND) {
17104 		/* check explicit source operand */
17105 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
17106 		if (err)
17107 			return err;
17108 	}
17109 
17110 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
17111 	if (err < 0)
17112 		return err;
17113 
17114 	/* reset caller saved regs to unreadable */
17115 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
17116 		mark_reg_not_init(env, regs, caller_saved[i]);
17117 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
17118 	}
17119 
17120 	/* mark destination R0 register as readable, since it contains
17121 	 * the value fetched from the packet.
17122 	 * Already marked as written above.
17123 	 */
17124 	mark_reg_unknown(env, regs, BPF_REG_0);
17125 	/* ld_abs load up to 32-bit skb data. */
17126 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
17127 	return 0;
17128 }
17129 
17130 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
17131 {
17132 	const char *exit_ctx = "At program exit";
17133 	struct tnum enforce_attach_type_range = tnum_unknown;
17134 	const struct bpf_prog *prog = env->prog;
17135 	struct bpf_reg_state *reg = reg_state(env, regno);
17136 	struct bpf_retval_range range = retval_range(0, 1);
17137 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
17138 	int err;
17139 	struct bpf_func_state *frame = env->cur_state->frame[0];
17140 	const bool is_subprog = frame->subprogno;
17141 	bool return_32bit = false;
17142 	const struct btf_type *reg_type, *ret_type = NULL;
17143 
17144 	/* LSM and struct_ops func-ptr's return type could be "void" */
17145 	if (!is_subprog || frame->in_exception_callback_fn) {
17146 		switch (prog_type) {
17147 		case BPF_PROG_TYPE_LSM:
17148 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
17149 				/* See below, can be 0 or 0-1 depending on hook. */
17150 				break;
17151 			if (!prog->aux->attach_func_proto->type)
17152 				return 0;
17153 			break;
17154 		case BPF_PROG_TYPE_STRUCT_OPS:
17155 			if (!prog->aux->attach_func_proto->type)
17156 				return 0;
17157 
17158 			if (frame->in_exception_callback_fn)
17159 				break;
17160 
17161 			/* Allow a struct_ops program to return a referenced kptr if it
17162 			 * matches the operator's return type and is in its unmodified
17163 			 * form. A scalar zero (i.e., a null pointer) is also allowed.
17164 			 */
17165 			reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL;
17166 			ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
17167 							prog->aux->attach_func_proto->type,
17168 							NULL);
17169 			if (ret_type && ret_type == reg_type && reg->ref_obj_id)
17170 				return __check_ptr_off_reg(env, reg, regno, false);
17171 			break;
17172 		default:
17173 			break;
17174 		}
17175 	}
17176 
17177 	/* eBPF calling convention is such that R0 is used
17178 	 * to return the value from eBPF program.
17179 	 * Make sure that it's readable at this time
17180 	 * of bpf_exit, which means that program wrote
17181 	 * something into it earlier
17182 	 */
17183 	err = check_reg_arg(env, regno, SRC_OP);
17184 	if (err)
17185 		return err;
17186 
17187 	if (is_pointer_value(env, regno)) {
17188 		verbose(env, "R%d leaks addr as return value\n", regno);
17189 		return -EACCES;
17190 	}
17191 
17192 	if (frame->in_async_callback_fn) {
17193 		exit_ctx = "At async callback return";
17194 		range = frame->callback_ret_range;
17195 		goto enforce_retval;
17196 	}
17197 
17198 	if (is_subprog && !frame->in_exception_callback_fn) {
17199 		if (reg->type != SCALAR_VALUE) {
17200 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
17201 				regno, reg_type_str(env, reg->type));
17202 			return -EINVAL;
17203 		}
17204 		return 0;
17205 	}
17206 
17207 	switch (prog_type) {
17208 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
17209 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
17210 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
17211 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
17212 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
17213 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
17214 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
17215 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
17216 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
17217 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
17218 			range = retval_range(1, 1);
17219 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
17220 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
17221 			range = retval_range(0, 3);
17222 		break;
17223 	case BPF_PROG_TYPE_CGROUP_SKB:
17224 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
17225 			range = retval_range(0, 3);
17226 			enforce_attach_type_range = tnum_range(2, 3);
17227 		}
17228 		break;
17229 	case BPF_PROG_TYPE_CGROUP_SOCK:
17230 	case BPF_PROG_TYPE_SOCK_OPS:
17231 	case BPF_PROG_TYPE_CGROUP_DEVICE:
17232 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
17233 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
17234 		break;
17235 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17236 		if (!env->prog->aux->attach_btf_id)
17237 			return 0;
17238 		range = retval_range(0, 0);
17239 		break;
17240 	case BPF_PROG_TYPE_TRACING:
17241 		switch (env->prog->expected_attach_type) {
17242 		case BPF_TRACE_FENTRY:
17243 		case BPF_TRACE_FEXIT:
17244 			range = retval_range(0, 0);
17245 			break;
17246 		case BPF_TRACE_RAW_TP:
17247 		case BPF_MODIFY_RETURN:
17248 			return 0;
17249 		case BPF_TRACE_ITER:
17250 			break;
17251 		default:
17252 			return -ENOTSUPP;
17253 		}
17254 		break;
17255 	case BPF_PROG_TYPE_KPROBE:
17256 		switch (env->prog->expected_attach_type) {
17257 		case BPF_TRACE_KPROBE_SESSION:
17258 		case BPF_TRACE_UPROBE_SESSION:
17259 			range = retval_range(0, 1);
17260 			break;
17261 		default:
17262 			return 0;
17263 		}
17264 		break;
17265 	case BPF_PROG_TYPE_SK_LOOKUP:
17266 		range = retval_range(SK_DROP, SK_PASS);
17267 		break;
17268 
17269 	case BPF_PROG_TYPE_LSM:
17270 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
17271 			/* no range found, any return value is allowed */
17272 			if (!get_func_retval_range(env->prog, &range))
17273 				return 0;
17274 			/* no restricted range, any return value is allowed */
17275 			if (range.minval == S32_MIN && range.maxval == S32_MAX)
17276 				return 0;
17277 			return_32bit = true;
17278 		} else if (!env->prog->aux->attach_func_proto->type) {
17279 			/* Make sure programs that attach to void
17280 			 * hooks don't try to modify return value.
17281 			 */
17282 			range = retval_range(1, 1);
17283 		}
17284 		break;
17285 
17286 	case BPF_PROG_TYPE_NETFILTER:
17287 		range = retval_range(NF_DROP, NF_ACCEPT);
17288 		break;
17289 	case BPF_PROG_TYPE_STRUCT_OPS:
17290 		if (!ret_type)
17291 			return 0;
17292 		range = retval_range(0, 0);
17293 		break;
17294 	case BPF_PROG_TYPE_EXT:
17295 		/* freplace program can return anything as its return value
17296 		 * depends on the to-be-replaced kernel func or bpf program.
17297 		 */
17298 	default:
17299 		return 0;
17300 	}
17301 
17302 enforce_retval:
17303 	if (reg->type != SCALAR_VALUE) {
17304 		verbose(env, "%s the register R%d is not a known value (%s)\n",
17305 			exit_ctx, regno, reg_type_str(env, reg->type));
17306 		return -EINVAL;
17307 	}
17308 
17309 	err = mark_chain_precision(env, regno);
17310 	if (err)
17311 		return err;
17312 
17313 	if (!retval_range_within(range, reg, return_32bit)) {
17314 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
17315 		if (!is_subprog &&
17316 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
17317 		    prog_type == BPF_PROG_TYPE_LSM &&
17318 		    !prog->aux->attach_func_proto->type)
17319 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
17320 		return -EINVAL;
17321 	}
17322 
17323 	if (!tnum_is_unknown(enforce_attach_type_range) &&
17324 	    tnum_in(enforce_attach_type_range, reg->var_off))
17325 		env->prog->enforce_expected_attach_type = 1;
17326 	return 0;
17327 }
17328 
17329 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off)
17330 {
17331 	struct bpf_subprog_info *subprog;
17332 
17333 	subprog = bpf_find_containing_subprog(env, off);
17334 	subprog->changes_pkt_data = true;
17335 }
17336 
17337 static void mark_subprog_might_sleep(struct bpf_verifier_env *env, int off)
17338 {
17339 	struct bpf_subprog_info *subprog;
17340 
17341 	subprog = bpf_find_containing_subprog(env, off);
17342 	subprog->might_sleep = true;
17343 }
17344 
17345 /* 't' is an index of a call-site.
17346  * 'w' is a callee entry point.
17347  * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED.
17348  * Rely on DFS traversal order and absence of recursive calls to guarantee that
17349  * callee's change_pkt_data marks would be correct at that moment.
17350  */
17351 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)
17352 {
17353 	struct bpf_subprog_info *caller, *callee;
17354 
17355 	caller = bpf_find_containing_subprog(env, t);
17356 	callee = bpf_find_containing_subprog(env, w);
17357 	caller->changes_pkt_data |= callee->changes_pkt_data;
17358 	caller->might_sleep |= callee->might_sleep;
17359 }
17360 
17361 /* non-recursive DFS pseudo code
17362  * 1  procedure DFS-iterative(G,v):
17363  * 2      label v as discovered
17364  * 3      let S be a stack
17365  * 4      S.push(v)
17366  * 5      while S is not empty
17367  * 6            t <- S.peek()
17368  * 7            if t is what we're looking for:
17369  * 8                return t
17370  * 9            for all edges e in G.adjacentEdges(t) do
17371  * 10               if edge e is already labelled
17372  * 11                   continue with the next edge
17373  * 12               w <- G.adjacentVertex(t,e)
17374  * 13               if vertex w is not discovered and not explored
17375  * 14                   label e as tree-edge
17376  * 15                   label w as discovered
17377  * 16                   S.push(w)
17378  * 17                   continue at 5
17379  * 18               else if vertex w is discovered
17380  * 19                   label e as back-edge
17381  * 20               else
17382  * 21                   // vertex w is explored
17383  * 22                   label e as forward- or cross-edge
17384  * 23           label t as explored
17385  * 24           S.pop()
17386  *
17387  * convention:
17388  * 0x10 - discovered
17389  * 0x11 - discovered and fall-through edge labelled
17390  * 0x12 - discovered and fall-through and branch edges labelled
17391  * 0x20 - explored
17392  */
17393 
17394 enum {
17395 	DISCOVERED = 0x10,
17396 	EXPLORED = 0x20,
17397 	FALLTHROUGH = 1,
17398 	BRANCH = 2,
17399 };
17400 
17401 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
17402 {
17403 	env->insn_aux_data[idx].prune_point = true;
17404 }
17405 
17406 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
17407 {
17408 	return env->insn_aux_data[insn_idx].prune_point;
17409 }
17410 
17411 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
17412 {
17413 	env->insn_aux_data[idx].force_checkpoint = true;
17414 }
17415 
17416 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
17417 {
17418 	return env->insn_aux_data[insn_idx].force_checkpoint;
17419 }
17420 
17421 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
17422 {
17423 	env->insn_aux_data[idx].calls_callback = true;
17424 }
17425 
17426 bool bpf_calls_callback(struct bpf_verifier_env *env, int insn_idx)
17427 {
17428 	return env->insn_aux_data[insn_idx].calls_callback;
17429 }
17430 
17431 enum {
17432 	DONE_EXPLORING = 0,
17433 	KEEP_EXPLORING = 1,
17434 };
17435 
17436 /* t, w, e - match pseudo-code above:
17437  * t - index of current instruction
17438  * w - next instruction
17439  * e - edge
17440  */
17441 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
17442 {
17443 	int *insn_stack = env->cfg.insn_stack;
17444 	int *insn_state = env->cfg.insn_state;
17445 
17446 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
17447 		return DONE_EXPLORING;
17448 
17449 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
17450 		return DONE_EXPLORING;
17451 
17452 	if (w < 0 || w >= env->prog->len) {
17453 		verbose_linfo(env, t, "%d: ", t);
17454 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
17455 		return -EINVAL;
17456 	}
17457 
17458 	if (e == BRANCH) {
17459 		/* mark branch target for state pruning */
17460 		mark_prune_point(env, w);
17461 		mark_jmp_point(env, w);
17462 	}
17463 
17464 	if (insn_state[w] == 0) {
17465 		/* tree-edge */
17466 		insn_state[t] = DISCOVERED | e;
17467 		insn_state[w] = DISCOVERED;
17468 		if (env->cfg.cur_stack >= env->prog->len)
17469 			return -E2BIG;
17470 		insn_stack[env->cfg.cur_stack++] = w;
17471 		return KEEP_EXPLORING;
17472 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
17473 		if (env->bpf_capable)
17474 			return DONE_EXPLORING;
17475 		verbose_linfo(env, t, "%d: ", t);
17476 		verbose_linfo(env, w, "%d: ", w);
17477 		verbose(env, "back-edge from insn %d to %d\n", t, w);
17478 		return -EINVAL;
17479 	} else if (insn_state[w] == EXPLORED) {
17480 		/* forward- or cross-edge */
17481 		insn_state[t] = DISCOVERED | e;
17482 	} else {
17483 		verifier_bug(env, "insn state internal bug");
17484 		return -EFAULT;
17485 	}
17486 	return DONE_EXPLORING;
17487 }
17488 
17489 static int visit_func_call_insn(int t, struct bpf_insn *insns,
17490 				struct bpf_verifier_env *env,
17491 				bool visit_callee)
17492 {
17493 	int ret, insn_sz;
17494 	int w;
17495 
17496 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
17497 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
17498 	if (ret)
17499 		return ret;
17500 
17501 	mark_prune_point(env, t + insn_sz);
17502 	/* when we exit from subprog, we need to record non-linear history */
17503 	mark_jmp_point(env, t + insn_sz);
17504 
17505 	if (visit_callee) {
17506 		w = t + insns[t].imm + 1;
17507 		mark_prune_point(env, t);
17508 		merge_callee_effects(env, t, w);
17509 		ret = push_insn(t, w, BRANCH, env);
17510 	}
17511 	return ret;
17512 }
17513 
17514 /* Bitmask with 1s for all caller saved registers */
17515 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
17516 
17517 /* True if do_misc_fixups() replaces calls to helper number 'imm',
17518  * replacement patch is presumed to follow bpf_fastcall contract
17519  * (see mark_fastcall_pattern_for_call() below).
17520  */
17521 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
17522 {
17523 	switch (imm) {
17524 #ifdef CONFIG_X86_64
17525 	case BPF_FUNC_get_smp_processor_id:
17526 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
17527 #endif
17528 	default:
17529 		return false;
17530 	}
17531 }
17532 
17533 struct call_summary {
17534 	u8 num_params;
17535 	bool is_void;
17536 	bool fastcall;
17537 };
17538 
17539 /* If @call is a kfunc or helper call, fills @cs and returns true,
17540  * otherwise returns false.
17541  */
17542 static bool get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
17543 			     struct call_summary *cs)
17544 {
17545 	struct bpf_kfunc_call_arg_meta meta;
17546 	const struct bpf_func_proto *fn;
17547 	int i;
17548 
17549 	if (bpf_helper_call(call)) {
17550 
17551 		if (get_helper_proto(env, call->imm, &fn) < 0)
17552 			/* error would be reported later */
17553 			return false;
17554 		cs->fastcall = fn->allow_fastcall &&
17555 			       (verifier_inlines_helper_call(env, call->imm) ||
17556 				bpf_jit_inlines_helper_call(call->imm));
17557 		cs->is_void = fn->ret_type == RET_VOID;
17558 		cs->num_params = 0;
17559 		for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
17560 			if (fn->arg_type[i] == ARG_DONTCARE)
17561 				break;
17562 			cs->num_params++;
17563 		}
17564 		return true;
17565 	}
17566 
17567 	if (bpf_pseudo_kfunc_call(call)) {
17568 		int err;
17569 
17570 		err = fetch_kfunc_meta(env, call, &meta, NULL);
17571 		if (err < 0)
17572 			/* error would be reported later */
17573 			return false;
17574 		cs->num_params = btf_type_vlen(meta.func_proto);
17575 		cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
17576 		cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
17577 		return true;
17578 	}
17579 
17580 	return false;
17581 }
17582 
17583 /* LLVM define a bpf_fastcall function attribute.
17584  * This attribute means that function scratches only some of
17585  * the caller saved registers defined by ABI.
17586  * For BPF the set of such registers could be defined as follows:
17587  * - R0 is scratched only if function is non-void;
17588  * - R1-R5 are scratched only if corresponding parameter type is defined
17589  *   in the function prototype.
17590  *
17591  * The contract between kernel and clang allows to simultaneously use
17592  * such functions and maintain backwards compatibility with old
17593  * kernels that don't understand bpf_fastcall calls:
17594  *
17595  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
17596  *   registers are not scratched by the call;
17597  *
17598  * - as a post-processing step, clang visits each bpf_fastcall call and adds
17599  *   spill/fill for every live r0-r5;
17600  *
17601  * - stack offsets used for the spill/fill are allocated as lowest
17602  *   stack offsets in whole function and are not used for any other
17603  *   purposes;
17604  *
17605  * - when kernel loads a program, it looks for such patterns
17606  *   (bpf_fastcall function surrounded by spills/fills) and checks if
17607  *   spill/fill stack offsets are used exclusively in fastcall patterns;
17608  *
17609  * - if so, and if verifier or current JIT inlines the call to the
17610  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
17611  *   spill/fill pairs;
17612  *
17613  * - when old kernel loads a program, presence of spill/fill pairs
17614  *   keeps BPF program valid, albeit slightly less efficient.
17615  *
17616  * For example:
17617  *
17618  *   r1 = 1;
17619  *   r2 = 2;
17620  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
17621  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
17622  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
17623  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
17624  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
17625  *   r0 = r1;                            exit;
17626  *   r0 += r2;
17627  *   exit;
17628  *
17629  * The purpose of mark_fastcall_pattern_for_call is to:
17630  * - look for such patterns;
17631  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
17632  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
17633  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
17634  *   at which bpf_fastcall spill/fill stack slots start;
17635  * - update env->subprog_info[*]->keep_fastcall_stack.
17636  *
17637  * The .fastcall_pattern and .fastcall_stack_off are used by
17638  * check_fastcall_stack_contract() to check if every stack access to
17639  * fastcall spill/fill stack slot originates from spill/fill
17640  * instructions, members of fastcall patterns.
17641  *
17642  * If such condition holds true for a subprogram, fastcall patterns could
17643  * be rewritten by remove_fastcall_spills_fills().
17644  * Otherwise bpf_fastcall patterns are not changed in the subprogram
17645  * (code, presumably, generated by an older clang version).
17646  *
17647  * For example, it is *not* safe to remove spill/fill below:
17648  *
17649  *   r1 = 1;
17650  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
17651  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
17652  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
17653  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
17654  *   r0 += r1;                           exit;
17655  *   exit;
17656  */
17657 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
17658 					   struct bpf_subprog_info *subprog,
17659 					   int insn_idx, s16 lowest_off)
17660 {
17661 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
17662 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
17663 	u32 clobbered_regs_mask;
17664 	struct call_summary cs;
17665 	u32 expected_regs_mask;
17666 	s16 off;
17667 	int i;
17668 
17669 	if (!get_call_summary(env, call, &cs))
17670 		return;
17671 
17672 	/* A bitmask specifying which caller saved registers are clobbered
17673 	 * by a call to a helper/kfunc *as if* this helper/kfunc follows
17674 	 * bpf_fastcall contract:
17675 	 * - includes R0 if function is non-void;
17676 	 * - includes R1-R5 if corresponding parameter has is described
17677 	 *   in the function prototype.
17678 	 */
17679 	clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0);
17680 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
17681 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
17682 
17683 	/* match pairs of form:
17684 	 *
17685 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
17686 	 * ...
17687 	 * call %[to_be_inlined]
17688 	 * ...
17689 	 * rX = *(u64 *)(r10 - Y)
17690 	 */
17691 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
17692 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
17693 			break;
17694 		stx = &insns[insn_idx - i];
17695 		ldx = &insns[insn_idx + i];
17696 		/* must be a stack spill/fill pair */
17697 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17698 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
17699 		    stx->dst_reg != BPF_REG_10 ||
17700 		    ldx->src_reg != BPF_REG_10)
17701 			break;
17702 		/* must be a spill/fill for the same reg */
17703 		if (stx->src_reg != ldx->dst_reg)
17704 			break;
17705 		/* must be one of the previously unseen registers */
17706 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
17707 			break;
17708 		/* must be a spill/fill for the same expected offset,
17709 		 * no need to check offset alignment, BPF_DW stack access
17710 		 * is always 8-byte aligned.
17711 		 */
17712 		if (stx->off != off || ldx->off != off)
17713 			break;
17714 		expected_regs_mask &= ~BIT(stx->src_reg);
17715 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
17716 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
17717 	}
17718 	if (i == 1)
17719 		return;
17720 
17721 	/* Conditionally set 'fastcall_spills_num' to allow forward
17722 	 * compatibility when more helper functions are marked as
17723 	 * bpf_fastcall at compile time than current kernel supports, e.g:
17724 	 *
17725 	 *   1: *(u64 *)(r10 - 8) = r1
17726 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
17727 	 *   3: r1 = *(u64 *)(r10 - 8)
17728 	 *   4: *(u64 *)(r10 - 8) = r1
17729 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
17730 	 *   6: r1 = *(u64 *)(r10 - 8)
17731 	 *
17732 	 * There is no need to block bpf_fastcall rewrite for such program.
17733 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
17734 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
17735 	 * does not remove spill/fill pair {4,6}.
17736 	 */
17737 	if (cs.fastcall)
17738 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
17739 	else
17740 		subprog->keep_fastcall_stack = 1;
17741 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
17742 }
17743 
17744 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
17745 {
17746 	struct bpf_subprog_info *subprog = env->subprog_info;
17747 	struct bpf_insn *insn;
17748 	s16 lowest_off;
17749 	int s, i;
17750 
17751 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
17752 		/* find lowest stack spill offset used in this subprog */
17753 		lowest_off = 0;
17754 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17755 			insn = env->prog->insnsi + i;
17756 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17757 			    insn->dst_reg != BPF_REG_10)
17758 				continue;
17759 			lowest_off = min(lowest_off, insn->off);
17760 		}
17761 		/* use this offset to find fastcall patterns */
17762 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17763 			insn = env->prog->insnsi + i;
17764 			if (insn->code != (BPF_JMP | BPF_CALL))
17765 				continue;
17766 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
17767 		}
17768 	}
17769 	return 0;
17770 }
17771 
17772 /* Visits the instruction at index t and returns one of the following:
17773  *  < 0 - an error occurred
17774  *  DONE_EXPLORING - the instruction was fully explored
17775  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
17776  */
17777 static int visit_insn(int t, struct bpf_verifier_env *env)
17778 {
17779 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
17780 	int ret, off, insn_sz;
17781 
17782 	if (bpf_pseudo_func(insn))
17783 		return visit_func_call_insn(t, insns, env, true);
17784 
17785 	/* All non-branch instructions have a single fall-through edge. */
17786 	if (BPF_CLASS(insn->code) != BPF_JMP &&
17787 	    BPF_CLASS(insn->code) != BPF_JMP32) {
17788 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
17789 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
17790 	}
17791 
17792 	switch (BPF_OP(insn->code)) {
17793 	case BPF_EXIT:
17794 		return DONE_EXPLORING;
17795 
17796 	case BPF_CALL:
17797 		if (is_async_callback_calling_insn(insn))
17798 			/* Mark this call insn as a prune point to trigger
17799 			 * is_state_visited() check before call itself is
17800 			 * processed by __check_func_call(). Otherwise new
17801 			 * async state will be pushed for further exploration.
17802 			 */
17803 			mark_prune_point(env, t);
17804 		/* For functions that invoke callbacks it is not known how many times
17805 		 * callback would be called. Verifier models callback calling functions
17806 		 * by repeatedly visiting callback bodies and returning to origin call
17807 		 * instruction.
17808 		 * In order to stop such iteration verifier needs to identify when a
17809 		 * state identical some state from a previous iteration is reached.
17810 		 * Check below forces creation of checkpoint before callback calling
17811 		 * instruction to allow search for such identical states.
17812 		 */
17813 		if (is_sync_callback_calling_insn(insn)) {
17814 			mark_calls_callback(env, t);
17815 			mark_force_checkpoint(env, t);
17816 			mark_prune_point(env, t);
17817 			mark_jmp_point(env, t);
17818 		}
17819 		if (bpf_helper_call(insn)) {
17820 			const struct bpf_func_proto *fp;
17821 
17822 			ret = get_helper_proto(env, insn->imm, &fp);
17823 			/* If called in a non-sleepable context program will be
17824 			 * rejected anyway, so we should end up with precise
17825 			 * sleepable marks on subprogs, except for dead code
17826 			 * elimination.
17827 			 */
17828 			if (ret == 0 && fp->might_sleep)
17829 				mark_subprog_might_sleep(env, t);
17830 			if (bpf_helper_changes_pkt_data(insn->imm))
17831 				mark_subprog_changes_pkt_data(env, t);
17832 		} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17833 			struct bpf_kfunc_call_arg_meta meta;
17834 
17835 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
17836 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
17837 				mark_prune_point(env, t);
17838 				/* Checking and saving state checkpoints at iter_next() call
17839 				 * is crucial for fast convergence of open-coded iterator loop
17840 				 * logic, so we need to force it. If we don't do that,
17841 				 * is_state_visited() might skip saving a checkpoint, causing
17842 				 * unnecessarily long sequence of not checkpointed
17843 				 * instructions and jumps, leading to exhaustion of jump
17844 				 * history buffer, and potentially other undesired outcomes.
17845 				 * It is expected that with correct open-coded iterators
17846 				 * convergence will happen quickly, so we don't run a risk of
17847 				 * exhausting memory.
17848 				 */
17849 				mark_force_checkpoint(env, t);
17850 			}
17851 			/* Same as helpers, if called in a non-sleepable context
17852 			 * program will be rejected anyway, so we should end up
17853 			 * with precise sleepable marks on subprogs, except for
17854 			 * dead code elimination.
17855 			 */
17856 			if (ret == 0 && is_kfunc_sleepable(&meta))
17857 				mark_subprog_might_sleep(env, t);
17858 			if (ret == 0 && is_kfunc_pkt_changing(&meta))
17859 				mark_subprog_changes_pkt_data(env, t);
17860 		}
17861 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
17862 
17863 	case BPF_JA:
17864 		if (BPF_SRC(insn->code) != BPF_K)
17865 			return -EINVAL;
17866 
17867 		if (BPF_CLASS(insn->code) == BPF_JMP)
17868 			off = insn->off;
17869 		else
17870 			off = insn->imm;
17871 
17872 		/* unconditional jump with single edge */
17873 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
17874 		if (ret)
17875 			return ret;
17876 
17877 		mark_prune_point(env, t + off + 1);
17878 		mark_jmp_point(env, t + off + 1);
17879 
17880 		return ret;
17881 
17882 	default:
17883 		/* conditional jump with two edges */
17884 		mark_prune_point(env, t);
17885 		if (is_may_goto_insn(insn))
17886 			mark_force_checkpoint(env, t);
17887 
17888 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
17889 		if (ret)
17890 			return ret;
17891 
17892 		return push_insn(t, t + insn->off + 1, BRANCH, env);
17893 	}
17894 }
17895 
17896 /* non-recursive depth-first-search to detect loops in BPF program
17897  * loop == back-edge in directed graph
17898  */
17899 static int check_cfg(struct bpf_verifier_env *env)
17900 {
17901 	int insn_cnt = env->prog->len;
17902 	int *insn_stack, *insn_state;
17903 	int ex_insn_beg, i, ret = 0;
17904 
17905 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
17906 	if (!insn_state)
17907 		return -ENOMEM;
17908 
17909 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
17910 	if (!insn_stack) {
17911 		kvfree(insn_state);
17912 		return -ENOMEM;
17913 	}
17914 
17915 	ex_insn_beg = env->exception_callback_subprog
17916 		      ? env->subprog_info[env->exception_callback_subprog].start
17917 		      : 0;
17918 
17919 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
17920 	insn_stack[0] = 0; /* 0 is the first instruction */
17921 	env->cfg.cur_stack = 1;
17922 
17923 walk_cfg:
17924 	while (env->cfg.cur_stack > 0) {
17925 		int t = insn_stack[env->cfg.cur_stack - 1];
17926 
17927 		ret = visit_insn(t, env);
17928 		switch (ret) {
17929 		case DONE_EXPLORING:
17930 			insn_state[t] = EXPLORED;
17931 			env->cfg.cur_stack--;
17932 			break;
17933 		case KEEP_EXPLORING:
17934 			break;
17935 		default:
17936 			if (ret > 0) {
17937 				verifier_bug(env, "visit_insn internal bug");
17938 				ret = -EFAULT;
17939 			}
17940 			goto err_free;
17941 		}
17942 	}
17943 
17944 	if (env->cfg.cur_stack < 0) {
17945 		verifier_bug(env, "pop stack internal bug");
17946 		ret = -EFAULT;
17947 		goto err_free;
17948 	}
17949 
17950 	if (ex_insn_beg && insn_state[ex_insn_beg] != EXPLORED) {
17951 		insn_state[ex_insn_beg] = DISCOVERED;
17952 		insn_stack[0] = ex_insn_beg;
17953 		env->cfg.cur_stack = 1;
17954 		goto walk_cfg;
17955 	}
17956 
17957 	for (i = 0; i < insn_cnt; i++) {
17958 		struct bpf_insn *insn = &env->prog->insnsi[i];
17959 
17960 		if (insn_state[i] != EXPLORED) {
17961 			verbose(env, "unreachable insn %d\n", i);
17962 			ret = -EINVAL;
17963 			goto err_free;
17964 		}
17965 		if (bpf_is_ldimm64(insn)) {
17966 			if (insn_state[i + 1] != 0) {
17967 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
17968 				ret = -EINVAL;
17969 				goto err_free;
17970 			}
17971 			i++; /* skip second half of ldimm64 */
17972 		}
17973 	}
17974 	ret = 0; /* cfg looks good */
17975 	env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data;
17976 	env->prog->aux->might_sleep = env->subprog_info[0].might_sleep;
17977 
17978 err_free:
17979 	kvfree(insn_state);
17980 	kvfree(insn_stack);
17981 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
17982 	return ret;
17983 }
17984 
17985 /*
17986  * For each subprogram 'i' fill array env->cfg.insn_subprogram sub-range
17987  * [env->subprog_info[i].postorder_start, env->subprog_info[i+1].postorder_start)
17988  * with indices of 'i' instructions in postorder.
17989  */
17990 static int compute_postorder(struct bpf_verifier_env *env)
17991 {
17992 	u32 cur_postorder, i, top, stack_sz, s, succ_cnt, succ[2];
17993 	int *stack = NULL, *postorder = NULL, *state = NULL;
17994 
17995 	postorder = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
17996 	state = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
17997 	stack = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
17998 	if (!postorder || !state || !stack) {
17999 		kvfree(postorder);
18000 		kvfree(state);
18001 		kvfree(stack);
18002 		return -ENOMEM;
18003 	}
18004 	cur_postorder = 0;
18005 	for (i = 0; i < env->subprog_cnt; i++) {
18006 		env->subprog_info[i].postorder_start = cur_postorder;
18007 		stack[0] = env->subprog_info[i].start;
18008 		stack_sz = 1;
18009 		do {
18010 			top = stack[stack_sz - 1];
18011 			state[top] |= DISCOVERED;
18012 			if (state[top] & EXPLORED) {
18013 				postorder[cur_postorder++] = top;
18014 				stack_sz--;
18015 				continue;
18016 			}
18017 			succ_cnt = bpf_insn_successors(env->prog, top, succ);
18018 			for (s = 0; s < succ_cnt; ++s) {
18019 				if (!state[succ[s]]) {
18020 					stack[stack_sz++] = succ[s];
18021 					state[succ[s]] |= DISCOVERED;
18022 				}
18023 			}
18024 			state[top] |= EXPLORED;
18025 		} while (stack_sz);
18026 	}
18027 	env->subprog_info[i].postorder_start = cur_postorder;
18028 	env->cfg.insn_postorder = postorder;
18029 	env->cfg.cur_postorder = cur_postorder;
18030 	kvfree(stack);
18031 	kvfree(state);
18032 	return 0;
18033 }
18034 
18035 static int check_abnormal_return(struct bpf_verifier_env *env)
18036 {
18037 	int i;
18038 
18039 	for (i = 1; i < env->subprog_cnt; i++) {
18040 		if (env->subprog_info[i].has_ld_abs) {
18041 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
18042 			return -EINVAL;
18043 		}
18044 		if (env->subprog_info[i].has_tail_call) {
18045 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
18046 			return -EINVAL;
18047 		}
18048 	}
18049 	return 0;
18050 }
18051 
18052 /* The minimum supported BTF func info size */
18053 #define MIN_BPF_FUNCINFO_SIZE	8
18054 #define MAX_FUNCINFO_REC_SIZE	252
18055 
18056 static int check_btf_func_early(struct bpf_verifier_env *env,
18057 				const union bpf_attr *attr,
18058 				bpfptr_t uattr)
18059 {
18060 	u32 krec_size = sizeof(struct bpf_func_info);
18061 	const struct btf_type *type, *func_proto;
18062 	u32 i, nfuncs, urec_size, min_size;
18063 	struct bpf_func_info *krecord;
18064 	struct bpf_prog *prog;
18065 	const struct btf *btf;
18066 	u32 prev_offset = 0;
18067 	bpfptr_t urecord;
18068 	int ret = -ENOMEM;
18069 
18070 	nfuncs = attr->func_info_cnt;
18071 	if (!nfuncs) {
18072 		if (check_abnormal_return(env))
18073 			return -EINVAL;
18074 		return 0;
18075 	}
18076 
18077 	urec_size = attr->func_info_rec_size;
18078 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
18079 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
18080 	    urec_size % sizeof(u32)) {
18081 		verbose(env, "invalid func info rec size %u\n", urec_size);
18082 		return -EINVAL;
18083 	}
18084 
18085 	prog = env->prog;
18086 	btf = prog->aux->btf;
18087 
18088 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
18089 	min_size = min_t(u32, krec_size, urec_size);
18090 
18091 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18092 	if (!krecord)
18093 		return -ENOMEM;
18094 
18095 	for (i = 0; i < nfuncs; i++) {
18096 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
18097 		if (ret) {
18098 			if (ret == -E2BIG) {
18099 				verbose(env, "nonzero tailing record in func info");
18100 				/* set the size kernel expects so loader can zero
18101 				 * out the rest of the record.
18102 				 */
18103 				if (copy_to_bpfptr_offset(uattr,
18104 							  offsetof(union bpf_attr, func_info_rec_size),
18105 							  &min_size, sizeof(min_size)))
18106 					ret = -EFAULT;
18107 			}
18108 			goto err_free;
18109 		}
18110 
18111 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
18112 			ret = -EFAULT;
18113 			goto err_free;
18114 		}
18115 
18116 		/* check insn_off */
18117 		ret = -EINVAL;
18118 		if (i == 0) {
18119 			if (krecord[i].insn_off) {
18120 				verbose(env,
18121 					"nonzero insn_off %u for the first func info record",
18122 					krecord[i].insn_off);
18123 				goto err_free;
18124 			}
18125 		} else if (krecord[i].insn_off <= prev_offset) {
18126 			verbose(env,
18127 				"same or smaller insn offset (%u) than previous func info record (%u)",
18128 				krecord[i].insn_off, prev_offset);
18129 			goto err_free;
18130 		}
18131 
18132 		/* check type_id */
18133 		type = btf_type_by_id(btf, krecord[i].type_id);
18134 		if (!type || !btf_type_is_func(type)) {
18135 			verbose(env, "invalid type id %d in func info",
18136 				krecord[i].type_id);
18137 			goto err_free;
18138 		}
18139 
18140 		func_proto = btf_type_by_id(btf, type->type);
18141 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
18142 			/* btf_func_check() already verified it during BTF load */
18143 			goto err_free;
18144 
18145 		prev_offset = krecord[i].insn_off;
18146 		bpfptr_add(&urecord, urec_size);
18147 	}
18148 
18149 	prog->aux->func_info = krecord;
18150 	prog->aux->func_info_cnt = nfuncs;
18151 	return 0;
18152 
18153 err_free:
18154 	kvfree(krecord);
18155 	return ret;
18156 }
18157 
18158 static int check_btf_func(struct bpf_verifier_env *env,
18159 			  const union bpf_attr *attr,
18160 			  bpfptr_t uattr)
18161 {
18162 	const struct btf_type *type, *func_proto, *ret_type;
18163 	u32 i, nfuncs, urec_size;
18164 	struct bpf_func_info *krecord;
18165 	struct bpf_func_info_aux *info_aux = NULL;
18166 	struct bpf_prog *prog;
18167 	const struct btf *btf;
18168 	bpfptr_t urecord;
18169 	bool scalar_return;
18170 	int ret = -ENOMEM;
18171 
18172 	nfuncs = attr->func_info_cnt;
18173 	if (!nfuncs) {
18174 		if (check_abnormal_return(env))
18175 			return -EINVAL;
18176 		return 0;
18177 	}
18178 	if (nfuncs != env->subprog_cnt) {
18179 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
18180 		return -EINVAL;
18181 	}
18182 
18183 	urec_size = attr->func_info_rec_size;
18184 
18185 	prog = env->prog;
18186 	btf = prog->aux->btf;
18187 
18188 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
18189 
18190 	krecord = prog->aux->func_info;
18191 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18192 	if (!info_aux)
18193 		return -ENOMEM;
18194 
18195 	for (i = 0; i < nfuncs; i++) {
18196 		/* check insn_off */
18197 		ret = -EINVAL;
18198 
18199 		if (env->subprog_info[i].start != krecord[i].insn_off) {
18200 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
18201 			goto err_free;
18202 		}
18203 
18204 		/* Already checked type_id */
18205 		type = btf_type_by_id(btf, krecord[i].type_id);
18206 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
18207 		/* Already checked func_proto */
18208 		func_proto = btf_type_by_id(btf, type->type);
18209 
18210 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
18211 		scalar_return =
18212 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
18213 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
18214 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
18215 			goto err_free;
18216 		}
18217 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
18218 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
18219 			goto err_free;
18220 		}
18221 
18222 		bpfptr_add(&urecord, urec_size);
18223 	}
18224 
18225 	prog->aux->func_info_aux = info_aux;
18226 	return 0;
18227 
18228 err_free:
18229 	kfree(info_aux);
18230 	return ret;
18231 }
18232 
18233 static void adjust_btf_func(struct bpf_verifier_env *env)
18234 {
18235 	struct bpf_prog_aux *aux = env->prog->aux;
18236 	int i;
18237 
18238 	if (!aux->func_info)
18239 		return;
18240 
18241 	/* func_info is not available for hidden subprogs */
18242 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
18243 		aux->func_info[i].insn_off = env->subprog_info[i].start;
18244 }
18245 
18246 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
18247 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
18248 
18249 static int check_btf_line(struct bpf_verifier_env *env,
18250 			  const union bpf_attr *attr,
18251 			  bpfptr_t uattr)
18252 {
18253 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
18254 	struct bpf_subprog_info *sub;
18255 	struct bpf_line_info *linfo;
18256 	struct bpf_prog *prog;
18257 	const struct btf *btf;
18258 	bpfptr_t ulinfo;
18259 	int err;
18260 
18261 	nr_linfo = attr->line_info_cnt;
18262 	if (!nr_linfo)
18263 		return 0;
18264 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
18265 		return -EINVAL;
18266 
18267 	rec_size = attr->line_info_rec_size;
18268 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
18269 	    rec_size > MAX_LINEINFO_REC_SIZE ||
18270 	    rec_size & (sizeof(u32) - 1))
18271 		return -EINVAL;
18272 
18273 	/* Need to zero it in case the userspace may
18274 	 * pass in a smaller bpf_line_info object.
18275 	 */
18276 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
18277 			 GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18278 	if (!linfo)
18279 		return -ENOMEM;
18280 
18281 	prog = env->prog;
18282 	btf = prog->aux->btf;
18283 
18284 	s = 0;
18285 	sub = env->subprog_info;
18286 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
18287 	expected_size = sizeof(struct bpf_line_info);
18288 	ncopy = min_t(u32, expected_size, rec_size);
18289 	for (i = 0; i < nr_linfo; i++) {
18290 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
18291 		if (err) {
18292 			if (err == -E2BIG) {
18293 				verbose(env, "nonzero tailing record in line_info");
18294 				if (copy_to_bpfptr_offset(uattr,
18295 							  offsetof(union bpf_attr, line_info_rec_size),
18296 							  &expected_size, sizeof(expected_size)))
18297 					err = -EFAULT;
18298 			}
18299 			goto err_free;
18300 		}
18301 
18302 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
18303 			err = -EFAULT;
18304 			goto err_free;
18305 		}
18306 
18307 		/*
18308 		 * Check insn_off to ensure
18309 		 * 1) strictly increasing AND
18310 		 * 2) bounded by prog->len
18311 		 *
18312 		 * The linfo[0].insn_off == 0 check logically falls into
18313 		 * the later "missing bpf_line_info for func..." case
18314 		 * because the first linfo[0].insn_off must be the
18315 		 * first sub also and the first sub must have
18316 		 * subprog_info[0].start == 0.
18317 		 */
18318 		if ((i && linfo[i].insn_off <= prev_offset) ||
18319 		    linfo[i].insn_off >= prog->len) {
18320 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
18321 				i, linfo[i].insn_off, prev_offset,
18322 				prog->len);
18323 			err = -EINVAL;
18324 			goto err_free;
18325 		}
18326 
18327 		if (!prog->insnsi[linfo[i].insn_off].code) {
18328 			verbose(env,
18329 				"Invalid insn code at line_info[%u].insn_off\n",
18330 				i);
18331 			err = -EINVAL;
18332 			goto err_free;
18333 		}
18334 
18335 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
18336 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
18337 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
18338 			err = -EINVAL;
18339 			goto err_free;
18340 		}
18341 
18342 		if (s != env->subprog_cnt) {
18343 			if (linfo[i].insn_off == sub[s].start) {
18344 				sub[s].linfo_idx = i;
18345 				s++;
18346 			} else if (sub[s].start < linfo[i].insn_off) {
18347 				verbose(env, "missing bpf_line_info for func#%u\n", s);
18348 				err = -EINVAL;
18349 				goto err_free;
18350 			}
18351 		}
18352 
18353 		prev_offset = linfo[i].insn_off;
18354 		bpfptr_add(&ulinfo, rec_size);
18355 	}
18356 
18357 	if (s != env->subprog_cnt) {
18358 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
18359 			env->subprog_cnt - s, s);
18360 		err = -EINVAL;
18361 		goto err_free;
18362 	}
18363 
18364 	prog->aux->linfo = linfo;
18365 	prog->aux->nr_linfo = nr_linfo;
18366 
18367 	return 0;
18368 
18369 err_free:
18370 	kvfree(linfo);
18371 	return err;
18372 }
18373 
18374 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
18375 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
18376 
18377 static int check_core_relo(struct bpf_verifier_env *env,
18378 			   const union bpf_attr *attr,
18379 			   bpfptr_t uattr)
18380 {
18381 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
18382 	struct bpf_core_relo core_relo = {};
18383 	struct bpf_prog *prog = env->prog;
18384 	const struct btf *btf = prog->aux->btf;
18385 	struct bpf_core_ctx ctx = {
18386 		.log = &env->log,
18387 		.btf = btf,
18388 	};
18389 	bpfptr_t u_core_relo;
18390 	int err;
18391 
18392 	nr_core_relo = attr->core_relo_cnt;
18393 	if (!nr_core_relo)
18394 		return 0;
18395 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
18396 		return -EINVAL;
18397 
18398 	rec_size = attr->core_relo_rec_size;
18399 	if (rec_size < MIN_CORE_RELO_SIZE ||
18400 	    rec_size > MAX_CORE_RELO_SIZE ||
18401 	    rec_size % sizeof(u32))
18402 		return -EINVAL;
18403 
18404 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
18405 	expected_size = sizeof(struct bpf_core_relo);
18406 	ncopy = min_t(u32, expected_size, rec_size);
18407 
18408 	/* Unlike func_info and line_info, copy and apply each CO-RE
18409 	 * relocation record one at a time.
18410 	 */
18411 	for (i = 0; i < nr_core_relo; i++) {
18412 		/* future proofing when sizeof(bpf_core_relo) changes */
18413 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
18414 		if (err) {
18415 			if (err == -E2BIG) {
18416 				verbose(env, "nonzero tailing record in core_relo");
18417 				if (copy_to_bpfptr_offset(uattr,
18418 							  offsetof(union bpf_attr, core_relo_rec_size),
18419 							  &expected_size, sizeof(expected_size)))
18420 					err = -EFAULT;
18421 			}
18422 			break;
18423 		}
18424 
18425 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
18426 			err = -EFAULT;
18427 			break;
18428 		}
18429 
18430 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
18431 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
18432 				i, core_relo.insn_off, prog->len);
18433 			err = -EINVAL;
18434 			break;
18435 		}
18436 
18437 		err = bpf_core_apply(&ctx, &core_relo, i,
18438 				     &prog->insnsi[core_relo.insn_off / 8]);
18439 		if (err)
18440 			break;
18441 		bpfptr_add(&u_core_relo, rec_size);
18442 	}
18443 	return err;
18444 }
18445 
18446 static int check_btf_info_early(struct bpf_verifier_env *env,
18447 				const union bpf_attr *attr,
18448 				bpfptr_t uattr)
18449 {
18450 	struct btf *btf;
18451 	int err;
18452 
18453 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
18454 		if (check_abnormal_return(env))
18455 			return -EINVAL;
18456 		return 0;
18457 	}
18458 
18459 	btf = btf_get_by_fd(attr->prog_btf_fd);
18460 	if (IS_ERR(btf))
18461 		return PTR_ERR(btf);
18462 	if (btf_is_kernel(btf)) {
18463 		btf_put(btf);
18464 		return -EACCES;
18465 	}
18466 	env->prog->aux->btf = btf;
18467 
18468 	err = check_btf_func_early(env, attr, uattr);
18469 	if (err)
18470 		return err;
18471 	return 0;
18472 }
18473 
18474 static int check_btf_info(struct bpf_verifier_env *env,
18475 			  const union bpf_attr *attr,
18476 			  bpfptr_t uattr)
18477 {
18478 	int err;
18479 
18480 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
18481 		if (check_abnormal_return(env))
18482 			return -EINVAL;
18483 		return 0;
18484 	}
18485 
18486 	err = check_btf_func(env, attr, uattr);
18487 	if (err)
18488 		return err;
18489 
18490 	err = check_btf_line(env, attr, uattr);
18491 	if (err)
18492 		return err;
18493 
18494 	err = check_core_relo(env, attr, uattr);
18495 	if (err)
18496 		return err;
18497 
18498 	return 0;
18499 }
18500 
18501 /* check %cur's range satisfies %old's */
18502 static bool range_within(const struct bpf_reg_state *old,
18503 			 const struct bpf_reg_state *cur)
18504 {
18505 	return old->umin_value <= cur->umin_value &&
18506 	       old->umax_value >= cur->umax_value &&
18507 	       old->smin_value <= cur->smin_value &&
18508 	       old->smax_value >= cur->smax_value &&
18509 	       old->u32_min_value <= cur->u32_min_value &&
18510 	       old->u32_max_value >= cur->u32_max_value &&
18511 	       old->s32_min_value <= cur->s32_min_value &&
18512 	       old->s32_max_value >= cur->s32_max_value;
18513 }
18514 
18515 /* If in the old state two registers had the same id, then they need to have
18516  * the same id in the new state as well.  But that id could be different from
18517  * the old state, so we need to track the mapping from old to new ids.
18518  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
18519  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
18520  * regs with a different old id could still have new id 9, we don't care about
18521  * that.
18522  * So we look through our idmap to see if this old id has been seen before.  If
18523  * so, we require the new id to match; otherwise, we add the id pair to the map.
18524  */
18525 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18526 {
18527 	struct bpf_id_pair *map = idmap->map;
18528 	unsigned int i;
18529 
18530 	/* either both IDs should be set or both should be zero */
18531 	if (!!old_id != !!cur_id)
18532 		return false;
18533 
18534 	if (old_id == 0) /* cur_id == 0 as well */
18535 		return true;
18536 
18537 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
18538 		if (!map[i].old) {
18539 			/* Reached an empty slot; haven't seen this id before */
18540 			map[i].old = old_id;
18541 			map[i].cur = cur_id;
18542 			return true;
18543 		}
18544 		if (map[i].old == old_id)
18545 			return map[i].cur == cur_id;
18546 		if (map[i].cur == cur_id)
18547 			return false;
18548 	}
18549 	/* We ran out of idmap slots, which should be impossible */
18550 	WARN_ON_ONCE(1);
18551 	return false;
18552 }
18553 
18554 /* Similar to check_ids(), but allocate a unique temporary ID
18555  * for 'old_id' or 'cur_id' of zero.
18556  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
18557  */
18558 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18559 {
18560 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
18561 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
18562 
18563 	return check_ids(old_id, cur_id, idmap);
18564 }
18565 
18566 static void clean_func_state(struct bpf_verifier_env *env,
18567 			     struct bpf_func_state *st,
18568 			     u32 ip)
18569 {
18570 	u16 live_regs = env->insn_aux_data[ip].live_regs_before;
18571 	int i, j;
18572 
18573 	for (i = 0; i < BPF_REG_FP; i++) {
18574 		/* liveness must not touch this register anymore */
18575 		if (!(live_regs & BIT(i)))
18576 			/* since the register is unused, clear its state
18577 			 * to make further comparison simpler
18578 			 */
18579 			__mark_reg_not_init(env, &st->regs[i]);
18580 	}
18581 
18582 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
18583 		if (!bpf_stack_slot_alive(env, st->frameno, i)) {
18584 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
18585 			for (j = 0; j < BPF_REG_SIZE; j++)
18586 				st->stack[i].slot_type[j] = STACK_INVALID;
18587 		}
18588 	}
18589 }
18590 
18591 static void clean_verifier_state(struct bpf_verifier_env *env,
18592 				 struct bpf_verifier_state *st)
18593 {
18594 	int i, ip;
18595 
18596 	bpf_live_stack_query_init(env, st);
18597 	st->cleaned = true;
18598 	for (i = 0; i <= st->curframe; i++) {
18599 		ip = frame_insn_idx(st, i);
18600 		clean_func_state(env, st->frame[i], ip);
18601 	}
18602 }
18603 
18604 /* the parentage chains form a tree.
18605  * the verifier states are added to state lists at given insn and
18606  * pushed into state stack for future exploration.
18607  * when the verifier reaches bpf_exit insn some of the verifier states
18608  * stored in the state lists have their final liveness state already,
18609  * but a lot of states will get revised from liveness point of view when
18610  * the verifier explores other branches.
18611  * Example:
18612  * 1: *(u64)(r10 - 8) = 1
18613  * 2: if r1 == 100 goto pc+1
18614  * 3: *(u64)(r10 - 8) = 2
18615  * 4: r0 = *(u64)(r10 - 8)
18616  * 5: exit
18617  * when the verifier reaches exit insn the stack slot -8 in the state list of
18618  * insn 2 is not yet marked alive. Then the verifier pops the other_branch
18619  * of insn 2 and goes exploring further. After the insn 4 read, liveness
18620  * analysis would propagate read mark for -8 at insn 2.
18621  *
18622  * Since the verifier pushes the branch states as it sees them while exploring
18623  * the program the condition of walking the branch instruction for the second
18624  * time means that all states below this branch were already explored and
18625  * their final liveness marks are already propagated.
18626  * Hence when the verifier completes the search of state list in is_state_visited()
18627  * we can call this clean_live_states() function to clear dead the registers and stack
18628  * slots to simplify state merging.
18629  *
18630  * Important note here that walking the same branch instruction in the callee
18631  * doesn't meant that the states are DONE. The verifier has to compare
18632  * the callsites
18633  */
18634 static void clean_live_states(struct bpf_verifier_env *env, int insn,
18635 			      struct bpf_verifier_state *cur)
18636 {
18637 	struct bpf_verifier_state_list *sl;
18638 	struct list_head *pos, *head;
18639 
18640 	head = explored_state(env, insn);
18641 	list_for_each(pos, head) {
18642 		sl = container_of(pos, struct bpf_verifier_state_list, node);
18643 		if (sl->state.branches)
18644 			continue;
18645 		if (sl->state.insn_idx != insn ||
18646 		    !same_callsites(&sl->state, cur))
18647 			continue;
18648 		if (sl->state.cleaned)
18649 			/* all regs in this state in all frames were already marked */
18650 			continue;
18651 		if (incomplete_read_marks(env, &sl->state))
18652 			continue;
18653 		clean_verifier_state(env, &sl->state);
18654 	}
18655 }
18656 
18657 static bool regs_exact(const struct bpf_reg_state *rold,
18658 		       const struct bpf_reg_state *rcur,
18659 		       struct bpf_idmap *idmap)
18660 {
18661 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
18662 	       check_ids(rold->id, rcur->id, idmap) &&
18663 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
18664 }
18665 
18666 enum exact_level {
18667 	NOT_EXACT,
18668 	EXACT,
18669 	RANGE_WITHIN
18670 };
18671 
18672 /* Returns true if (rold safe implies rcur safe) */
18673 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
18674 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
18675 		    enum exact_level exact)
18676 {
18677 	if (exact == EXACT)
18678 		return regs_exact(rold, rcur, idmap);
18679 
18680 	if (rold->type == NOT_INIT) {
18681 		if (exact == NOT_EXACT || rcur->type == NOT_INIT)
18682 			/* explored state can't have used this */
18683 			return true;
18684 	}
18685 
18686 	/* Enforce that register types have to match exactly, including their
18687 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
18688 	 * rule.
18689 	 *
18690 	 * One can make a point that using a pointer register as unbounded
18691 	 * SCALAR would be technically acceptable, but this could lead to
18692 	 * pointer leaks because scalars are allowed to leak while pointers
18693 	 * are not. We could make this safe in special cases if root is
18694 	 * calling us, but it's probably not worth the hassle.
18695 	 *
18696 	 * Also, register types that are *not* MAYBE_NULL could technically be
18697 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
18698 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
18699 	 * to the same map).
18700 	 * However, if the old MAYBE_NULL register then got NULL checked,
18701 	 * doing so could have affected others with the same id, and we can't
18702 	 * check for that because we lost the id when we converted to
18703 	 * a non-MAYBE_NULL variant.
18704 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
18705 	 * non-MAYBE_NULL registers as well.
18706 	 */
18707 	if (rold->type != rcur->type)
18708 		return false;
18709 
18710 	switch (base_type(rold->type)) {
18711 	case SCALAR_VALUE:
18712 		if (env->explore_alu_limits) {
18713 			/* explore_alu_limits disables tnum_in() and range_within()
18714 			 * logic and requires everything to be strict
18715 			 */
18716 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
18717 			       check_scalar_ids(rold->id, rcur->id, idmap);
18718 		}
18719 		if (!rold->precise && exact == NOT_EXACT)
18720 			return true;
18721 		if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
18722 			return false;
18723 		if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off))
18724 			return false;
18725 		/* Why check_ids() for scalar registers?
18726 		 *
18727 		 * Consider the following BPF code:
18728 		 *   1: r6 = ... unbound scalar, ID=a ...
18729 		 *   2: r7 = ... unbound scalar, ID=b ...
18730 		 *   3: if (r6 > r7) goto +1
18731 		 *   4: r6 = r7
18732 		 *   5: if (r6 > X) goto ...
18733 		 *   6: ... memory operation using r7 ...
18734 		 *
18735 		 * First verification path is [1-6]:
18736 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
18737 		 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
18738 		 *   r7 <= X, because r6 and r7 share same id.
18739 		 * Next verification path is [1-4, 6].
18740 		 *
18741 		 * Instruction (6) would be reached in two states:
18742 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
18743 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
18744 		 *
18745 		 * Use check_ids() to distinguish these states.
18746 		 * ---
18747 		 * Also verify that new value satisfies old value range knowledge.
18748 		 */
18749 		return range_within(rold, rcur) &&
18750 		       tnum_in(rold->var_off, rcur->var_off) &&
18751 		       check_scalar_ids(rold->id, rcur->id, idmap);
18752 	case PTR_TO_MAP_KEY:
18753 	case PTR_TO_MAP_VALUE:
18754 	case PTR_TO_MEM:
18755 	case PTR_TO_BUF:
18756 	case PTR_TO_TP_BUFFER:
18757 		/* If the new min/max/var_off satisfy the old ones and
18758 		 * everything else matches, we are OK.
18759 		 */
18760 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
18761 		       range_within(rold, rcur) &&
18762 		       tnum_in(rold->var_off, rcur->var_off) &&
18763 		       check_ids(rold->id, rcur->id, idmap) &&
18764 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
18765 	case PTR_TO_PACKET_META:
18766 	case PTR_TO_PACKET:
18767 		/* We must have at least as much range as the old ptr
18768 		 * did, so that any accesses which were safe before are
18769 		 * still safe.  This is true even if old range < old off,
18770 		 * since someone could have accessed through (ptr - k), or
18771 		 * even done ptr -= k in a register, to get a safe access.
18772 		 */
18773 		if (rold->range > rcur->range)
18774 			return false;
18775 		/* If the offsets don't match, we can't trust our alignment;
18776 		 * nor can we be sure that we won't fall out of range.
18777 		 */
18778 		if (rold->off != rcur->off)
18779 			return false;
18780 		/* id relations must be preserved */
18781 		if (!check_ids(rold->id, rcur->id, idmap))
18782 			return false;
18783 		/* new val must satisfy old val knowledge */
18784 		return range_within(rold, rcur) &&
18785 		       tnum_in(rold->var_off, rcur->var_off);
18786 	case PTR_TO_STACK:
18787 		/* two stack pointers are equal only if they're pointing to
18788 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
18789 		 */
18790 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
18791 	case PTR_TO_ARENA:
18792 		return true;
18793 	default:
18794 		return regs_exact(rold, rcur, idmap);
18795 	}
18796 }
18797 
18798 static struct bpf_reg_state unbound_reg;
18799 
18800 static __init int unbound_reg_init(void)
18801 {
18802 	__mark_reg_unknown_imprecise(&unbound_reg);
18803 	return 0;
18804 }
18805 late_initcall(unbound_reg_init);
18806 
18807 static bool is_stack_all_misc(struct bpf_verifier_env *env,
18808 			      struct bpf_stack_state *stack)
18809 {
18810 	u32 i;
18811 
18812 	for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
18813 		if ((stack->slot_type[i] == STACK_MISC) ||
18814 		    (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
18815 			continue;
18816 		return false;
18817 	}
18818 
18819 	return true;
18820 }
18821 
18822 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
18823 						  struct bpf_stack_state *stack)
18824 {
18825 	if (is_spilled_scalar_reg64(stack))
18826 		return &stack->spilled_ptr;
18827 
18828 	if (is_stack_all_misc(env, stack))
18829 		return &unbound_reg;
18830 
18831 	return NULL;
18832 }
18833 
18834 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
18835 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
18836 		      enum exact_level exact)
18837 {
18838 	int i, spi;
18839 
18840 	/* walk slots of the explored stack and ignore any additional
18841 	 * slots in the current stack, since explored(safe) state
18842 	 * didn't use them
18843 	 */
18844 	for (i = 0; i < old->allocated_stack; i++) {
18845 		struct bpf_reg_state *old_reg, *cur_reg;
18846 
18847 		spi = i / BPF_REG_SIZE;
18848 
18849 		if (exact != NOT_EXACT &&
18850 		    (i >= cur->allocated_stack ||
18851 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
18852 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
18853 			return false;
18854 
18855 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
18856 			continue;
18857 
18858 		if (env->allow_uninit_stack &&
18859 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
18860 			continue;
18861 
18862 		/* explored stack has more populated slots than current stack
18863 		 * and these slots were used
18864 		 */
18865 		if (i >= cur->allocated_stack)
18866 			return false;
18867 
18868 		/* 64-bit scalar spill vs all slots MISC and vice versa.
18869 		 * Load from all slots MISC produces unbound scalar.
18870 		 * Construct a fake register for such stack and call
18871 		 * regsafe() to ensure scalar ids are compared.
18872 		 */
18873 		old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
18874 		cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
18875 		if (old_reg && cur_reg) {
18876 			if (!regsafe(env, old_reg, cur_reg, idmap, exact))
18877 				return false;
18878 			i += BPF_REG_SIZE - 1;
18879 			continue;
18880 		}
18881 
18882 		/* if old state was safe with misc data in the stack
18883 		 * it will be safe with zero-initialized stack.
18884 		 * The opposite is not true
18885 		 */
18886 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
18887 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
18888 			continue;
18889 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
18890 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
18891 			/* Ex: old explored (safe) state has STACK_SPILL in
18892 			 * this stack slot, but current has STACK_MISC ->
18893 			 * this verifier states are not equivalent,
18894 			 * return false to continue verification of this path
18895 			 */
18896 			return false;
18897 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
18898 			continue;
18899 		/* Both old and cur are having same slot_type */
18900 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
18901 		case STACK_SPILL:
18902 			/* when explored and current stack slot are both storing
18903 			 * spilled registers, check that stored pointers types
18904 			 * are the same as well.
18905 			 * Ex: explored safe path could have stored
18906 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
18907 			 * but current path has stored:
18908 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
18909 			 * such verifier states are not equivalent.
18910 			 * return false to continue verification of this path
18911 			 */
18912 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
18913 				     &cur->stack[spi].spilled_ptr, idmap, exact))
18914 				return false;
18915 			break;
18916 		case STACK_DYNPTR:
18917 			old_reg = &old->stack[spi].spilled_ptr;
18918 			cur_reg = &cur->stack[spi].spilled_ptr;
18919 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
18920 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
18921 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
18922 				return false;
18923 			break;
18924 		case STACK_ITER:
18925 			old_reg = &old->stack[spi].spilled_ptr;
18926 			cur_reg = &cur->stack[spi].spilled_ptr;
18927 			/* iter.depth is not compared between states as it
18928 			 * doesn't matter for correctness and would otherwise
18929 			 * prevent convergence; we maintain it only to prevent
18930 			 * infinite loop check triggering, see
18931 			 * iter_active_depths_differ()
18932 			 */
18933 			if (old_reg->iter.btf != cur_reg->iter.btf ||
18934 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
18935 			    old_reg->iter.state != cur_reg->iter.state ||
18936 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
18937 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
18938 				return false;
18939 			break;
18940 		case STACK_IRQ_FLAG:
18941 			old_reg = &old->stack[spi].spilled_ptr;
18942 			cur_reg = &cur->stack[spi].spilled_ptr;
18943 			if (!check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) ||
18944 			    old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class)
18945 				return false;
18946 			break;
18947 		case STACK_MISC:
18948 		case STACK_ZERO:
18949 		case STACK_INVALID:
18950 			continue;
18951 		/* Ensure that new unhandled slot types return false by default */
18952 		default:
18953 			return false;
18954 		}
18955 	}
18956 	return true;
18957 }
18958 
18959 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur,
18960 		    struct bpf_idmap *idmap)
18961 {
18962 	int i;
18963 
18964 	if (old->acquired_refs != cur->acquired_refs)
18965 		return false;
18966 
18967 	if (old->active_locks != cur->active_locks)
18968 		return false;
18969 
18970 	if (old->active_preempt_locks != cur->active_preempt_locks)
18971 		return false;
18972 
18973 	if (old->active_rcu_lock != cur->active_rcu_lock)
18974 		return false;
18975 
18976 	if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap))
18977 		return false;
18978 
18979 	if (!check_ids(old->active_lock_id, cur->active_lock_id, idmap) ||
18980 	    old->active_lock_ptr != cur->active_lock_ptr)
18981 		return false;
18982 
18983 	for (i = 0; i < old->acquired_refs; i++) {
18984 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) ||
18985 		    old->refs[i].type != cur->refs[i].type)
18986 			return false;
18987 		switch (old->refs[i].type) {
18988 		case REF_TYPE_PTR:
18989 		case REF_TYPE_IRQ:
18990 			break;
18991 		case REF_TYPE_LOCK:
18992 		case REF_TYPE_RES_LOCK:
18993 		case REF_TYPE_RES_LOCK_IRQ:
18994 			if (old->refs[i].ptr != cur->refs[i].ptr)
18995 				return false;
18996 			break;
18997 		default:
18998 			WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type);
18999 			return false;
19000 		}
19001 	}
19002 
19003 	return true;
19004 }
19005 
19006 /* compare two verifier states
19007  *
19008  * all states stored in state_list are known to be valid, since
19009  * verifier reached 'bpf_exit' instruction through them
19010  *
19011  * this function is called when verifier exploring different branches of
19012  * execution popped from the state stack. If it sees an old state that has
19013  * more strict register state and more strict stack state then this execution
19014  * branch doesn't need to be explored further, since verifier already
19015  * concluded that more strict state leads to valid finish.
19016  *
19017  * Therefore two states are equivalent if register state is more conservative
19018  * and explored stack state is more conservative than the current one.
19019  * Example:
19020  *       explored                   current
19021  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
19022  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
19023  *
19024  * In other words if current stack state (one being explored) has more
19025  * valid slots than old one that already passed validation, it means
19026  * the verifier can stop exploring and conclude that current state is valid too
19027  *
19028  * Similarly with registers. If explored state has register type as invalid
19029  * whereas register type in current state is meaningful, it means that
19030  * the current state will reach 'bpf_exit' instruction safely
19031  */
19032 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
19033 			      struct bpf_func_state *cur, u32 insn_idx, enum exact_level exact)
19034 {
19035 	u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
19036 	u16 i;
19037 
19038 	if (old->callback_depth > cur->callback_depth)
19039 		return false;
19040 
19041 	for (i = 0; i < MAX_BPF_REG; i++)
19042 		if (((1 << i) & live_regs) &&
19043 		    !regsafe(env, &old->regs[i], &cur->regs[i],
19044 			     &env->idmap_scratch, exact))
19045 			return false;
19046 
19047 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
19048 		return false;
19049 
19050 	return true;
19051 }
19052 
19053 static void reset_idmap_scratch(struct bpf_verifier_env *env)
19054 {
19055 	env->idmap_scratch.tmp_id_gen = env->id_gen;
19056 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
19057 }
19058 
19059 static bool states_equal(struct bpf_verifier_env *env,
19060 			 struct bpf_verifier_state *old,
19061 			 struct bpf_verifier_state *cur,
19062 			 enum exact_level exact)
19063 {
19064 	u32 insn_idx;
19065 	int i;
19066 
19067 	if (old->curframe != cur->curframe)
19068 		return false;
19069 
19070 	reset_idmap_scratch(env);
19071 
19072 	/* Verification state from speculative execution simulation
19073 	 * must never prune a non-speculative execution one.
19074 	 */
19075 	if (old->speculative && !cur->speculative)
19076 		return false;
19077 
19078 	if (old->in_sleepable != cur->in_sleepable)
19079 		return false;
19080 
19081 	if (!refsafe(old, cur, &env->idmap_scratch))
19082 		return false;
19083 
19084 	/* for states to be equal callsites have to be the same
19085 	 * and all frame states need to be equivalent
19086 	 */
19087 	for (i = 0; i <= old->curframe; i++) {
19088 		insn_idx = frame_insn_idx(old, i);
19089 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
19090 			return false;
19091 		if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact))
19092 			return false;
19093 	}
19094 	return true;
19095 }
19096 
19097 /* find precise scalars in the previous equivalent state and
19098  * propagate them into the current state
19099  */
19100 static int propagate_precision(struct bpf_verifier_env *env,
19101 			       const struct bpf_verifier_state *old,
19102 			       struct bpf_verifier_state *cur,
19103 			       bool *changed)
19104 {
19105 	struct bpf_reg_state *state_reg;
19106 	struct bpf_func_state *state;
19107 	int i, err = 0, fr;
19108 	bool first;
19109 
19110 	for (fr = old->curframe; fr >= 0; fr--) {
19111 		state = old->frame[fr];
19112 		state_reg = state->regs;
19113 		first = true;
19114 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
19115 			if (state_reg->type != SCALAR_VALUE ||
19116 			    !state_reg->precise)
19117 				continue;
19118 			if (env->log.level & BPF_LOG_LEVEL2) {
19119 				if (first)
19120 					verbose(env, "frame %d: propagating r%d", fr, i);
19121 				else
19122 					verbose(env, ",r%d", i);
19123 			}
19124 			bt_set_frame_reg(&env->bt, fr, i);
19125 			first = false;
19126 		}
19127 
19128 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19129 			if (!is_spilled_reg(&state->stack[i]))
19130 				continue;
19131 			state_reg = &state->stack[i].spilled_ptr;
19132 			if (state_reg->type != SCALAR_VALUE ||
19133 			    !state_reg->precise)
19134 				continue;
19135 			if (env->log.level & BPF_LOG_LEVEL2) {
19136 				if (first)
19137 					verbose(env, "frame %d: propagating fp%d",
19138 						fr, (-i - 1) * BPF_REG_SIZE);
19139 				else
19140 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
19141 			}
19142 			bt_set_frame_slot(&env->bt, fr, i);
19143 			first = false;
19144 		}
19145 		if (!first)
19146 			verbose(env, "\n");
19147 	}
19148 
19149 	err = __mark_chain_precision(env, cur, -1, changed);
19150 	if (err < 0)
19151 		return err;
19152 
19153 	return 0;
19154 }
19155 
19156 #define MAX_BACKEDGE_ITERS 64
19157 
19158 /* Propagate read and precision marks from visit->backedges[*].state->equal_state
19159  * to corresponding parent states of visit->backedges[*].state until fixed point is reached,
19160  * then free visit->backedges.
19161  * After execution of this function incomplete_read_marks() will return false
19162  * for all states corresponding to @visit->callchain.
19163  */
19164 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit)
19165 {
19166 	struct bpf_scc_backedge *backedge;
19167 	struct bpf_verifier_state *st;
19168 	bool changed;
19169 	int i, err;
19170 
19171 	i = 0;
19172 	do {
19173 		if (i++ > MAX_BACKEDGE_ITERS) {
19174 			if (env->log.level & BPF_LOG_LEVEL2)
19175 				verbose(env, "%s: too many iterations\n", __func__);
19176 			for (backedge = visit->backedges; backedge; backedge = backedge->next)
19177 				mark_all_scalars_precise(env, &backedge->state);
19178 			break;
19179 		}
19180 		changed = false;
19181 		for (backedge = visit->backedges; backedge; backedge = backedge->next) {
19182 			st = &backedge->state;
19183 			err = propagate_precision(env, st->equal_state, st, &changed);
19184 			if (err)
19185 				return err;
19186 		}
19187 	} while (changed);
19188 
19189 	free_backedges(visit);
19190 	return 0;
19191 }
19192 
19193 static bool states_maybe_looping(struct bpf_verifier_state *old,
19194 				 struct bpf_verifier_state *cur)
19195 {
19196 	struct bpf_func_state *fold, *fcur;
19197 	int i, fr = cur->curframe;
19198 
19199 	if (old->curframe != fr)
19200 		return false;
19201 
19202 	fold = old->frame[fr];
19203 	fcur = cur->frame[fr];
19204 	for (i = 0; i < MAX_BPF_REG; i++)
19205 		if (memcmp(&fold->regs[i], &fcur->regs[i],
19206 			   offsetof(struct bpf_reg_state, frameno)))
19207 			return false;
19208 	return true;
19209 }
19210 
19211 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
19212 {
19213 	return env->insn_aux_data[insn_idx].is_iter_next;
19214 }
19215 
19216 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
19217  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
19218  * states to match, which otherwise would look like an infinite loop. So while
19219  * iter_next() calls are taken care of, we still need to be careful and
19220  * prevent erroneous and too eager declaration of "infinite loop", when
19221  * iterators are involved.
19222  *
19223  * Here's a situation in pseudo-BPF assembly form:
19224  *
19225  *   0: again:                          ; set up iter_next() call args
19226  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
19227  *   2:   call bpf_iter_num_next        ; this is iter_next() call
19228  *   3:   if r0 == 0 goto done
19229  *   4:   ... something useful here ...
19230  *   5:   goto again                    ; another iteration
19231  *   6: done:
19232  *   7:   r1 = &it
19233  *   8:   call bpf_iter_num_destroy     ; clean up iter state
19234  *   9:   exit
19235  *
19236  * This is a typical loop. Let's assume that we have a prune point at 1:,
19237  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
19238  * again`, assuming other heuristics don't get in a way).
19239  *
19240  * When we first time come to 1:, let's say we have some state X. We proceed
19241  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
19242  * Now we come back to validate that forked ACTIVE state. We proceed through
19243  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
19244  * are converging. But the problem is that we don't know that yet, as this
19245  * convergence has to happen at iter_next() call site only. So if nothing is
19246  * done, at 1: verifier will use bounded loop logic and declare infinite
19247  * looping (and would be *technically* correct, if not for iterator's
19248  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
19249  * don't want that. So what we do in process_iter_next_call() when we go on
19250  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
19251  * a different iteration. So when we suspect an infinite loop, we additionally
19252  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
19253  * pretend we are not looping and wait for next iter_next() call.
19254  *
19255  * This only applies to ACTIVE state. In DRAINED state we don't expect to
19256  * loop, because that would actually mean infinite loop, as DRAINED state is
19257  * "sticky", and so we'll keep returning into the same instruction with the
19258  * same state (at least in one of possible code paths).
19259  *
19260  * This approach allows to keep infinite loop heuristic even in the face of
19261  * active iterator. E.g., C snippet below is and will be detected as
19262  * infinitely looping:
19263  *
19264  *   struct bpf_iter_num it;
19265  *   int *p, x;
19266  *
19267  *   bpf_iter_num_new(&it, 0, 10);
19268  *   while ((p = bpf_iter_num_next(&t))) {
19269  *       x = p;
19270  *       while (x--) {} // <<-- infinite loop here
19271  *   }
19272  *
19273  */
19274 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
19275 {
19276 	struct bpf_reg_state *slot, *cur_slot;
19277 	struct bpf_func_state *state;
19278 	int i, fr;
19279 
19280 	for (fr = old->curframe; fr >= 0; fr--) {
19281 		state = old->frame[fr];
19282 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19283 			if (state->stack[i].slot_type[0] != STACK_ITER)
19284 				continue;
19285 
19286 			slot = &state->stack[i].spilled_ptr;
19287 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
19288 				continue;
19289 
19290 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
19291 			if (cur_slot->iter.depth != slot->iter.depth)
19292 				return true;
19293 		}
19294 	}
19295 	return false;
19296 }
19297 
19298 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
19299 {
19300 	struct bpf_verifier_state_list *new_sl;
19301 	struct bpf_verifier_state_list *sl;
19302 	struct bpf_verifier_state *cur = env->cur_state, *new;
19303 	bool force_new_state, add_new_state, loop;
19304 	int n, err, states_cnt = 0;
19305 	struct list_head *pos, *tmp, *head;
19306 
19307 	force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
19308 			  /* Avoid accumulating infinitely long jmp history */
19309 			  cur->jmp_history_cnt > 40;
19310 
19311 	/* bpf progs typically have pruning point every 4 instructions
19312 	 * http://vger.kernel.org/bpfconf2019.html#session-1
19313 	 * Do not add new state for future pruning if the verifier hasn't seen
19314 	 * at least 2 jumps and at least 8 instructions.
19315 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
19316 	 * In tests that amounts to up to 50% reduction into total verifier
19317 	 * memory consumption and 20% verifier time speedup.
19318 	 */
19319 	add_new_state = force_new_state;
19320 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
19321 	    env->insn_processed - env->prev_insn_processed >= 8)
19322 		add_new_state = true;
19323 
19324 	clean_live_states(env, insn_idx, cur);
19325 
19326 	loop = false;
19327 	head = explored_state(env, insn_idx);
19328 	list_for_each_safe(pos, tmp, head) {
19329 		sl = container_of(pos, struct bpf_verifier_state_list, node);
19330 		states_cnt++;
19331 		if (sl->state.insn_idx != insn_idx)
19332 			continue;
19333 
19334 		if (sl->state.branches) {
19335 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
19336 
19337 			if (frame->in_async_callback_fn &&
19338 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
19339 				/* Different async_entry_cnt means that the verifier is
19340 				 * processing another entry into async callback.
19341 				 * Seeing the same state is not an indication of infinite
19342 				 * loop or infinite recursion.
19343 				 * But finding the same state doesn't mean that it's safe
19344 				 * to stop processing the current state. The previous state
19345 				 * hasn't yet reached bpf_exit, since state.branches > 0.
19346 				 * Checking in_async_callback_fn alone is not enough either.
19347 				 * Since the verifier still needs to catch infinite loops
19348 				 * inside async callbacks.
19349 				 */
19350 				goto skip_inf_loop_check;
19351 			}
19352 			/* BPF open-coded iterators loop detection is special.
19353 			 * states_maybe_looping() logic is too simplistic in detecting
19354 			 * states that *might* be equivalent, because it doesn't know
19355 			 * about ID remapping, so don't even perform it.
19356 			 * See process_iter_next_call() and iter_active_depths_differ()
19357 			 * for overview of the logic. When current and one of parent
19358 			 * states are detected as equivalent, it's a good thing: we prove
19359 			 * convergence and can stop simulating further iterations.
19360 			 * It's safe to assume that iterator loop will finish, taking into
19361 			 * account iter_next() contract of eventually returning
19362 			 * sticky NULL result.
19363 			 *
19364 			 * Note, that states have to be compared exactly in this case because
19365 			 * read and precision marks might not be finalized inside the loop.
19366 			 * E.g. as in the program below:
19367 			 *
19368 			 *     1. r7 = -16
19369 			 *     2. r6 = bpf_get_prandom_u32()
19370 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
19371 			 *     4.   if (r6 != 42) {
19372 			 *     5.     r7 = -32
19373 			 *     6.     r6 = bpf_get_prandom_u32()
19374 			 *     7.     continue
19375 			 *     8.   }
19376 			 *     9.   r0 = r10
19377 			 *    10.   r0 += r7
19378 			 *    11.   r8 = *(u64 *)(r0 + 0)
19379 			 *    12.   r6 = bpf_get_prandom_u32()
19380 			 *    13. }
19381 			 *
19382 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
19383 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
19384 			 * not have read or precision mark for r7 yet, thus inexact states
19385 			 * comparison would discard current state with r7=-32
19386 			 * => unsafe memory access at 11 would not be caught.
19387 			 */
19388 			if (is_iter_next_insn(env, insn_idx)) {
19389 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19390 					struct bpf_func_state *cur_frame;
19391 					struct bpf_reg_state *iter_state, *iter_reg;
19392 					int spi;
19393 
19394 					cur_frame = cur->frame[cur->curframe];
19395 					/* btf_check_iter_kfuncs() enforces that
19396 					 * iter state pointer is always the first arg
19397 					 */
19398 					iter_reg = &cur_frame->regs[BPF_REG_1];
19399 					/* current state is valid due to states_equal(),
19400 					 * so we can assume valid iter and reg state,
19401 					 * no need for extra (re-)validations
19402 					 */
19403 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
19404 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
19405 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
19406 						loop = true;
19407 						goto hit;
19408 					}
19409 				}
19410 				goto skip_inf_loop_check;
19411 			}
19412 			if (is_may_goto_insn_at(env, insn_idx)) {
19413 				if (sl->state.may_goto_depth != cur->may_goto_depth &&
19414 				    states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19415 					loop = true;
19416 					goto hit;
19417 				}
19418 			}
19419 			if (bpf_calls_callback(env, insn_idx)) {
19420 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
19421 					goto hit;
19422 				goto skip_inf_loop_check;
19423 			}
19424 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
19425 			if (states_maybe_looping(&sl->state, cur) &&
19426 			    states_equal(env, &sl->state, cur, EXACT) &&
19427 			    !iter_active_depths_differ(&sl->state, cur) &&
19428 			    sl->state.may_goto_depth == cur->may_goto_depth &&
19429 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
19430 				verbose_linfo(env, insn_idx, "; ");
19431 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
19432 				verbose(env, "cur state:");
19433 				print_verifier_state(env, cur, cur->curframe, true);
19434 				verbose(env, "old state:");
19435 				print_verifier_state(env, &sl->state, cur->curframe, true);
19436 				return -EINVAL;
19437 			}
19438 			/* if the verifier is processing a loop, avoid adding new state
19439 			 * too often, since different loop iterations have distinct
19440 			 * states and may not help future pruning.
19441 			 * This threshold shouldn't be too low to make sure that
19442 			 * a loop with large bound will be rejected quickly.
19443 			 * The most abusive loop will be:
19444 			 * r1 += 1
19445 			 * if r1 < 1000000 goto pc-2
19446 			 * 1M insn_procssed limit / 100 == 10k peak states.
19447 			 * This threshold shouldn't be too high either, since states
19448 			 * at the end of the loop are likely to be useful in pruning.
19449 			 */
19450 skip_inf_loop_check:
19451 			if (!force_new_state &&
19452 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
19453 			    env->insn_processed - env->prev_insn_processed < 100)
19454 				add_new_state = false;
19455 			goto miss;
19456 		}
19457 		/* See comments for mark_all_regs_read_and_precise() */
19458 		loop = incomplete_read_marks(env, &sl->state);
19459 		if (states_equal(env, &sl->state, cur, loop ? RANGE_WITHIN : NOT_EXACT)) {
19460 hit:
19461 			sl->hit_cnt++;
19462 
19463 			/* if previous state reached the exit with precision and
19464 			 * current state is equivalent to it (except precision marks)
19465 			 * the precision needs to be propagated back in
19466 			 * the current state.
19467 			 */
19468 			err = 0;
19469 			if (is_jmp_point(env, env->insn_idx))
19470 				err = push_jmp_history(env, cur, 0, 0);
19471 			err = err ? : propagate_precision(env, &sl->state, cur, NULL);
19472 			if (err)
19473 				return err;
19474 			/* When processing iterator based loops above propagate_liveness and
19475 			 * propagate_precision calls are not sufficient to transfer all relevant
19476 			 * read and precision marks. E.g. consider the following case:
19477 			 *
19478 			 *  .-> A --.  Assume the states are visited in the order A, B, C.
19479 			 *  |   |   |  Assume that state B reaches a state equivalent to state A.
19480 			 *  |   v   v  At this point, state C is not processed yet, so state A
19481 			 *  '-- B   C  has not received any read or precision marks from C.
19482 			 *             Thus, marks propagated from A to B are incomplete.
19483 			 *
19484 			 * The verifier mitigates this by performing the following steps:
19485 			 *
19486 			 * - Prior to the main verification pass, strongly connected components
19487 			 *   (SCCs) are computed over the program's control flow graph,
19488 			 *   intraprocedurally.
19489 			 *
19490 			 * - During the main verification pass, `maybe_enter_scc()` checks
19491 			 *   whether the current verifier state is entering an SCC. If so, an
19492 			 *   instance of a `bpf_scc_visit` object is created, and the state
19493 			 *   entering the SCC is recorded as the entry state.
19494 			 *
19495 			 * - This instance is associated not with the SCC itself, but with a
19496 			 *   `bpf_scc_callchain`: a tuple consisting of the call sites leading to
19497 			 *   the SCC and the SCC id. See `compute_scc_callchain()`.
19498 			 *
19499 			 * - When a verification path encounters a `states_equal(...,
19500 			 *   RANGE_WITHIN)` condition, there exists a call chain describing the
19501 			 *   current state and a corresponding `bpf_scc_visit` instance. A copy
19502 			 *   of the current state is created and added to
19503 			 *   `bpf_scc_visit->backedges`.
19504 			 *
19505 			 * - When a verification path terminates, `maybe_exit_scc()` is called
19506 			 *   from `update_branch_counts()`. For states with `branches == 0`, it
19507 			 *   checks whether the state is the entry state of any `bpf_scc_visit`
19508 			 *   instance. If it is, this indicates that all paths originating from
19509 			 *   this SCC visit have been explored. `propagate_backedges()` is then
19510 			 *   called, which propagates read and precision marks through the
19511 			 *   backedges until a fixed point is reached.
19512 			 *   (In the earlier example, this would propagate marks from A to B,
19513 			 *    from C to A, and then again from A to B.)
19514 			 *
19515 			 * A note on callchains
19516 			 * --------------------
19517 			 *
19518 			 * Consider the following example:
19519 			 *
19520 			 *     void foo() { loop { ... SCC#1 ... } }
19521 			 *     void main() {
19522 			 *       A: foo();
19523 			 *       B: ...
19524 			 *       C: foo();
19525 			 *     }
19526 			 *
19527 			 * Here, there are two distinct callchains leading to SCC#1:
19528 			 * - (A, SCC#1)
19529 			 * - (C, SCC#1)
19530 			 *
19531 			 * Each callchain identifies a separate `bpf_scc_visit` instance that
19532 			 * accumulates backedge states. The `propagate_{liveness,precision}()`
19533 			 * functions traverse the parent state of each backedge state, which
19534 			 * means these parent states must remain valid (i.e., not freed) while
19535 			 * the corresponding `bpf_scc_visit` instance exists.
19536 			 *
19537 			 * Associating `bpf_scc_visit` instances directly with SCCs instead of
19538 			 * callchains would break this invariant:
19539 			 * - States explored during `C: foo()` would contribute backedges to
19540 			 *   SCC#1, but SCC#1 would only be exited once the exploration of
19541 			 *   `A: foo()` completes.
19542 			 * - By that time, the states explored between `A: foo()` and `C: foo()`
19543 			 *   (i.e., `B: ...`) may have already been freed, causing the parent
19544 			 *   links for states from `C: foo()` to become invalid.
19545 			 */
19546 			if (loop) {
19547 				struct bpf_scc_backedge *backedge;
19548 
19549 				backedge = kzalloc(sizeof(*backedge), GFP_KERNEL_ACCOUNT);
19550 				if (!backedge)
19551 					return -ENOMEM;
19552 				err = copy_verifier_state(&backedge->state, cur);
19553 				backedge->state.equal_state = &sl->state;
19554 				backedge->state.insn_idx = insn_idx;
19555 				err = err ?: add_scc_backedge(env, &sl->state, backedge);
19556 				if (err) {
19557 					free_verifier_state(&backedge->state, false);
19558 					kfree(backedge);
19559 					return err;
19560 				}
19561 			}
19562 			return 1;
19563 		}
19564 miss:
19565 		/* when new state is not going to be added do not increase miss count.
19566 		 * Otherwise several loop iterations will remove the state
19567 		 * recorded earlier. The goal of these heuristics is to have
19568 		 * states from some iterations of the loop (some in the beginning
19569 		 * and some at the end) to help pruning.
19570 		 */
19571 		if (add_new_state)
19572 			sl->miss_cnt++;
19573 		/* heuristic to determine whether this state is beneficial
19574 		 * to keep checking from state equivalence point of view.
19575 		 * Higher numbers increase max_states_per_insn and verification time,
19576 		 * but do not meaningfully decrease insn_processed.
19577 		 * 'n' controls how many times state could miss before eviction.
19578 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
19579 		 * too early would hinder iterator convergence.
19580 		 */
19581 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
19582 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
19583 			/* the state is unlikely to be useful. Remove it to
19584 			 * speed up verification
19585 			 */
19586 			sl->in_free_list = true;
19587 			list_del(&sl->node);
19588 			list_add(&sl->node, &env->free_list);
19589 			env->free_list_size++;
19590 			env->explored_states_size--;
19591 			maybe_free_verifier_state(env, sl);
19592 		}
19593 	}
19594 
19595 	if (env->max_states_per_insn < states_cnt)
19596 		env->max_states_per_insn = states_cnt;
19597 
19598 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
19599 		return 0;
19600 
19601 	if (!add_new_state)
19602 		return 0;
19603 
19604 	/* There were no equivalent states, remember the current one.
19605 	 * Technically the current state is not proven to be safe yet,
19606 	 * but it will either reach outer most bpf_exit (which means it's safe)
19607 	 * or it will be rejected. When there are no loops the verifier won't be
19608 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
19609 	 * again on the way to bpf_exit.
19610 	 * When looping the sl->state.branches will be > 0 and this state
19611 	 * will not be considered for equivalence until branches == 0.
19612 	 */
19613 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL_ACCOUNT);
19614 	if (!new_sl)
19615 		return -ENOMEM;
19616 	env->total_states++;
19617 	env->explored_states_size++;
19618 	update_peak_states(env);
19619 	env->prev_jmps_processed = env->jmps_processed;
19620 	env->prev_insn_processed = env->insn_processed;
19621 
19622 	/* forget precise markings we inherited, see __mark_chain_precision */
19623 	if (env->bpf_capable)
19624 		mark_all_scalars_imprecise(env, cur);
19625 
19626 	/* add new state to the head of linked list */
19627 	new = &new_sl->state;
19628 	err = copy_verifier_state(new, cur);
19629 	if (err) {
19630 		free_verifier_state(new, false);
19631 		kfree(new_sl);
19632 		return err;
19633 	}
19634 	new->insn_idx = insn_idx;
19635 	verifier_bug_if(new->branches != 1, env,
19636 			"%s:branches_to_explore=%d insn %d",
19637 			__func__, new->branches, insn_idx);
19638 	err = maybe_enter_scc(env, new);
19639 	if (err) {
19640 		free_verifier_state(new, false);
19641 		kfree(new_sl);
19642 		return err;
19643 	}
19644 
19645 	cur->parent = new;
19646 	cur->first_insn_idx = insn_idx;
19647 	cur->dfs_depth = new->dfs_depth + 1;
19648 	clear_jmp_history(cur);
19649 	list_add(&new_sl->node, head);
19650 	return 0;
19651 }
19652 
19653 /* Return true if it's OK to have the same insn return a different type. */
19654 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
19655 {
19656 	switch (base_type(type)) {
19657 	case PTR_TO_CTX:
19658 	case PTR_TO_SOCKET:
19659 	case PTR_TO_SOCK_COMMON:
19660 	case PTR_TO_TCP_SOCK:
19661 	case PTR_TO_XDP_SOCK:
19662 	case PTR_TO_BTF_ID:
19663 	case PTR_TO_ARENA:
19664 		return false;
19665 	default:
19666 		return true;
19667 	}
19668 }
19669 
19670 /* If an instruction was previously used with particular pointer types, then we
19671  * need to be careful to avoid cases such as the below, where it may be ok
19672  * for one branch accessing the pointer, but not ok for the other branch:
19673  *
19674  * R1 = sock_ptr
19675  * goto X;
19676  * ...
19677  * R1 = some_other_valid_ptr;
19678  * goto X;
19679  * ...
19680  * R2 = *(u32 *)(R1 + 0);
19681  */
19682 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
19683 {
19684 	return src != prev && (!reg_type_mismatch_ok(src) ||
19685 			       !reg_type_mismatch_ok(prev));
19686 }
19687 
19688 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)
19689 {
19690 	switch (base_type(type)) {
19691 	case PTR_TO_MEM:
19692 	case PTR_TO_BTF_ID:
19693 		return true;
19694 	default:
19695 		return false;
19696 	}
19697 }
19698 
19699 static bool is_ptr_to_mem(enum bpf_reg_type type)
19700 {
19701 	return base_type(type) == PTR_TO_MEM;
19702 }
19703 
19704 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
19705 			     bool allow_trust_mismatch)
19706 {
19707 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
19708 	enum bpf_reg_type merged_type;
19709 
19710 	if (*prev_type == NOT_INIT) {
19711 		/* Saw a valid insn
19712 		 * dst_reg = *(u32 *)(src_reg + off)
19713 		 * save type to validate intersecting paths
19714 		 */
19715 		*prev_type = type;
19716 	} else if (reg_type_mismatch(type, *prev_type)) {
19717 		/* Abuser program is trying to use the same insn
19718 		 * dst_reg = *(u32*) (src_reg + off)
19719 		 * with different pointer types:
19720 		 * src_reg == ctx in one branch and
19721 		 * src_reg == stack|map in some other branch.
19722 		 * Reject it.
19723 		 */
19724 		if (allow_trust_mismatch &&
19725 		    is_ptr_to_mem_or_btf_id(type) &&
19726 		    is_ptr_to_mem_or_btf_id(*prev_type)) {
19727 			/*
19728 			 * Have to support a use case when one path through
19729 			 * the program yields TRUSTED pointer while another
19730 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
19731 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
19732 			 * Same behavior of MEM_RDONLY flag.
19733 			 */
19734 			if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type))
19735 				merged_type = PTR_TO_MEM;
19736 			else
19737 				merged_type = PTR_TO_BTF_ID;
19738 			if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED))
19739 				merged_type |= PTR_UNTRUSTED;
19740 			if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY))
19741 				merged_type |= MEM_RDONLY;
19742 			*prev_type = merged_type;
19743 		} else {
19744 			verbose(env, "same insn cannot be used with different pointers\n");
19745 			return -EINVAL;
19746 		}
19747 	}
19748 
19749 	return 0;
19750 }
19751 
19752 enum {
19753 	PROCESS_BPF_EXIT = 1
19754 };
19755 
19756 static int process_bpf_exit_full(struct bpf_verifier_env *env,
19757 				 bool *do_print_state,
19758 				 bool exception_exit)
19759 {
19760 	/* We must do check_reference_leak here before
19761 	 * prepare_func_exit to handle the case when
19762 	 * state->curframe > 0, it may be a callback function,
19763 	 * for which reference_state must match caller reference
19764 	 * state when it exits.
19765 	 */
19766 	int err = check_resource_leak(env, exception_exit,
19767 				      !env->cur_state->curframe,
19768 				      "BPF_EXIT instruction in main prog");
19769 	if (err)
19770 		return err;
19771 
19772 	/* The side effect of the prepare_func_exit which is
19773 	 * being skipped is that it frees bpf_func_state.
19774 	 * Typically, process_bpf_exit will only be hit with
19775 	 * outermost exit. copy_verifier_state in pop_stack will
19776 	 * handle freeing of any extra bpf_func_state left over
19777 	 * from not processing all nested function exits. We
19778 	 * also skip return code checks as they are not needed
19779 	 * for exceptional exits.
19780 	 */
19781 	if (exception_exit)
19782 		return PROCESS_BPF_EXIT;
19783 
19784 	if (env->cur_state->curframe) {
19785 		err = bpf_update_live_stack(env);
19786 		if (err)
19787 			return err;
19788 		/* exit from nested function */
19789 		err = prepare_func_exit(env, &env->insn_idx);
19790 		if (err)
19791 			return err;
19792 		*do_print_state = true;
19793 		return 0;
19794 	}
19795 
19796 	err = check_return_code(env, BPF_REG_0, "R0");
19797 	if (err)
19798 		return err;
19799 	return PROCESS_BPF_EXIT;
19800 }
19801 
19802 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
19803 {
19804 	int err;
19805 	struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
19806 	u8 class = BPF_CLASS(insn->code);
19807 
19808 	if (class == BPF_ALU || class == BPF_ALU64) {
19809 		err = check_alu_op(env, insn);
19810 		if (err)
19811 			return err;
19812 
19813 	} else if (class == BPF_LDX) {
19814 		bool is_ldsx = BPF_MODE(insn->code) == BPF_MEMSX;
19815 
19816 		/* Check for reserved fields is already done in
19817 		 * resolve_pseudo_ldimm64().
19818 		 */
19819 		err = check_load_mem(env, insn, false, is_ldsx, true, "ldx");
19820 		if (err)
19821 			return err;
19822 	} else if (class == BPF_STX) {
19823 		if (BPF_MODE(insn->code) == BPF_ATOMIC) {
19824 			err = check_atomic(env, insn);
19825 			if (err)
19826 				return err;
19827 			env->insn_idx++;
19828 			return 0;
19829 		}
19830 
19831 		if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
19832 			verbose(env, "BPF_STX uses reserved fields\n");
19833 			return -EINVAL;
19834 		}
19835 
19836 		err = check_store_reg(env, insn, false);
19837 		if (err)
19838 			return err;
19839 	} else if (class == BPF_ST) {
19840 		enum bpf_reg_type dst_reg_type;
19841 
19842 		if (BPF_MODE(insn->code) != BPF_MEM ||
19843 		    insn->src_reg != BPF_REG_0) {
19844 			verbose(env, "BPF_ST uses reserved fields\n");
19845 			return -EINVAL;
19846 		}
19847 		/* check src operand */
19848 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
19849 		if (err)
19850 			return err;
19851 
19852 		dst_reg_type = cur_regs(env)[insn->dst_reg].type;
19853 
19854 		/* check that memory (dst_reg + off) is writeable */
19855 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
19856 				       insn->off, BPF_SIZE(insn->code),
19857 				       BPF_WRITE, -1, false, false);
19858 		if (err)
19859 			return err;
19860 
19861 		err = save_aux_ptr_type(env, dst_reg_type, false);
19862 		if (err)
19863 			return err;
19864 	} else if (class == BPF_JMP || class == BPF_JMP32) {
19865 		u8 opcode = BPF_OP(insn->code);
19866 
19867 		env->jmps_processed++;
19868 		if (opcode == BPF_CALL) {
19869 			if (BPF_SRC(insn->code) != BPF_K ||
19870 			    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL &&
19871 			     insn->off != 0) ||
19872 			    (insn->src_reg != BPF_REG_0 &&
19873 			     insn->src_reg != BPF_PSEUDO_CALL &&
19874 			     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
19875 			    insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) {
19876 				verbose(env, "BPF_CALL uses reserved fields\n");
19877 				return -EINVAL;
19878 			}
19879 
19880 			if (env->cur_state->active_locks) {
19881 				if ((insn->src_reg == BPF_REG_0 &&
19882 				     insn->imm != BPF_FUNC_spin_unlock) ||
19883 				    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
19884 				     (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) {
19885 					verbose(env,
19886 						"function calls are not allowed while holding a lock\n");
19887 					return -EINVAL;
19888 				}
19889 			}
19890 			if (insn->src_reg == BPF_PSEUDO_CALL) {
19891 				err = check_func_call(env, insn, &env->insn_idx);
19892 			} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19893 				err = check_kfunc_call(env, insn, &env->insn_idx);
19894 				if (!err && is_bpf_throw_kfunc(insn))
19895 					return process_bpf_exit_full(env, do_print_state, true);
19896 			} else {
19897 				err = check_helper_call(env, insn, &env->insn_idx);
19898 			}
19899 			if (err)
19900 				return err;
19901 
19902 			mark_reg_scratched(env, BPF_REG_0);
19903 		} else if (opcode == BPF_JA) {
19904 			if (BPF_SRC(insn->code) != BPF_K ||
19905 			    insn->src_reg != BPF_REG_0 ||
19906 			    insn->dst_reg != BPF_REG_0 ||
19907 			    (class == BPF_JMP && insn->imm != 0) ||
19908 			    (class == BPF_JMP32 && insn->off != 0)) {
19909 				verbose(env, "BPF_JA uses reserved fields\n");
19910 				return -EINVAL;
19911 			}
19912 
19913 			if (class == BPF_JMP)
19914 				env->insn_idx += insn->off + 1;
19915 			else
19916 				env->insn_idx += insn->imm + 1;
19917 			return 0;
19918 		} else if (opcode == BPF_EXIT) {
19919 			if (BPF_SRC(insn->code) != BPF_K ||
19920 			    insn->imm != 0 ||
19921 			    insn->src_reg != BPF_REG_0 ||
19922 			    insn->dst_reg != BPF_REG_0 ||
19923 			    class == BPF_JMP32) {
19924 				verbose(env, "BPF_EXIT uses reserved fields\n");
19925 				return -EINVAL;
19926 			}
19927 			return process_bpf_exit_full(env, do_print_state, false);
19928 		} else {
19929 			err = check_cond_jmp_op(env, insn, &env->insn_idx);
19930 			if (err)
19931 				return err;
19932 		}
19933 	} else if (class == BPF_LD) {
19934 		u8 mode = BPF_MODE(insn->code);
19935 
19936 		if (mode == BPF_ABS || mode == BPF_IND) {
19937 			err = check_ld_abs(env, insn);
19938 			if (err)
19939 				return err;
19940 
19941 		} else if (mode == BPF_IMM) {
19942 			err = check_ld_imm(env, insn);
19943 			if (err)
19944 				return err;
19945 
19946 			env->insn_idx++;
19947 			sanitize_mark_insn_seen(env);
19948 		} else {
19949 			verbose(env, "invalid BPF_LD mode\n");
19950 			return -EINVAL;
19951 		}
19952 	} else {
19953 		verbose(env, "unknown insn class %d\n", class);
19954 		return -EINVAL;
19955 	}
19956 
19957 	env->insn_idx++;
19958 	return 0;
19959 }
19960 
19961 static int do_check(struct bpf_verifier_env *env)
19962 {
19963 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19964 	struct bpf_verifier_state *state = env->cur_state;
19965 	struct bpf_insn *insns = env->prog->insnsi;
19966 	int insn_cnt = env->prog->len;
19967 	bool do_print_state = false;
19968 	int prev_insn_idx = -1;
19969 
19970 	for (;;) {
19971 		struct bpf_insn *insn;
19972 		struct bpf_insn_aux_data *insn_aux;
19973 		int err, marks_err;
19974 
19975 		/* reset current history entry on each new instruction */
19976 		env->cur_hist_ent = NULL;
19977 
19978 		env->prev_insn_idx = prev_insn_idx;
19979 		if (env->insn_idx >= insn_cnt) {
19980 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
19981 				env->insn_idx, insn_cnt);
19982 			return -EFAULT;
19983 		}
19984 
19985 		insn = &insns[env->insn_idx];
19986 		insn_aux = &env->insn_aux_data[env->insn_idx];
19987 
19988 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
19989 			verbose(env,
19990 				"BPF program is too large. Processed %d insn\n",
19991 				env->insn_processed);
19992 			return -E2BIG;
19993 		}
19994 
19995 		state->last_insn_idx = env->prev_insn_idx;
19996 		state->insn_idx = env->insn_idx;
19997 
19998 		if (is_prune_point(env, env->insn_idx)) {
19999 			err = is_state_visited(env, env->insn_idx);
20000 			if (err < 0)
20001 				return err;
20002 			if (err == 1) {
20003 				/* found equivalent state, can prune the search */
20004 				if (env->log.level & BPF_LOG_LEVEL) {
20005 					if (do_print_state)
20006 						verbose(env, "\nfrom %d to %d%s: safe\n",
20007 							env->prev_insn_idx, env->insn_idx,
20008 							env->cur_state->speculative ?
20009 							" (speculative execution)" : "");
20010 					else
20011 						verbose(env, "%d: safe\n", env->insn_idx);
20012 				}
20013 				goto process_bpf_exit;
20014 			}
20015 		}
20016 
20017 		if (is_jmp_point(env, env->insn_idx)) {
20018 			err = push_jmp_history(env, state, 0, 0);
20019 			if (err)
20020 				return err;
20021 		}
20022 
20023 		if (signal_pending(current))
20024 			return -EAGAIN;
20025 
20026 		if (need_resched())
20027 			cond_resched();
20028 
20029 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
20030 			verbose(env, "\nfrom %d to %d%s:",
20031 				env->prev_insn_idx, env->insn_idx,
20032 				env->cur_state->speculative ?
20033 				" (speculative execution)" : "");
20034 			print_verifier_state(env, state, state->curframe, true);
20035 			do_print_state = false;
20036 		}
20037 
20038 		if (env->log.level & BPF_LOG_LEVEL) {
20039 			if (verifier_state_scratched(env))
20040 				print_insn_state(env, state, state->curframe);
20041 
20042 			verbose_linfo(env, env->insn_idx, "; ");
20043 			env->prev_log_pos = env->log.end_pos;
20044 			verbose(env, "%d: ", env->insn_idx);
20045 			verbose_insn(env, insn);
20046 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
20047 			env->prev_log_pos = env->log.end_pos;
20048 		}
20049 
20050 		if (bpf_prog_is_offloaded(env->prog->aux)) {
20051 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
20052 							   env->prev_insn_idx);
20053 			if (err)
20054 				return err;
20055 		}
20056 
20057 		sanitize_mark_insn_seen(env);
20058 		prev_insn_idx = env->insn_idx;
20059 
20060 		/* Reduce verification complexity by stopping speculative path
20061 		 * verification when a nospec is encountered.
20062 		 */
20063 		if (state->speculative && insn_aux->nospec)
20064 			goto process_bpf_exit;
20065 
20066 		err = bpf_reset_stack_write_marks(env, env->insn_idx);
20067 		if (err)
20068 			return err;
20069 		err = do_check_insn(env, &do_print_state);
20070 		if (err >= 0 || error_recoverable_with_nospec(err)) {
20071 			marks_err = bpf_commit_stack_write_marks(env);
20072 			if (marks_err)
20073 				return marks_err;
20074 		}
20075 		if (error_recoverable_with_nospec(err) && state->speculative) {
20076 			/* Prevent this speculative path from ever reaching the
20077 			 * insn that would have been unsafe to execute.
20078 			 */
20079 			insn_aux->nospec = true;
20080 			/* If it was an ADD/SUB insn, potentially remove any
20081 			 * markings for alu sanitization.
20082 			 */
20083 			insn_aux->alu_state = 0;
20084 			goto process_bpf_exit;
20085 		} else if (err < 0) {
20086 			return err;
20087 		} else if (err == PROCESS_BPF_EXIT) {
20088 			goto process_bpf_exit;
20089 		}
20090 		WARN_ON_ONCE(err);
20091 
20092 		if (state->speculative && insn_aux->nospec_result) {
20093 			/* If we are on a path that performed a jump-op, this
20094 			 * may skip a nospec patched-in after the jump. This can
20095 			 * currently never happen because nospec_result is only
20096 			 * used for the write-ops
20097 			 * `*(size*)(dst_reg+off)=src_reg|imm32` which must
20098 			 * never skip the following insn. Still, add a warning
20099 			 * to document this in case nospec_result is used
20100 			 * elsewhere in the future.
20101 			 *
20102 			 * All non-branch instructions have a single
20103 			 * fall-through edge. For these, nospec_result should
20104 			 * already work.
20105 			 */
20106 			if (verifier_bug_if(BPF_CLASS(insn->code) == BPF_JMP ||
20107 					    BPF_CLASS(insn->code) == BPF_JMP32, env,
20108 					    "speculation barrier after jump instruction may not have the desired effect"))
20109 				return -EFAULT;
20110 process_bpf_exit:
20111 			mark_verifier_state_scratched(env);
20112 			err = update_branch_counts(env, env->cur_state);
20113 			if (err)
20114 				return err;
20115 			err = bpf_update_live_stack(env);
20116 			if (err)
20117 				return err;
20118 			err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
20119 					pop_log);
20120 			if (err < 0) {
20121 				if (err != -ENOENT)
20122 					return err;
20123 				break;
20124 			} else {
20125 				do_print_state = true;
20126 				continue;
20127 			}
20128 		}
20129 	}
20130 
20131 	return 0;
20132 }
20133 
20134 static int find_btf_percpu_datasec(struct btf *btf)
20135 {
20136 	const struct btf_type *t;
20137 	const char *tname;
20138 	int i, n;
20139 
20140 	/*
20141 	 * Both vmlinux and module each have their own ".data..percpu"
20142 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
20143 	 * types to look at only module's own BTF types.
20144 	 */
20145 	n = btf_nr_types(btf);
20146 	if (btf_is_module(btf))
20147 		i = btf_nr_types(btf_vmlinux);
20148 	else
20149 		i = 1;
20150 
20151 	for(; i < n; i++) {
20152 		t = btf_type_by_id(btf, i);
20153 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
20154 			continue;
20155 
20156 		tname = btf_name_by_offset(btf, t->name_off);
20157 		if (!strcmp(tname, ".data..percpu"))
20158 			return i;
20159 	}
20160 
20161 	return -ENOENT;
20162 }
20163 
20164 /*
20165  * Add btf to the used_btfs array and return the index. (If the btf was
20166  * already added, then just return the index.) Upon successful insertion
20167  * increase btf refcnt, and, if present, also refcount the corresponding
20168  * kernel module.
20169  */
20170 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
20171 {
20172 	struct btf_mod_pair *btf_mod;
20173 	int i;
20174 
20175 	/* check whether we recorded this BTF (and maybe module) already */
20176 	for (i = 0; i < env->used_btf_cnt; i++)
20177 		if (env->used_btfs[i].btf == btf)
20178 			return i;
20179 
20180 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
20181 		verbose(env, "The total number of btfs per program has reached the limit of %u\n",
20182 			MAX_USED_BTFS);
20183 		return -E2BIG;
20184 	}
20185 
20186 	btf_get(btf);
20187 
20188 	btf_mod = &env->used_btfs[env->used_btf_cnt];
20189 	btf_mod->btf = btf;
20190 	btf_mod->module = NULL;
20191 
20192 	/* if we reference variables from kernel module, bump its refcount */
20193 	if (btf_is_module(btf)) {
20194 		btf_mod->module = btf_try_get_module(btf);
20195 		if (!btf_mod->module) {
20196 			btf_put(btf);
20197 			return -ENXIO;
20198 		}
20199 	}
20200 
20201 	return env->used_btf_cnt++;
20202 }
20203 
20204 /* replace pseudo btf_id with kernel symbol address */
20205 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
20206 				 struct bpf_insn *insn,
20207 				 struct bpf_insn_aux_data *aux,
20208 				 struct btf *btf)
20209 {
20210 	const struct btf_var_secinfo *vsi;
20211 	const struct btf_type *datasec;
20212 	const struct btf_type *t;
20213 	const char *sym_name;
20214 	bool percpu = false;
20215 	u32 type, id = insn->imm;
20216 	s32 datasec_id;
20217 	u64 addr;
20218 	int i;
20219 
20220 	t = btf_type_by_id(btf, id);
20221 	if (!t) {
20222 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
20223 		return -ENOENT;
20224 	}
20225 
20226 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
20227 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
20228 		return -EINVAL;
20229 	}
20230 
20231 	sym_name = btf_name_by_offset(btf, t->name_off);
20232 	addr = kallsyms_lookup_name(sym_name);
20233 	if (!addr) {
20234 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
20235 			sym_name);
20236 		return -ENOENT;
20237 	}
20238 	insn[0].imm = (u32)addr;
20239 	insn[1].imm = addr >> 32;
20240 
20241 	if (btf_type_is_func(t)) {
20242 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20243 		aux->btf_var.mem_size = 0;
20244 		return 0;
20245 	}
20246 
20247 	datasec_id = find_btf_percpu_datasec(btf);
20248 	if (datasec_id > 0) {
20249 		datasec = btf_type_by_id(btf, datasec_id);
20250 		for_each_vsi(i, datasec, vsi) {
20251 			if (vsi->type == id) {
20252 				percpu = true;
20253 				break;
20254 			}
20255 		}
20256 	}
20257 
20258 	type = t->type;
20259 	t = btf_type_skip_modifiers(btf, type, NULL);
20260 	if (percpu) {
20261 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
20262 		aux->btf_var.btf = btf;
20263 		aux->btf_var.btf_id = type;
20264 	} else if (!btf_type_is_struct(t)) {
20265 		const struct btf_type *ret;
20266 		const char *tname;
20267 		u32 tsize;
20268 
20269 		/* resolve the type size of ksym. */
20270 		ret = btf_resolve_size(btf, t, &tsize);
20271 		if (IS_ERR(ret)) {
20272 			tname = btf_name_by_offset(btf, t->name_off);
20273 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
20274 				tname, PTR_ERR(ret));
20275 			return -EINVAL;
20276 		}
20277 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20278 		aux->btf_var.mem_size = tsize;
20279 	} else {
20280 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
20281 		aux->btf_var.btf = btf;
20282 		aux->btf_var.btf_id = type;
20283 	}
20284 
20285 	return 0;
20286 }
20287 
20288 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
20289 			       struct bpf_insn *insn,
20290 			       struct bpf_insn_aux_data *aux)
20291 {
20292 	struct btf *btf;
20293 	int btf_fd;
20294 	int err;
20295 
20296 	btf_fd = insn[1].imm;
20297 	if (btf_fd) {
20298 		CLASS(fd, f)(btf_fd);
20299 
20300 		btf = __btf_get_by_fd(f);
20301 		if (IS_ERR(btf)) {
20302 			verbose(env, "invalid module BTF object FD specified.\n");
20303 			return -EINVAL;
20304 		}
20305 	} else {
20306 		if (!btf_vmlinux) {
20307 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
20308 			return -EINVAL;
20309 		}
20310 		btf = btf_vmlinux;
20311 	}
20312 
20313 	err = __check_pseudo_btf_id(env, insn, aux, btf);
20314 	if (err)
20315 		return err;
20316 
20317 	err = __add_used_btf(env, btf);
20318 	if (err < 0)
20319 		return err;
20320 	return 0;
20321 }
20322 
20323 static bool is_tracing_prog_type(enum bpf_prog_type type)
20324 {
20325 	switch (type) {
20326 	case BPF_PROG_TYPE_KPROBE:
20327 	case BPF_PROG_TYPE_TRACEPOINT:
20328 	case BPF_PROG_TYPE_PERF_EVENT:
20329 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
20330 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
20331 		return true;
20332 	default:
20333 		return false;
20334 	}
20335 }
20336 
20337 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
20338 {
20339 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
20340 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
20341 }
20342 
20343 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
20344 					struct bpf_map *map,
20345 					struct bpf_prog *prog)
20346 
20347 {
20348 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
20349 
20350 	if (map->excl_prog_sha &&
20351 	    memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) {
20352 		verbose(env, "program's hash doesn't match map's excl_prog_hash\n");
20353 		return -EACCES;
20354 	}
20355 
20356 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
20357 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
20358 		if (is_tracing_prog_type(prog_type)) {
20359 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
20360 			return -EINVAL;
20361 		}
20362 	}
20363 
20364 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
20365 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
20366 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
20367 			return -EINVAL;
20368 		}
20369 
20370 		if (is_tracing_prog_type(prog_type)) {
20371 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
20372 			return -EINVAL;
20373 		}
20374 	}
20375 
20376 	if (btf_record_has_field(map->record, BPF_TIMER)) {
20377 		if (is_tracing_prog_type(prog_type)) {
20378 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
20379 			return -EINVAL;
20380 		}
20381 	}
20382 
20383 	if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
20384 		if (is_tracing_prog_type(prog_type)) {
20385 			verbose(env, "tracing progs cannot use bpf_wq yet\n");
20386 			return -EINVAL;
20387 		}
20388 	}
20389 
20390 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
20391 	    !bpf_offload_prog_map_match(prog, map)) {
20392 		verbose(env, "offload device mismatch between prog and map\n");
20393 		return -EINVAL;
20394 	}
20395 
20396 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
20397 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
20398 		return -EINVAL;
20399 	}
20400 
20401 	if (prog->sleepable)
20402 		switch (map->map_type) {
20403 		case BPF_MAP_TYPE_HASH:
20404 		case BPF_MAP_TYPE_LRU_HASH:
20405 		case BPF_MAP_TYPE_ARRAY:
20406 		case BPF_MAP_TYPE_PERCPU_HASH:
20407 		case BPF_MAP_TYPE_PERCPU_ARRAY:
20408 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
20409 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
20410 		case BPF_MAP_TYPE_HASH_OF_MAPS:
20411 		case BPF_MAP_TYPE_RINGBUF:
20412 		case BPF_MAP_TYPE_USER_RINGBUF:
20413 		case BPF_MAP_TYPE_INODE_STORAGE:
20414 		case BPF_MAP_TYPE_SK_STORAGE:
20415 		case BPF_MAP_TYPE_TASK_STORAGE:
20416 		case BPF_MAP_TYPE_CGRP_STORAGE:
20417 		case BPF_MAP_TYPE_QUEUE:
20418 		case BPF_MAP_TYPE_STACK:
20419 		case BPF_MAP_TYPE_ARENA:
20420 			break;
20421 		default:
20422 			verbose(env,
20423 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
20424 			return -EINVAL;
20425 		}
20426 
20427 	if (bpf_map_is_cgroup_storage(map) &&
20428 	    bpf_cgroup_storage_assign(env->prog->aux, map)) {
20429 		verbose(env, "only one cgroup storage of each type is allowed\n");
20430 		return -EBUSY;
20431 	}
20432 
20433 	if (map->map_type == BPF_MAP_TYPE_ARENA) {
20434 		if (env->prog->aux->arena) {
20435 			verbose(env, "Only one arena per program\n");
20436 			return -EBUSY;
20437 		}
20438 		if (!env->allow_ptr_leaks || !env->bpf_capable) {
20439 			verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
20440 			return -EPERM;
20441 		}
20442 		if (!env->prog->jit_requested) {
20443 			verbose(env, "JIT is required to use arena\n");
20444 			return -EOPNOTSUPP;
20445 		}
20446 		if (!bpf_jit_supports_arena()) {
20447 			verbose(env, "JIT doesn't support arena\n");
20448 			return -EOPNOTSUPP;
20449 		}
20450 		env->prog->aux->arena = (void *)map;
20451 		if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
20452 			verbose(env, "arena's user address must be set via map_extra or mmap()\n");
20453 			return -EINVAL;
20454 		}
20455 	}
20456 
20457 	return 0;
20458 }
20459 
20460 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
20461 {
20462 	int i, err;
20463 
20464 	/* check whether we recorded this map already */
20465 	for (i = 0; i < env->used_map_cnt; i++)
20466 		if (env->used_maps[i] == map)
20467 			return i;
20468 
20469 	if (env->used_map_cnt >= MAX_USED_MAPS) {
20470 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
20471 			MAX_USED_MAPS);
20472 		return -E2BIG;
20473 	}
20474 
20475 	err = check_map_prog_compatibility(env, map, env->prog);
20476 	if (err)
20477 		return err;
20478 
20479 	if (env->prog->sleepable)
20480 		atomic64_inc(&map->sleepable_refcnt);
20481 
20482 	/* hold the map. If the program is rejected by verifier,
20483 	 * the map will be released by release_maps() or it
20484 	 * will be used by the valid program until it's unloaded
20485 	 * and all maps are released in bpf_free_used_maps()
20486 	 */
20487 	bpf_map_inc(map);
20488 
20489 	env->used_maps[env->used_map_cnt++] = map;
20490 
20491 	return env->used_map_cnt - 1;
20492 }
20493 
20494 /* Add map behind fd to used maps list, if it's not already there, and return
20495  * its index.
20496  * Returns <0 on error, or >= 0 index, on success.
20497  */
20498 static int add_used_map(struct bpf_verifier_env *env, int fd)
20499 {
20500 	struct bpf_map *map;
20501 	CLASS(fd, f)(fd);
20502 
20503 	map = __bpf_map_get(f);
20504 	if (IS_ERR(map)) {
20505 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
20506 		return PTR_ERR(map);
20507 	}
20508 
20509 	return __add_used_map(env, map);
20510 }
20511 
20512 /* find and rewrite pseudo imm in ld_imm64 instructions:
20513  *
20514  * 1. if it accesses map FD, replace it with actual map pointer.
20515  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
20516  *
20517  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
20518  */
20519 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
20520 {
20521 	struct bpf_insn *insn = env->prog->insnsi;
20522 	int insn_cnt = env->prog->len;
20523 	int i, err;
20524 
20525 	err = bpf_prog_calc_tag(env->prog);
20526 	if (err)
20527 		return err;
20528 
20529 	for (i = 0; i < insn_cnt; i++, insn++) {
20530 		if (BPF_CLASS(insn->code) == BPF_LDX &&
20531 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
20532 		    insn->imm != 0)) {
20533 			verbose(env, "BPF_LDX uses reserved fields\n");
20534 			return -EINVAL;
20535 		}
20536 
20537 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
20538 			struct bpf_insn_aux_data *aux;
20539 			struct bpf_map *map;
20540 			int map_idx;
20541 			u64 addr;
20542 			u32 fd;
20543 
20544 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
20545 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
20546 			    insn[1].off != 0) {
20547 				verbose(env, "invalid bpf_ld_imm64 insn\n");
20548 				return -EINVAL;
20549 			}
20550 
20551 			if (insn[0].src_reg == 0)
20552 				/* valid generic load 64-bit imm */
20553 				goto next_insn;
20554 
20555 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
20556 				aux = &env->insn_aux_data[i];
20557 				err = check_pseudo_btf_id(env, insn, aux);
20558 				if (err)
20559 					return err;
20560 				goto next_insn;
20561 			}
20562 
20563 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
20564 				aux = &env->insn_aux_data[i];
20565 				aux->ptr_type = PTR_TO_FUNC;
20566 				goto next_insn;
20567 			}
20568 
20569 			/* In final convert_pseudo_ld_imm64() step, this is
20570 			 * converted into regular 64-bit imm load insn.
20571 			 */
20572 			switch (insn[0].src_reg) {
20573 			case BPF_PSEUDO_MAP_VALUE:
20574 			case BPF_PSEUDO_MAP_IDX_VALUE:
20575 				break;
20576 			case BPF_PSEUDO_MAP_FD:
20577 			case BPF_PSEUDO_MAP_IDX:
20578 				if (insn[1].imm == 0)
20579 					break;
20580 				fallthrough;
20581 			default:
20582 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
20583 				return -EINVAL;
20584 			}
20585 
20586 			switch (insn[0].src_reg) {
20587 			case BPF_PSEUDO_MAP_IDX_VALUE:
20588 			case BPF_PSEUDO_MAP_IDX:
20589 				if (bpfptr_is_null(env->fd_array)) {
20590 					verbose(env, "fd_idx without fd_array is invalid\n");
20591 					return -EPROTO;
20592 				}
20593 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
20594 							    insn[0].imm * sizeof(fd),
20595 							    sizeof(fd)))
20596 					return -EFAULT;
20597 				break;
20598 			default:
20599 				fd = insn[0].imm;
20600 				break;
20601 			}
20602 
20603 			map_idx = add_used_map(env, fd);
20604 			if (map_idx < 0)
20605 				return map_idx;
20606 			map = env->used_maps[map_idx];
20607 
20608 			aux = &env->insn_aux_data[i];
20609 			aux->map_index = map_idx;
20610 
20611 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
20612 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
20613 				addr = (unsigned long)map;
20614 			} else {
20615 				u32 off = insn[1].imm;
20616 
20617 				if (off >= BPF_MAX_VAR_OFF) {
20618 					verbose(env, "direct value offset of %u is not allowed\n", off);
20619 					return -EINVAL;
20620 				}
20621 
20622 				if (!map->ops->map_direct_value_addr) {
20623 					verbose(env, "no direct value access support for this map type\n");
20624 					return -EINVAL;
20625 				}
20626 
20627 				err = map->ops->map_direct_value_addr(map, &addr, off);
20628 				if (err) {
20629 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
20630 						map->value_size, off);
20631 					return err;
20632 				}
20633 
20634 				aux->map_off = off;
20635 				addr += off;
20636 			}
20637 
20638 			insn[0].imm = (u32)addr;
20639 			insn[1].imm = addr >> 32;
20640 
20641 next_insn:
20642 			insn++;
20643 			i++;
20644 			continue;
20645 		}
20646 
20647 		/* Basic sanity check before we invest more work here. */
20648 		if (!bpf_opcode_in_insntable(insn->code)) {
20649 			verbose(env, "unknown opcode %02x\n", insn->code);
20650 			return -EINVAL;
20651 		}
20652 	}
20653 
20654 	/* now all pseudo BPF_LD_IMM64 instructions load valid
20655 	 * 'struct bpf_map *' into a register instead of user map_fd.
20656 	 * These pointers will be used later by verifier to validate map access.
20657 	 */
20658 	return 0;
20659 }
20660 
20661 /* drop refcnt of maps used by the rejected program */
20662 static void release_maps(struct bpf_verifier_env *env)
20663 {
20664 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
20665 			     env->used_map_cnt);
20666 }
20667 
20668 /* drop refcnt of maps used by the rejected program */
20669 static void release_btfs(struct bpf_verifier_env *env)
20670 {
20671 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
20672 }
20673 
20674 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
20675 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
20676 {
20677 	struct bpf_insn *insn = env->prog->insnsi;
20678 	int insn_cnt = env->prog->len;
20679 	int i;
20680 
20681 	for (i = 0; i < insn_cnt; i++, insn++) {
20682 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
20683 			continue;
20684 		if (insn->src_reg == BPF_PSEUDO_FUNC)
20685 			continue;
20686 		insn->src_reg = 0;
20687 	}
20688 }
20689 
20690 /* single env->prog->insni[off] instruction was replaced with the range
20691  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
20692  * [0, off) and [off, end) to new locations, so the patched range stays zero
20693  */
20694 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
20695 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
20696 {
20697 	struct bpf_insn_aux_data *data = env->insn_aux_data;
20698 	struct bpf_insn *insn = new_prog->insnsi;
20699 	u32 old_seen = data[off].seen;
20700 	u32 prog_len;
20701 	int i;
20702 
20703 	/* aux info at OFF always needs adjustment, no matter fast path
20704 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
20705 	 * original insn at old prog.
20706 	 */
20707 	data[off].zext_dst = insn_has_def32(insn + off + cnt - 1);
20708 
20709 	if (cnt == 1)
20710 		return;
20711 	prog_len = new_prog->len;
20712 
20713 	memmove(data + off + cnt - 1, data + off,
20714 		sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
20715 	memset(data + off, 0, sizeof(struct bpf_insn_aux_data) * (cnt - 1));
20716 	for (i = off; i < off + cnt - 1; i++) {
20717 		/* Expand insni[off]'s seen count to the patched range. */
20718 		data[i].seen = old_seen;
20719 		data[i].zext_dst = insn_has_def32(insn + i);
20720 	}
20721 }
20722 
20723 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
20724 {
20725 	int i;
20726 
20727 	if (len == 1)
20728 		return;
20729 	/* NOTE: fake 'exit' subprog should be updated as well. */
20730 	for (i = 0; i <= env->subprog_cnt; i++) {
20731 		if (env->subprog_info[i].start <= off)
20732 			continue;
20733 		env->subprog_info[i].start += len - 1;
20734 	}
20735 }
20736 
20737 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
20738 {
20739 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
20740 	int i, sz = prog->aux->size_poke_tab;
20741 	struct bpf_jit_poke_descriptor *desc;
20742 
20743 	for (i = 0; i < sz; i++) {
20744 		desc = &tab[i];
20745 		if (desc->insn_idx <= off)
20746 			continue;
20747 		desc->insn_idx += len - 1;
20748 	}
20749 }
20750 
20751 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
20752 					    const struct bpf_insn *patch, u32 len)
20753 {
20754 	struct bpf_prog *new_prog;
20755 	struct bpf_insn_aux_data *new_data = NULL;
20756 
20757 	if (len > 1) {
20758 		new_data = vrealloc(env->insn_aux_data,
20759 				    array_size(env->prog->len + len - 1,
20760 					       sizeof(struct bpf_insn_aux_data)),
20761 				    GFP_KERNEL_ACCOUNT | __GFP_ZERO);
20762 		if (!new_data)
20763 			return NULL;
20764 
20765 		env->insn_aux_data = new_data;
20766 	}
20767 
20768 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
20769 	if (IS_ERR(new_prog)) {
20770 		if (PTR_ERR(new_prog) == -ERANGE)
20771 			verbose(env,
20772 				"insn %d cannot be patched due to 16-bit range\n",
20773 				env->insn_aux_data[off].orig_idx);
20774 		return NULL;
20775 	}
20776 	adjust_insn_aux_data(env, new_prog, off, len);
20777 	adjust_subprog_starts(env, off, len);
20778 	adjust_poke_descs(new_prog, off, len);
20779 	return new_prog;
20780 }
20781 
20782 /*
20783  * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
20784  * jump offset by 'delta'.
20785  */
20786 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
20787 {
20788 	struct bpf_insn *insn = prog->insnsi;
20789 	u32 insn_cnt = prog->len, i;
20790 	s32 imm;
20791 	s16 off;
20792 
20793 	for (i = 0; i < insn_cnt; i++, insn++) {
20794 		u8 code = insn->code;
20795 
20796 		if (tgt_idx <= i && i < tgt_idx + delta)
20797 			continue;
20798 
20799 		if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
20800 		    BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
20801 			continue;
20802 
20803 		if (insn->code == (BPF_JMP32 | BPF_JA)) {
20804 			if (i + 1 + insn->imm != tgt_idx)
20805 				continue;
20806 			if (check_add_overflow(insn->imm, delta, &imm))
20807 				return -ERANGE;
20808 			insn->imm = imm;
20809 		} else {
20810 			if (i + 1 + insn->off != tgt_idx)
20811 				continue;
20812 			if (check_add_overflow(insn->off, delta, &off))
20813 				return -ERANGE;
20814 			insn->off = off;
20815 		}
20816 	}
20817 	return 0;
20818 }
20819 
20820 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
20821 					      u32 off, u32 cnt)
20822 {
20823 	int i, j;
20824 
20825 	/* find first prog starting at or after off (first to remove) */
20826 	for (i = 0; i < env->subprog_cnt; i++)
20827 		if (env->subprog_info[i].start >= off)
20828 			break;
20829 	/* find first prog starting at or after off + cnt (first to stay) */
20830 	for (j = i; j < env->subprog_cnt; j++)
20831 		if (env->subprog_info[j].start >= off + cnt)
20832 			break;
20833 	/* if j doesn't start exactly at off + cnt, we are just removing
20834 	 * the front of previous prog
20835 	 */
20836 	if (env->subprog_info[j].start != off + cnt)
20837 		j--;
20838 
20839 	if (j > i) {
20840 		struct bpf_prog_aux *aux = env->prog->aux;
20841 		int move;
20842 
20843 		/* move fake 'exit' subprog as well */
20844 		move = env->subprog_cnt + 1 - j;
20845 
20846 		memmove(env->subprog_info + i,
20847 			env->subprog_info + j,
20848 			sizeof(*env->subprog_info) * move);
20849 		env->subprog_cnt -= j - i;
20850 
20851 		/* remove func_info */
20852 		if (aux->func_info) {
20853 			move = aux->func_info_cnt - j;
20854 
20855 			memmove(aux->func_info + i,
20856 				aux->func_info + j,
20857 				sizeof(*aux->func_info) * move);
20858 			aux->func_info_cnt -= j - i;
20859 			/* func_info->insn_off is set after all code rewrites,
20860 			 * in adjust_btf_func() - no need to adjust
20861 			 */
20862 		}
20863 	} else {
20864 		/* convert i from "first prog to remove" to "first to adjust" */
20865 		if (env->subprog_info[i].start == off)
20866 			i++;
20867 	}
20868 
20869 	/* update fake 'exit' subprog as well */
20870 	for (; i <= env->subprog_cnt; i++)
20871 		env->subprog_info[i].start -= cnt;
20872 
20873 	return 0;
20874 }
20875 
20876 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
20877 				      u32 cnt)
20878 {
20879 	struct bpf_prog *prog = env->prog;
20880 	u32 i, l_off, l_cnt, nr_linfo;
20881 	struct bpf_line_info *linfo;
20882 
20883 	nr_linfo = prog->aux->nr_linfo;
20884 	if (!nr_linfo)
20885 		return 0;
20886 
20887 	linfo = prog->aux->linfo;
20888 
20889 	/* find first line info to remove, count lines to be removed */
20890 	for (i = 0; i < nr_linfo; i++)
20891 		if (linfo[i].insn_off >= off)
20892 			break;
20893 
20894 	l_off = i;
20895 	l_cnt = 0;
20896 	for (; i < nr_linfo; i++)
20897 		if (linfo[i].insn_off < off + cnt)
20898 			l_cnt++;
20899 		else
20900 			break;
20901 
20902 	/* First live insn doesn't match first live linfo, it needs to "inherit"
20903 	 * last removed linfo.  prog is already modified, so prog->len == off
20904 	 * means no live instructions after (tail of the program was removed).
20905 	 */
20906 	if (prog->len != off && l_cnt &&
20907 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
20908 		l_cnt--;
20909 		linfo[--i].insn_off = off + cnt;
20910 	}
20911 
20912 	/* remove the line info which refer to the removed instructions */
20913 	if (l_cnt) {
20914 		memmove(linfo + l_off, linfo + i,
20915 			sizeof(*linfo) * (nr_linfo - i));
20916 
20917 		prog->aux->nr_linfo -= l_cnt;
20918 		nr_linfo = prog->aux->nr_linfo;
20919 	}
20920 
20921 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
20922 	for (i = l_off; i < nr_linfo; i++)
20923 		linfo[i].insn_off -= cnt;
20924 
20925 	/* fix up all subprogs (incl. 'exit') which start >= off */
20926 	for (i = 0; i <= env->subprog_cnt; i++)
20927 		if (env->subprog_info[i].linfo_idx > l_off) {
20928 			/* program may have started in the removed region but
20929 			 * may not be fully removed
20930 			 */
20931 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
20932 				env->subprog_info[i].linfo_idx -= l_cnt;
20933 			else
20934 				env->subprog_info[i].linfo_idx = l_off;
20935 		}
20936 
20937 	return 0;
20938 }
20939 
20940 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
20941 {
20942 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20943 	unsigned int orig_prog_len = env->prog->len;
20944 	int err;
20945 
20946 	if (bpf_prog_is_offloaded(env->prog->aux))
20947 		bpf_prog_offload_remove_insns(env, off, cnt);
20948 
20949 	err = bpf_remove_insns(env->prog, off, cnt);
20950 	if (err)
20951 		return err;
20952 
20953 	err = adjust_subprog_starts_after_remove(env, off, cnt);
20954 	if (err)
20955 		return err;
20956 
20957 	err = bpf_adj_linfo_after_remove(env, off, cnt);
20958 	if (err)
20959 		return err;
20960 
20961 	memmove(aux_data + off,	aux_data + off + cnt,
20962 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
20963 
20964 	return 0;
20965 }
20966 
20967 /* The verifier does more data flow analysis than llvm and will not
20968  * explore branches that are dead at run time. Malicious programs can
20969  * have dead code too. Therefore replace all dead at-run-time code
20970  * with 'ja -1'.
20971  *
20972  * Just nops are not optimal, e.g. if they would sit at the end of the
20973  * program and through another bug we would manage to jump there, then
20974  * we'd execute beyond program memory otherwise. Returning exception
20975  * code also wouldn't work since we can have subprogs where the dead
20976  * code could be located.
20977  */
20978 static void sanitize_dead_code(struct bpf_verifier_env *env)
20979 {
20980 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20981 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
20982 	struct bpf_insn *insn = env->prog->insnsi;
20983 	const int insn_cnt = env->prog->len;
20984 	int i;
20985 
20986 	for (i = 0; i < insn_cnt; i++) {
20987 		if (aux_data[i].seen)
20988 			continue;
20989 		memcpy(insn + i, &trap, sizeof(trap));
20990 		aux_data[i].zext_dst = false;
20991 	}
20992 }
20993 
20994 static bool insn_is_cond_jump(u8 code)
20995 {
20996 	u8 op;
20997 
20998 	op = BPF_OP(code);
20999 	if (BPF_CLASS(code) == BPF_JMP32)
21000 		return op != BPF_JA;
21001 
21002 	if (BPF_CLASS(code) != BPF_JMP)
21003 		return false;
21004 
21005 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
21006 }
21007 
21008 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
21009 {
21010 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21011 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
21012 	struct bpf_insn *insn = env->prog->insnsi;
21013 	const int insn_cnt = env->prog->len;
21014 	int i;
21015 
21016 	for (i = 0; i < insn_cnt; i++, insn++) {
21017 		if (!insn_is_cond_jump(insn->code))
21018 			continue;
21019 
21020 		if (!aux_data[i + 1].seen)
21021 			ja.off = insn->off;
21022 		else if (!aux_data[i + 1 + insn->off].seen)
21023 			ja.off = 0;
21024 		else
21025 			continue;
21026 
21027 		if (bpf_prog_is_offloaded(env->prog->aux))
21028 			bpf_prog_offload_replace_insn(env, i, &ja);
21029 
21030 		memcpy(insn, &ja, sizeof(ja));
21031 	}
21032 }
21033 
21034 static int opt_remove_dead_code(struct bpf_verifier_env *env)
21035 {
21036 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21037 	int insn_cnt = env->prog->len;
21038 	int i, err;
21039 
21040 	for (i = 0; i < insn_cnt; i++) {
21041 		int j;
21042 
21043 		j = 0;
21044 		while (i + j < insn_cnt && !aux_data[i + j].seen)
21045 			j++;
21046 		if (!j)
21047 			continue;
21048 
21049 		err = verifier_remove_insns(env, i, j);
21050 		if (err)
21051 			return err;
21052 		insn_cnt = env->prog->len;
21053 	}
21054 
21055 	return 0;
21056 }
21057 
21058 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
21059 static const struct bpf_insn MAY_GOTO_0 = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0);
21060 
21061 static int opt_remove_nops(struct bpf_verifier_env *env)
21062 {
21063 	struct bpf_insn *insn = env->prog->insnsi;
21064 	int insn_cnt = env->prog->len;
21065 	bool is_may_goto_0, is_ja;
21066 	int i, err;
21067 
21068 	for (i = 0; i < insn_cnt; i++) {
21069 		is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0));
21070 		is_ja = !memcmp(&insn[i], &NOP, sizeof(NOP));
21071 
21072 		if (!is_may_goto_0 && !is_ja)
21073 			continue;
21074 
21075 		err = verifier_remove_insns(env, i, 1);
21076 		if (err)
21077 			return err;
21078 		insn_cnt--;
21079 		/* Go back one insn to catch may_goto +1; may_goto +0 sequence */
21080 		i -= (is_may_goto_0 && i > 0) ? 2 : 1;
21081 	}
21082 
21083 	return 0;
21084 }
21085 
21086 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
21087 					 const union bpf_attr *attr)
21088 {
21089 	struct bpf_insn *patch;
21090 	/* use env->insn_buf as two independent buffers */
21091 	struct bpf_insn *zext_patch = env->insn_buf;
21092 	struct bpf_insn *rnd_hi32_patch = &env->insn_buf[2];
21093 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
21094 	int i, patch_len, delta = 0, len = env->prog->len;
21095 	struct bpf_insn *insns = env->prog->insnsi;
21096 	struct bpf_prog *new_prog;
21097 	bool rnd_hi32;
21098 
21099 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
21100 	zext_patch[1] = BPF_ZEXT_REG(0);
21101 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
21102 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
21103 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
21104 	for (i = 0; i < len; i++) {
21105 		int adj_idx = i + delta;
21106 		struct bpf_insn insn;
21107 		int load_reg;
21108 
21109 		insn = insns[adj_idx];
21110 		load_reg = insn_def_regno(&insn);
21111 		if (!aux[adj_idx].zext_dst) {
21112 			u8 code, class;
21113 			u32 imm_rnd;
21114 
21115 			if (!rnd_hi32)
21116 				continue;
21117 
21118 			code = insn.code;
21119 			class = BPF_CLASS(code);
21120 			if (load_reg == -1)
21121 				continue;
21122 
21123 			/* NOTE: arg "reg" (the fourth one) is only used for
21124 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
21125 			 *       here.
21126 			 */
21127 			if (is_reg64(&insn, load_reg, NULL, DST_OP)) {
21128 				if (class == BPF_LD &&
21129 				    BPF_MODE(code) == BPF_IMM)
21130 					i++;
21131 				continue;
21132 			}
21133 
21134 			/* ctx load could be transformed into wider load. */
21135 			if (class == BPF_LDX &&
21136 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
21137 				continue;
21138 
21139 			imm_rnd = get_random_u32();
21140 			rnd_hi32_patch[0] = insn;
21141 			rnd_hi32_patch[1].imm = imm_rnd;
21142 			rnd_hi32_patch[3].dst_reg = load_reg;
21143 			patch = rnd_hi32_patch;
21144 			patch_len = 4;
21145 			goto apply_patch_buffer;
21146 		}
21147 
21148 		/* Add in an zero-extend instruction if a) the JIT has requested
21149 		 * it or b) it's a CMPXCHG.
21150 		 *
21151 		 * The latter is because: BPF_CMPXCHG always loads a value into
21152 		 * R0, therefore always zero-extends. However some archs'
21153 		 * equivalent instruction only does this load when the
21154 		 * comparison is successful. This detail of CMPXCHG is
21155 		 * orthogonal to the general zero-extension behaviour of the
21156 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
21157 		 */
21158 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
21159 			continue;
21160 
21161 		/* Zero-extension is done by the caller. */
21162 		if (bpf_pseudo_kfunc_call(&insn))
21163 			continue;
21164 
21165 		if (verifier_bug_if(load_reg == -1, env,
21166 				    "zext_dst is set, but no reg is defined"))
21167 			return -EFAULT;
21168 
21169 		zext_patch[0] = insn;
21170 		zext_patch[1].dst_reg = load_reg;
21171 		zext_patch[1].src_reg = load_reg;
21172 		patch = zext_patch;
21173 		patch_len = 2;
21174 apply_patch_buffer:
21175 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
21176 		if (!new_prog)
21177 			return -ENOMEM;
21178 		env->prog = new_prog;
21179 		insns = new_prog->insnsi;
21180 		aux = env->insn_aux_data;
21181 		delta += patch_len - 1;
21182 	}
21183 
21184 	return 0;
21185 }
21186 
21187 /* convert load instructions that access fields of a context type into a
21188  * sequence of instructions that access fields of the underlying structure:
21189  *     struct __sk_buff    -> struct sk_buff
21190  *     struct bpf_sock_ops -> struct sock
21191  */
21192 static int convert_ctx_accesses(struct bpf_verifier_env *env)
21193 {
21194 	struct bpf_subprog_info *subprogs = env->subprog_info;
21195 	const struct bpf_verifier_ops *ops = env->ops;
21196 	int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0;
21197 	const int insn_cnt = env->prog->len;
21198 	struct bpf_insn *epilogue_buf = env->epilogue_buf;
21199 	struct bpf_insn *insn_buf = env->insn_buf;
21200 	struct bpf_insn *insn;
21201 	u32 target_size, size_default, off;
21202 	struct bpf_prog *new_prog;
21203 	enum bpf_access_type type;
21204 	bool is_narrower_load;
21205 	int epilogue_idx = 0;
21206 
21207 	if (ops->gen_epilogue) {
21208 		epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
21209 						 -(subprogs[0].stack_depth + 8));
21210 		if (epilogue_cnt >= INSN_BUF_SIZE) {
21211 			verifier_bug(env, "epilogue is too long");
21212 			return -EFAULT;
21213 		} else if (epilogue_cnt) {
21214 			/* Save the ARG_PTR_TO_CTX for the epilogue to use */
21215 			cnt = 0;
21216 			subprogs[0].stack_depth += 8;
21217 			insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
21218 						      -subprogs[0].stack_depth);
21219 			insn_buf[cnt++] = env->prog->insnsi[0];
21220 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
21221 			if (!new_prog)
21222 				return -ENOMEM;
21223 			env->prog = new_prog;
21224 			delta += cnt - 1;
21225 
21226 			ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1);
21227 			if (ret < 0)
21228 				return ret;
21229 		}
21230 	}
21231 
21232 	if (ops->gen_prologue || env->seen_direct_write) {
21233 		if (!ops->gen_prologue) {
21234 			verifier_bug(env, "gen_prologue is null");
21235 			return -EFAULT;
21236 		}
21237 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
21238 					env->prog);
21239 		if (cnt >= INSN_BUF_SIZE) {
21240 			verifier_bug(env, "prologue is too long");
21241 			return -EFAULT;
21242 		} else if (cnt) {
21243 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
21244 			if (!new_prog)
21245 				return -ENOMEM;
21246 
21247 			env->prog = new_prog;
21248 			delta += cnt - 1;
21249 
21250 			ret = add_kfunc_in_insns(env, insn_buf, cnt - 1);
21251 			if (ret < 0)
21252 				return ret;
21253 		}
21254 	}
21255 
21256 	if (delta)
21257 		WARN_ON(adjust_jmp_off(env->prog, 0, delta));
21258 
21259 	if (bpf_prog_is_offloaded(env->prog->aux))
21260 		return 0;
21261 
21262 	insn = env->prog->insnsi + delta;
21263 
21264 	for (i = 0; i < insn_cnt; i++, insn++) {
21265 		bpf_convert_ctx_access_t convert_ctx_access;
21266 		u8 mode;
21267 
21268 		if (env->insn_aux_data[i + delta].nospec) {
21269 			WARN_ON_ONCE(env->insn_aux_data[i + delta].alu_state);
21270 			struct bpf_insn *patch = insn_buf;
21271 
21272 			*patch++ = BPF_ST_NOSPEC();
21273 			*patch++ = *insn;
21274 			cnt = patch - insn_buf;
21275 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21276 			if (!new_prog)
21277 				return -ENOMEM;
21278 
21279 			delta    += cnt - 1;
21280 			env->prog = new_prog;
21281 			insn      = new_prog->insnsi + i + delta;
21282 			/* This can not be easily merged with the
21283 			 * nospec_result-case, because an insn may require a
21284 			 * nospec before and after itself. Therefore also do not
21285 			 * 'continue' here but potentially apply further
21286 			 * patching to insn. *insn should equal patch[1] now.
21287 			 */
21288 		}
21289 
21290 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
21291 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
21292 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
21293 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
21294 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
21295 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
21296 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
21297 			type = BPF_READ;
21298 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
21299 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
21300 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
21301 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
21302 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
21303 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
21304 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
21305 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
21306 			type = BPF_WRITE;
21307 		} else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_B) ||
21308 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_H) ||
21309 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
21310 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
21311 			   env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
21312 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
21313 			env->prog->aux->num_exentries++;
21314 			continue;
21315 		} else if (insn->code == (BPF_JMP | BPF_EXIT) &&
21316 			   epilogue_cnt &&
21317 			   i + delta < subprogs[1].start) {
21318 			/* Generate epilogue for the main prog */
21319 			if (epilogue_idx) {
21320 				/* jump back to the earlier generated epilogue */
21321 				insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
21322 				cnt = 1;
21323 			} else {
21324 				memcpy(insn_buf, epilogue_buf,
21325 				       epilogue_cnt * sizeof(*epilogue_buf));
21326 				cnt = epilogue_cnt;
21327 				/* epilogue_idx cannot be 0. It must have at
21328 				 * least one ctx ptr saving insn before the
21329 				 * epilogue.
21330 				 */
21331 				epilogue_idx = i + delta;
21332 			}
21333 			goto patch_insn_buf;
21334 		} else {
21335 			continue;
21336 		}
21337 
21338 		if (type == BPF_WRITE &&
21339 		    env->insn_aux_data[i + delta].nospec_result) {
21340 			/* nospec_result is only used to mitigate Spectre v4 and
21341 			 * to limit verification-time for Spectre v1.
21342 			 */
21343 			struct bpf_insn *patch = insn_buf;
21344 
21345 			*patch++ = *insn;
21346 			*patch++ = BPF_ST_NOSPEC();
21347 			cnt = patch - insn_buf;
21348 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21349 			if (!new_prog)
21350 				return -ENOMEM;
21351 
21352 			delta    += cnt - 1;
21353 			env->prog = new_prog;
21354 			insn      = new_prog->insnsi + i + delta;
21355 			continue;
21356 		}
21357 
21358 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
21359 		case PTR_TO_CTX:
21360 			if (!ops->convert_ctx_access)
21361 				continue;
21362 			convert_ctx_access = ops->convert_ctx_access;
21363 			break;
21364 		case PTR_TO_SOCKET:
21365 		case PTR_TO_SOCK_COMMON:
21366 			convert_ctx_access = bpf_sock_convert_ctx_access;
21367 			break;
21368 		case PTR_TO_TCP_SOCK:
21369 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
21370 			break;
21371 		case PTR_TO_XDP_SOCK:
21372 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
21373 			break;
21374 		case PTR_TO_BTF_ID:
21375 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
21376 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
21377 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
21378 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
21379 		 * any faults for loads into such types. BPF_WRITE is disallowed
21380 		 * for this case.
21381 		 */
21382 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
21383 		case PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED:
21384 			if (type == BPF_READ) {
21385 				if (BPF_MODE(insn->code) == BPF_MEM)
21386 					insn->code = BPF_LDX | BPF_PROBE_MEM |
21387 						     BPF_SIZE((insn)->code);
21388 				else
21389 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
21390 						     BPF_SIZE((insn)->code);
21391 				env->prog->aux->num_exentries++;
21392 			}
21393 			continue;
21394 		case PTR_TO_ARENA:
21395 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
21396 				if (!bpf_jit_supports_insn(insn, true)) {
21397 					verbose(env, "sign extending loads from arena are not supported yet\n");
21398 					return -EOPNOTSUPP;
21399 				}
21400 				insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32SX | BPF_SIZE(insn->code);
21401 			} else {
21402 				insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
21403 			}
21404 			env->prog->aux->num_exentries++;
21405 			continue;
21406 		default:
21407 			continue;
21408 		}
21409 
21410 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
21411 		size = BPF_LDST_BYTES(insn);
21412 		mode = BPF_MODE(insn->code);
21413 
21414 		/* If the read access is a narrower load of the field,
21415 		 * convert to a 4/8-byte load, to minimum program type specific
21416 		 * convert_ctx_access changes. If conversion is successful,
21417 		 * we will apply proper mask to the result.
21418 		 */
21419 		is_narrower_load = size < ctx_field_size;
21420 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
21421 		off = insn->off;
21422 		if (is_narrower_load) {
21423 			u8 size_code;
21424 
21425 			if (type == BPF_WRITE) {
21426 				verifier_bug(env, "narrow ctx access misconfigured");
21427 				return -EFAULT;
21428 			}
21429 
21430 			size_code = BPF_H;
21431 			if (ctx_field_size == 4)
21432 				size_code = BPF_W;
21433 			else if (ctx_field_size == 8)
21434 				size_code = BPF_DW;
21435 
21436 			insn->off = off & ~(size_default - 1);
21437 			insn->code = BPF_LDX | BPF_MEM | size_code;
21438 		}
21439 
21440 		target_size = 0;
21441 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
21442 					 &target_size);
21443 		if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
21444 		    (ctx_field_size && !target_size)) {
21445 			verifier_bug(env, "error during ctx access conversion (%d)", cnt);
21446 			return -EFAULT;
21447 		}
21448 
21449 		if (is_narrower_load && size < target_size) {
21450 			u8 shift = bpf_ctx_narrow_access_offset(
21451 				off, size, size_default) * 8;
21452 			if (shift && cnt + 1 >= INSN_BUF_SIZE) {
21453 				verifier_bug(env, "narrow ctx load misconfigured");
21454 				return -EFAULT;
21455 			}
21456 			if (ctx_field_size <= 4) {
21457 				if (shift)
21458 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
21459 									insn->dst_reg,
21460 									shift);
21461 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
21462 								(1 << size * 8) - 1);
21463 			} else {
21464 				if (shift)
21465 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
21466 									insn->dst_reg,
21467 									shift);
21468 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
21469 								(1ULL << size * 8) - 1);
21470 			}
21471 		}
21472 		if (mode == BPF_MEMSX)
21473 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
21474 						       insn->dst_reg, insn->dst_reg,
21475 						       size * 8, 0);
21476 
21477 patch_insn_buf:
21478 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21479 		if (!new_prog)
21480 			return -ENOMEM;
21481 
21482 		delta += cnt - 1;
21483 
21484 		/* keep walking new program and skip insns we just inserted */
21485 		env->prog = new_prog;
21486 		insn      = new_prog->insnsi + i + delta;
21487 	}
21488 
21489 	return 0;
21490 }
21491 
21492 static int jit_subprogs(struct bpf_verifier_env *env)
21493 {
21494 	struct bpf_prog *prog = env->prog, **func, *tmp;
21495 	int i, j, subprog_start, subprog_end = 0, len, subprog;
21496 	struct bpf_map *map_ptr;
21497 	struct bpf_insn *insn;
21498 	void *old_bpf_func;
21499 	int err, num_exentries;
21500 
21501 	if (env->subprog_cnt <= 1)
21502 		return 0;
21503 
21504 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
21505 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
21506 			continue;
21507 
21508 		/* Upon error here we cannot fall back to interpreter but
21509 		 * need a hard reject of the program. Thus -EFAULT is
21510 		 * propagated in any case.
21511 		 */
21512 		subprog = find_subprog(env, i + insn->imm + 1);
21513 		if (verifier_bug_if(subprog < 0, env, "No program to jit at insn %d",
21514 				    i + insn->imm + 1))
21515 			return -EFAULT;
21516 		/* temporarily remember subprog id inside insn instead of
21517 		 * aux_data, since next loop will split up all insns into funcs
21518 		 */
21519 		insn->off = subprog;
21520 		/* remember original imm in case JIT fails and fallback
21521 		 * to interpreter will be needed
21522 		 */
21523 		env->insn_aux_data[i].call_imm = insn->imm;
21524 		/* point imm to __bpf_call_base+1 from JITs point of view */
21525 		insn->imm = 1;
21526 		if (bpf_pseudo_func(insn)) {
21527 #if defined(MODULES_VADDR)
21528 			u64 addr = MODULES_VADDR;
21529 #else
21530 			u64 addr = VMALLOC_START;
21531 #endif
21532 			/* jit (e.g. x86_64) may emit fewer instructions
21533 			 * if it learns a u32 imm is the same as a u64 imm.
21534 			 * Set close enough to possible prog address.
21535 			 */
21536 			insn[0].imm = (u32)addr;
21537 			insn[1].imm = addr >> 32;
21538 		}
21539 	}
21540 
21541 	err = bpf_prog_alloc_jited_linfo(prog);
21542 	if (err)
21543 		goto out_undo_insn;
21544 
21545 	err = -ENOMEM;
21546 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
21547 	if (!func)
21548 		goto out_undo_insn;
21549 
21550 	for (i = 0; i < env->subprog_cnt; i++) {
21551 		subprog_start = subprog_end;
21552 		subprog_end = env->subprog_info[i + 1].start;
21553 
21554 		len = subprog_end - subprog_start;
21555 		/* bpf_prog_run() doesn't call subprogs directly,
21556 		 * hence main prog stats include the runtime of subprogs.
21557 		 * subprogs don't have IDs and not reachable via prog_get_next_id
21558 		 * func[i]->stats will never be accessed and stays NULL
21559 		 */
21560 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
21561 		if (!func[i])
21562 			goto out_free;
21563 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
21564 		       len * sizeof(struct bpf_insn));
21565 		func[i]->type = prog->type;
21566 		func[i]->len = len;
21567 		if (bpf_prog_calc_tag(func[i]))
21568 			goto out_free;
21569 		func[i]->is_func = 1;
21570 		func[i]->sleepable = prog->sleepable;
21571 		func[i]->aux->func_idx = i;
21572 		/* Below members will be freed only at prog->aux */
21573 		func[i]->aux->btf = prog->aux->btf;
21574 		func[i]->aux->func_info = prog->aux->func_info;
21575 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
21576 		func[i]->aux->poke_tab = prog->aux->poke_tab;
21577 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
21578 		func[i]->aux->main_prog_aux = prog->aux;
21579 
21580 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
21581 			struct bpf_jit_poke_descriptor *poke;
21582 
21583 			poke = &prog->aux->poke_tab[j];
21584 			if (poke->insn_idx < subprog_end &&
21585 			    poke->insn_idx >= subprog_start)
21586 				poke->aux = func[i]->aux;
21587 		}
21588 
21589 		func[i]->aux->name[0] = 'F';
21590 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
21591 		if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE)
21592 			func[i]->aux->jits_use_priv_stack = true;
21593 
21594 		func[i]->jit_requested = 1;
21595 		func[i]->blinding_requested = prog->blinding_requested;
21596 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
21597 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
21598 		func[i]->aux->linfo = prog->aux->linfo;
21599 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
21600 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
21601 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
21602 		func[i]->aux->arena = prog->aux->arena;
21603 		num_exentries = 0;
21604 		insn = func[i]->insnsi;
21605 		for (j = 0; j < func[i]->len; j++, insn++) {
21606 			if (BPF_CLASS(insn->code) == BPF_LDX &&
21607 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
21608 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
21609 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32SX ||
21610 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
21611 				num_exentries++;
21612 			if ((BPF_CLASS(insn->code) == BPF_STX ||
21613 			     BPF_CLASS(insn->code) == BPF_ST) &&
21614 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
21615 				num_exentries++;
21616 			if (BPF_CLASS(insn->code) == BPF_STX &&
21617 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
21618 				num_exentries++;
21619 		}
21620 		func[i]->aux->num_exentries = num_exentries;
21621 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
21622 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
21623 		func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
21624 		func[i]->aux->might_sleep = env->subprog_info[i].might_sleep;
21625 		if (!i)
21626 			func[i]->aux->exception_boundary = env->seen_exception;
21627 		func[i] = bpf_int_jit_compile(func[i]);
21628 		if (!func[i]->jited) {
21629 			err = -ENOTSUPP;
21630 			goto out_free;
21631 		}
21632 		cond_resched();
21633 	}
21634 
21635 	/* at this point all bpf functions were successfully JITed
21636 	 * now populate all bpf_calls with correct addresses and
21637 	 * run last pass of JIT
21638 	 */
21639 	for (i = 0; i < env->subprog_cnt; i++) {
21640 		insn = func[i]->insnsi;
21641 		for (j = 0; j < func[i]->len; j++, insn++) {
21642 			if (bpf_pseudo_func(insn)) {
21643 				subprog = insn->off;
21644 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
21645 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
21646 				continue;
21647 			}
21648 			if (!bpf_pseudo_call(insn))
21649 				continue;
21650 			subprog = insn->off;
21651 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
21652 		}
21653 
21654 		/* we use the aux data to keep a list of the start addresses
21655 		 * of the JITed images for each function in the program
21656 		 *
21657 		 * for some architectures, such as powerpc64, the imm field
21658 		 * might not be large enough to hold the offset of the start
21659 		 * address of the callee's JITed image from __bpf_call_base
21660 		 *
21661 		 * in such cases, we can lookup the start address of a callee
21662 		 * by using its subprog id, available from the off field of
21663 		 * the call instruction, as an index for this list
21664 		 */
21665 		func[i]->aux->func = func;
21666 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
21667 		func[i]->aux->real_func_cnt = env->subprog_cnt;
21668 	}
21669 	for (i = 0; i < env->subprog_cnt; i++) {
21670 		old_bpf_func = func[i]->bpf_func;
21671 		tmp = bpf_int_jit_compile(func[i]);
21672 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
21673 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
21674 			err = -ENOTSUPP;
21675 			goto out_free;
21676 		}
21677 		cond_resched();
21678 	}
21679 
21680 	/* finally lock prog and jit images for all functions and
21681 	 * populate kallsysm. Begin at the first subprogram, since
21682 	 * bpf_prog_load will add the kallsyms for the main program.
21683 	 */
21684 	for (i = 1; i < env->subprog_cnt; i++) {
21685 		err = bpf_prog_lock_ro(func[i]);
21686 		if (err)
21687 			goto out_free;
21688 	}
21689 
21690 	for (i = 1; i < env->subprog_cnt; i++)
21691 		bpf_prog_kallsyms_add(func[i]);
21692 
21693 	/* Last step: make now unused interpreter insns from main
21694 	 * prog consistent for later dump requests, so they can
21695 	 * later look the same as if they were interpreted only.
21696 	 */
21697 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
21698 		if (bpf_pseudo_func(insn)) {
21699 			insn[0].imm = env->insn_aux_data[i].call_imm;
21700 			insn[1].imm = insn->off;
21701 			insn->off = 0;
21702 			continue;
21703 		}
21704 		if (!bpf_pseudo_call(insn))
21705 			continue;
21706 		insn->off = env->insn_aux_data[i].call_imm;
21707 		subprog = find_subprog(env, i + insn->off + 1);
21708 		insn->imm = subprog;
21709 	}
21710 
21711 	prog->jited = 1;
21712 	prog->bpf_func = func[0]->bpf_func;
21713 	prog->jited_len = func[0]->jited_len;
21714 	prog->aux->extable = func[0]->aux->extable;
21715 	prog->aux->num_exentries = func[0]->aux->num_exentries;
21716 	prog->aux->func = func;
21717 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
21718 	prog->aux->real_func_cnt = env->subprog_cnt;
21719 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
21720 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
21721 	bpf_prog_jit_attempt_done(prog);
21722 	return 0;
21723 out_free:
21724 	/* We failed JIT'ing, so at this point we need to unregister poke
21725 	 * descriptors from subprogs, so that kernel is not attempting to
21726 	 * patch it anymore as we're freeing the subprog JIT memory.
21727 	 */
21728 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
21729 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
21730 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
21731 	}
21732 	/* At this point we're guaranteed that poke descriptors are not
21733 	 * live anymore. We can just unlink its descriptor table as it's
21734 	 * released with the main prog.
21735 	 */
21736 	for (i = 0; i < env->subprog_cnt; i++) {
21737 		if (!func[i])
21738 			continue;
21739 		func[i]->aux->poke_tab = NULL;
21740 		bpf_jit_free(func[i]);
21741 	}
21742 	kfree(func);
21743 out_undo_insn:
21744 	/* cleanup main prog to be interpreted */
21745 	prog->jit_requested = 0;
21746 	prog->blinding_requested = 0;
21747 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
21748 		if (!bpf_pseudo_call(insn))
21749 			continue;
21750 		insn->off = 0;
21751 		insn->imm = env->insn_aux_data[i].call_imm;
21752 	}
21753 	bpf_prog_jit_attempt_done(prog);
21754 	return err;
21755 }
21756 
21757 static int fixup_call_args(struct bpf_verifier_env *env)
21758 {
21759 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
21760 	struct bpf_prog *prog = env->prog;
21761 	struct bpf_insn *insn = prog->insnsi;
21762 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
21763 	int i, depth;
21764 #endif
21765 	int err = 0;
21766 
21767 	if (env->prog->jit_requested &&
21768 	    !bpf_prog_is_offloaded(env->prog->aux)) {
21769 		err = jit_subprogs(env);
21770 		if (err == 0)
21771 			return 0;
21772 		if (err == -EFAULT)
21773 			return err;
21774 	}
21775 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
21776 	if (has_kfunc_call) {
21777 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
21778 		return -EINVAL;
21779 	}
21780 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
21781 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
21782 		 * have to be rejected, since interpreter doesn't support them yet.
21783 		 */
21784 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
21785 		return -EINVAL;
21786 	}
21787 	for (i = 0; i < prog->len; i++, insn++) {
21788 		if (bpf_pseudo_func(insn)) {
21789 			/* When JIT fails the progs with callback calls
21790 			 * have to be rejected, since interpreter doesn't support them yet.
21791 			 */
21792 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
21793 			return -EINVAL;
21794 		}
21795 
21796 		if (!bpf_pseudo_call(insn))
21797 			continue;
21798 		depth = get_callee_stack_depth(env, insn, i);
21799 		if (depth < 0)
21800 			return depth;
21801 		bpf_patch_call_args(insn, depth);
21802 	}
21803 	err = 0;
21804 #endif
21805 	return err;
21806 }
21807 
21808 /* replace a generic kfunc with a specialized version if necessary */
21809 static void specialize_kfunc(struct bpf_verifier_env *env,
21810 			     u32 func_id, u16 offset, unsigned long *addr)
21811 {
21812 	struct bpf_prog *prog = env->prog;
21813 	bool seen_direct_write;
21814 	void *xdp_kfunc;
21815 	bool is_rdonly;
21816 
21817 	if (bpf_dev_bound_kfunc_id(func_id)) {
21818 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
21819 		if (xdp_kfunc) {
21820 			*addr = (unsigned long)xdp_kfunc;
21821 			return;
21822 		}
21823 		/* fallback to default kfunc when not supported by netdev */
21824 	}
21825 
21826 	if (offset)
21827 		return;
21828 
21829 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
21830 		seen_direct_write = env->seen_direct_write;
21831 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
21832 
21833 		if (is_rdonly)
21834 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
21835 
21836 		/* restore env->seen_direct_write to its original value, since
21837 		 * may_access_direct_pkt_data mutates it
21838 		 */
21839 		env->seen_direct_write = seen_direct_write;
21840 	}
21841 
21842 	if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr] &&
21843 	    bpf_lsm_has_d_inode_locked(prog))
21844 		*addr = (unsigned long)bpf_set_dentry_xattr_locked;
21845 
21846 	if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr] &&
21847 	    bpf_lsm_has_d_inode_locked(prog))
21848 		*addr = (unsigned long)bpf_remove_dentry_xattr_locked;
21849 }
21850 
21851 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
21852 					    u16 struct_meta_reg,
21853 					    u16 node_offset_reg,
21854 					    struct bpf_insn *insn,
21855 					    struct bpf_insn *insn_buf,
21856 					    int *cnt)
21857 {
21858 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
21859 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
21860 
21861 	insn_buf[0] = addr[0];
21862 	insn_buf[1] = addr[1];
21863 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
21864 	insn_buf[3] = *insn;
21865 	*cnt = 4;
21866 }
21867 
21868 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
21869 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
21870 {
21871 	const struct bpf_kfunc_desc *desc;
21872 
21873 	if (!insn->imm) {
21874 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
21875 		return -EINVAL;
21876 	}
21877 
21878 	*cnt = 0;
21879 
21880 	/* insn->imm has the btf func_id. Replace it with an offset relative to
21881 	 * __bpf_call_base, unless the JIT needs to call functions that are
21882 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
21883 	 */
21884 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
21885 	if (!desc) {
21886 		verifier_bug(env, "kernel function descriptor not found for func_id %u",
21887 			     insn->imm);
21888 		return -EFAULT;
21889 	}
21890 
21891 	if (!bpf_jit_supports_far_kfunc_call())
21892 		insn->imm = BPF_CALL_IMM(desc->addr);
21893 	if (insn->off)
21894 		return 0;
21895 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
21896 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
21897 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21898 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
21899 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
21900 
21901 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
21902 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
21903 				     insn_idx);
21904 			return -EFAULT;
21905 		}
21906 
21907 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
21908 		insn_buf[1] = addr[0];
21909 		insn_buf[2] = addr[1];
21910 		insn_buf[3] = *insn;
21911 		*cnt = 4;
21912 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
21913 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
21914 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
21915 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21916 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
21917 
21918 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
21919 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
21920 				     insn_idx);
21921 			return -EFAULT;
21922 		}
21923 
21924 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
21925 		    !kptr_struct_meta) {
21926 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
21927 				     insn_idx);
21928 			return -EFAULT;
21929 		}
21930 
21931 		insn_buf[0] = addr[0];
21932 		insn_buf[1] = addr[1];
21933 		insn_buf[2] = *insn;
21934 		*cnt = 3;
21935 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
21936 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
21937 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
21938 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21939 		int struct_meta_reg = BPF_REG_3;
21940 		int node_offset_reg = BPF_REG_4;
21941 
21942 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
21943 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
21944 			struct_meta_reg = BPF_REG_4;
21945 			node_offset_reg = BPF_REG_5;
21946 		}
21947 
21948 		if (!kptr_struct_meta) {
21949 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
21950 				     insn_idx);
21951 			return -EFAULT;
21952 		}
21953 
21954 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
21955 						node_offset_reg, insn, insn_buf, cnt);
21956 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
21957 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
21958 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
21959 		*cnt = 1;
21960 	}
21961 
21962 	if (env->insn_aux_data[insn_idx].arg_prog) {
21963 		u32 regno = env->insn_aux_data[insn_idx].arg_prog;
21964 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) };
21965 		int idx = *cnt;
21966 
21967 		insn_buf[idx++] = ld_addrs[0];
21968 		insn_buf[idx++] = ld_addrs[1];
21969 		insn_buf[idx++] = *insn;
21970 		*cnt = idx;
21971 	}
21972 	return 0;
21973 }
21974 
21975 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
21976 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
21977 {
21978 	struct bpf_subprog_info *info = env->subprog_info;
21979 	int cnt = env->subprog_cnt;
21980 	struct bpf_prog *prog;
21981 
21982 	/* We only reserve one slot for hidden subprogs in subprog_info. */
21983 	if (env->hidden_subprog_cnt) {
21984 		verifier_bug(env, "only one hidden subprog supported");
21985 		return -EFAULT;
21986 	}
21987 	/* We're not patching any existing instruction, just appending the new
21988 	 * ones for the hidden subprog. Hence all of the adjustment operations
21989 	 * in bpf_patch_insn_data are no-ops.
21990 	 */
21991 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
21992 	if (!prog)
21993 		return -ENOMEM;
21994 	env->prog = prog;
21995 	info[cnt + 1].start = info[cnt].start;
21996 	info[cnt].start = prog->len - len + 1;
21997 	env->subprog_cnt++;
21998 	env->hidden_subprog_cnt++;
21999 	return 0;
22000 }
22001 
22002 /* Do various post-verification rewrites in a single program pass.
22003  * These rewrites simplify JIT and interpreter implementations.
22004  */
22005 static int do_misc_fixups(struct bpf_verifier_env *env)
22006 {
22007 	struct bpf_prog *prog = env->prog;
22008 	enum bpf_attach_type eatype = prog->expected_attach_type;
22009 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
22010 	struct bpf_insn *insn = prog->insnsi;
22011 	const struct bpf_func_proto *fn;
22012 	const int insn_cnt = prog->len;
22013 	const struct bpf_map_ops *ops;
22014 	struct bpf_insn_aux_data *aux;
22015 	struct bpf_insn *insn_buf = env->insn_buf;
22016 	struct bpf_prog *new_prog;
22017 	struct bpf_map *map_ptr;
22018 	int i, ret, cnt, delta = 0, cur_subprog = 0;
22019 	struct bpf_subprog_info *subprogs = env->subprog_info;
22020 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
22021 	u16 stack_depth_extra = 0;
22022 
22023 	if (env->seen_exception && !env->exception_callback_subprog) {
22024 		struct bpf_insn *patch = insn_buf;
22025 
22026 		*patch++ = env->prog->insnsi[insn_cnt - 1];
22027 		*patch++ = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
22028 		*patch++ = BPF_EXIT_INSN();
22029 		ret = add_hidden_subprog(env, insn_buf, patch - insn_buf);
22030 		if (ret < 0)
22031 			return ret;
22032 		prog = env->prog;
22033 		insn = prog->insnsi;
22034 
22035 		env->exception_callback_subprog = env->subprog_cnt - 1;
22036 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
22037 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
22038 	}
22039 
22040 	for (i = 0; i < insn_cnt;) {
22041 		if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
22042 			if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
22043 			    (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
22044 				/* convert to 32-bit mov that clears upper 32-bit */
22045 				insn->code = BPF_ALU | BPF_MOV | BPF_X;
22046 				/* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
22047 				insn->off = 0;
22048 				insn->imm = 0;
22049 			} /* cast from as(0) to as(1) should be handled by JIT */
22050 			goto next_insn;
22051 		}
22052 
22053 		if (env->insn_aux_data[i + delta].needs_zext)
22054 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
22055 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
22056 
22057 		/* Make sdiv/smod divide-by-minus-one exceptions impossible. */
22058 		if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
22059 		     insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
22060 		     insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
22061 		     insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
22062 		    insn->off == 1 && insn->imm == -1) {
22063 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
22064 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
22065 			struct bpf_insn *patch = insn_buf;
22066 
22067 			if (isdiv)
22068 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22069 							BPF_NEG | BPF_K, insn->dst_reg,
22070 							0, 0, 0);
22071 			else
22072 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
22073 
22074 			cnt = patch - insn_buf;
22075 
22076 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22077 			if (!new_prog)
22078 				return -ENOMEM;
22079 
22080 			delta    += cnt - 1;
22081 			env->prog = prog = new_prog;
22082 			insn      = new_prog->insnsi + i + delta;
22083 			goto next_insn;
22084 		}
22085 
22086 		/* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
22087 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
22088 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
22089 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
22090 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
22091 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
22092 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
22093 			bool is_sdiv = isdiv && insn->off == 1;
22094 			bool is_smod = !isdiv && insn->off == 1;
22095 			struct bpf_insn *patch = insn_buf;
22096 
22097 			if (is_sdiv) {
22098 				/* [R,W]x sdiv 0 -> 0
22099 				 * LLONG_MIN sdiv -1 -> LLONG_MIN
22100 				 * INT_MIN sdiv -1 -> INT_MIN
22101 				 */
22102 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22103 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22104 							BPF_ADD | BPF_K, BPF_REG_AX,
22105 							0, 0, 1);
22106 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22107 							BPF_JGT | BPF_K, BPF_REG_AX,
22108 							0, 4, 1);
22109 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22110 							BPF_JEQ | BPF_K, BPF_REG_AX,
22111 							0, 1, 0);
22112 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22113 							BPF_MOV | BPF_K, insn->dst_reg,
22114 							0, 0, 0);
22115 				/* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
22116 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22117 							BPF_NEG | BPF_K, insn->dst_reg,
22118 							0, 0, 0);
22119 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22120 				*patch++ = *insn;
22121 				cnt = patch - insn_buf;
22122 			} else if (is_smod) {
22123 				/* [R,W]x mod 0 -> [R,W]x */
22124 				/* [R,W]x mod -1 -> 0 */
22125 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22126 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22127 							BPF_ADD | BPF_K, BPF_REG_AX,
22128 							0, 0, 1);
22129 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22130 							BPF_JGT | BPF_K, BPF_REG_AX,
22131 							0, 3, 1);
22132 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22133 							BPF_JEQ | BPF_K, BPF_REG_AX,
22134 							0, 3 + (is64 ? 0 : 1), 1);
22135 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
22136 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22137 				*patch++ = *insn;
22138 
22139 				if (!is64) {
22140 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22141 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
22142 				}
22143 				cnt = patch - insn_buf;
22144 			} else if (isdiv) {
22145 				/* [R,W]x div 0 -> 0 */
22146 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22147 							BPF_JNE | BPF_K, insn->src_reg,
22148 							0, 2, 0);
22149 				*patch++ = BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg);
22150 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22151 				*patch++ = *insn;
22152 				cnt = patch - insn_buf;
22153 			} else {
22154 				/* [R,W]x mod 0 -> [R,W]x */
22155 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22156 							BPF_JEQ | BPF_K, insn->src_reg,
22157 							0, 1 + (is64 ? 0 : 1), 0);
22158 				*patch++ = *insn;
22159 
22160 				if (!is64) {
22161 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22162 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
22163 				}
22164 				cnt = patch - insn_buf;
22165 			}
22166 
22167 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22168 			if (!new_prog)
22169 				return -ENOMEM;
22170 
22171 			delta    += cnt - 1;
22172 			env->prog = prog = new_prog;
22173 			insn      = new_prog->insnsi + i + delta;
22174 			goto next_insn;
22175 		}
22176 
22177 		/* Make it impossible to de-reference a userspace address */
22178 		if (BPF_CLASS(insn->code) == BPF_LDX &&
22179 		    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
22180 		     BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
22181 			struct bpf_insn *patch = insn_buf;
22182 			u64 uaddress_limit = bpf_arch_uaddress_limit();
22183 
22184 			if (!uaddress_limit)
22185 				goto next_insn;
22186 
22187 			*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22188 			if (insn->off)
22189 				*patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
22190 			*patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
22191 			*patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
22192 			*patch++ = *insn;
22193 			*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22194 			*patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
22195 
22196 			cnt = patch - insn_buf;
22197 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22198 			if (!new_prog)
22199 				return -ENOMEM;
22200 
22201 			delta    += cnt - 1;
22202 			env->prog = prog = new_prog;
22203 			insn      = new_prog->insnsi + i + delta;
22204 			goto next_insn;
22205 		}
22206 
22207 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
22208 		if (BPF_CLASS(insn->code) == BPF_LD &&
22209 		    (BPF_MODE(insn->code) == BPF_ABS ||
22210 		     BPF_MODE(insn->code) == BPF_IND)) {
22211 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
22212 			if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
22213 				verifier_bug(env, "%d insns generated for ld_abs", cnt);
22214 				return -EFAULT;
22215 			}
22216 
22217 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22218 			if (!new_prog)
22219 				return -ENOMEM;
22220 
22221 			delta    += cnt - 1;
22222 			env->prog = prog = new_prog;
22223 			insn      = new_prog->insnsi + i + delta;
22224 			goto next_insn;
22225 		}
22226 
22227 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
22228 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
22229 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
22230 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
22231 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
22232 			struct bpf_insn *patch = insn_buf;
22233 			bool issrc, isneg, isimm;
22234 			u32 off_reg;
22235 
22236 			aux = &env->insn_aux_data[i + delta];
22237 			if (!aux->alu_state ||
22238 			    aux->alu_state == BPF_ALU_NON_POINTER)
22239 				goto next_insn;
22240 
22241 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
22242 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
22243 				BPF_ALU_SANITIZE_SRC;
22244 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
22245 
22246 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
22247 			if (isimm) {
22248 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
22249 			} else {
22250 				if (isneg)
22251 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
22252 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
22253 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
22254 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
22255 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
22256 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
22257 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
22258 			}
22259 			if (!issrc)
22260 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
22261 			insn->src_reg = BPF_REG_AX;
22262 			if (isneg)
22263 				insn->code = insn->code == code_add ?
22264 					     code_sub : code_add;
22265 			*patch++ = *insn;
22266 			if (issrc && isneg && !isimm)
22267 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
22268 			cnt = patch - insn_buf;
22269 
22270 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22271 			if (!new_prog)
22272 				return -ENOMEM;
22273 
22274 			delta    += cnt - 1;
22275 			env->prog = prog = new_prog;
22276 			insn      = new_prog->insnsi + i + delta;
22277 			goto next_insn;
22278 		}
22279 
22280 		if (is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) {
22281 			int stack_off_cnt = -stack_depth - 16;
22282 
22283 			/*
22284 			 * Two 8 byte slots, depth-16 stores the count, and
22285 			 * depth-8 stores the start timestamp of the loop.
22286 			 *
22287 			 * The starting value of count is BPF_MAX_TIMED_LOOPS
22288 			 * (0xffff).  Every iteration loads it and subs it by 1,
22289 			 * until the value becomes 0 in AX (thus, 1 in stack),
22290 			 * after which we call arch_bpf_timed_may_goto, which
22291 			 * either sets AX to 0xffff to keep looping, or to 0
22292 			 * upon timeout. AX is then stored into the stack. In
22293 			 * the next iteration, we either see 0 and break out, or
22294 			 * continue iterating until the next time value is 0
22295 			 * after subtraction, rinse and repeat.
22296 			 */
22297 			stack_depth_extra = 16;
22298 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off_cnt);
22299 			if (insn->off >= 0)
22300 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 5);
22301 			else
22302 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
22303 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
22304 			insn_buf[3] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
22305 			/*
22306 			 * AX is used as an argument to pass in stack_off_cnt
22307 			 * (to add to r10/fp), and also as the return value of
22308 			 * the call to arch_bpf_timed_may_goto.
22309 			 */
22310 			insn_buf[4] = BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt);
22311 			insn_buf[5] = BPF_EMIT_CALL(arch_bpf_timed_may_goto);
22312 			insn_buf[6] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt);
22313 			cnt = 7;
22314 
22315 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22316 			if (!new_prog)
22317 				return -ENOMEM;
22318 
22319 			delta += cnt - 1;
22320 			env->prog = prog = new_prog;
22321 			insn = new_prog->insnsi + i + delta;
22322 			goto next_insn;
22323 		} else if (is_may_goto_insn(insn)) {
22324 			int stack_off = -stack_depth - 8;
22325 
22326 			stack_depth_extra = 8;
22327 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
22328 			if (insn->off >= 0)
22329 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
22330 			else
22331 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
22332 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
22333 			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
22334 			cnt = 4;
22335 
22336 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22337 			if (!new_prog)
22338 				return -ENOMEM;
22339 
22340 			delta += cnt - 1;
22341 			env->prog = prog = new_prog;
22342 			insn = new_prog->insnsi + i + delta;
22343 			goto next_insn;
22344 		}
22345 
22346 		if (insn->code != (BPF_JMP | BPF_CALL))
22347 			goto next_insn;
22348 		if (insn->src_reg == BPF_PSEUDO_CALL)
22349 			goto next_insn;
22350 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
22351 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
22352 			if (ret)
22353 				return ret;
22354 			if (cnt == 0)
22355 				goto next_insn;
22356 
22357 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22358 			if (!new_prog)
22359 				return -ENOMEM;
22360 
22361 			delta	 += cnt - 1;
22362 			env->prog = prog = new_prog;
22363 			insn	  = new_prog->insnsi + i + delta;
22364 			goto next_insn;
22365 		}
22366 
22367 		/* Skip inlining the helper call if the JIT does it. */
22368 		if (bpf_jit_inlines_helper_call(insn->imm))
22369 			goto next_insn;
22370 
22371 		if (insn->imm == BPF_FUNC_get_route_realm)
22372 			prog->dst_needed = 1;
22373 		if (insn->imm == BPF_FUNC_get_prandom_u32)
22374 			bpf_user_rnd_init_once();
22375 		if (insn->imm == BPF_FUNC_override_return)
22376 			prog->kprobe_override = 1;
22377 		if (insn->imm == BPF_FUNC_tail_call) {
22378 			/* If we tail call into other programs, we
22379 			 * cannot make any assumptions since they can
22380 			 * be replaced dynamically during runtime in
22381 			 * the program array.
22382 			 */
22383 			prog->cb_access = 1;
22384 			if (!allow_tail_call_in_subprogs(env))
22385 				prog->aux->stack_depth = MAX_BPF_STACK;
22386 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
22387 
22388 			/* mark bpf_tail_call as different opcode to avoid
22389 			 * conditional branch in the interpreter for every normal
22390 			 * call and to prevent accidental JITing by JIT compiler
22391 			 * that doesn't support bpf_tail_call yet
22392 			 */
22393 			insn->imm = 0;
22394 			insn->code = BPF_JMP | BPF_TAIL_CALL;
22395 
22396 			aux = &env->insn_aux_data[i + delta];
22397 			if (env->bpf_capable && !prog->blinding_requested &&
22398 			    prog->jit_requested &&
22399 			    !bpf_map_key_poisoned(aux) &&
22400 			    !bpf_map_ptr_poisoned(aux) &&
22401 			    !bpf_map_ptr_unpriv(aux)) {
22402 				struct bpf_jit_poke_descriptor desc = {
22403 					.reason = BPF_POKE_REASON_TAIL_CALL,
22404 					.tail_call.map = aux->map_ptr_state.map_ptr,
22405 					.tail_call.key = bpf_map_key_immediate(aux),
22406 					.insn_idx = i + delta,
22407 				};
22408 
22409 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
22410 				if (ret < 0) {
22411 					verbose(env, "adding tail call poke descriptor failed\n");
22412 					return ret;
22413 				}
22414 
22415 				insn->imm = ret + 1;
22416 				goto next_insn;
22417 			}
22418 
22419 			if (!bpf_map_ptr_unpriv(aux))
22420 				goto next_insn;
22421 
22422 			/* instead of changing every JIT dealing with tail_call
22423 			 * emit two extra insns:
22424 			 * if (index >= max_entries) goto out;
22425 			 * index &= array->index_mask;
22426 			 * to avoid out-of-bounds cpu speculation
22427 			 */
22428 			if (bpf_map_ptr_poisoned(aux)) {
22429 				verbose(env, "tail_call abusing map_ptr\n");
22430 				return -EINVAL;
22431 			}
22432 
22433 			map_ptr = aux->map_ptr_state.map_ptr;
22434 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
22435 						  map_ptr->max_entries, 2);
22436 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
22437 						    container_of(map_ptr,
22438 								 struct bpf_array,
22439 								 map)->index_mask);
22440 			insn_buf[2] = *insn;
22441 			cnt = 3;
22442 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22443 			if (!new_prog)
22444 				return -ENOMEM;
22445 
22446 			delta    += cnt - 1;
22447 			env->prog = prog = new_prog;
22448 			insn      = new_prog->insnsi + i + delta;
22449 			goto next_insn;
22450 		}
22451 
22452 		if (insn->imm == BPF_FUNC_timer_set_callback) {
22453 			/* The verifier will process callback_fn as many times as necessary
22454 			 * with different maps and the register states prepared by
22455 			 * set_timer_callback_state will be accurate.
22456 			 *
22457 			 * The following use case is valid:
22458 			 *   map1 is shared by prog1, prog2, prog3.
22459 			 *   prog1 calls bpf_timer_init for some map1 elements
22460 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
22461 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
22462 			 *   prog3 calls bpf_timer_start for some map1 elements.
22463 			 *     Those that were not both bpf_timer_init-ed and
22464 			 *     bpf_timer_set_callback-ed will return -EINVAL.
22465 			 */
22466 			struct bpf_insn ld_addrs[2] = {
22467 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
22468 			};
22469 
22470 			insn_buf[0] = ld_addrs[0];
22471 			insn_buf[1] = ld_addrs[1];
22472 			insn_buf[2] = *insn;
22473 			cnt = 3;
22474 
22475 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22476 			if (!new_prog)
22477 				return -ENOMEM;
22478 
22479 			delta    += cnt - 1;
22480 			env->prog = prog = new_prog;
22481 			insn      = new_prog->insnsi + i + delta;
22482 			goto patch_call_imm;
22483 		}
22484 
22485 		if (is_storage_get_function(insn->imm)) {
22486 			if (!in_sleepable(env) ||
22487 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
22488 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
22489 			else
22490 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
22491 			insn_buf[1] = *insn;
22492 			cnt = 2;
22493 
22494 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22495 			if (!new_prog)
22496 				return -ENOMEM;
22497 
22498 			delta += cnt - 1;
22499 			env->prog = prog = new_prog;
22500 			insn = new_prog->insnsi + i + delta;
22501 			goto patch_call_imm;
22502 		}
22503 
22504 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
22505 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
22506 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
22507 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
22508 			 */
22509 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
22510 			insn_buf[1] = *insn;
22511 			cnt = 2;
22512 
22513 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22514 			if (!new_prog)
22515 				return -ENOMEM;
22516 
22517 			delta += cnt - 1;
22518 			env->prog = prog = new_prog;
22519 			insn = new_prog->insnsi + i + delta;
22520 			goto patch_call_imm;
22521 		}
22522 
22523 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
22524 		 * and other inlining handlers are currently limited to 64 bit
22525 		 * only.
22526 		 */
22527 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
22528 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
22529 		     insn->imm == BPF_FUNC_map_update_elem ||
22530 		     insn->imm == BPF_FUNC_map_delete_elem ||
22531 		     insn->imm == BPF_FUNC_map_push_elem   ||
22532 		     insn->imm == BPF_FUNC_map_pop_elem    ||
22533 		     insn->imm == BPF_FUNC_map_peek_elem   ||
22534 		     insn->imm == BPF_FUNC_redirect_map    ||
22535 		     insn->imm == BPF_FUNC_for_each_map_elem ||
22536 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
22537 			aux = &env->insn_aux_data[i + delta];
22538 			if (bpf_map_ptr_poisoned(aux))
22539 				goto patch_call_imm;
22540 
22541 			map_ptr = aux->map_ptr_state.map_ptr;
22542 			ops = map_ptr->ops;
22543 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
22544 			    ops->map_gen_lookup) {
22545 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
22546 				if (cnt == -EOPNOTSUPP)
22547 					goto patch_map_ops_generic;
22548 				if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
22549 					verifier_bug(env, "%d insns generated for map lookup", cnt);
22550 					return -EFAULT;
22551 				}
22552 
22553 				new_prog = bpf_patch_insn_data(env, i + delta,
22554 							       insn_buf, cnt);
22555 				if (!new_prog)
22556 					return -ENOMEM;
22557 
22558 				delta    += cnt - 1;
22559 				env->prog = prog = new_prog;
22560 				insn      = new_prog->insnsi + i + delta;
22561 				goto next_insn;
22562 			}
22563 
22564 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
22565 				     (void *(*)(struct bpf_map *map, void *key))NULL));
22566 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
22567 				     (long (*)(struct bpf_map *map, void *key))NULL));
22568 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
22569 				     (long (*)(struct bpf_map *map, void *key, void *value,
22570 					      u64 flags))NULL));
22571 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
22572 				     (long (*)(struct bpf_map *map, void *value,
22573 					      u64 flags))NULL));
22574 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
22575 				     (long (*)(struct bpf_map *map, void *value))NULL));
22576 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
22577 				     (long (*)(struct bpf_map *map, void *value))NULL));
22578 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
22579 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
22580 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
22581 				     (long (*)(struct bpf_map *map,
22582 					      bpf_callback_t callback_fn,
22583 					      void *callback_ctx,
22584 					      u64 flags))NULL));
22585 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
22586 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
22587 
22588 patch_map_ops_generic:
22589 			switch (insn->imm) {
22590 			case BPF_FUNC_map_lookup_elem:
22591 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
22592 				goto next_insn;
22593 			case BPF_FUNC_map_update_elem:
22594 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
22595 				goto next_insn;
22596 			case BPF_FUNC_map_delete_elem:
22597 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
22598 				goto next_insn;
22599 			case BPF_FUNC_map_push_elem:
22600 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
22601 				goto next_insn;
22602 			case BPF_FUNC_map_pop_elem:
22603 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
22604 				goto next_insn;
22605 			case BPF_FUNC_map_peek_elem:
22606 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
22607 				goto next_insn;
22608 			case BPF_FUNC_redirect_map:
22609 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
22610 				goto next_insn;
22611 			case BPF_FUNC_for_each_map_elem:
22612 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
22613 				goto next_insn;
22614 			case BPF_FUNC_map_lookup_percpu_elem:
22615 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
22616 				goto next_insn;
22617 			}
22618 
22619 			goto patch_call_imm;
22620 		}
22621 
22622 		/* Implement bpf_jiffies64 inline. */
22623 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
22624 		    insn->imm == BPF_FUNC_jiffies64) {
22625 			struct bpf_insn ld_jiffies_addr[2] = {
22626 				BPF_LD_IMM64(BPF_REG_0,
22627 					     (unsigned long)&jiffies),
22628 			};
22629 
22630 			insn_buf[0] = ld_jiffies_addr[0];
22631 			insn_buf[1] = ld_jiffies_addr[1];
22632 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
22633 						  BPF_REG_0, 0);
22634 			cnt = 3;
22635 
22636 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
22637 						       cnt);
22638 			if (!new_prog)
22639 				return -ENOMEM;
22640 
22641 			delta    += cnt - 1;
22642 			env->prog = prog = new_prog;
22643 			insn      = new_prog->insnsi + i + delta;
22644 			goto next_insn;
22645 		}
22646 
22647 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
22648 		/* Implement bpf_get_smp_processor_id() inline. */
22649 		if (insn->imm == BPF_FUNC_get_smp_processor_id &&
22650 		    verifier_inlines_helper_call(env, insn->imm)) {
22651 			/* BPF_FUNC_get_smp_processor_id inlining is an
22652 			 * optimization, so if cpu_number is ever
22653 			 * changed in some incompatible and hard to support
22654 			 * way, it's fine to back out this inlining logic
22655 			 */
22656 #ifdef CONFIG_SMP
22657 			insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&cpu_number);
22658 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
22659 			insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
22660 			cnt = 3;
22661 #else
22662 			insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
22663 			cnt = 1;
22664 #endif
22665 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22666 			if (!new_prog)
22667 				return -ENOMEM;
22668 
22669 			delta    += cnt - 1;
22670 			env->prog = prog = new_prog;
22671 			insn      = new_prog->insnsi + i + delta;
22672 			goto next_insn;
22673 		}
22674 #endif
22675 		/* Implement bpf_get_func_arg inline. */
22676 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22677 		    insn->imm == BPF_FUNC_get_func_arg) {
22678 			/* Load nr_args from ctx - 8 */
22679 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22680 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
22681 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
22682 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
22683 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
22684 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
22685 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
22686 			insn_buf[7] = BPF_JMP_A(1);
22687 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
22688 			cnt = 9;
22689 
22690 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22691 			if (!new_prog)
22692 				return -ENOMEM;
22693 
22694 			delta    += cnt - 1;
22695 			env->prog = prog = new_prog;
22696 			insn      = new_prog->insnsi + i + delta;
22697 			goto next_insn;
22698 		}
22699 
22700 		/* Implement bpf_get_func_ret inline. */
22701 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22702 		    insn->imm == BPF_FUNC_get_func_ret) {
22703 			if (eatype == BPF_TRACE_FEXIT ||
22704 			    eatype == BPF_MODIFY_RETURN) {
22705 				/* Load nr_args from ctx - 8 */
22706 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22707 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
22708 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
22709 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
22710 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
22711 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
22712 				cnt = 6;
22713 			} else {
22714 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
22715 				cnt = 1;
22716 			}
22717 
22718 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22719 			if (!new_prog)
22720 				return -ENOMEM;
22721 
22722 			delta    += cnt - 1;
22723 			env->prog = prog = new_prog;
22724 			insn      = new_prog->insnsi + i + delta;
22725 			goto next_insn;
22726 		}
22727 
22728 		/* Implement get_func_arg_cnt inline. */
22729 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22730 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
22731 			/* Load nr_args from ctx - 8 */
22732 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22733 
22734 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
22735 			if (!new_prog)
22736 				return -ENOMEM;
22737 
22738 			env->prog = prog = new_prog;
22739 			insn      = new_prog->insnsi + i + delta;
22740 			goto next_insn;
22741 		}
22742 
22743 		/* Implement bpf_get_func_ip inline. */
22744 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22745 		    insn->imm == BPF_FUNC_get_func_ip) {
22746 			/* Load IP address from ctx - 16 */
22747 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
22748 
22749 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
22750 			if (!new_prog)
22751 				return -ENOMEM;
22752 
22753 			env->prog = prog = new_prog;
22754 			insn      = new_prog->insnsi + i + delta;
22755 			goto next_insn;
22756 		}
22757 
22758 		/* Implement bpf_get_branch_snapshot inline. */
22759 		if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
22760 		    prog->jit_requested && BITS_PER_LONG == 64 &&
22761 		    insn->imm == BPF_FUNC_get_branch_snapshot) {
22762 			/* We are dealing with the following func protos:
22763 			 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
22764 			 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
22765 			 */
22766 			const u32 br_entry_size = sizeof(struct perf_branch_entry);
22767 
22768 			/* struct perf_branch_entry is part of UAPI and is
22769 			 * used as an array element, so extremely unlikely to
22770 			 * ever grow or shrink
22771 			 */
22772 			BUILD_BUG_ON(br_entry_size != 24);
22773 
22774 			/* if (unlikely(flags)) return -EINVAL */
22775 			insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
22776 
22777 			/* Transform size (bytes) into number of entries (cnt = size / 24).
22778 			 * But to avoid expensive division instruction, we implement
22779 			 * divide-by-3 through multiplication, followed by further
22780 			 * division by 8 through 3-bit right shift.
22781 			 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
22782 			 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
22783 			 *
22784 			 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
22785 			 */
22786 			insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
22787 			insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
22788 			insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
22789 
22790 			/* call perf_snapshot_branch_stack implementation */
22791 			insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
22792 			/* if (entry_cnt == 0) return -ENOENT */
22793 			insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
22794 			/* return entry_cnt * sizeof(struct perf_branch_entry) */
22795 			insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
22796 			insn_buf[7] = BPF_JMP_A(3);
22797 			/* return -EINVAL; */
22798 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
22799 			insn_buf[9] = BPF_JMP_A(1);
22800 			/* return -ENOENT; */
22801 			insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
22802 			cnt = 11;
22803 
22804 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22805 			if (!new_prog)
22806 				return -ENOMEM;
22807 
22808 			delta    += cnt - 1;
22809 			env->prog = prog = new_prog;
22810 			insn      = new_prog->insnsi + i + delta;
22811 			goto next_insn;
22812 		}
22813 
22814 		/* Implement bpf_kptr_xchg inline */
22815 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
22816 		    insn->imm == BPF_FUNC_kptr_xchg &&
22817 		    bpf_jit_supports_ptr_xchg()) {
22818 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
22819 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
22820 			cnt = 2;
22821 
22822 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22823 			if (!new_prog)
22824 				return -ENOMEM;
22825 
22826 			delta    += cnt - 1;
22827 			env->prog = prog = new_prog;
22828 			insn      = new_prog->insnsi + i + delta;
22829 			goto next_insn;
22830 		}
22831 patch_call_imm:
22832 		fn = env->ops->get_func_proto(insn->imm, env->prog);
22833 		/* all functions that have prototype and verifier allowed
22834 		 * programs to call them, must be real in-kernel functions
22835 		 */
22836 		if (!fn->func) {
22837 			verifier_bug(env,
22838 				     "not inlined functions %s#%d is missing func",
22839 				     func_id_name(insn->imm), insn->imm);
22840 			return -EFAULT;
22841 		}
22842 		insn->imm = fn->func - __bpf_call_base;
22843 next_insn:
22844 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
22845 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
22846 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
22847 
22848 			stack_depth = subprogs[cur_subprog].stack_depth;
22849 			if (stack_depth > MAX_BPF_STACK && !prog->jit_requested) {
22850 				verbose(env, "stack size %d(extra %d) is too large\n",
22851 					stack_depth, stack_depth_extra);
22852 				return -EINVAL;
22853 			}
22854 			cur_subprog++;
22855 			stack_depth = subprogs[cur_subprog].stack_depth;
22856 			stack_depth_extra = 0;
22857 		}
22858 		i++;
22859 		insn++;
22860 	}
22861 
22862 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
22863 	for (i = 0; i < env->subprog_cnt; i++) {
22864 		int delta = bpf_jit_supports_timed_may_goto() ? 2 : 1;
22865 		int subprog_start = subprogs[i].start;
22866 		int stack_slots = subprogs[i].stack_extra / 8;
22867 		int slots = delta, cnt = 0;
22868 
22869 		if (!stack_slots)
22870 			continue;
22871 		/* We need two slots in case timed may_goto is supported. */
22872 		if (stack_slots > slots) {
22873 			verifier_bug(env, "stack_slots supports may_goto only");
22874 			return -EFAULT;
22875 		}
22876 
22877 		stack_depth = subprogs[i].stack_depth;
22878 		if (bpf_jit_supports_timed_may_goto()) {
22879 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
22880 						     BPF_MAX_TIMED_LOOPS);
22881 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth + 8, 0);
22882 		} else {
22883 			/* Add ST insn to subprog prologue to init extra stack */
22884 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
22885 						     BPF_MAX_LOOPS);
22886 		}
22887 		/* Copy first actual insn to preserve it */
22888 		insn_buf[cnt++] = env->prog->insnsi[subprog_start];
22889 
22890 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, cnt);
22891 		if (!new_prog)
22892 			return -ENOMEM;
22893 		env->prog = prog = new_prog;
22894 		/*
22895 		 * If may_goto is a first insn of a prog there could be a jmp
22896 		 * insn that points to it, hence adjust all such jmps to point
22897 		 * to insn after BPF_ST that inits may_goto count.
22898 		 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
22899 		 */
22900 		WARN_ON(adjust_jmp_off(env->prog, subprog_start, delta));
22901 	}
22902 
22903 	/* Since poke tab is now finalized, publish aux to tracker. */
22904 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
22905 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
22906 		if (!map_ptr->ops->map_poke_track ||
22907 		    !map_ptr->ops->map_poke_untrack ||
22908 		    !map_ptr->ops->map_poke_run) {
22909 			verifier_bug(env, "poke tab is misconfigured");
22910 			return -EFAULT;
22911 		}
22912 
22913 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
22914 		if (ret < 0) {
22915 			verbose(env, "tracking tail call prog failed\n");
22916 			return ret;
22917 		}
22918 	}
22919 
22920 	sort_kfunc_descs_by_imm_off(env->prog);
22921 
22922 	return 0;
22923 }
22924 
22925 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
22926 					int position,
22927 					s32 stack_base,
22928 					u32 callback_subprogno,
22929 					u32 *total_cnt)
22930 {
22931 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
22932 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
22933 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
22934 	int reg_loop_max = BPF_REG_6;
22935 	int reg_loop_cnt = BPF_REG_7;
22936 	int reg_loop_ctx = BPF_REG_8;
22937 
22938 	struct bpf_insn *insn_buf = env->insn_buf;
22939 	struct bpf_prog *new_prog;
22940 	u32 callback_start;
22941 	u32 call_insn_offset;
22942 	s32 callback_offset;
22943 	u32 cnt = 0;
22944 
22945 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
22946 	 * be careful to modify this code in sync.
22947 	 */
22948 
22949 	/* Return error and jump to the end of the patch if
22950 	 * expected number of iterations is too big.
22951 	 */
22952 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
22953 	insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
22954 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
22955 	/* spill R6, R7, R8 to use these as loop vars */
22956 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
22957 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
22958 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
22959 	/* initialize loop vars */
22960 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
22961 	insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
22962 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
22963 	/* loop header,
22964 	 * if reg_loop_cnt >= reg_loop_max skip the loop body
22965 	 */
22966 	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
22967 	/* callback call,
22968 	 * correct callback offset would be set after patching
22969 	 */
22970 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
22971 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
22972 	insn_buf[cnt++] = BPF_CALL_REL(0);
22973 	/* increment loop counter */
22974 	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
22975 	/* jump to loop header if callback returned 0 */
22976 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
22977 	/* return value of bpf_loop,
22978 	 * set R0 to the number of iterations
22979 	 */
22980 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
22981 	/* restore original values of R6, R7, R8 */
22982 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
22983 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
22984 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
22985 
22986 	*total_cnt = cnt;
22987 	new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
22988 	if (!new_prog)
22989 		return new_prog;
22990 
22991 	/* callback start is known only after patching */
22992 	callback_start = env->subprog_info[callback_subprogno].start;
22993 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
22994 	call_insn_offset = position + 12;
22995 	callback_offset = callback_start - call_insn_offset - 1;
22996 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
22997 
22998 	return new_prog;
22999 }
23000 
23001 static bool is_bpf_loop_call(struct bpf_insn *insn)
23002 {
23003 	return insn->code == (BPF_JMP | BPF_CALL) &&
23004 		insn->src_reg == 0 &&
23005 		insn->imm == BPF_FUNC_loop;
23006 }
23007 
23008 /* For all sub-programs in the program (including main) check
23009  * insn_aux_data to see if there are bpf_loop calls that require
23010  * inlining. If such calls are found the calls are replaced with a
23011  * sequence of instructions produced by `inline_bpf_loop` function and
23012  * subprog stack_depth is increased by the size of 3 registers.
23013  * This stack space is used to spill values of the R6, R7, R8.  These
23014  * registers are used to store the loop bound, counter and context
23015  * variables.
23016  */
23017 static int optimize_bpf_loop(struct bpf_verifier_env *env)
23018 {
23019 	struct bpf_subprog_info *subprogs = env->subprog_info;
23020 	int i, cur_subprog = 0, cnt, delta = 0;
23021 	struct bpf_insn *insn = env->prog->insnsi;
23022 	int insn_cnt = env->prog->len;
23023 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
23024 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
23025 	u16 stack_depth_extra = 0;
23026 
23027 	for (i = 0; i < insn_cnt; i++, insn++) {
23028 		struct bpf_loop_inline_state *inline_state =
23029 			&env->insn_aux_data[i + delta].loop_inline_state;
23030 
23031 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
23032 			struct bpf_prog *new_prog;
23033 
23034 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
23035 			new_prog = inline_bpf_loop(env,
23036 						   i + delta,
23037 						   -(stack_depth + stack_depth_extra),
23038 						   inline_state->callback_subprogno,
23039 						   &cnt);
23040 			if (!new_prog)
23041 				return -ENOMEM;
23042 
23043 			delta     += cnt - 1;
23044 			env->prog  = new_prog;
23045 			insn       = new_prog->insnsi + i + delta;
23046 		}
23047 
23048 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
23049 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
23050 			cur_subprog++;
23051 			stack_depth = subprogs[cur_subprog].stack_depth;
23052 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
23053 			stack_depth_extra = 0;
23054 		}
23055 	}
23056 
23057 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
23058 
23059 	return 0;
23060 }
23061 
23062 /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
23063  * adjust subprograms stack depth when possible.
23064  */
23065 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env)
23066 {
23067 	struct bpf_subprog_info *subprog = env->subprog_info;
23068 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
23069 	struct bpf_insn *insn = env->prog->insnsi;
23070 	int insn_cnt = env->prog->len;
23071 	u32 spills_num;
23072 	bool modified = false;
23073 	int i, j;
23074 
23075 	for (i = 0; i < insn_cnt; i++, insn++) {
23076 		if (aux[i].fastcall_spills_num > 0) {
23077 			spills_num = aux[i].fastcall_spills_num;
23078 			/* NOPs would be removed by opt_remove_nops() */
23079 			for (j = 1; j <= spills_num; ++j) {
23080 				*(insn - j) = NOP;
23081 				*(insn + j) = NOP;
23082 			}
23083 			modified = true;
23084 		}
23085 		if ((subprog + 1)->start == i + 1) {
23086 			if (modified && !subprog->keep_fastcall_stack)
23087 				subprog->stack_depth = -subprog->fastcall_stack_off;
23088 			subprog++;
23089 			modified = false;
23090 		}
23091 	}
23092 
23093 	return 0;
23094 }
23095 
23096 static void free_states(struct bpf_verifier_env *env)
23097 {
23098 	struct bpf_verifier_state_list *sl;
23099 	struct list_head *head, *pos, *tmp;
23100 	struct bpf_scc_info *info;
23101 	int i, j;
23102 
23103 	free_verifier_state(env->cur_state, true);
23104 	env->cur_state = NULL;
23105 	while (!pop_stack(env, NULL, NULL, false));
23106 
23107 	list_for_each_safe(pos, tmp, &env->free_list) {
23108 		sl = container_of(pos, struct bpf_verifier_state_list, node);
23109 		free_verifier_state(&sl->state, false);
23110 		kfree(sl);
23111 	}
23112 	INIT_LIST_HEAD(&env->free_list);
23113 
23114 	for (i = 0; i < env->scc_cnt; ++i) {
23115 		info = env->scc_info[i];
23116 		if (!info)
23117 			continue;
23118 		for (j = 0; j < info->num_visits; j++)
23119 			free_backedges(&info->visits[j]);
23120 		kvfree(info);
23121 		env->scc_info[i] = NULL;
23122 	}
23123 
23124 	if (!env->explored_states)
23125 		return;
23126 
23127 	for (i = 0; i < state_htab_size(env); i++) {
23128 		head = &env->explored_states[i];
23129 
23130 		list_for_each_safe(pos, tmp, head) {
23131 			sl = container_of(pos, struct bpf_verifier_state_list, node);
23132 			free_verifier_state(&sl->state, false);
23133 			kfree(sl);
23134 		}
23135 		INIT_LIST_HEAD(&env->explored_states[i]);
23136 	}
23137 }
23138 
23139 static int do_check_common(struct bpf_verifier_env *env, int subprog)
23140 {
23141 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
23142 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
23143 	struct bpf_prog_aux *aux = env->prog->aux;
23144 	struct bpf_verifier_state *state;
23145 	struct bpf_reg_state *regs;
23146 	int ret, i;
23147 
23148 	env->prev_linfo = NULL;
23149 	env->pass_cnt++;
23150 
23151 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL_ACCOUNT);
23152 	if (!state)
23153 		return -ENOMEM;
23154 	state->curframe = 0;
23155 	state->speculative = false;
23156 	state->branches = 1;
23157 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL_ACCOUNT);
23158 	if (!state->frame[0]) {
23159 		kfree(state);
23160 		return -ENOMEM;
23161 	}
23162 	env->cur_state = state;
23163 	init_func_state(env, state->frame[0],
23164 			BPF_MAIN_FUNC /* callsite */,
23165 			0 /* frameno */,
23166 			subprog);
23167 	state->first_insn_idx = env->subprog_info[subprog].start;
23168 	state->last_insn_idx = -1;
23169 
23170 	regs = state->frame[state->curframe]->regs;
23171 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
23172 		const char *sub_name = subprog_name(env, subprog);
23173 		struct bpf_subprog_arg_info *arg;
23174 		struct bpf_reg_state *reg;
23175 
23176 		verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
23177 		ret = btf_prepare_func_args(env, subprog);
23178 		if (ret)
23179 			goto out;
23180 
23181 		if (subprog_is_exc_cb(env, subprog)) {
23182 			state->frame[0]->in_exception_callback_fn = true;
23183 			/* We have already ensured that the callback returns an integer, just
23184 			 * like all global subprogs. We need to determine it only has a single
23185 			 * scalar argument.
23186 			 */
23187 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
23188 				verbose(env, "exception cb only supports single integer argument\n");
23189 				ret = -EINVAL;
23190 				goto out;
23191 			}
23192 		}
23193 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
23194 			arg = &sub->args[i - BPF_REG_1];
23195 			reg = &regs[i];
23196 
23197 			if (arg->arg_type == ARG_PTR_TO_CTX) {
23198 				reg->type = PTR_TO_CTX;
23199 				mark_reg_known_zero(env, regs, i);
23200 			} else if (arg->arg_type == ARG_ANYTHING) {
23201 				reg->type = SCALAR_VALUE;
23202 				mark_reg_unknown(env, regs, i);
23203 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
23204 				/* assume unspecial LOCAL dynptr type */
23205 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
23206 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
23207 				reg->type = PTR_TO_MEM;
23208 				reg->type |= arg->arg_type &
23209 					     (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY);
23210 				mark_reg_known_zero(env, regs, i);
23211 				reg->mem_size = arg->mem_size;
23212 				if (arg->arg_type & PTR_MAYBE_NULL)
23213 					reg->id = ++env->id_gen;
23214 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
23215 				reg->type = PTR_TO_BTF_ID;
23216 				if (arg->arg_type & PTR_MAYBE_NULL)
23217 					reg->type |= PTR_MAYBE_NULL;
23218 				if (arg->arg_type & PTR_UNTRUSTED)
23219 					reg->type |= PTR_UNTRUSTED;
23220 				if (arg->arg_type & PTR_TRUSTED)
23221 					reg->type |= PTR_TRUSTED;
23222 				mark_reg_known_zero(env, regs, i);
23223 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
23224 				reg->btf_id = arg->btf_id;
23225 				reg->id = ++env->id_gen;
23226 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
23227 				/* caller can pass either PTR_TO_ARENA or SCALAR */
23228 				mark_reg_unknown(env, regs, i);
23229 			} else {
23230 				verifier_bug(env, "unhandled arg#%d type %d",
23231 					     i - BPF_REG_1, arg->arg_type);
23232 				ret = -EFAULT;
23233 				goto out;
23234 			}
23235 		}
23236 	} else {
23237 		/* if main BPF program has associated BTF info, validate that
23238 		 * it's matching expected signature, and otherwise mark BTF
23239 		 * info for main program as unreliable
23240 		 */
23241 		if (env->prog->aux->func_info_aux) {
23242 			ret = btf_prepare_func_args(env, 0);
23243 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
23244 				env->prog->aux->func_info_aux[0].unreliable = true;
23245 		}
23246 
23247 		/* 1st arg to a function */
23248 		regs[BPF_REG_1].type = PTR_TO_CTX;
23249 		mark_reg_known_zero(env, regs, BPF_REG_1);
23250 	}
23251 
23252 	/* Acquire references for struct_ops program arguments tagged with "__ref" */
23253 	if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
23254 		for (i = 0; i < aux->ctx_arg_info_size; i++)
23255 			aux->ctx_arg_info[i].ref_obj_id = aux->ctx_arg_info[i].refcounted ?
23256 							  acquire_reference(env, 0) : 0;
23257 	}
23258 
23259 	ret = do_check(env);
23260 out:
23261 	if (!ret && pop_log)
23262 		bpf_vlog_reset(&env->log, 0);
23263 	free_states(env);
23264 	return ret;
23265 }
23266 
23267 /* Lazily verify all global functions based on their BTF, if they are called
23268  * from main BPF program or any of subprograms transitively.
23269  * BPF global subprogs called from dead code are not validated.
23270  * All callable global functions must pass verification.
23271  * Otherwise the whole program is rejected.
23272  * Consider:
23273  * int bar(int);
23274  * int foo(int f)
23275  * {
23276  *    return bar(f);
23277  * }
23278  * int bar(int b)
23279  * {
23280  *    ...
23281  * }
23282  * foo() will be verified first for R1=any_scalar_value. During verification it
23283  * will be assumed that bar() already verified successfully and call to bar()
23284  * from foo() will be checked for type match only. Later bar() will be verified
23285  * independently to check that it's safe for R1=any_scalar_value.
23286  */
23287 static int do_check_subprogs(struct bpf_verifier_env *env)
23288 {
23289 	struct bpf_prog_aux *aux = env->prog->aux;
23290 	struct bpf_func_info_aux *sub_aux;
23291 	int i, ret, new_cnt;
23292 
23293 	if (!aux->func_info)
23294 		return 0;
23295 
23296 	/* exception callback is presumed to be always called */
23297 	if (env->exception_callback_subprog)
23298 		subprog_aux(env, env->exception_callback_subprog)->called = true;
23299 
23300 again:
23301 	new_cnt = 0;
23302 	for (i = 1; i < env->subprog_cnt; i++) {
23303 		if (!subprog_is_global(env, i))
23304 			continue;
23305 
23306 		sub_aux = subprog_aux(env, i);
23307 		if (!sub_aux->called || sub_aux->verified)
23308 			continue;
23309 
23310 		env->insn_idx = env->subprog_info[i].start;
23311 		WARN_ON_ONCE(env->insn_idx == 0);
23312 		ret = do_check_common(env, i);
23313 		if (ret) {
23314 			return ret;
23315 		} else if (env->log.level & BPF_LOG_LEVEL) {
23316 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
23317 				i, subprog_name(env, i));
23318 		}
23319 
23320 		/* We verified new global subprog, it might have called some
23321 		 * more global subprogs that we haven't verified yet, so we
23322 		 * need to do another pass over subprogs to verify those.
23323 		 */
23324 		sub_aux->verified = true;
23325 		new_cnt++;
23326 	}
23327 
23328 	/* We can't loop forever as we verify at least one global subprog on
23329 	 * each pass.
23330 	 */
23331 	if (new_cnt)
23332 		goto again;
23333 
23334 	return 0;
23335 }
23336 
23337 static int do_check_main(struct bpf_verifier_env *env)
23338 {
23339 	int ret;
23340 
23341 	env->insn_idx = 0;
23342 	ret = do_check_common(env, 0);
23343 	if (!ret)
23344 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
23345 	return ret;
23346 }
23347 
23348 
23349 static void print_verification_stats(struct bpf_verifier_env *env)
23350 {
23351 	int i;
23352 
23353 	if (env->log.level & BPF_LOG_STATS) {
23354 		verbose(env, "verification time %lld usec\n",
23355 			div_u64(env->verification_time, 1000));
23356 		verbose(env, "stack depth ");
23357 		for (i = 0; i < env->subprog_cnt; i++) {
23358 			u32 depth = env->subprog_info[i].stack_depth;
23359 
23360 			verbose(env, "%d", depth);
23361 			if (i + 1 < env->subprog_cnt)
23362 				verbose(env, "+");
23363 		}
23364 		verbose(env, "\n");
23365 	}
23366 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
23367 		"total_states %d peak_states %d mark_read %d\n",
23368 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
23369 		env->max_states_per_insn, env->total_states,
23370 		env->peak_states, env->longest_mark_read_walk);
23371 }
23372 
23373 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
23374 			       const struct bpf_ctx_arg_aux *info, u32 cnt)
23375 {
23376 	prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT);
23377 	prog->aux->ctx_arg_info_size = cnt;
23378 
23379 	return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
23380 }
23381 
23382 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
23383 {
23384 	const struct btf_type *t, *func_proto;
23385 	const struct bpf_struct_ops_desc *st_ops_desc;
23386 	const struct bpf_struct_ops *st_ops;
23387 	const struct btf_member *member;
23388 	struct bpf_prog *prog = env->prog;
23389 	bool has_refcounted_arg = false;
23390 	u32 btf_id, member_idx, member_off;
23391 	struct btf *btf;
23392 	const char *mname;
23393 	int i, err;
23394 
23395 	if (!prog->gpl_compatible) {
23396 		verbose(env, "struct ops programs must have a GPL compatible license\n");
23397 		return -EINVAL;
23398 	}
23399 
23400 	if (!prog->aux->attach_btf_id)
23401 		return -ENOTSUPP;
23402 
23403 	btf = prog->aux->attach_btf;
23404 	if (btf_is_module(btf)) {
23405 		/* Make sure st_ops is valid through the lifetime of env */
23406 		env->attach_btf_mod = btf_try_get_module(btf);
23407 		if (!env->attach_btf_mod) {
23408 			verbose(env, "struct_ops module %s is not found\n",
23409 				btf_get_name(btf));
23410 			return -ENOTSUPP;
23411 		}
23412 	}
23413 
23414 	btf_id = prog->aux->attach_btf_id;
23415 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
23416 	if (!st_ops_desc) {
23417 		verbose(env, "attach_btf_id %u is not a supported struct\n",
23418 			btf_id);
23419 		return -ENOTSUPP;
23420 	}
23421 	st_ops = st_ops_desc->st_ops;
23422 
23423 	t = st_ops_desc->type;
23424 	member_idx = prog->expected_attach_type;
23425 	if (member_idx >= btf_type_vlen(t)) {
23426 		verbose(env, "attach to invalid member idx %u of struct %s\n",
23427 			member_idx, st_ops->name);
23428 		return -EINVAL;
23429 	}
23430 
23431 	member = &btf_type_member(t)[member_idx];
23432 	mname = btf_name_by_offset(btf, member->name_off);
23433 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
23434 					       NULL);
23435 	if (!func_proto) {
23436 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
23437 			mname, member_idx, st_ops->name);
23438 		return -EINVAL;
23439 	}
23440 
23441 	member_off = __btf_member_bit_offset(t, member) / 8;
23442 	err = bpf_struct_ops_supported(st_ops, member_off);
23443 	if (err) {
23444 		verbose(env, "attach to unsupported member %s of struct %s\n",
23445 			mname, st_ops->name);
23446 		return err;
23447 	}
23448 
23449 	if (st_ops->check_member) {
23450 		err = st_ops->check_member(t, member, prog);
23451 
23452 		if (err) {
23453 			verbose(env, "attach to unsupported member %s of struct %s\n",
23454 				mname, st_ops->name);
23455 			return err;
23456 		}
23457 	}
23458 
23459 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
23460 		verbose(env, "Private stack not supported by jit\n");
23461 		return -EACCES;
23462 	}
23463 
23464 	for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) {
23465 		if (st_ops_desc->arg_info[member_idx].info->refcounted) {
23466 			has_refcounted_arg = true;
23467 			break;
23468 		}
23469 	}
23470 
23471 	/* Tail call is not allowed for programs with refcounted arguments since we
23472 	 * cannot guarantee that valid refcounted kptrs will be passed to the callee.
23473 	 */
23474 	for (i = 0; i < env->subprog_cnt; i++) {
23475 		if (has_refcounted_arg && env->subprog_info[i].has_tail_call) {
23476 			verbose(env, "program with __ref argument cannot tail call\n");
23477 			return -EINVAL;
23478 		}
23479 	}
23480 
23481 	prog->aux->st_ops = st_ops;
23482 	prog->aux->attach_st_ops_member_off = member_off;
23483 
23484 	prog->aux->attach_func_proto = func_proto;
23485 	prog->aux->attach_func_name = mname;
23486 	env->ops = st_ops->verifier_ops;
23487 
23488 	return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info,
23489 					  st_ops_desc->arg_info[member_idx].cnt);
23490 }
23491 #define SECURITY_PREFIX "security_"
23492 
23493 static int check_attach_modify_return(unsigned long addr, const char *func_name)
23494 {
23495 	if (within_error_injection_list(addr) ||
23496 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
23497 		return 0;
23498 
23499 	return -EINVAL;
23500 }
23501 
23502 /* list of non-sleepable functions that are otherwise on
23503  * ALLOW_ERROR_INJECTION list
23504  */
23505 BTF_SET_START(btf_non_sleepable_error_inject)
23506 /* Three functions below can be called from sleepable and non-sleepable context.
23507  * Assume non-sleepable from bpf safety point of view.
23508  */
23509 BTF_ID(func, __filemap_add_folio)
23510 #ifdef CONFIG_FAIL_PAGE_ALLOC
23511 BTF_ID(func, should_fail_alloc_page)
23512 #endif
23513 #ifdef CONFIG_FAILSLAB
23514 BTF_ID(func, should_failslab)
23515 #endif
23516 BTF_SET_END(btf_non_sleepable_error_inject)
23517 
23518 static int check_non_sleepable_error_inject(u32 btf_id)
23519 {
23520 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
23521 }
23522 
23523 int bpf_check_attach_target(struct bpf_verifier_log *log,
23524 			    const struct bpf_prog *prog,
23525 			    const struct bpf_prog *tgt_prog,
23526 			    u32 btf_id,
23527 			    struct bpf_attach_target_info *tgt_info)
23528 {
23529 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
23530 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
23531 	char trace_symbol[KSYM_SYMBOL_LEN];
23532 	const char prefix[] = "btf_trace_";
23533 	struct bpf_raw_event_map *btp;
23534 	int ret = 0, subprog = -1, i;
23535 	const struct btf_type *t;
23536 	bool conservative = true;
23537 	const char *tname, *fname;
23538 	struct btf *btf;
23539 	long addr = 0;
23540 	struct module *mod = NULL;
23541 
23542 	if (!btf_id) {
23543 		bpf_log(log, "Tracing programs must provide btf_id\n");
23544 		return -EINVAL;
23545 	}
23546 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
23547 	if (!btf) {
23548 		bpf_log(log,
23549 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
23550 		return -EINVAL;
23551 	}
23552 	t = btf_type_by_id(btf, btf_id);
23553 	if (!t) {
23554 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
23555 		return -EINVAL;
23556 	}
23557 	tname = btf_name_by_offset(btf, t->name_off);
23558 	if (!tname) {
23559 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
23560 		return -EINVAL;
23561 	}
23562 	if (tgt_prog) {
23563 		struct bpf_prog_aux *aux = tgt_prog->aux;
23564 		bool tgt_changes_pkt_data;
23565 		bool tgt_might_sleep;
23566 
23567 		if (bpf_prog_is_dev_bound(prog->aux) &&
23568 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
23569 			bpf_log(log, "Target program bound device mismatch");
23570 			return -EINVAL;
23571 		}
23572 
23573 		for (i = 0; i < aux->func_info_cnt; i++)
23574 			if (aux->func_info[i].type_id == btf_id) {
23575 				subprog = i;
23576 				break;
23577 			}
23578 		if (subprog == -1) {
23579 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
23580 			return -EINVAL;
23581 		}
23582 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
23583 			bpf_log(log,
23584 				"%s programs cannot attach to exception callback\n",
23585 				prog_extension ? "Extension" : "FENTRY/FEXIT");
23586 			return -EINVAL;
23587 		}
23588 		conservative = aux->func_info_aux[subprog].unreliable;
23589 		if (prog_extension) {
23590 			if (conservative) {
23591 				bpf_log(log,
23592 					"Cannot replace static functions\n");
23593 				return -EINVAL;
23594 			}
23595 			if (!prog->jit_requested) {
23596 				bpf_log(log,
23597 					"Extension programs should be JITed\n");
23598 				return -EINVAL;
23599 			}
23600 			tgt_changes_pkt_data = aux->func
23601 					       ? aux->func[subprog]->aux->changes_pkt_data
23602 					       : aux->changes_pkt_data;
23603 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
23604 				bpf_log(log,
23605 					"Extension program changes packet data, while original does not\n");
23606 				return -EINVAL;
23607 			}
23608 
23609 			tgt_might_sleep = aux->func
23610 					  ? aux->func[subprog]->aux->might_sleep
23611 					  : aux->might_sleep;
23612 			if (prog->aux->might_sleep && !tgt_might_sleep) {
23613 				bpf_log(log,
23614 					"Extension program may sleep, while original does not\n");
23615 				return -EINVAL;
23616 			}
23617 		}
23618 		if (!tgt_prog->jited) {
23619 			bpf_log(log, "Can attach to only JITed progs\n");
23620 			return -EINVAL;
23621 		}
23622 		if (prog_tracing) {
23623 			if (aux->attach_tracing_prog) {
23624 				/*
23625 				 * Target program is an fentry/fexit which is already attached
23626 				 * to another tracing program. More levels of nesting
23627 				 * attachment are not allowed.
23628 				 */
23629 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
23630 				return -EINVAL;
23631 			}
23632 		} else if (tgt_prog->type == prog->type) {
23633 			/*
23634 			 * To avoid potential call chain cycles, prevent attaching of a
23635 			 * program extension to another extension. It's ok to attach
23636 			 * fentry/fexit to extension program.
23637 			 */
23638 			bpf_log(log, "Cannot recursively attach\n");
23639 			return -EINVAL;
23640 		}
23641 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
23642 		    prog_extension &&
23643 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
23644 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
23645 			/* Program extensions can extend all program types
23646 			 * except fentry/fexit. The reason is the following.
23647 			 * The fentry/fexit programs are used for performance
23648 			 * analysis, stats and can be attached to any program
23649 			 * type. When extension program is replacing XDP function
23650 			 * it is necessary to allow performance analysis of all
23651 			 * functions. Both original XDP program and its program
23652 			 * extension. Hence attaching fentry/fexit to
23653 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
23654 			 * fentry/fexit was allowed it would be possible to create
23655 			 * long call chain fentry->extension->fentry->extension
23656 			 * beyond reasonable stack size. Hence extending fentry
23657 			 * is not allowed.
23658 			 */
23659 			bpf_log(log, "Cannot extend fentry/fexit\n");
23660 			return -EINVAL;
23661 		}
23662 	} else {
23663 		if (prog_extension) {
23664 			bpf_log(log, "Cannot replace kernel functions\n");
23665 			return -EINVAL;
23666 		}
23667 	}
23668 
23669 	switch (prog->expected_attach_type) {
23670 	case BPF_TRACE_RAW_TP:
23671 		if (tgt_prog) {
23672 			bpf_log(log,
23673 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
23674 			return -EINVAL;
23675 		}
23676 		if (!btf_type_is_typedef(t)) {
23677 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
23678 				btf_id);
23679 			return -EINVAL;
23680 		}
23681 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
23682 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
23683 				btf_id, tname);
23684 			return -EINVAL;
23685 		}
23686 		tname += sizeof(prefix) - 1;
23687 
23688 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
23689 		 * names. Thus using bpf_raw_event_map to get argument names.
23690 		 */
23691 		btp = bpf_get_raw_tracepoint(tname);
23692 		if (!btp)
23693 			return -EINVAL;
23694 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
23695 					trace_symbol);
23696 		bpf_put_raw_tracepoint(btp);
23697 
23698 		if (fname)
23699 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
23700 
23701 		if (!fname || ret < 0) {
23702 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
23703 				prefix, tname);
23704 			t = btf_type_by_id(btf, t->type);
23705 			if (!btf_type_is_ptr(t))
23706 				/* should never happen in valid vmlinux build */
23707 				return -EINVAL;
23708 		} else {
23709 			t = btf_type_by_id(btf, ret);
23710 			if (!btf_type_is_func(t))
23711 				/* should never happen in valid vmlinux build */
23712 				return -EINVAL;
23713 		}
23714 
23715 		t = btf_type_by_id(btf, t->type);
23716 		if (!btf_type_is_func_proto(t))
23717 			/* should never happen in valid vmlinux build */
23718 			return -EINVAL;
23719 
23720 		break;
23721 	case BPF_TRACE_ITER:
23722 		if (!btf_type_is_func(t)) {
23723 			bpf_log(log, "attach_btf_id %u is not a function\n",
23724 				btf_id);
23725 			return -EINVAL;
23726 		}
23727 		t = btf_type_by_id(btf, t->type);
23728 		if (!btf_type_is_func_proto(t))
23729 			return -EINVAL;
23730 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
23731 		if (ret)
23732 			return ret;
23733 		break;
23734 	default:
23735 		if (!prog_extension)
23736 			return -EINVAL;
23737 		fallthrough;
23738 	case BPF_MODIFY_RETURN:
23739 	case BPF_LSM_MAC:
23740 	case BPF_LSM_CGROUP:
23741 	case BPF_TRACE_FENTRY:
23742 	case BPF_TRACE_FEXIT:
23743 		if (!btf_type_is_func(t)) {
23744 			bpf_log(log, "attach_btf_id %u is not a function\n",
23745 				btf_id);
23746 			return -EINVAL;
23747 		}
23748 		if (prog_extension &&
23749 		    btf_check_type_match(log, prog, btf, t))
23750 			return -EINVAL;
23751 		t = btf_type_by_id(btf, t->type);
23752 		if (!btf_type_is_func_proto(t))
23753 			return -EINVAL;
23754 
23755 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
23756 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
23757 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
23758 			return -EINVAL;
23759 
23760 		if (tgt_prog && conservative)
23761 			t = NULL;
23762 
23763 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
23764 		if (ret < 0)
23765 			return ret;
23766 
23767 		if (tgt_prog) {
23768 			if (subprog == 0)
23769 				addr = (long) tgt_prog->bpf_func;
23770 			else
23771 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
23772 		} else {
23773 			if (btf_is_module(btf)) {
23774 				mod = btf_try_get_module(btf);
23775 				if (mod)
23776 					addr = find_kallsyms_symbol_value(mod, tname);
23777 				else
23778 					addr = 0;
23779 			} else {
23780 				addr = kallsyms_lookup_name(tname);
23781 			}
23782 			if (!addr) {
23783 				module_put(mod);
23784 				bpf_log(log,
23785 					"The address of function %s cannot be found\n",
23786 					tname);
23787 				return -ENOENT;
23788 			}
23789 		}
23790 
23791 		if (prog->sleepable) {
23792 			ret = -EINVAL;
23793 			switch (prog->type) {
23794 			case BPF_PROG_TYPE_TRACING:
23795 
23796 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
23797 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
23798 				 */
23799 				if (!check_non_sleepable_error_inject(btf_id) &&
23800 				    within_error_injection_list(addr))
23801 					ret = 0;
23802 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
23803 				 * in the fmodret id set with the KF_SLEEPABLE flag.
23804 				 */
23805 				else {
23806 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
23807 										prog);
23808 
23809 					if (flags && (*flags & KF_SLEEPABLE))
23810 						ret = 0;
23811 				}
23812 				break;
23813 			case BPF_PROG_TYPE_LSM:
23814 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
23815 				 * Only some of them are sleepable.
23816 				 */
23817 				if (bpf_lsm_is_sleepable_hook(btf_id))
23818 					ret = 0;
23819 				break;
23820 			default:
23821 				break;
23822 			}
23823 			if (ret) {
23824 				module_put(mod);
23825 				bpf_log(log, "%s is not sleepable\n", tname);
23826 				return ret;
23827 			}
23828 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
23829 			if (tgt_prog) {
23830 				module_put(mod);
23831 				bpf_log(log, "can't modify return codes of BPF programs\n");
23832 				return -EINVAL;
23833 			}
23834 			ret = -EINVAL;
23835 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
23836 			    !check_attach_modify_return(addr, tname))
23837 				ret = 0;
23838 			if (ret) {
23839 				module_put(mod);
23840 				bpf_log(log, "%s() is not modifiable\n", tname);
23841 				return ret;
23842 			}
23843 		}
23844 
23845 		break;
23846 	}
23847 	tgt_info->tgt_addr = addr;
23848 	tgt_info->tgt_name = tname;
23849 	tgt_info->tgt_type = t;
23850 	tgt_info->tgt_mod = mod;
23851 	return 0;
23852 }
23853 
23854 BTF_SET_START(btf_id_deny)
23855 BTF_ID_UNUSED
23856 #ifdef CONFIG_SMP
23857 BTF_ID(func, ___migrate_enable)
23858 BTF_ID(func, migrate_disable)
23859 BTF_ID(func, migrate_enable)
23860 #endif
23861 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
23862 BTF_ID(func, rcu_read_unlock_strict)
23863 #endif
23864 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
23865 BTF_ID(func, preempt_count_add)
23866 BTF_ID(func, preempt_count_sub)
23867 #endif
23868 #ifdef CONFIG_PREEMPT_RCU
23869 BTF_ID(func, __rcu_read_lock)
23870 BTF_ID(func, __rcu_read_unlock)
23871 #endif
23872 BTF_SET_END(btf_id_deny)
23873 
23874 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
23875  * Currently, we must manually list all __noreturn functions here. Once a more
23876  * robust solution is implemented, this workaround can be removed.
23877  */
23878 BTF_SET_START(noreturn_deny)
23879 #ifdef CONFIG_IA32_EMULATION
23880 BTF_ID(func, __ia32_sys_exit)
23881 BTF_ID(func, __ia32_sys_exit_group)
23882 #endif
23883 #ifdef CONFIG_KUNIT
23884 BTF_ID(func, __kunit_abort)
23885 BTF_ID(func, kunit_try_catch_throw)
23886 #endif
23887 #ifdef CONFIG_MODULES
23888 BTF_ID(func, __module_put_and_kthread_exit)
23889 #endif
23890 #ifdef CONFIG_X86_64
23891 BTF_ID(func, __x64_sys_exit)
23892 BTF_ID(func, __x64_sys_exit_group)
23893 #endif
23894 BTF_ID(func, do_exit)
23895 BTF_ID(func, do_group_exit)
23896 BTF_ID(func, kthread_complete_and_exit)
23897 BTF_ID(func, kthread_exit)
23898 BTF_ID(func, make_task_dead)
23899 BTF_SET_END(noreturn_deny)
23900 
23901 static bool can_be_sleepable(struct bpf_prog *prog)
23902 {
23903 	if (prog->type == BPF_PROG_TYPE_TRACING) {
23904 		switch (prog->expected_attach_type) {
23905 		case BPF_TRACE_FENTRY:
23906 		case BPF_TRACE_FEXIT:
23907 		case BPF_MODIFY_RETURN:
23908 		case BPF_TRACE_ITER:
23909 			return true;
23910 		default:
23911 			return false;
23912 		}
23913 	}
23914 	return prog->type == BPF_PROG_TYPE_LSM ||
23915 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
23916 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
23917 }
23918 
23919 static int check_attach_btf_id(struct bpf_verifier_env *env)
23920 {
23921 	struct bpf_prog *prog = env->prog;
23922 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
23923 	struct bpf_attach_target_info tgt_info = {};
23924 	u32 btf_id = prog->aux->attach_btf_id;
23925 	struct bpf_trampoline *tr;
23926 	int ret;
23927 	u64 key;
23928 
23929 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
23930 		if (prog->sleepable)
23931 			/* attach_btf_id checked to be zero already */
23932 			return 0;
23933 		verbose(env, "Syscall programs can only be sleepable\n");
23934 		return -EINVAL;
23935 	}
23936 
23937 	if (prog->sleepable && !can_be_sleepable(prog)) {
23938 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
23939 		return -EINVAL;
23940 	}
23941 
23942 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
23943 		return check_struct_ops_btf_id(env);
23944 
23945 	if (prog->type != BPF_PROG_TYPE_TRACING &&
23946 	    prog->type != BPF_PROG_TYPE_LSM &&
23947 	    prog->type != BPF_PROG_TYPE_EXT)
23948 		return 0;
23949 
23950 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
23951 	if (ret)
23952 		return ret;
23953 
23954 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
23955 		/* to make freplace equivalent to their targets, they need to
23956 		 * inherit env->ops and expected_attach_type for the rest of the
23957 		 * verification
23958 		 */
23959 		env->ops = bpf_verifier_ops[tgt_prog->type];
23960 		prog->expected_attach_type = tgt_prog->expected_attach_type;
23961 	}
23962 
23963 	/* store info about the attachment target that will be used later */
23964 	prog->aux->attach_func_proto = tgt_info.tgt_type;
23965 	prog->aux->attach_func_name = tgt_info.tgt_name;
23966 	prog->aux->mod = tgt_info.tgt_mod;
23967 
23968 	if (tgt_prog) {
23969 		prog->aux->saved_dst_prog_type = tgt_prog->type;
23970 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
23971 	}
23972 
23973 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
23974 		prog->aux->attach_btf_trace = true;
23975 		return 0;
23976 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
23977 		return bpf_iter_prog_supported(prog);
23978 	}
23979 
23980 	if (prog->type == BPF_PROG_TYPE_LSM) {
23981 		ret = bpf_lsm_verify_prog(&env->log, prog);
23982 		if (ret < 0)
23983 			return ret;
23984 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
23985 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
23986 		verbose(env, "Attaching tracing programs to function '%s' is rejected.\n",
23987 			tgt_info.tgt_name);
23988 		return -EINVAL;
23989 	} else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
23990 		   prog->expected_attach_type == BPF_MODIFY_RETURN) &&
23991 		   btf_id_set_contains(&noreturn_deny, btf_id)) {
23992 		verbose(env, "Attaching fexit/fmod_ret to __noreturn function '%s' is rejected.\n",
23993 			tgt_info.tgt_name);
23994 		return -EINVAL;
23995 	}
23996 
23997 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
23998 	tr = bpf_trampoline_get(key, &tgt_info);
23999 	if (!tr)
24000 		return -ENOMEM;
24001 
24002 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
24003 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
24004 
24005 	prog->aux->dst_trampoline = tr;
24006 	return 0;
24007 }
24008 
24009 struct btf *bpf_get_btf_vmlinux(void)
24010 {
24011 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
24012 		mutex_lock(&bpf_verifier_lock);
24013 		if (!btf_vmlinux)
24014 			btf_vmlinux = btf_parse_vmlinux();
24015 		mutex_unlock(&bpf_verifier_lock);
24016 	}
24017 	return btf_vmlinux;
24018 }
24019 
24020 /*
24021  * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
24022  * this case expect that every file descriptor in the array is either a map or
24023  * a BTF. Everything else is considered to be trash.
24024  */
24025 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd)
24026 {
24027 	struct bpf_map *map;
24028 	struct btf *btf;
24029 	CLASS(fd, f)(fd);
24030 	int err;
24031 
24032 	map = __bpf_map_get(f);
24033 	if (!IS_ERR(map)) {
24034 		err = __add_used_map(env, map);
24035 		if (err < 0)
24036 			return err;
24037 		return 0;
24038 	}
24039 
24040 	btf = __btf_get_by_fd(f);
24041 	if (!IS_ERR(btf)) {
24042 		err = __add_used_btf(env, btf);
24043 		if (err < 0)
24044 			return err;
24045 		return 0;
24046 	}
24047 
24048 	verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
24049 	return PTR_ERR(map);
24050 }
24051 
24052 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr)
24053 {
24054 	size_t size = sizeof(int);
24055 	int ret;
24056 	int fd;
24057 	u32 i;
24058 
24059 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
24060 
24061 	/*
24062 	 * The only difference between old (no fd_array_cnt is given) and new
24063 	 * APIs is that in the latter case the fd_array is expected to be
24064 	 * continuous and is scanned for map fds right away
24065 	 */
24066 	if (!attr->fd_array_cnt)
24067 		return 0;
24068 
24069 	/* Check for integer overflow */
24070 	if (attr->fd_array_cnt >= (U32_MAX / size)) {
24071 		verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt);
24072 		return -EINVAL;
24073 	}
24074 
24075 	for (i = 0; i < attr->fd_array_cnt; i++) {
24076 		if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size))
24077 			return -EFAULT;
24078 
24079 		ret = add_fd_from_fd_array(env, fd);
24080 		if (ret)
24081 			return ret;
24082 	}
24083 
24084 	return 0;
24085 }
24086 
24087 /* Each field is a register bitmask */
24088 struct insn_live_regs {
24089 	u16 use;	/* registers read by instruction */
24090 	u16 def;	/* registers written by instruction */
24091 	u16 in;		/* registers that may be alive before instruction */
24092 	u16 out;	/* registers that may be alive after instruction */
24093 };
24094 
24095 /* Bitmask with 1s for all caller saved registers */
24096 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
24097 
24098 /* Compute info->{use,def} fields for the instruction */
24099 static void compute_insn_live_regs(struct bpf_verifier_env *env,
24100 				   struct bpf_insn *insn,
24101 				   struct insn_live_regs *info)
24102 {
24103 	struct call_summary cs;
24104 	u8 class = BPF_CLASS(insn->code);
24105 	u8 code = BPF_OP(insn->code);
24106 	u8 mode = BPF_MODE(insn->code);
24107 	u16 src = BIT(insn->src_reg);
24108 	u16 dst = BIT(insn->dst_reg);
24109 	u16 r0  = BIT(0);
24110 	u16 def = 0;
24111 	u16 use = 0xffff;
24112 
24113 	switch (class) {
24114 	case BPF_LD:
24115 		switch (mode) {
24116 		case BPF_IMM:
24117 			if (BPF_SIZE(insn->code) == BPF_DW) {
24118 				def = dst;
24119 				use = 0;
24120 			}
24121 			break;
24122 		case BPF_LD | BPF_ABS:
24123 		case BPF_LD | BPF_IND:
24124 			/* stick with defaults */
24125 			break;
24126 		}
24127 		break;
24128 	case BPF_LDX:
24129 		switch (mode) {
24130 		case BPF_MEM:
24131 		case BPF_MEMSX:
24132 			def = dst;
24133 			use = src;
24134 			break;
24135 		}
24136 		break;
24137 	case BPF_ST:
24138 		switch (mode) {
24139 		case BPF_MEM:
24140 			def = 0;
24141 			use = dst;
24142 			break;
24143 		}
24144 		break;
24145 	case BPF_STX:
24146 		switch (mode) {
24147 		case BPF_MEM:
24148 			def = 0;
24149 			use = dst | src;
24150 			break;
24151 		case BPF_ATOMIC:
24152 			switch (insn->imm) {
24153 			case BPF_CMPXCHG:
24154 				use = r0 | dst | src;
24155 				def = r0;
24156 				break;
24157 			case BPF_LOAD_ACQ:
24158 				def = dst;
24159 				use = src;
24160 				break;
24161 			case BPF_STORE_REL:
24162 				def = 0;
24163 				use = dst | src;
24164 				break;
24165 			default:
24166 				use = dst | src;
24167 				if (insn->imm & BPF_FETCH)
24168 					def = src;
24169 				else
24170 					def = 0;
24171 			}
24172 			break;
24173 		}
24174 		break;
24175 	case BPF_ALU:
24176 	case BPF_ALU64:
24177 		switch (code) {
24178 		case BPF_END:
24179 			use = dst;
24180 			def = dst;
24181 			break;
24182 		case BPF_MOV:
24183 			def = dst;
24184 			if (BPF_SRC(insn->code) == BPF_K)
24185 				use = 0;
24186 			else
24187 				use = src;
24188 			break;
24189 		default:
24190 			def = dst;
24191 			if (BPF_SRC(insn->code) == BPF_K)
24192 				use = dst;
24193 			else
24194 				use = dst | src;
24195 		}
24196 		break;
24197 	case BPF_JMP:
24198 	case BPF_JMP32:
24199 		switch (code) {
24200 		case BPF_JA:
24201 		case BPF_JCOND:
24202 			def = 0;
24203 			use = 0;
24204 			break;
24205 		case BPF_EXIT:
24206 			def = 0;
24207 			use = r0;
24208 			break;
24209 		case BPF_CALL:
24210 			def = ALL_CALLER_SAVED_REGS;
24211 			use = def & ~BIT(BPF_REG_0);
24212 			if (get_call_summary(env, insn, &cs))
24213 				use = GENMASK(cs.num_params, 1);
24214 			break;
24215 		default:
24216 			def = 0;
24217 			if (BPF_SRC(insn->code) == BPF_K)
24218 				use = dst;
24219 			else
24220 				use = dst | src;
24221 		}
24222 		break;
24223 	}
24224 
24225 	info->def = def;
24226 	info->use = use;
24227 }
24228 
24229 /* Compute may-live registers after each instruction in the program.
24230  * The register is live after the instruction I if it is read by some
24231  * instruction S following I during program execution and is not
24232  * overwritten between I and S.
24233  *
24234  * Store result in env->insn_aux_data[i].live_regs.
24235  */
24236 static int compute_live_registers(struct bpf_verifier_env *env)
24237 {
24238 	struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
24239 	struct bpf_insn *insns = env->prog->insnsi;
24240 	struct insn_live_regs *state;
24241 	int insn_cnt = env->prog->len;
24242 	int err = 0, i, j;
24243 	bool changed;
24244 
24245 	/* Use the following algorithm:
24246 	 * - define the following:
24247 	 *   - I.use : a set of all registers read by instruction I;
24248 	 *   - I.def : a set of all registers written by instruction I;
24249 	 *   - I.in  : a set of all registers that may be alive before I execution;
24250 	 *   - I.out : a set of all registers that may be alive after I execution;
24251 	 *   - insn_successors(I): a set of instructions S that might immediately
24252 	 *                         follow I for some program execution;
24253 	 * - associate separate empty sets 'I.in' and 'I.out' with each instruction;
24254 	 * - visit each instruction in a postorder and update
24255 	 *   state[i].in, state[i].out as follows:
24256 	 *
24257 	 *       state[i].out = U [state[s].in for S in insn_successors(i)]
24258 	 *       state[i].in  = (state[i].out / state[i].def) U state[i].use
24259 	 *
24260 	 *   (where U stands for set union, / stands for set difference)
24261 	 * - repeat the computation while {in,out} fields changes for
24262 	 *   any instruction.
24263 	 */
24264 	state = kvcalloc(insn_cnt, sizeof(*state), GFP_KERNEL_ACCOUNT);
24265 	if (!state) {
24266 		err = -ENOMEM;
24267 		goto out;
24268 	}
24269 
24270 	for (i = 0; i < insn_cnt; ++i)
24271 		compute_insn_live_regs(env, &insns[i], &state[i]);
24272 
24273 	changed = true;
24274 	while (changed) {
24275 		changed = false;
24276 		for (i = 0; i < env->cfg.cur_postorder; ++i) {
24277 			int insn_idx = env->cfg.insn_postorder[i];
24278 			struct insn_live_regs *live = &state[insn_idx];
24279 			int succ_num;
24280 			u32 succ[2];
24281 			u16 new_out = 0;
24282 			u16 new_in = 0;
24283 
24284 			succ_num = bpf_insn_successors(env->prog, insn_idx, succ);
24285 			for (int s = 0; s < succ_num; ++s)
24286 				new_out |= state[succ[s]].in;
24287 			new_in = (new_out & ~live->def) | live->use;
24288 			if (new_out != live->out || new_in != live->in) {
24289 				live->in = new_in;
24290 				live->out = new_out;
24291 				changed = true;
24292 			}
24293 		}
24294 	}
24295 
24296 	for (i = 0; i < insn_cnt; ++i)
24297 		insn_aux[i].live_regs_before = state[i].in;
24298 
24299 	if (env->log.level & BPF_LOG_LEVEL2) {
24300 		verbose(env, "Live regs before insn:\n");
24301 		for (i = 0; i < insn_cnt; ++i) {
24302 			if (env->insn_aux_data[i].scc)
24303 				verbose(env, "%3d ", env->insn_aux_data[i].scc);
24304 			else
24305 				verbose(env, "    ");
24306 			verbose(env, "%3d: ", i);
24307 			for (j = BPF_REG_0; j < BPF_REG_10; ++j)
24308 				if (insn_aux[i].live_regs_before & BIT(j))
24309 					verbose(env, "%d", j);
24310 				else
24311 					verbose(env, ".");
24312 			verbose(env, " ");
24313 			verbose_insn(env, &insns[i]);
24314 			if (bpf_is_ldimm64(&insns[i]))
24315 				i++;
24316 		}
24317 	}
24318 
24319 out:
24320 	kvfree(state);
24321 	return err;
24322 }
24323 
24324 /*
24325  * Compute strongly connected components (SCCs) on the CFG.
24326  * Assign an SCC number to each instruction, recorded in env->insn_aux[*].scc.
24327  * If instruction is a sole member of its SCC and there are no self edges,
24328  * assign it SCC number of zero.
24329  * Uses a non-recursive adaptation of Tarjan's algorithm for SCC computation.
24330  */
24331 static int compute_scc(struct bpf_verifier_env *env)
24332 {
24333 	const u32 NOT_ON_STACK = U32_MAX;
24334 
24335 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
24336 	const u32 insn_cnt = env->prog->len;
24337 	int stack_sz, dfs_sz, err = 0;
24338 	u32 *stack, *pre, *low, *dfs;
24339 	u32 succ_cnt, i, j, t, w;
24340 	u32 next_preorder_num;
24341 	u32 next_scc_id;
24342 	bool assign_scc;
24343 	u32 succ[2];
24344 
24345 	next_preorder_num = 1;
24346 	next_scc_id = 1;
24347 	/*
24348 	 * - 'stack' accumulates vertices in DFS order, see invariant comment below;
24349 	 * - 'pre[t] == p' => preorder number of vertex 't' is 'p';
24350 	 * - 'low[t] == n' => smallest preorder number of the vertex reachable from 't' is 'n';
24351 	 * - 'dfs' DFS traversal stack, used to emulate explicit recursion.
24352 	 */
24353 	stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24354 	pre = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24355 	low = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24356 	dfs = kvcalloc(insn_cnt, sizeof(*dfs), GFP_KERNEL_ACCOUNT);
24357 	if (!stack || !pre || !low || !dfs) {
24358 		err = -ENOMEM;
24359 		goto exit;
24360 	}
24361 	/*
24362 	 * References:
24363 	 * [1] R. Tarjan "Depth-First Search and Linear Graph Algorithms"
24364 	 * [2] D. J. Pearce "A Space-Efficient Algorithm for Finding Strongly Connected Components"
24365 	 *
24366 	 * The algorithm maintains the following invariant:
24367 	 * - suppose there is a path 'u' ~> 'v', such that 'pre[v] < pre[u]';
24368 	 * - then, vertex 'u' remains on stack while vertex 'v' is on stack.
24369 	 *
24370 	 * Consequently:
24371 	 * - If 'low[v] < pre[v]', there is a path from 'v' to some vertex 'u',
24372 	 *   such that 'pre[u] == low[v]'; vertex 'u' is currently on the stack,
24373 	 *   and thus there is an SCC (loop) containing both 'u' and 'v'.
24374 	 * - If 'low[v] == pre[v]', loops containing 'v' have been explored,
24375 	 *   and 'v' can be considered the root of some SCC.
24376 	 *
24377 	 * Here is a pseudo-code for an explicitly recursive version of the algorithm:
24378 	 *
24379 	 *    NOT_ON_STACK = insn_cnt + 1
24380 	 *    pre = [0] * insn_cnt
24381 	 *    low = [0] * insn_cnt
24382 	 *    scc = [0] * insn_cnt
24383 	 *    stack = []
24384 	 *
24385 	 *    next_preorder_num = 1
24386 	 *    next_scc_id = 1
24387 	 *
24388 	 *    def recur(w):
24389 	 *        nonlocal next_preorder_num
24390 	 *        nonlocal next_scc_id
24391 	 *
24392 	 *        pre[w] = next_preorder_num
24393 	 *        low[w] = next_preorder_num
24394 	 *        next_preorder_num += 1
24395 	 *        stack.append(w)
24396 	 *        for s in successors(w):
24397 	 *            # Note: for classic algorithm the block below should look as:
24398 	 *            #
24399 	 *            # if pre[s] == 0:
24400 	 *            #     recur(s)
24401 	 *            #	    low[w] = min(low[w], low[s])
24402 	 *            # elif low[s] != NOT_ON_STACK:
24403 	 *            #     low[w] = min(low[w], pre[s])
24404 	 *            #
24405 	 *            # But replacing both 'min' instructions with 'low[w] = min(low[w], low[s])'
24406 	 *            # does not break the invariant and makes itartive version of the algorithm
24407 	 *            # simpler. See 'Algorithm #3' from [2].
24408 	 *
24409 	 *            # 's' not yet visited
24410 	 *            if pre[s] == 0:
24411 	 *                recur(s)
24412 	 *            # if 's' is on stack, pick lowest reachable preorder number from it;
24413 	 *            # if 's' is not on stack 'low[s] == NOT_ON_STACK > low[w]',
24414 	 *            # so 'min' would be a noop.
24415 	 *            low[w] = min(low[w], low[s])
24416 	 *
24417 	 *        if low[w] == pre[w]:
24418 	 *            # 'w' is the root of an SCC, pop all vertices
24419 	 *            # below 'w' on stack and assign same SCC to them.
24420 	 *            while True:
24421 	 *                t = stack.pop()
24422 	 *                low[t] = NOT_ON_STACK
24423 	 *                scc[t] = next_scc_id
24424 	 *                if t == w:
24425 	 *                    break
24426 	 *            next_scc_id += 1
24427 	 *
24428 	 *    for i in range(0, insn_cnt):
24429 	 *        if pre[i] == 0:
24430 	 *            recur(i)
24431 	 *
24432 	 * Below implementation replaces explicit recursion with array 'dfs'.
24433 	 */
24434 	for (i = 0; i < insn_cnt; i++) {
24435 		if (pre[i])
24436 			continue;
24437 		stack_sz = 0;
24438 		dfs_sz = 1;
24439 		dfs[0] = i;
24440 dfs_continue:
24441 		while (dfs_sz) {
24442 			w = dfs[dfs_sz - 1];
24443 			if (pre[w] == 0) {
24444 				low[w] = next_preorder_num;
24445 				pre[w] = next_preorder_num;
24446 				next_preorder_num++;
24447 				stack[stack_sz++] = w;
24448 			}
24449 			/* Visit 'w' successors */
24450 			succ_cnt = bpf_insn_successors(env->prog, w, succ);
24451 			for (j = 0; j < succ_cnt; ++j) {
24452 				if (pre[succ[j]]) {
24453 					low[w] = min(low[w], low[succ[j]]);
24454 				} else {
24455 					dfs[dfs_sz++] = succ[j];
24456 					goto dfs_continue;
24457 				}
24458 			}
24459 			/*
24460 			 * Preserve the invariant: if some vertex above in the stack
24461 			 * is reachable from 'w', keep 'w' on the stack.
24462 			 */
24463 			if (low[w] < pre[w]) {
24464 				dfs_sz--;
24465 				goto dfs_continue;
24466 			}
24467 			/*
24468 			 * Assign SCC number only if component has two or more elements,
24469 			 * or if component has a self reference.
24470 			 */
24471 			assign_scc = stack[stack_sz - 1] != w;
24472 			for (j = 0; j < succ_cnt; ++j) {
24473 				if (succ[j] == w) {
24474 					assign_scc = true;
24475 					break;
24476 				}
24477 			}
24478 			/* Pop component elements from stack */
24479 			do {
24480 				t = stack[--stack_sz];
24481 				low[t] = NOT_ON_STACK;
24482 				if (assign_scc)
24483 					aux[t].scc = next_scc_id;
24484 			} while (t != w);
24485 			if (assign_scc)
24486 				next_scc_id++;
24487 			dfs_sz--;
24488 		}
24489 	}
24490 	env->scc_info = kvcalloc(next_scc_id, sizeof(*env->scc_info), GFP_KERNEL_ACCOUNT);
24491 	if (!env->scc_info) {
24492 		err = -ENOMEM;
24493 		goto exit;
24494 	}
24495 	env->scc_cnt = next_scc_id;
24496 exit:
24497 	kvfree(stack);
24498 	kvfree(pre);
24499 	kvfree(low);
24500 	kvfree(dfs);
24501 	return err;
24502 }
24503 
24504 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
24505 {
24506 	u64 start_time = ktime_get_ns();
24507 	struct bpf_verifier_env *env;
24508 	int i, len, ret = -EINVAL, err;
24509 	u32 log_true_size;
24510 	bool is_priv;
24511 
24512 	BTF_TYPE_EMIT(enum bpf_features);
24513 
24514 	/* no program is valid */
24515 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
24516 		return -EINVAL;
24517 
24518 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
24519 	 * allocate/free it every time bpf_check() is called
24520 	 */
24521 	env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL_ACCOUNT);
24522 	if (!env)
24523 		return -ENOMEM;
24524 
24525 	env->bt.env = env;
24526 
24527 	len = (*prog)->len;
24528 	env->insn_aux_data =
24529 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
24530 	ret = -ENOMEM;
24531 	if (!env->insn_aux_data)
24532 		goto err_free_env;
24533 	for (i = 0; i < len; i++)
24534 		env->insn_aux_data[i].orig_idx = i;
24535 	env->prog = *prog;
24536 	env->ops = bpf_verifier_ops[env->prog->type];
24537 
24538 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
24539 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
24540 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
24541 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
24542 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
24543 
24544 	bpf_get_btf_vmlinux();
24545 
24546 	/* grab the mutex to protect few globals used by verifier */
24547 	if (!is_priv)
24548 		mutex_lock(&bpf_verifier_lock);
24549 
24550 	/* user could have requested verbose verifier output
24551 	 * and supplied buffer to store the verification trace
24552 	 */
24553 	ret = bpf_vlog_init(&env->log, attr->log_level,
24554 			    (char __user *) (unsigned long) attr->log_buf,
24555 			    attr->log_size);
24556 	if (ret)
24557 		goto err_unlock;
24558 
24559 	ret = process_fd_array(env, attr, uattr);
24560 	if (ret)
24561 		goto skip_full_check;
24562 
24563 	mark_verifier_state_clean(env);
24564 
24565 	if (IS_ERR(btf_vmlinux)) {
24566 		/* Either gcc or pahole or kernel are broken. */
24567 		verbose(env, "in-kernel BTF is malformed\n");
24568 		ret = PTR_ERR(btf_vmlinux);
24569 		goto skip_full_check;
24570 	}
24571 
24572 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
24573 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
24574 		env->strict_alignment = true;
24575 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
24576 		env->strict_alignment = false;
24577 
24578 	if (is_priv)
24579 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
24580 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
24581 
24582 	env->explored_states = kvcalloc(state_htab_size(env),
24583 				       sizeof(struct list_head),
24584 				       GFP_KERNEL_ACCOUNT);
24585 	ret = -ENOMEM;
24586 	if (!env->explored_states)
24587 		goto skip_full_check;
24588 
24589 	for (i = 0; i < state_htab_size(env); i++)
24590 		INIT_LIST_HEAD(&env->explored_states[i]);
24591 	INIT_LIST_HEAD(&env->free_list);
24592 
24593 	ret = check_btf_info_early(env, attr, uattr);
24594 	if (ret < 0)
24595 		goto skip_full_check;
24596 
24597 	ret = add_subprog_and_kfunc(env);
24598 	if (ret < 0)
24599 		goto skip_full_check;
24600 
24601 	ret = check_subprogs(env);
24602 	if (ret < 0)
24603 		goto skip_full_check;
24604 
24605 	ret = check_btf_info(env, attr, uattr);
24606 	if (ret < 0)
24607 		goto skip_full_check;
24608 
24609 	ret = resolve_pseudo_ldimm64(env);
24610 	if (ret < 0)
24611 		goto skip_full_check;
24612 
24613 	if (bpf_prog_is_offloaded(env->prog->aux)) {
24614 		ret = bpf_prog_offload_verifier_prep(env->prog);
24615 		if (ret)
24616 			goto skip_full_check;
24617 	}
24618 
24619 	ret = check_cfg(env);
24620 	if (ret < 0)
24621 		goto skip_full_check;
24622 
24623 	ret = compute_postorder(env);
24624 	if (ret < 0)
24625 		goto skip_full_check;
24626 
24627 	ret = bpf_stack_liveness_init(env);
24628 	if (ret)
24629 		goto skip_full_check;
24630 
24631 	ret = check_attach_btf_id(env);
24632 	if (ret)
24633 		goto skip_full_check;
24634 
24635 	ret = compute_scc(env);
24636 	if (ret < 0)
24637 		goto skip_full_check;
24638 
24639 	ret = compute_live_registers(env);
24640 	if (ret < 0)
24641 		goto skip_full_check;
24642 
24643 	ret = mark_fastcall_patterns(env);
24644 	if (ret < 0)
24645 		goto skip_full_check;
24646 
24647 	ret = do_check_main(env);
24648 	ret = ret ?: do_check_subprogs(env);
24649 
24650 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
24651 		ret = bpf_prog_offload_finalize(env);
24652 
24653 skip_full_check:
24654 	kvfree(env->explored_states);
24655 
24656 	/* might decrease stack depth, keep it before passes that
24657 	 * allocate additional slots.
24658 	 */
24659 	if (ret == 0)
24660 		ret = remove_fastcall_spills_fills(env);
24661 
24662 	if (ret == 0)
24663 		ret = check_max_stack_depth(env);
24664 
24665 	/* instruction rewrites happen after this point */
24666 	if (ret == 0)
24667 		ret = optimize_bpf_loop(env);
24668 
24669 	if (is_priv) {
24670 		if (ret == 0)
24671 			opt_hard_wire_dead_code_branches(env);
24672 		if (ret == 0)
24673 			ret = opt_remove_dead_code(env);
24674 		if (ret == 0)
24675 			ret = opt_remove_nops(env);
24676 	} else {
24677 		if (ret == 0)
24678 			sanitize_dead_code(env);
24679 	}
24680 
24681 	if (ret == 0)
24682 		/* program is valid, convert *(u32*)(ctx + off) accesses */
24683 		ret = convert_ctx_accesses(env);
24684 
24685 	if (ret == 0)
24686 		ret = do_misc_fixups(env);
24687 
24688 	/* do 32-bit optimization after insn patching has done so those patched
24689 	 * insns could be handled correctly.
24690 	 */
24691 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
24692 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
24693 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
24694 								     : false;
24695 	}
24696 
24697 	if (ret == 0)
24698 		ret = fixup_call_args(env);
24699 
24700 	env->verification_time = ktime_get_ns() - start_time;
24701 	print_verification_stats(env);
24702 	env->prog->aux->verified_insns = env->insn_processed;
24703 
24704 	/* preserve original error even if log finalization is successful */
24705 	err = bpf_vlog_finalize(&env->log, &log_true_size);
24706 	if (err)
24707 		ret = err;
24708 
24709 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
24710 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
24711 				  &log_true_size, sizeof(log_true_size))) {
24712 		ret = -EFAULT;
24713 		goto err_release_maps;
24714 	}
24715 
24716 	if (ret)
24717 		goto err_release_maps;
24718 
24719 	if (env->used_map_cnt) {
24720 		/* if program passed verifier, update used_maps in bpf_prog_info */
24721 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
24722 							  sizeof(env->used_maps[0]),
24723 							  GFP_KERNEL_ACCOUNT);
24724 
24725 		if (!env->prog->aux->used_maps) {
24726 			ret = -ENOMEM;
24727 			goto err_release_maps;
24728 		}
24729 
24730 		memcpy(env->prog->aux->used_maps, env->used_maps,
24731 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
24732 		env->prog->aux->used_map_cnt = env->used_map_cnt;
24733 	}
24734 	if (env->used_btf_cnt) {
24735 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
24736 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
24737 							  sizeof(env->used_btfs[0]),
24738 							  GFP_KERNEL_ACCOUNT);
24739 		if (!env->prog->aux->used_btfs) {
24740 			ret = -ENOMEM;
24741 			goto err_release_maps;
24742 		}
24743 
24744 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
24745 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
24746 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
24747 	}
24748 	if (env->used_map_cnt || env->used_btf_cnt) {
24749 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
24750 		 * bpf_ld_imm64 instructions
24751 		 */
24752 		convert_pseudo_ld_imm64(env);
24753 	}
24754 
24755 	adjust_btf_func(env);
24756 
24757 err_release_maps:
24758 	if (!env->prog->aux->used_maps)
24759 		/* if we didn't copy map pointers into bpf_prog_info, release
24760 		 * them now. Otherwise free_used_maps() will release them.
24761 		 */
24762 		release_maps(env);
24763 	if (!env->prog->aux->used_btfs)
24764 		release_btfs(env);
24765 
24766 	/* extension progs temporarily inherit the attach_type of their targets
24767 	   for verification purposes, so set it back to zero before returning
24768 	 */
24769 	if (env->prog->type == BPF_PROG_TYPE_EXT)
24770 		env->prog->expected_attach_type = 0;
24771 
24772 	*prog = env->prog;
24773 
24774 	module_put(env->attach_btf_mod);
24775 err_unlock:
24776 	if (!is_priv)
24777 		mutex_unlock(&bpf_verifier_lock);
24778 	vfree(env->insn_aux_data);
24779 err_free_env:
24780 	bpf_stack_liveness_free(env);
24781 	kvfree(env->cfg.insn_postorder);
24782 	kvfree(env->scc_info);
24783 	kvfree(env);
24784 	return ret;
24785 }
24786