xref: /linux/kernel/bpf/verifier.c (revision 7a433e519364c3c19643e5c857f4fbfaebec441c)
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 bool is_trusted_reg(const struct bpf_reg_state *reg);
213 
214 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
215 {
216 	return aux->map_ptr_state.poison;
217 }
218 
219 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
220 {
221 	return aux->map_ptr_state.unpriv;
222 }
223 
224 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
225 			      struct bpf_map *map,
226 			      bool unpriv, bool poison)
227 {
228 	unpriv |= bpf_map_ptr_unpriv(aux);
229 	aux->map_ptr_state.unpriv = unpriv;
230 	aux->map_ptr_state.poison = poison;
231 	aux->map_ptr_state.map_ptr = map;
232 }
233 
234 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
235 {
236 	return aux->map_key_state & BPF_MAP_KEY_POISON;
237 }
238 
239 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
240 {
241 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
242 }
243 
244 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
245 {
246 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
247 }
248 
249 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
250 {
251 	bool poisoned = bpf_map_key_poisoned(aux);
252 
253 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
254 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
255 }
256 
257 static bool bpf_helper_call(const struct bpf_insn *insn)
258 {
259 	return insn->code == (BPF_JMP | BPF_CALL) &&
260 	       insn->src_reg == 0;
261 }
262 
263 static bool bpf_pseudo_call(const struct bpf_insn *insn)
264 {
265 	return insn->code == (BPF_JMP | BPF_CALL) &&
266 	       insn->src_reg == BPF_PSEUDO_CALL;
267 }
268 
269 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
270 {
271 	return insn->code == (BPF_JMP | BPF_CALL) &&
272 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
273 }
274 
275 struct bpf_map_desc {
276 	struct bpf_map *ptr;
277 	int uid;
278 };
279 
280 struct bpf_call_arg_meta {
281 	struct bpf_map_desc map;
282 	bool raw_mode;
283 	bool pkt_access;
284 	u8 release_regno;
285 	int regno;
286 	int access_size;
287 	int mem_size;
288 	u64 msize_max_value;
289 	int ref_obj_id;
290 	int dynptr_id;
291 	int func_id;
292 	struct btf *btf;
293 	u32 btf_id;
294 	struct btf *ret_btf;
295 	u32 ret_btf_id;
296 	u32 subprogno;
297 	struct btf_field *kptr_field;
298 	s64 const_map_key;
299 };
300 
301 struct bpf_kfunc_meta {
302 	struct btf *btf;
303 	const struct btf_type *proto;
304 	const char *name;
305 	const u32 *flags;
306 	s32 id;
307 };
308 
309 struct bpf_kfunc_call_arg_meta {
310 	/* In parameters */
311 	struct btf *btf;
312 	u32 func_id;
313 	u32 kfunc_flags;
314 	const struct btf_type *func_proto;
315 	const char *func_name;
316 	/* Out parameters */
317 	u32 ref_obj_id;
318 	u8 release_regno;
319 	bool r0_rdonly;
320 	u32 ret_btf_id;
321 	u64 r0_size;
322 	u32 subprogno;
323 	struct {
324 		u64 value;
325 		bool found;
326 	} arg_constant;
327 
328 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
329 	 * generally to pass info about user-defined local kptr types to later
330 	 * verification logic
331 	 *   bpf_obj_drop/bpf_percpu_obj_drop
332 	 *     Record the local kptr type to be drop'd
333 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
334 	 *     Record the local kptr type to be refcount_incr'd and use
335 	 *     arg_owning_ref to determine whether refcount_acquire should be
336 	 *     fallible
337 	 */
338 	struct btf *arg_btf;
339 	u32 arg_btf_id;
340 	bool arg_owning_ref;
341 	bool arg_prog;
342 
343 	struct {
344 		struct btf_field *field;
345 	} arg_list_head;
346 	struct {
347 		struct btf_field *field;
348 	} arg_rbtree_root;
349 	struct {
350 		enum bpf_dynptr_type type;
351 		u32 id;
352 		u32 ref_obj_id;
353 	} initialized_dynptr;
354 	struct {
355 		u8 spi;
356 		u8 frameno;
357 	} iter;
358 	struct bpf_map_desc map;
359 	u64 mem_size;
360 };
361 
362 struct btf *btf_vmlinux;
363 
364 static const char *btf_type_name(const struct btf *btf, u32 id)
365 {
366 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
367 }
368 
369 static DEFINE_MUTEX(bpf_verifier_lock);
370 static DEFINE_MUTEX(bpf_percpu_ma_lock);
371 
372 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
373 {
374 	struct bpf_verifier_env *env = private_data;
375 	va_list args;
376 
377 	if (!bpf_verifier_log_needed(&env->log))
378 		return;
379 
380 	va_start(args, fmt);
381 	bpf_verifier_vlog(&env->log, fmt, args);
382 	va_end(args);
383 }
384 
385 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
386 				   struct bpf_reg_state *reg,
387 				   struct bpf_retval_range range, const char *ctx,
388 				   const char *reg_name)
389 {
390 	bool unknown = true;
391 
392 	verbose(env, "%s the register %s has", ctx, reg_name);
393 	if (reg->smin_value > S64_MIN) {
394 		verbose(env, " smin=%lld", reg->smin_value);
395 		unknown = false;
396 	}
397 	if (reg->smax_value < S64_MAX) {
398 		verbose(env, " smax=%lld", reg->smax_value);
399 		unknown = false;
400 	}
401 	if (unknown)
402 		verbose(env, " unknown scalar value");
403 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
404 }
405 
406 static bool reg_not_null(const struct bpf_reg_state *reg)
407 {
408 	enum bpf_reg_type type;
409 
410 	type = reg->type;
411 	if (type_may_be_null(type))
412 		return false;
413 
414 	type = base_type(type);
415 	return type == PTR_TO_SOCKET ||
416 		type == PTR_TO_TCP_SOCK ||
417 		type == PTR_TO_MAP_VALUE ||
418 		type == PTR_TO_MAP_KEY ||
419 		type == PTR_TO_SOCK_COMMON ||
420 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
421 		(type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) ||
422 		type == CONST_PTR_TO_MAP;
423 }
424 
425 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
426 {
427 	struct btf_record *rec = NULL;
428 	struct btf_struct_meta *meta;
429 
430 	if (reg->type == PTR_TO_MAP_VALUE) {
431 		rec = reg->map_ptr->record;
432 	} else if (type_is_ptr_alloc_obj(reg->type)) {
433 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
434 		if (meta)
435 			rec = meta->record;
436 	}
437 	return rec;
438 }
439 
440 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
441 {
442 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
443 
444 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
445 }
446 
447 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
448 {
449 	struct bpf_func_info *info;
450 
451 	if (!env->prog->aux->func_info)
452 		return "";
453 
454 	info = &env->prog->aux->func_info[subprog];
455 	return btf_type_name(env->prog->aux->btf, info->type_id);
456 }
457 
458 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
459 {
460 	struct bpf_subprog_info *info = subprog_info(env, subprog);
461 
462 	info->is_cb = true;
463 	info->is_async_cb = true;
464 	info->is_exception_cb = true;
465 }
466 
467 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
468 {
469 	return subprog_info(env, subprog)->is_exception_cb;
470 }
471 
472 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
473 {
474 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK);
475 }
476 
477 static bool type_is_rdonly_mem(u32 type)
478 {
479 	return type & MEM_RDONLY;
480 }
481 
482 static bool is_acquire_function(enum bpf_func_id func_id,
483 				const struct bpf_map *map)
484 {
485 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
486 
487 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
488 	    func_id == BPF_FUNC_sk_lookup_udp ||
489 	    func_id == BPF_FUNC_skc_lookup_tcp ||
490 	    func_id == BPF_FUNC_ringbuf_reserve ||
491 	    func_id == BPF_FUNC_kptr_xchg)
492 		return true;
493 
494 	if (func_id == BPF_FUNC_map_lookup_elem &&
495 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
496 	     map_type == BPF_MAP_TYPE_SOCKHASH))
497 		return true;
498 
499 	return false;
500 }
501 
502 static bool is_ptr_cast_function(enum bpf_func_id func_id)
503 {
504 	return func_id == BPF_FUNC_tcp_sock ||
505 		func_id == BPF_FUNC_sk_fullsock ||
506 		func_id == BPF_FUNC_skc_to_tcp_sock ||
507 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
508 		func_id == BPF_FUNC_skc_to_udp6_sock ||
509 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
510 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
511 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
512 }
513 
514 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
515 {
516 	return func_id == BPF_FUNC_dynptr_data;
517 }
518 
519 static bool is_sync_callback_calling_kfunc(u32 btf_id);
520 static bool is_async_callback_calling_kfunc(u32 btf_id);
521 static bool is_callback_calling_kfunc(u32 btf_id);
522 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
523 
524 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id);
525 static bool is_task_work_add_kfunc(u32 func_id);
526 
527 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
528 {
529 	return func_id == BPF_FUNC_for_each_map_elem ||
530 	       func_id == BPF_FUNC_find_vma ||
531 	       func_id == BPF_FUNC_loop ||
532 	       func_id == BPF_FUNC_user_ringbuf_drain;
533 }
534 
535 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
536 {
537 	return func_id == BPF_FUNC_timer_set_callback;
538 }
539 
540 static bool is_callback_calling_function(enum bpf_func_id func_id)
541 {
542 	return is_sync_callback_calling_function(func_id) ||
543 	       is_async_callback_calling_function(func_id);
544 }
545 
546 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
547 {
548 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
549 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
550 }
551 
552 static bool is_async_callback_calling_insn(struct bpf_insn *insn)
553 {
554 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
555 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
556 }
557 
558 static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn *insn)
559 {
560 	/* bpf_timer callbacks are never sleepable. */
561 	if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_timer_set_callback)
562 		return false;
563 
564 	/* bpf_wq and bpf_task_work callbacks are always sleepable. */
565 	if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
566 	    (is_bpf_wq_set_callback_kfunc(insn->imm) || is_task_work_add_kfunc(insn->imm)))
567 		return true;
568 
569 	verifier_bug(env, "unhandled async callback in is_async_cb_sleepable");
570 	return false;
571 }
572 
573 static bool is_may_goto_insn(struct bpf_insn *insn)
574 {
575 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
576 }
577 
578 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
579 {
580 	return is_may_goto_insn(&env->prog->insnsi[insn_idx]);
581 }
582 
583 static bool is_storage_get_function(enum bpf_func_id func_id)
584 {
585 	return func_id == BPF_FUNC_sk_storage_get ||
586 	       func_id == BPF_FUNC_inode_storage_get ||
587 	       func_id == BPF_FUNC_task_storage_get ||
588 	       func_id == BPF_FUNC_cgrp_storage_get;
589 }
590 
591 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
592 					const struct bpf_map *map)
593 {
594 	int ref_obj_uses = 0;
595 
596 	if (is_ptr_cast_function(func_id))
597 		ref_obj_uses++;
598 	if (is_acquire_function(func_id, map))
599 		ref_obj_uses++;
600 	if (is_dynptr_ref_function(func_id))
601 		ref_obj_uses++;
602 
603 	return ref_obj_uses > 1;
604 }
605 
606 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
607 {
608 	return BPF_CLASS(insn->code) == BPF_STX &&
609 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
610 	       insn->imm == BPF_CMPXCHG;
611 }
612 
613 static bool is_atomic_load_insn(const struct bpf_insn *insn)
614 {
615 	return BPF_CLASS(insn->code) == BPF_STX &&
616 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
617 	       insn->imm == BPF_LOAD_ACQ;
618 }
619 
620 static int __get_spi(s32 off)
621 {
622 	return (-off - 1) / BPF_REG_SIZE;
623 }
624 
625 static struct bpf_func_state *func(struct bpf_verifier_env *env,
626 				   const struct bpf_reg_state *reg)
627 {
628 	struct bpf_verifier_state *cur = env->cur_state;
629 
630 	return cur->frame[reg->frameno];
631 }
632 
633 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
634 {
635        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
636 
637        /* We need to check that slots between [spi - nr_slots + 1, spi] are
638 	* within [0, allocated_stack).
639 	*
640 	* Please note that the spi grows downwards. For example, a dynptr
641 	* takes the size of two stack slots; the first slot will be at
642 	* spi and the second slot will be at spi - 1.
643 	*/
644        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
645 }
646 
647 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
648 			          const char *obj_kind, int nr_slots)
649 {
650 	int off, spi;
651 
652 	if (!tnum_is_const(reg->var_off)) {
653 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
654 		return -EINVAL;
655 	}
656 
657 	off = reg->off + reg->var_off.value;
658 	if (off % BPF_REG_SIZE) {
659 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
660 		return -EINVAL;
661 	}
662 
663 	spi = __get_spi(off);
664 	if (spi + 1 < nr_slots) {
665 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
666 		return -EINVAL;
667 	}
668 
669 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
670 		return -ERANGE;
671 	return spi;
672 }
673 
674 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
675 {
676 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
677 }
678 
679 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
680 {
681 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
682 }
683 
684 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
685 {
686 	return stack_slot_obj_get_spi(env, reg, "irq_flag", 1);
687 }
688 
689 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
690 {
691 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
692 	case DYNPTR_TYPE_LOCAL:
693 		return BPF_DYNPTR_TYPE_LOCAL;
694 	case DYNPTR_TYPE_RINGBUF:
695 		return BPF_DYNPTR_TYPE_RINGBUF;
696 	case DYNPTR_TYPE_SKB:
697 		return BPF_DYNPTR_TYPE_SKB;
698 	case DYNPTR_TYPE_XDP:
699 		return BPF_DYNPTR_TYPE_XDP;
700 	case DYNPTR_TYPE_SKB_META:
701 		return BPF_DYNPTR_TYPE_SKB_META;
702 	case DYNPTR_TYPE_FILE:
703 		return BPF_DYNPTR_TYPE_FILE;
704 	default:
705 		return BPF_DYNPTR_TYPE_INVALID;
706 	}
707 }
708 
709 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
710 {
711 	switch (type) {
712 	case BPF_DYNPTR_TYPE_LOCAL:
713 		return DYNPTR_TYPE_LOCAL;
714 	case BPF_DYNPTR_TYPE_RINGBUF:
715 		return DYNPTR_TYPE_RINGBUF;
716 	case BPF_DYNPTR_TYPE_SKB:
717 		return DYNPTR_TYPE_SKB;
718 	case BPF_DYNPTR_TYPE_XDP:
719 		return DYNPTR_TYPE_XDP;
720 	case BPF_DYNPTR_TYPE_SKB_META:
721 		return DYNPTR_TYPE_SKB_META;
722 	case BPF_DYNPTR_TYPE_FILE:
723 		return DYNPTR_TYPE_FILE;
724 	default:
725 		return 0;
726 	}
727 }
728 
729 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
730 {
731 	return type == BPF_DYNPTR_TYPE_RINGBUF || type == BPF_DYNPTR_TYPE_FILE;
732 }
733 
734 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
735 			      enum bpf_dynptr_type type,
736 			      bool first_slot, int dynptr_id);
737 
738 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
739 				struct bpf_reg_state *reg);
740 
741 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
742 				   struct bpf_reg_state *sreg1,
743 				   struct bpf_reg_state *sreg2,
744 				   enum bpf_dynptr_type type)
745 {
746 	int id = ++env->id_gen;
747 
748 	__mark_dynptr_reg(sreg1, type, true, id);
749 	__mark_dynptr_reg(sreg2, type, false, id);
750 }
751 
752 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
753 			       struct bpf_reg_state *reg,
754 			       enum bpf_dynptr_type type)
755 {
756 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
757 }
758 
759 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
760 				        struct bpf_func_state *state, int spi);
761 
762 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
763 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
764 {
765 	struct bpf_func_state *state = func(env, reg);
766 	enum bpf_dynptr_type type;
767 	int spi, i, err;
768 
769 	spi = dynptr_get_spi(env, reg);
770 	if (spi < 0)
771 		return spi;
772 
773 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
774 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
775 	 * to ensure that for the following example:
776 	 *	[d1][d1][d2][d2]
777 	 * spi    3   2   1   0
778 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
779 	 * case they do belong to same dynptr, second call won't see slot_type
780 	 * as STACK_DYNPTR and will simply skip destruction.
781 	 */
782 	err = destroy_if_dynptr_stack_slot(env, state, spi);
783 	if (err)
784 		return err;
785 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
786 	if (err)
787 		return err;
788 
789 	for (i = 0; i < BPF_REG_SIZE; i++) {
790 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
791 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
792 	}
793 
794 	type = arg_to_dynptr_type(arg_type);
795 	if (type == BPF_DYNPTR_TYPE_INVALID)
796 		return -EINVAL;
797 
798 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
799 			       &state->stack[spi - 1].spilled_ptr, type);
800 
801 	if (dynptr_type_refcounted(type)) {
802 		/* The id is used to track proper releasing */
803 		int id;
804 
805 		if (clone_ref_obj_id)
806 			id = clone_ref_obj_id;
807 		else
808 			id = acquire_reference(env, insn_idx);
809 
810 		if (id < 0)
811 			return id;
812 
813 		state->stack[spi].spilled_ptr.ref_obj_id = id;
814 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
815 	}
816 
817 	bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
818 
819 	return 0;
820 }
821 
822 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
823 {
824 	int i;
825 
826 	for (i = 0; i < BPF_REG_SIZE; i++) {
827 		state->stack[spi].slot_type[i] = STACK_INVALID;
828 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
829 	}
830 
831 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
832 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
833 
834 	bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
835 }
836 
837 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
838 {
839 	struct bpf_func_state *state = func(env, reg);
840 	int spi, ref_obj_id, i;
841 
842 	/*
843 	 * This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
844 	 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
845 	 * is safe to do directly.
846 	 */
847 	if (reg->type == CONST_PTR_TO_DYNPTR) {
848 		verifier_bug(env, "CONST_PTR_TO_DYNPTR cannot be released");
849 		return -EFAULT;
850 	}
851 	spi = dynptr_get_spi(env, reg);
852 	if (spi < 0)
853 		return spi;
854 
855 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
856 		invalidate_dynptr(env, state, spi);
857 		return 0;
858 	}
859 
860 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
861 
862 	/* If the dynptr has a ref_obj_id, then we need to invalidate
863 	 * two things:
864 	 *
865 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
866 	 * 2) Any slices derived from this dynptr.
867 	 */
868 
869 	/* Invalidate any slices associated with this dynptr */
870 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
871 
872 	/* Invalidate any dynptr clones */
873 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
874 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
875 			continue;
876 
877 		/* it should always be the case that if the ref obj id
878 		 * matches then the stack slot also belongs to a
879 		 * dynptr
880 		 */
881 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
882 			verifier_bug(env, "misconfigured ref_obj_id");
883 			return -EFAULT;
884 		}
885 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
886 			invalidate_dynptr(env, state, i);
887 	}
888 
889 	return 0;
890 }
891 
892 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
893 			       struct bpf_reg_state *reg);
894 
895 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
896 {
897 	if (!env->allow_ptr_leaks)
898 		__mark_reg_not_init(env, reg);
899 	else
900 		__mark_reg_unknown(env, reg);
901 }
902 
903 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
904 				        struct bpf_func_state *state, int spi)
905 {
906 	struct bpf_func_state *fstate;
907 	struct bpf_reg_state *dreg;
908 	int i, dynptr_id;
909 
910 	/* We always ensure that STACK_DYNPTR is never set partially,
911 	 * hence just checking for slot_type[0] is enough. This is
912 	 * different for STACK_SPILL, where it may be only set for
913 	 * 1 byte, so code has to use is_spilled_reg.
914 	 */
915 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
916 		return 0;
917 
918 	/* Reposition spi to first slot */
919 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
920 		spi = spi + 1;
921 
922 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
923 		verbose(env, "cannot overwrite referenced dynptr\n");
924 		return -EINVAL;
925 	}
926 
927 	mark_stack_slot_scratched(env, spi);
928 	mark_stack_slot_scratched(env, spi - 1);
929 
930 	/* Writing partially to one dynptr stack slot destroys both. */
931 	for (i = 0; i < BPF_REG_SIZE; i++) {
932 		state->stack[spi].slot_type[i] = STACK_INVALID;
933 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
934 	}
935 
936 	dynptr_id = state->stack[spi].spilled_ptr.id;
937 	/* Invalidate any slices associated with this dynptr */
938 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
939 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
940 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
941 			continue;
942 		if (dreg->dynptr_id == dynptr_id)
943 			mark_reg_invalid(env, dreg);
944 	}));
945 
946 	/* Do not release reference state, we are destroying dynptr on stack,
947 	 * not using some helper to release it. Just reset register.
948 	 */
949 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
950 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
951 
952 	bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
953 
954 	return 0;
955 }
956 
957 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
958 {
959 	int spi;
960 
961 	if (reg->type == CONST_PTR_TO_DYNPTR)
962 		return false;
963 
964 	spi = dynptr_get_spi(env, reg);
965 
966 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
967 	 * error because this just means the stack state hasn't been updated yet.
968 	 * We will do check_mem_access to check and update stack bounds later.
969 	 */
970 	if (spi < 0 && spi != -ERANGE)
971 		return false;
972 
973 	/* We don't need to check if the stack slots are marked by previous
974 	 * dynptr initializations because we allow overwriting existing unreferenced
975 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
976 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
977 	 * touching are completely destructed before we reinitialize them for a new
978 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
979 	 * instead of delaying it until the end where the user will get "Unreleased
980 	 * reference" error.
981 	 */
982 	return true;
983 }
984 
985 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
986 {
987 	struct bpf_func_state *state = func(env, reg);
988 	int i, spi;
989 
990 	/* This already represents first slot of initialized bpf_dynptr.
991 	 *
992 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
993 	 * check_func_arg_reg_off's logic, so we don't need to check its
994 	 * offset and alignment.
995 	 */
996 	if (reg->type == CONST_PTR_TO_DYNPTR)
997 		return true;
998 
999 	spi = dynptr_get_spi(env, reg);
1000 	if (spi < 0)
1001 		return false;
1002 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1003 		return false;
1004 
1005 	for (i = 0; i < BPF_REG_SIZE; i++) {
1006 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1007 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1008 			return false;
1009 	}
1010 
1011 	return true;
1012 }
1013 
1014 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1015 				    enum bpf_arg_type arg_type)
1016 {
1017 	struct bpf_func_state *state = func(env, reg);
1018 	enum bpf_dynptr_type dynptr_type;
1019 	int spi;
1020 
1021 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1022 	if (arg_type == ARG_PTR_TO_DYNPTR)
1023 		return true;
1024 
1025 	dynptr_type = arg_to_dynptr_type(arg_type);
1026 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1027 		return reg->dynptr.type == dynptr_type;
1028 	} else {
1029 		spi = dynptr_get_spi(env, reg);
1030 		if (spi < 0)
1031 			return false;
1032 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1033 	}
1034 }
1035 
1036 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1037 
1038 static bool in_rcu_cs(struct bpf_verifier_env *env);
1039 
1040 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1041 
1042 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1043 				 struct bpf_kfunc_call_arg_meta *meta,
1044 				 struct bpf_reg_state *reg, int insn_idx,
1045 				 struct btf *btf, u32 btf_id, int nr_slots)
1046 {
1047 	struct bpf_func_state *state = func(env, reg);
1048 	int spi, i, j, id;
1049 
1050 	spi = iter_get_spi(env, reg, nr_slots);
1051 	if (spi < 0)
1052 		return spi;
1053 
1054 	id = acquire_reference(env, insn_idx);
1055 	if (id < 0)
1056 		return id;
1057 
1058 	for (i = 0; i < nr_slots; i++) {
1059 		struct bpf_stack_state *slot = &state->stack[spi - i];
1060 		struct bpf_reg_state *st = &slot->spilled_ptr;
1061 
1062 		__mark_reg_known_zero(st);
1063 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1064 		if (is_kfunc_rcu_protected(meta)) {
1065 			if (in_rcu_cs(env))
1066 				st->type |= MEM_RCU;
1067 			else
1068 				st->type |= PTR_UNTRUSTED;
1069 		}
1070 		st->ref_obj_id = i == 0 ? id : 0;
1071 		st->iter.btf = btf;
1072 		st->iter.btf_id = btf_id;
1073 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1074 		st->iter.depth = 0;
1075 
1076 		for (j = 0; j < BPF_REG_SIZE; j++)
1077 			slot->slot_type[j] = STACK_ITER;
1078 
1079 		bpf_mark_stack_write(env, state->frameno, BIT(spi - i));
1080 		mark_stack_slot_scratched(env, spi - i);
1081 	}
1082 
1083 	return 0;
1084 }
1085 
1086 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1087 				   struct bpf_reg_state *reg, int nr_slots)
1088 {
1089 	struct bpf_func_state *state = func(env, reg);
1090 	int spi, i, j;
1091 
1092 	spi = iter_get_spi(env, reg, nr_slots);
1093 	if (spi < 0)
1094 		return spi;
1095 
1096 	for (i = 0; i < nr_slots; i++) {
1097 		struct bpf_stack_state *slot = &state->stack[spi - i];
1098 		struct bpf_reg_state *st = &slot->spilled_ptr;
1099 
1100 		if (i == 0)
1101 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1102 
1103 		__mark_reg_not_init(env, st);
1104 
1105 		for (j = 0; j < BPF_REG_SIZE; j++)
1106 			slot->slot_type[j] = STACK_INVALID;
1107 
1108 		bpf_mark_stack_write(env, state->frameno, BIT(spi - i));
1109 		mark_stack_slot_scratched(env, spi - i);
1110 	}
1111 
1112 	return 0;
1113 }
1114 
1115 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1116 				     struct bpf_reg_state *reg, int nr_slots)
1117 {
1118 	struct bpf_func_state *state = func(env, reg);
1119 	int spi, i, j;
1120 
1121 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1122 	 * will do check_mem_access to check and update stack bounds later, so
1123 	 * return true for that case.
1124 	 */
1125 	spi = iter_get_spi(env, reg, nr_slots);
1126 	if (spi == -ERANGE)
1127 		return true;
1128 	if (spi < 0)
1129 		return false;
1130 
1131 	for (i = 0; i < nr_slots; i++) {
1132 		struct bpf_stack_state *slot = &state->stack[spi - i];
1133 
1134 		for (j = 0; j < BPF_REG_SIZE; j++)
1135 			if (slot->slot_type[j] == STACK_ITER)
1136 				return false;
1137 	}
1138 
1139 	return true;
1140 }
1141 
1142 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1143 				   struct btf *btf, u32 btf_id, int nr_slots)
1144 {
1145 	struct bpf_func_state *state = func(env, reg);
1146 	int spi, i, j;
1147 
1148 	spi = iter_get_spi(env, reg, nr_slots);
1149 	if (spi < 0)
1150 		return -EINVAL;
1151 
1152 	for (i = 0; i < nr_slots; i++) {
1153 		struct bpf_stack_state *slot = &state->stack[spi - i];
1154 		struct bpf_reg_state *st = &slot->spilled_ptr;
1155 
1156 		if (st->type & PTR_UNTRUSTED)
1157 			return -EPROTO;
1158 		/* only main (first) slot has ref_obj_id set */
1159 		if (i == 0 && !st->ref_obj_id)
1160 			return -EINVAL;
1161 		if (i != 0 && st->ref_obj_id)
1162 			return -EINVAL;
1163 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1164 			return -EINVAL;
1165 
1166 		for (j = 0; j < BPF_REG_SIZE; j++)
1167 			if (slot->slot_type[j] != STACK_ITER)
1168 				return -EINVAL;
1169 	}
1170 
1171 	return 0;
1172 }
1173 
1174 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
1175 static int release_irq_state(struct bpf_verifier_state *state, int id);
1176 
1177 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
1178 				     struct bpf_kfunc_call_arg_meta *meta,
1179 				     struct bpf_reg_state *reg, int insn_idx,
1180 				     int kfunc_class)
1181 {
1182 	struct bpf_func_state *state = func(env, reg);
1183 	struct bpf_stack_state *slot;
1184 	struct bpf_reg_state *st;
1185 	int spi, i, id;
1186 
1187 	spi = irq_flag_get_spi(env, reg);
1188 	if (spi < 0)
1189 		return spi;
1190 
1191 	id = acquire_irq_state(env, insn_idx);
1192 	if (id < 0)
1193 		return id;
1194 
1195 	slot = &state->stack[spi];
1196 	st = &slot->spilled_ptr;
1197 
1198 	bpf_mark_stack_write(env, reg->frameno, BIT(spi));
1199 	__mark_reg_known_zero(st);
1200 	st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1201 	st->ref_obj_id = id;
1202 	st->irq.kfunc_class = kfunc_class;
1203 
1204 	for (i = 0; i < BPF_REG_SIZE; i++)
1205 		slot->slot_type[i] = STACK_IRQ_FLAG;
1206 
1207 	mark_stack_slot_scratched(env, spi);
1208 	return 0;
1209 }
1210 
1211 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1212 				      int kfunc_class)
1213 {
1214 	struct bpf_func_state *state = func(env, reg);
1215 	struct bpf_stack_state *slot;
1216 	struct bpf_reg_state *st;
1217 	int spi, i, err;
1218 
1219 	spi = irq_flag_get_spi(env, reg);
1220 	if (spi < 0)
1221 		return spi;
1222 
1223 	slot = &state->stack[spi];
1224 	st = &slot->spilled_ptr;
1225 
1226 	if (st->irq.kfunc_class != kfunc_class) {
1227 		const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1228 		const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1229 
1230 		verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n",
1231 			flag_kfunc, used_kfunc);
1232 		return -EINVAL;
1233 	}
1234 
1235 	err = release_irq_state(env->cur_state, st->ref_obj_id);
1236 	WARN_ON_ONCE(err && err != -EACCES);
1237 	if (err) {
1238 		int insn_idx = 0;
1239 
1240 		for (int i = 0; i < env->cur_state->acquired_refs; i++) {
1241 			if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) {
1242 				insn_idx = env->cur_state->refs[i].insn_idx;
1243 				break;
1244 			}
1245 		}
1246 
1247 		verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n",
1248 			env->cur_state->active_irq_id, insn_idx);
1249 		return err;
1250 	}
1251 
1252 	__mark_reg_not_init(env, st);
1253 
1254 	bpf_mark_stack_write(env, reg->frameno, BIT(spi));
1255 
1256 	for (i = 0; i < BPF_REG_SIZE; i++)
1257 		slot->slot_type[i] = STACK_INVALID;
1258 
1259 	mark_stack_slot_scratched(env, spi);
1260 	return 0;
1261 }
1262 
1263 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1264 {
1265 	struct bpf_func_state *state = func(env, reg);
1266 	struct bpf_stack_state *slot;
1267 	int spi, i;
1268 
1269 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1270 	 * will do check_mem_access to check and update stack bounds later, so
1271 	 * return true for that case.
1272 	 */
1273 	spi = irq_flag_get_spi(env, reg);
1274 	if (spi == -ERANGE)
1275 		return true;
1276 	if (spi < 0)
1277 		return false;
1278 
1279 	slot = &state->stack[spi];
1280 
1281 	for (i = 0; i < BPF_REG_SIZE; i++)
1282 		if (slot->slot_type[i] == STACK_IRQ_FLAG)
1283 			return false;
1284 	return true;
1285 }
1286 
1287 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1288 {
1289 	struct bpf_func_state *state = func(env, reg);
1290 	struct bpf_stack_state *slot;
1291 	struct bpf_reg_state *st;
1292 	int spi, i;
1293 
1294 	spi = irq_flag_get_spi(env, reg);
1295 	if (spi < 0)
1296 		return -EINVAL;
1297 
1298 	slot = &state->stack[spi];
1299 	st = &slot->spilled_ptr;
1300 
1301 	if (!st->ref_obj_id)
1302 		return -EINVAL;
1303 
1304 	for (i = 0; i < BPF_REG_SIZE; i++)
1305 		if (slot->slot_type[i] != STACK_IRQ_FLAG)
1306 			return -EINVAL;
1307 	return 0;
1308 }
1309 
1310 /* Check if given stack slot is "special":
1311  *   - spilled register state (STACK_SPILL);
1312  *   - dynptr state (STACK_DYNPTR);
1313  *   - iter state (STACK_ITER).
1314  *   - irq flag state (STACK_IRQ_FLAG)
1315  */
1316 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1317 {
1318 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1319 
1320 	switch (type) {
1321 	case STACK_SPILL:
1322 	case STACK_DYNPTR:
1323 	case STACK_ITER:
1324 	case STACK_IRQ_FLAG:
1325 		return true;
1326 	case STACK_INVALID:
1327 	case STACK_MISC:
1328 	case STACK_ZERO:
1329 		return false;
1330 	default:
1331 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1332 		return true;
1333 	}
1334 }
1335 
1336 /* The reg state of a pointer or a bounded scalar was saved when
1337  * it was spilled to the stack.
1338  */
1339 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1340 {
1341 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1342 }
1343 
1344 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1345 {
1346 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1347 	       stack->spilled_ptr.type == SCALAR_VALUE;
1348 }
1349 
1350 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1351 {
1352 	return stack->slot_type[0] == STACK_SPILL &&
1353 	       stack->spilled_ptr.type == SCALAR_VALUE;
1354 }
1355 
1356 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1357  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1358  * more precise STACK_ZERO.
1359  * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1360  * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1361  * unnecessary as both are considered equivalent when loading data and pruning,
1362  * in case of unprivileged mode it will be incorrect to allow reads of invalid
1363  * slots.
1364  */
1365 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1366 {
1367 	if (*stype == STACK_ZERO)
1368 		return;
1369 	if (*stype == STACK_INVALID)
1370 		return;
1371 	*stype = STACK_MISC;
1372 }
1373 
1374 static void scrub_spilled_slot(u8 *stype)
1375 {
1376 	if (*stype != STACK_INVALID)
1377 		*stype = STACK_MISC;
1378 }
1379 
1380 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1381  * small to hold src. This is different from krealloc since we don't want to preserve
1382  * the contents of dst.
1383  *
1384  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1385  * not be allocated.
1386  */
1387 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1388 {
1389 	size_t alloc_bytes;
1390 	void *orig = dst;
1391 	size_t bytes;
1392 
1393 	if (ZERO_OR_NULL_PTR(src))
1394 		goto out;
1395 
1396 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1397 		return NULL;
1398 
1399 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1400 	dst = krealloc(orig, alloc_bytes, flags);
1401 	if (!dst) {
1402 		kfree(orig);
1403 		return NULL;
1404 	}
1405 
1406 	memcpy(dst, src, bytes);
1407 out:
1408 	return dst ? dst : ZERO_SIZE_PTR;
1409 }
1410 
1411 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1412  * small to hold new_n items. new items are zeroed out if the array grows.
1413  *
1414  * Contrary to krealloc_array, does not free arr if new_n is zero.
1415  */
1416 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1417 {
1418 	size_t alloc_size;
1419 	void *new_arr;
1420 
1421 	if (!new_n || old_n == new_n)
1422 		goto out;
1423 
1424 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1425 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT);
1426 	if (!new_arr) {
1427 		kfree(arr);
1428 		return NULL;
1429 	}
1430 	arr = new_arr;
1431 
1432 	if (new_n > old_n)
1433 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1434 
1435 out:
1436 	return arr ? arr : ZERO_SIZE_PTR;
1437 }
1438 
1439 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
1440 {
1441 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1442 			       sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT);
1443 	if (!dst->refs)
1444 		return -ENOMEM;
1445 
1446 	dst->acquired_refs = src->acquired_refs;
1447 	dst->active_locks = src->active_locks;
1448 	dst->active_preempt_locks = src->active_preempt_locks;
1449 	dst->active_rcu_locks = src->active_rcu_locks;
1450 	dst->active_irq_id = src->active_irq_id;
1451 	dst->active_lock_id = src->active_lock_id;
1452 	dst->active_lock_ptr = src->active_lock_ptr;
1453 	return 0;
1454 }
1455 
1456 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1457 {
1458 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1459 
1460 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1461 				GFP_KERNEL_ACCOUNT);
1462 	if (!dst->stack)
1463 		return -ENOMEM;
1464 
1465 	dst->allocated_stack = src->allocated_stack;
1466 	return 0;
1467 }
1468 
1469 static int resize_reference_state(struct bpf_verifier_state *state, size_t n)
1470 {
1471 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1472 				    sizeof(struct bpf_reference_state));
1473 	if (!state->refs)
1474 		return -ENOMEM;
1475 
1476 	state->acquired_refs = n;
1477 	return 0;
1478 }
1479 
1480 /* Possibly update state->allocated_stack to be at least size bytes. Also
1481  * possibly update the function's high-water mark in its bpf_subprog_info.
1482  */
1483 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1484 {
1485 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1486 
1487 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1488 	size = round_up(size, BPF_REG_SIZE);
1489 	n = size / BPF_REG_SIZE;
1490 
1491 	if (old_n >= n)
1492 		return 0;
1493 
1494 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1495 	if (!state->stack)
1496 		return -ENOMEM;
1497 
1498 	state->allocated_stack = size;
1499 
1500 	/* update known max for given subprogram */
1501 	if (env->subprog_info[state->subprogno].stack_depth < size)
1502 		env->subprog_info[state->subprogno].stack_depth = size;
1503 
1504 	return 0;
1505 }
1506 
1507 /* Acquire a pointer id from the env and update the state->refs to include
1508  * this new pointer reference.
1509  * On success, returns a valid pointer id to associate with the register
1510  * On failure, returns a negative errno.
1511  */
1512 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1513 {
1514 	struct bpf_verifier_state *state = env->cur_state;
1515 	int new_ofs = state->acquired_refs;
1516 	int err;
1517 
1518 	err = resize_reference_state(state, state->acquired_refs + 1);
1519 	if (err)
1520 		return NULL;
1521 	state->refs[new_ofs].insn_idx = insn_idx;
1522 
1523 	return &state->refs[new_ofs];
1524 }
1525 
1526 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx)
1527 {
1528 	struct bpf_reference_state *s;
1529 
1530 	s = acquire_reference_state(env, insn_idx);
1531 	if (!s)
1532 		return -ENOMEM;
1533 	s->type = REF_TYPE_PTR;
1534 	s->id = ++env->id_gen;
1535 	return s->id;
1536 }
1537 
1538 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1539 			      int id, void *ptr)
1540 {
1541 	struct bpf_verifier_state *state = env->cur_state;
1542 	struct bpf_reference_state *s;
1543 
1544 	s = acquire_reference_state(env, insn_idx);
1545 	if (!s)
1546 		return -ENOMEM;
1547 	s->type = type;
1548 	s->id = id;
1549 	s->ptr = ptr;
1550 
1551 	state->active_locks++;
1552 	state->active_lock_id = id;
1553 	state->active_lock_ptr = ptr;
1554 	return 0;
1555 }
1556 
1557 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
1558 {
1559 	struct bpf_verifier_state *state = env->cur_state;
1560 	struct bpf_reference_state *s;
1561 
1562 	s = acquire_reference_state(env, insn_idx);
1563 	if (!s)
1564 		return -ENOMEM;
1565 	s->type = REF_TYPE_IRQ;
1566 	s->id = ++env->id_gen;
1567 
1568 	state->active_irq_id = s->id;
1569 	return s->id;
1570 }
1571 
1572 static void release_reference_state(struct bpf_verifier_state *state, int idx)
1573 {
1574 	int last_idx;
1575 	size_t rem;
1576 
1577 	/* IRQ state requires the relative ordering of elements remaining the
1578 	 * same, since it relies on the refs array to behave as a stack, so that
1579 	 * it can detect out-of-order IRQ restore. Hence use memmove to shift
1580 	 * the array instead of swapping the final element into the deleted idx.
1581 	 */
1582 	last_idx = state->acquired_refs - 1;
1583 	rem = state->acquired_refs - idx - 1;
1584 	if (last_idx && idx != last_idx)
1585 		memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem);
1586 	memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1587 	state->acquired_refs--;
1588 	return;
1589 }
1590 
1591 static bool find_reference_state(struct bpf_verifier_state *state, int ptr_id)
1592 {
1593 	int i;
1594 
1595 	for (i = 0; i < state->acquired_refs; i++)
1596 		if (state->refs[i].id == ptr_id)
1597 			return true;
1598 
1599 	return false;
1600 }
1601 
1602 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr)
1603 {
1604 	void *prev_ptr = NULL;
1605 	u32 prev_id = 0;
1606 	int i;
1607 
1608 	for (i = 0; i < state->acquired_refs; i++) {
1609 		if (state->refs[i].type == type && state->refs[i].id == id &&
1610 		    state->refs[i].ptr == ptr) {
1611 			release_reference_state(state, i);
1612 			state->active_locks--;
1613 			/* Reassign active lock (id, ptr). */
1614 			state->active_lock_id = prev_id;
1615 			state->active_lock_ptr = prev_ptr;
1616 			return 0;
1617 		}
1618 		if (state->refs[i].type & REF_TYPE_LOCK_MASK) {
1619 			prev_id = state->refs[i].id;
1620 			prev_ptr = state->refs[i].ptr;
1621 		}
1622 	}
1623 	return -EINVAL;
1624 }
1625 
1626 static int release_irq_state(struct bpf_verifier_state *state, int id)
1627 {
1628 	u32 prev_id = 0;
1629 	int i;
1630 
1631 	if (id != state->active_irq_id)
1632 		return -EACCES;
1633 
1634 	for (i = 0; i < state->acquired_refs; i++) {
1635 		if (state->refs[i].type != REF_TYPE_IRQ)
1636 			continue;
1637 		if (state->refs[i].id == id) {
1638 			release_reference_state(state, i);
1639 			state->active_irq_id = prev_id;
1640 			return 0;
1641 		} else {
1642 			prev_id = state->refs[i].id;
1643 		}
1644 	}
1645 	return -EINVAL;
1646 }
1647 
1648 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,
1649 						   int id, void *ptr)
1650 {
1651 	int i;
1652 
1653 	for (i = 0; i < state->acquired_refs; i++) {
1654 		struct bpf_reference_state *s = &state->refs[i];
1655 
1656 		if (!(s->type & type))
1657 			continue;
1658 
1659 		if (s->id == id && s->ptr == ptr)
1660 			return s;
1661 	}
1662 	return NULL;
1663 }
1664 
1665 static void update_peak_states(struct bpf_verifier_env *env)
1666 {
1667 	u32 cur_states;
1668 
1669 	cur_states = env->explored_states_size + env->free_list_size + env->num_backedges;
1670 	env->peak_states = max(env->peak_states, cur_states);
1671 }
1672 
1673 static void free_func_state(struct bpf_func_state *state)
1674 {
1675 	if (!state)
1676 		return;
1677 	kfree(state->stack);
1678 	kfree(state);
1679 }
1680 
1681 static void clear_jmp_history(struct bpf_verifier_state *state)
1682 {
1683 	kfree(state->jmp_history);
1684 	state->jmp_history = NULL;
1685 	state->jmp_history_cnt = 0;
1686 }
1687 
1688 static void free_verifier_state(struct bpf_verifier_state *state,
1689 				bool free_self)
1690 {
1691 	int i;
1692 
1693 	for (i = 0; i <= state->curframe; i++) {
1694 		free_func_state(state->frame[i]);
1695 		state->frame[i] = NULL;
1696 	}
1697 	kfree(state->refs);
1698 	clear_jmp_history(state);
1699 	if (free_self)
1700 		kfree(state);
1701 }
1702 
1703 /* struct bpf_verifier_state->parent refers to states
1704  * that are in either of env->{expored_states,free_list}.
1705  * In both cases the state is contained in struct bpf_verifier_state_list.
1706  */
1707 static struct bpf_verifier_state_list *state_parent_as_list(struct bpf_verifier_state *st)
1708 {
1709 	if (st->parent)
1710 		return container_of(st->parent, struct bpf_verifier_state_list, state);
1711 	return NULL;
1712 }
1713 
1714 static bool incomplete_read_marks(struct bpf_verifier_env *env,
1715 				  struct bpf_verifier_state *st);
1716 
1717 /* A state can be freed if it is no longer referenced:
1718  * - is in the env->free_list;
1719  * - has no children states;
1720  */
1721 static void maybe_free_verifier_state(struct bpf_verifier_env *env,
1722 				      struct bpf_verifier_state_list *sl)
1723 {
1724 	if (!sl->in_free_list
1725 	    || sl->state.branches != 0
1726 	    || incomplete_read_marks(env, &sl->state))
1727 		return;
1728 	list_del(&sl->node);
1729 	free_verifier_state(&sl->state, false);
1730 	kfree(sl);
1731 	env->free_list_size--;
1732 }
1733 
1734 /* copy verifier state from src to dst growing dst stack space
1735  * when necessary to accommodate larger src stack
1736  */
1737 static int copy_func_state(struct bpf_func_state *dst,
1738 			   const struct bpf_func_state *src)
1739 {
1740 	memcpy(dst, src, offsetof(struct bpf_func_state, stack));
1741 	return copy_stack_state(dst, src);
1742 }
1743 
1744 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1745 			       const struct bpf_verifier_state *src)
1746 {
1747 	struct bpf_func_state *dst;
1748 	int i, err;
1749 
1750 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1751 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1752 					  GFP_KERNEL_ACCOUNT);
1753 	if (!dst_state->jmp_history)
1754 		return -ENOMEM;
1755 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1756 
1757 	/* if dst has more stack frames then src frame, free them, this is also
1758 	 * necessary in case of exceptional exits using bpf_throw.
1759 	 */
1760 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1761 		free_func_state(dst_state->frame[i]);
1762 		dst_state->frame[i] = NULL;
1763 	}
1764 	err = copy_reference_state(dst_state, src);
1765 	if (err)
1766 		return err;
1767 	dst_state->speculative = src->speculative;
1768 	dst_state->in_sleepable = src->in_sleepable;
1769 	dst_state->cleaned = src->cleaned;
1770 	dst_state->curframe = src->curframe;
1771 	dst_state->branches = src->branches;
1772 	dst_state->parent = src->parent;
1773 	dst_state->first_insn_idx = src->first_insn_idx;
1774 	dst_state->last_insn_idx = src->last_insn_idx;
1775 	dst_state->dfs_depth = src->dfs_depth;
1776 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1777 	dst_state->may_goto_depth = src->may_goto_depth;
1778 	dst_state->equal_state = src->equal_state;
1779 	for (i = 0; i <= src->curframe; i++) {
1780 		dst = dst_state->frame[i];
1781 		if (!dst) {
1782 			dst = kzalloc(sizeof(*dst), GFP_KERNEL_ACCOUNT);
1783 			if (!dst)
1784 				return -ENOMEM;
1785 			dst_state->frame[i] = dst;
1786 		}
1787 		err = copy_func_state(dst, src->frame[i]);
1788 		if (err)
1789 			return err;
1790 	}
1791 	return 0;
1792 }
1793 
1794 static u32 state_htab_size(struct bpf_verifier_env *env)
1795 {
1796 	return env->prog->len;
1797 }
1798 
1799 static struct list_head *explored_state(struct bpf_verifier_env *env, int idx)
1800 {
1801 	struct bpf_verifier_state *cur = env->cur_state;
1802 	struct bpf_func_state *state = cur->frame[cur->curframe];
1803 
1804 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1805 }
1806 
1807 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1808 {
1809 	int fr;
1810 
1811 	if (a->curframe != b->curframe)
1812 		return false;
1813 
1814 	for (fr = a->curframe; fr >= 0; fr--)
1815 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1816 			return false;
1817 
1818 	return true;
1819 }
1820 
1821 /* Return IP for a given frame in a call stack */
1822 static u32 frame_insn_idx(struct bpf_verifier_state *st, u32 frame)
1823 {
1824 	return frame == st->curframe
1825 	       ? st->insn_idx
1826 	       : st->frame[frame + 1]->callsite;
1827 }
1828 
1829 /* For state @st look for a topmost frame with frame_insn_idx() in some SCC,
1830  * if such frame exists form a corresponding @callchain as an array of
1831  * call sites leading to this frame and SCC id.
1832  * E.g.:
1833  *
1834  *    void foo()  { A: loop {... SCC#1 ...}; }
1835  *    void bar()  { B: loop { C: foo(); ... SCC#2 ... }
1836  *                  D: loop { E: foo(); ... SCC#3 ... } }
1837  *    void main() { F: bar(); }
1838  *
1839  * @callchain at (A) would be either (F,SCC#2) or (F,SCC#3) depending
1840  * on @st frame call sites being (F,C,A) or (F,E,A).
1841  */
1842 static bool compute_scc_callchain(struct bpf_verifier_env *env,
1843 				  struct bpf_verifier_state *st,
1844 				  struct bpf_scc_callchain *callchain)
1845 {
1846 	u32 i, scc, insn_idx;
1847 
1848 	memset(callchain, 0, sizeof(*callchain));
1849 	for (i = 0; i <= st->curframe; i++) {
1850 		insn_idx = frame_insn_idx(st, i);
1851 		scc = env->insn_aux_data[insn_idx].scc;
1852 		if (scc) {
1853 			callchain->scc = scc;
1854 			break;
1855 		} else if (i < st->curframe) {
1856 			callchain->callsites[i] = insn_idx;
1857 		} else {
1858 			return false;
1859 		}
1860 	}
1861 	return true;
1862 }
1863 
1864 /* Check if bpf_scc_visit instance for @callchain exists. */
1865 static struct bpf_scc_visit *scc_visit_lookup(struct bpf_verifier_env *env,
1866 					      struct bpf_scc_callchain *callchain)
1867 {
1868 	struct bpf_scc_info *info = env->scc_info[callchain->scc];
1869 	struct bpf_scc_visit *visits = info->visits;
1870 	u32 i;
1871 
1872 	if (!info)
1873 		return NULL;
1874 	for (i = 0; i < info->num_visits; i++)
1875 		if (memcmp(callchain, &visits[i].callchain, sizeof(*callchain)) == 0)
1876 			return &visits[i];
1877 	return NULL;
1878 }
1879 
1880 /* Allocate a new bpf_scc_visit instance corresponding to @callchain.
1881  * Allocated instances are alive for a duration of the do_check_common()
1882  * call and are freed by free_states().
1883  */
1884 static struct bpf_scc_visit *scc_visit_alloc(struct bpf_verifier_env *env,
1885 					     struct bpf_scc_callchain *callchain)
1886 {
1887 	struct bpf_scc_visit *visit;
1888 	struct bpf_scc_info *info;
1889 	u32 scc, num_visits;
1890 	u64 new_sz;
1891 
1892 	scc = callchain->scc;
1893 	info = env->scc_info[scc];
1894 	num_visits = info ? info->num_visits : 0;
1895 	new_sz = sizeof(*info) + sizeof(struct bpf_scc_visit) * (num_visits + 1);
1896 	info = kvrealloc(env->scc_info[scc], new_sz, GFP_KERNEL_ACCOUNT);
1897 	if (!info)
1898 		return NULL;
1899 	env->scc_info[scc] = info;
1900 	info->num_visits = num_visits + 1;
1901 	visit = &info->visits[num_visits];
1902 	memset(visit, 0, sizeof(*visit));
1903 	memcpy(&visit->callchain, callchain, sizeof(*callchain));
1904 	return visit;
1905 }
1906 
1907 /* Form a string '(callsite#1,callsite#2,...,scc)' in env->tmp_str_buf */
1908 static char *format_callchain(struct bpf_verifier_env *env, struct bpf_scc_callchain *callchain)
1909 {
1910 	char *buf = env->tmp_str_buf;
1911 	int i, delta = 0;
1912 
1913 	delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "(");
1914 	for (i = 0; i < ARRAY_SIZE(callchain->callsites); i++) {
1915 		if (!callchain->callsites[i])
1916 			break;
1917 		delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u,",
1918 				  callchain->callsites[i]);
1919 	}
1920 	delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u)", callchain->scc);
1921 	return env->tmp_str_buf;
1922 }
1923 
1924 /* If callchain for @st exists (@st is in some SCC), ensure that
1925  * bpf_scc_visit instance for this callchain exists.
1926  * If instance does not exist or is empty, assign visit->entry_state to @st.
1927  */
1928 static int maybe_enter_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1929 {
1930 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1931 	struct bpf_scc_visit *visit;
1932 
1933 	if (!compute_scc_callchain(env, st, callchain))
1934 		return 0;
1935 	visit = scc_visit_lookup(env, callchain);
1936 	visit = visit ?: scc_visit_alloc(env, callchain);
1937 	if (!visit)
1938 		return -ENOMEM;
1939 	if (!visit->entry_state) {
1940 		visit->entry_state = st;
1941 		if (env->log.level & BPF_LOG_LEVEL2)
1942 			verbose(env, "SCC enter %s\n", format_callchain(env, callchain));
1943 	}
1944 	return 0;
1945 }
1946 
1947 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit);
1948 
1949 /* If callchain for @st exists (@st is in some SCC), make it empty:
1950  * - set visit->entry_state to NULL;
1951  * - flush accumulated backedges.
1952  */
1953 static int maybe_exit_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1954 {
1955 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1956 	struct bpf_scc_visit *visit;
1957 
1958 	if (!compute_scc_callchain(env, st, callchain))
1959 		return 0;
1960 	visit = scc_visit_lookup(env, callchain);
1961 	if (!visit) {
1962 		/*
1963 		 * If path traversal stops inside an SCC, corresponding bpf_scc_visit
1964 		 * must exist for non-speculative paths. For non-speculative paths
1965 		 * traversal stops when:
1966 		 * a. Verification error is found, maybe_exit_scc() is not called.
1967 		 * b. Top level BPF_EXIT is reached. Top level BPF_EXIT is not a member
1968 		 *    of any SCC.
1969 		 * c. A checkpoint is reached and matched. Checkpoints are created by
1970 		 *    is_state_visited(), which calls maybe_enter_scc(), which allocates
1971 		 *    bpf_scc_visit instances for checkpoints within SCCs.
1972 		 * (c) is the only case that can reach this point.
1973 		 */
1974 		if (!st->speculative) {
1975 			verifier_bug(env, "scc exit: no visit info for call chain %s",
1976 				     format_callchain(env, callchain));
1977 			return -EFAULT;
1978 		}
1979 		return 0;
1980 	}
1981 	if (visit->entry_state != st)
1982 		return 0;
1983 	if (env->log.level & BPF_LOG_LEVEL2)
1984 		verbose(env, "SCC exit %s\n", format_callchain(env, callchain));
1985 	visit->entry_state = NULL;
1986 	env->num_backedges -= visit->num_backedges;
1987 	visit->num_backedges = 0;
1988 	update_peak_states(env);
1989 	return propagate_backedges(env, visit);
1990 }
1991 
1992 /* Lookup an bpf_scc_visit instance corresponding to @st callchain
1993  * and add @backedge to visit->backedges. @st callchain must exist.
1994  */
1995 static int add_scc_backedge(struct bpf_verifier_env *env,
1996 			    struct bpf_verifier_state *st,
1997 			    struct bpf_scc_backedge *backedge)
1998 {
1999 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
2000 	struct bpf_scc_visit *visit;
2001 
2002 	if (!compute_scc_callchain(env, st, callchain)) {
2003 		verifier_bug(env, "add backedge: no SCC in verification path, insn_idx %d",
2004 			     st->insn_idx);
2005 		return -EFAULT;
2006 	}
2007 	visit = scc_visit_lookup(env, callchain);
2008 	if (!visit) {
2009 		verifier_bug(env, "add backedge: no visit info for call chain %s",
2010 			     format_callchain(env, callchain));
2011 		return -EFAULT;
2012 	}
2013 	if (env->log.level & BPF_LOG_LEVEL2)
2014 		verbose(env, "SCC backedge %s\n", format_callchain(env, callchain));
2015 	backedge->next = visit->backedges;
2016 	visit->backedges = backedge;
2017 	visit->num_backedges++;
2018 	env->num_backedges++;
2019 	update_peak_states(env);
2020 	return 0;
2021 }
2022 
2023 /* bpf_reg_state->live marks for registers in a state @st are incomplete,
2024  * if state @st is in some SCC and not all execution paths starting at this
2025  * SCC are fully explored.
2026  */
2027 static bool incomplete_read_marks(struct bpf_verifier_env *env,
2028 				  struct bpf_verifier_state *st)
2029 {
2030 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
2031 	struct bpf_scc_visit *visit;
2032 
2033 	if (!compute_scc_callchain(env, st, callchain))
2034 		return false;
2035 	visit = scc_visit_lookup(env, callchain);
2036 	if (!visit)
2037 		return false;
2038 	return !!visit->backedges;
2039 }
2040 
2041 static void free_backedges(struct bpf_scc_visit *visit)
2042 {
2043 	struct bpf_scc_backedge *backedge, *next;
2044 
2045 	for (backedge = visit->backedges; backedge; backedge = next) {
2046 		free_verifier_state(&backedge->state, false);
2047 		next = backedge->next;
2048 		kfree(backedge);
2049 	}
2050 	visit->backedges = NULL;
2051 }
2052 
2053 static int update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2054 {
2055 	struct bpf_verifier_state_list *sl = NULL, *parent_sl;
2056 	struct bpf_verifier_state *parent;
2057 	int err;
2058 
2059 	while (st) {
2060 		u32 br = --st->branches;
2061 
2062 		/* verifier_bug_if(br > 1, ...) technically makes sense here,
2063 		 * but see comment in push_stack(), hence:
2064 		 */
2065 		verifier_bug_if((int)br < 0, env, "%s:branches_to_explore=%d", __func__, br);
2066 		if (br)
2067 			break;
2068 		err = maybe_exit_scc(env, st);
2069 		if (err)
2070 			return err;
2071 		parent = st->parent;
2072 		parent_sl = state_parent_as_list(st);
2073 		if (sl)
2074 			maybe_free_verifier_state(env, sl);
2075 		st = parent;
2076 		sl = parent_sl;
2077 	}
2078 	return 0;
2079 }
2080 
2081 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2082 		     int *insn_idx, bool pop_log)
2083 {
2084 	struct bpf_verifier_state *cur = env->cur_state;
2085 	struct bpf_verifier_stack_elem *elem, *head = env->head;
2086 	int err;
2087 
2088 	if (env->head == NULL)
2089 		return -ENOENT;
2090 
2091 	if (cur) {
2092 		err = copy_verifier_state(cur, &head->st);
2093 		if (err)
2094 			return err;
2095 	}
2096 	if (pop_log)
2097 		bpf_vlog_reset(&env->log, head->log_pos);
2098 	if (insn_idx)
2099 		*insn_idx = head->insn_idx;
2100 	if (prev_insn_idx)
2101 		*prev_insn_idx = head->prev_insn_idx;
2102 	elem = head->next;
2103 	free_verifier_state(&head->st, false);
2104 	kfree(head);
2105 	env->head = elem;
2106 	env->stack_size--;
2107 	return 0;
2108 }
2109 
2110 static bool error_recoverable_with_nospec(int err)
2111 {
2112 	/* Should only return true for non-fatal errors that are allowed to
2113 	 * occur during speculative verification. For these we can insert a
2114 	 * nospec and the program might still be accepted. Do not include
2115 	 * something like ENOMEM because it is likely to re-occur for the next
2116 	 * architectural path once it has been recovered-from in all speculative
2117 	 * paths.
2118 	 */
2119 	return err == -EPERM || err == -EACCES || err == -EINVAL;
2120 }
2121 
2122 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2123 					     int insn_idx, int prev_insn_idx,
2124 					     bool speculative)
2125 {
2126 	struct bpf_verifier_state *cur = env->cur_state;
2127 	struct bpf_verifier_stack_elem *elem;
2128 	int err;
2129 
2130 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
2131 	if (!elem)
2132 		return ERR_PTR(-ENOMEM);
2133 
2134 	elem->insn_idx = insn_idx;
2135 	elem->prev_insn_idx = prev_insn_idx;
2136 	elem->next = env->head;
2137 	elem->log_pos = env->log.end_pos;
2138 	env->head = elem;
2139 	env->stack_size++;
2140 	err = copy_verifier_state(&elem->st, cur);
2141 	if (err)
2142 		return ERR_PTR(-ENOMEM);
2143 	elem->st.speculative |= speculative;
2144 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2145 		verbose(env, "The sequence of %d jumps is too complex.\n",
2146 			env->stack_size);
2147 		return ERR_PTR(-E2BIG);
2148 	}
2149 	if (elem->st.parent) {
2150 		++elem->st.parent->branches;
2151 		/* WARN_ON(branches > 2) technically makes sense here,
2152 		 * but
2153 		 * 1. speculative states will bump 'branches' for non-branch
2154 		 * instructions
2155 		 * 2. is_state_visited() heuristics may decide not to create
2156 		 * a new state for a sequence of branches and all such current
2157 		 * and cloned states will be pointing to a single parent state
2158 		 * which might have large 'branches' count.
2159 		 */
2160 	}
2161 	return &elem->st;
2162 }
2163 
2164 #define CALLER_SAVED_REGS 6
2165 static const int caller_saved[CALLER_SAVED_REGS] = {
2166 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2167 };
2168 
2169 /* This helper doesn't clear reg->id */
2170 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2171 {
2172 	reg->var_off = tnum_const(imm);
2173 	reg->smin_value = (s64)imm;
2174 	reg->smax_value = (s64)imm;
2175 	reg->umin_value = imm;
2176 	reg->umax_value = imm;
2177 
2178 	reg->s32_min_value = (s32)imm;
2179 	reg->s32_max_value = (s32)imm;
2180 	reg->u32_min_value = (u32)imm;
2181 	reg->u32_max_value = (u32)imm;
2182 }
2183 
2184 /* Mark the unknown part of a register (variable offset or scalar value) as
2185  * known to have the value @imm.
2186  */
2187 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2188 {
2189 	/* Clear off and union(map_ptr, range) */
2190 	memset(((u8 *)reg) + sizeof(reg->type), 0,
2191 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2192 	reg->id = 0;
2193 	reg->ref_obj_id = 0;
2194 	___mark_reg_known(reg, imm);
2195 }
2196 
2197 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2198 {
2199 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2200 	reg->s32_min_value = (s32)imm;
2201 	reg->s32_max_value = (s32)imm;
2202 	reg->u32_min_value = (u32)imm;
2203 	reg->u32_max_value = (u32)imm;
2204 }
2205 
2206 /* Mark the 'variable offset' part of a register as zero.  This should be
2207  * used only on registers holding a pointer type.
2208  */
2209 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2210 {
2211 	__mark_reg_known(reg, 0);
2212 }
2213 
2214 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2215 {
2216 	__mark_reg_known(reg, 0);
2217 	reg->type = SCALAR_VALUE;
2218 	/* all scalars are assumed imprecise initially (unless unprivileged,
2219 	 * in which case everything is forced to be precise)
2220 	 */
2221 	reg->precise = !env->bpf_capable;
2222 }
2223 
2224 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2225 				struct bpf_reg_state *regs, u32 regno)
2226 {
2227 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2228 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2229 		/* Something bad happened, let's kill all regs */
2230 		for (regno = 0; regno < MAX_BPF_REG; regno++)
2231 			__mark_reg_not_init(env, regs + regno);
2232 		return;
2233 	}
2234 	__mark_reg_known_zero(regs + regno);
2235 }
2236 
2237 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2238 			      bool first_slot, int dynptr_id)
2239 {
2240 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2241 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2242 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2243 	 */
2244 	__mark_reg_known_zero(reg);
2245 	reg->type = CONST_PTR_TO_DYNPTR;
2246 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2247 	reg->id = dynptr_id;
2248 	reg->dynptr.type = type;
2249 	reg->dynptr.first_slot = first_slot;
2250 }
2251 
2252 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2253 {
2254 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2255 		const struct bpf_map *map = reg->map_ptr;
2256 
2257 		if (map->inner_map_meta) {
2258 			reg->type = CONST_PTR_TO_MAP;
2259 			reg->map_ptr = map->inner_map_meta;
2260 			/* transfer reg's id which is unique for every map_lookup_elem
2261 			 * as UID of the inner map.
2262 			 */
2263 			if (btf_record_has_field(map->inner_map_meta->record,
2264 						 BPF_TIMER | BPF_WORKQUEUE | BPF_TASK_WORK)) {
2265 				reg->map_uid = reg->id;
2266 			}
2267 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2268 			reg->type = PTR_TO_XDP_SOCK;
2269 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2270 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2271 			reg->type = PTR_TO_SOCKET;
2272 		} else {
2273 			reg->type = PTR_TO_MAP_VALUE;
2274 		}
2275 		return;
2276 	}
2277 
2278 	reg->type &= ~PTR_MAYBE_NULL;
2279 }
2280 
2281 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2282 				struct btf_field_graph_root *ds_head)
2283 {
2284 	__mark_reg_known_zero(&regs[regno]);
2285 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2286 	regs[regno].btf = ds_head->btf;
2287 	regs[regno].btf_id = ds_head->value_btf_id;
2288 	regs[regno].off = ds_head->node_offset;
2289 }
2290 
2291 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2292 {
2293 	return type_is_pkt_pointer(reg->type);
2294 }
2295 
2296 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2297 {
2298 	return reg_is_pkt_pointer(reg) ||
2299 	       reg->type == PTR_TO_PACKET_END;
2300 }
2301 
2302 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2303 {
2304 	return base_type(reg->type) == PTR_TO_MEM &&
2305 	       (reg->type &
2306 		(DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META));
2307 }
2308 
2309 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2310 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2311 				    enum bpf_reg_type which)
2312 {
2313 	/* The register can already have a range from prior markings.
2314 	 * This is fine as long as it hasn't been advanced from its
2315 	 * origin.
2316 	 */
2317 	return reg->type == which &&
2318 	       reg->id == 0 &&
2319 	       reg->off == 0 &&
2320 	       tnum_equals_const(reg->var_off, 0);
2321 }
2322 
2323 /* Reset the min/max bounds of a register */
2324 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2325 {
2326 	reg->smin_value = S64_MIN;
2327 	reg->smax_value = S64_MAX;
2328 	reg->umin_value = 0;
2329 	reg->umax_value = U64_MAX;
2330 
2331 	reg->s32_min_value = S32_MIN;
2332 	reg->s32_max_value = S32_MAX;
2333 	reg->u32_min_value = 0;
2334 	reg->u32_max_value = U32_MAX;
2335 }
2336 
2337 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2338 {
2339 	reg->smin_value = S64_MIN;
2340 	reg->smax_value = S64_MAX;
2341 	reg->umin_value = 0;
2342 	reg->umax_value = U64_MAX;
2343 }
2344 
2345 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2346 {
2347 	reg->s32_min_value = S32_MIN;
2348 	reg->s32_max_value = S32_MAX;
2349 	reg->u32_min_value = 0;
2350 	reg->u32_max_value = U32_MAX;
2351 }
2352 
2353 static void reset_reg64_and_tnum(struct bpf_reg_state *reg)
2354 {
2355 	__mark_reg64_unbounded(reg);
2356 	reg->var_off = tnum_unknown;
2357 }
2358 
2359 static void reset_reg32_and_tnum(struct bpf_reg_state *reg)
2360 {
2361 	__mark_reg32_unbounded(reg);
2362 	reg->var_off = tnum_unknown;
2363 }
2364 
2365 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2366 {
2367 	struct tnum var32_off = tnum_subreg(reg->var_off);
2368 
2369 	/* min signed is max(sign bit) | min(other bits) */
2370 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2371 			var32_off.value | (var32_off.mask & S32_MIN));
2372 	/* max signed is min(sign bit) | max(other bits) */
2373 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2374 			var32_off.value | (var32_off.mask & S32_MAX));
2375 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2376 	reg->u32_max_value = min(reg->u32_max_value,
2377 				 (u32)(var32_off.value | var32_off.mask));
2378 }
2379 
2380 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2381 {
2382 	/* min signed is max(sign bit) | min(other bits) */
2383 	reg->smin_value = max_t(s64, reg->smin_value,
2384 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2385 	/* max signed is min(sign bit) | max(other bits) */
2386 	reg->smax_value = min_t(s64, reg->smax_value,
2387 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2388 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2389 	reg->umax_value = min(reg->umax_value,
2390 			      reg->var_off.value | reg->var_off.mask);
2391 }
2392 
2393 static void __update_reg_bounds(struct bpf_reg_state *reg)
2394 {
2395 	__update_reg32_bounds(reg);
2396 	__update_reg64_bounds(reg);
2397 }
2398 
2399 /* Uses signed min/max values to inform unsigned, and vice-versa */
2400 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2401 {
2402 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
2403 	 * bits to improve our u32/s32 boundaries.
2404 	 *
2405 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
2406 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
2407 	 * [10, 20] range. But this property holds for any 64-bit range as
2408 	 * long as upper 32 bits in that entire range of values stay the same.
2409 	 *
2410 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
2411 	 * in decimal) has the same upper 32 bits throughout all the values in
2412 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
2413 	 * range.
2414 	 *
2415 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
2416 	 * following the rules outlined below about u64/s64 correspondence
2417 	 * (which equally applies to u32 vs s32 correspondence). In general it
2418 	 * depends on actual hexadecimal values of 32-bit range. They can form
2419 	 * only valid u32, or only valid s32 ranges in some cases.
2420 	 *
2421 	 * So we use all these insights to derive bounds for subregisters here.
2422 	 */
2423 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
2424 		/* u64 to u32 casting preserves validity of low 32 bits as
2425 		 * a range, if upper 32 bits are the same
2426 		 */
2427 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
2428 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
2429 
2430 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
2431 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2432 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2433 		}
2434 	}
2435 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2436 		/* low 32 bits should form a proper u32 range */
2437 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2438 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2439 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2440 		}
2441 		/* low 32 bits should form a proper s32 range */
2442 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2443 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2444 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2445 		}
2446 	}
2447 	/* Special case where upper bits form a small sequence of two
2448 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2449 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
2450 	 * going from negative numbers to positive numbers. E.g., let's say we
2451 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2452 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2453 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2454 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2455 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2456 	 * upper 32 bits. As a random example, s64 range
2457 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2458 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2459 	 */
2460 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2461 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2462 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2463 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2464 	}
2465 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2466 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2467 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2468 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2469 	}
2470 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2471 	 * try to learn from that
2472 	 */
2473 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2474 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2475 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2476 	}
2477 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2478 	 * are the same, so combine.  This works even in the negative case, e.g.
2479 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2480 	 */
2481 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2482 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2483 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2484 	}
2485 }
2486 
2487 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2488 {
2489 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2490 	 * try to learn from that. Let's do a bit of ASCII art to see when
2491 	 * this is happening. Let's take u64 range first:
2492 	 *
2493 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2494 	 * |-------------------------------|--------------------------------|
2495 	 *
2496 	 * Valid u64 range is formed when umin and umax are anywhere in the
2497 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2498 	 * straightforward. Let's see how s64 range maps onto the same range
2499 	 * of values, annotated below the line for comparison:
2500 	 *
2501 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2502 	 * |-------------------------------|--------------------------------|
2503 	 * 0                        S64_MAX S64_MIN                        -1
2504 	 *
2505 	 * So s64 values basically start in the middle and they are logically
2506 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2507 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2508 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2509 	 * more visually as mapped to sign-agnostic range of hex values.
2510 	 *
2511 	 *  u64 start                                               u64 end
2512 	 *  _______________________________________________________________
2513 	 * /                                                               \
2514 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2515 	 * |-------------------------------|--------------------------------|
2516 	 * 0                        S64_MAX S64_MIN                        -1
2517 	 *                                / \
2518 	 * >------------------------------   ------------------------------->
2519 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2520 	 *
2521 	 * What this means is that, in general, we can't always derive
2522 	 * something new about u64 from any random s64 range, and vice versa.
2523 	 *
2524 	 * But we can do that in two particular cases. One is when entire
2525 	 * u64/s64 range is *entirely* contained within left half of the above
2526 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2527 	 *
2528 	 * |-------------------------------|--------------------------------|
2529 	 *     ^                   ^            ^                 ^
2530 	 *     A                   B            C                 D
2531 	 *
2532 	 * [A, B] and [C, D] are contained entirely in their respective halves
2533 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2534 	 * will be non-negative both as u64 and s64 (and in fact it will be
2535 	 * identical ranges no matter the signedness). [C, D] treated as s64
2536 	 * will be a range of negative values, while in u64 it will be
2537 	 * non-negative range of values larger than 0x8000000000000000.
2538 	 *
2539 	 * Now, any other range here can't be represented in both u64 and s64
2540 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2541 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2542 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2543 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2544 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2545 	 * ranges as u64. Currently reg_state can't represent two segments per
2546 	 * numeric domain, so in such situations we can only derive maximal
2547 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2548 	 *
2549 	 * So we use these facts to derive umin/umax from smin/smax and vice
2550 	 * versa only if they stay within the same "half". This is equivalent
2551 	 * to checking sign bit: lower half will have sign bit as zero, upper
2552 	 * half have sign bit 1. Below in code we simplify this by just
2553 	 * casting umin/umax as smin/smax and checking if they form valid
2554 	 * range, and vice versa. Those are equivalent checks.
2555 	 */
2556 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2557 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2558 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2559 	}
2560 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2561 	 * are the same, so combine.  This works even in the negative case, e.g.
2562 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2563 	 */
2564 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2565 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2566 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2567 	} else {
2568 		/* If the s64 range crosses the sign boundary, then it's split
2569 		 * between the beginning and end of the U64 domain. In that
2570 		 * case, we can derive new bounds if the u64 range overlaps
2571 		 * with only one end of the s64 range.
2572 		 *
2573 		 * In the following example, the u64 range overlaps only with
2574 		 * positive portion of the s64 range.
2575 		 *
2576 		 * 0                                                   U64_MAX
2577 		 * |  [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx]              |
2578 		 * |----------------------------|----------------------------|
2579 		 * |xxxxx s64 range xxxxxxxxx]                       [xxxxxxx|
2580 		 * 0                     S64_MAX S64_MIN                    -1
2581 		 *
2582 		 * We can thus derive the following new s64 and u64 ranges.
2583 		 *
2584 		 * 0                                                   U64_MAX
2585 		 * |  [xxxxxx u64 range xxxxx]                               |
2586 		 * |----------------------------|----------------------------|
2587 		 * |  [xxxxxx s64 range xxxxx]                               |
2588 		 * 0                     S64_MAX S64_MIN                    -1
2589 		 *
2590 		 * If they overlap in two places, we can't derive anything
2591 		 * because reg_state can't represent two ranges per numeric
2592 		 * domain.
2593 		 *
2594 		 * 0                                                   U64_MAX
2595 		 * |  [xxxxxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxxxxx]        |
2596 		 * |----------------------------|----------------------------|
2597 		 * |xxxxx s64 range xxxxxxxxx]                    [xxxxxxxxxx|
2598 		 * 0                     S64_MAX S64_MIN                    -1
2599 		 *
2600 		 * The first condition below corresponds to the first diagram
2601 		 * above.
2602 		 */
2603 		if (reg->umax_value < (u64)reg->smin_value) {
2604 			reg->smin_value = (s64)reg->umin_value;
2605 			reg->umax_value = min_t(u64, reg->umax_value, reg->smax_value);
2606 		} else if ((u64)reg->smax_value < reg->umin_value) {
2607 			/* This second condition considers the case where the u64 range
2608 			 * overlaps with the negative portion of the s64 range:
2609 			 *
2610 			 * 0                                                   U64_MAX
2611 			 * |              [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx]  |
2612 			 * |----------------------------|----------------------------|
2613 			 * |xxxxxxxxx]                       [xxxxxxxxxxxx s64 range |
2614 			 * 0                     S64_MAX S64_MIN                    -1
2615 			 */
2616 			reg->smax_value = (s64)reg->umax_value;
2617 			reg->umin_value = max_t(u64, reg->umin_value, reg->smin_value);
2618 		}
2619 	}
2620 }
2621 
2622 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2623 {
2624 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2625 	 * values on both sides of 64-bit range in hope to have tighter range.
2626 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2627 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2628 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2629 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2630 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2631 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2632 	 * We just need to make sure that derived bounds we are intersecting
2633 	 * with are well-formed ranges in respective s64 or u64 domain, just
2634 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2635 	 */
2636 	__u64 new_umin, new_umax;
2637 	__s64 new_smin, new_smax;
2638 
2639 	/* u32 -> u64 tightening, it's always well-formed */
2640 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2641 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2642 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2643 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2644 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2645 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2646 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2647 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2648 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2649 
2650 	/* Here we would like to handle a special case after sign extending load,
2651 	 * when upper bits for a 64-bit range are all 1s or all 0s.
2652 	 *
2653 	 * Upper bits are all 1s when register is in a range:
2654 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff]
2655 	 * Upper bits are all 0s when register is in a range:
2656 	 *   [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff]
2657 	 * Together this forms are continuous range:
2658 	 *   [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff]
2659 	 *
2660 	 * Now, suppose that register range is in fact tighter:
2661 	 *   [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R)
2662 	 * Also suppose that it's 32-bit range is positive,
2663 	 * meaning that lower 32-bits of the full 64-bit register
2664 	 * are in the range:
2665 	 *   [0x0000_0000, 0x7fff_ffff] (W)
2666 	 *
2667 	 * If this happens, then any value in a range:
2668 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff]
2669 	 * is smaller than a lowest bound of the range (R):
2670 	 *   0xffff_ffff_8000_0000
2671 	 * which means that upper bits of the full 64-bit register
2672 	 * can't be all 1s, when lower bits are in range (W).
2673 	 *
2674 	 * Note that:
2675 	 *  - 0xffff_ffff_8000_0000 == (s64)S32_MIN
2676 	 *  - 0x0000_0000_7fff_ffff == (s64)S32_MAX
2677 	 * These relations are used in the conditions below.
2678 	 */
2679 	if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) {
2680 		reg->smin_value = reg->s32_min_value;
2681 		reg->smax_value = reg->s32_max_value;
2682 		reg->umin_value = reg->s32_min_value;
2683 		reg->umax_value = reg->s32_max_value;
2684 		reg->var_off = tnum_intersect(reg->var_off,
2685 					      tnum_range(reg->smin_value, reg->smax_value));
2686 	}
2687 }
2688 
2689 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2690 {
2691 	__reg32_deduce_bounds(reg);
2692 	__reg64_deduce_bounds(reg);
2693 	__reg_deduce_mixed_bounds(reg);
2694 }
2695 
2696 /* Attempts to improve var_off based on unsigned min/max information */
2697 static void __reg_bound_offset(struct bpf_reg_state *reg)
2698 {
2699 	struct tnum var64_off = tnum_intersect(reg->var_off,
2700 					       tnum_range(reg->umin_value,
2701 							  reg->umax_value));
2702 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2703 					       tnum_range(reg->u32_min_value,
2704 							  reg->u32_max_value));
2705 
2706 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2707 }
2708 
2709 static void reg_bounds_sync(struct bpf_reg_state *reg)
2710 {
2711 	/* We might have learned new bounds from the var_off. */
2712 	__update_reg_bounds(reg);
2713 	/* We might have learned something about the sign bit. */
2714 	__reg_deduce_bounds(reg);
2715 	__reg_deduce_bounds(reg);
2716 	__reg_deduce_bounds(reg);
2717 	/* We might have learned some bits from the bounds. */
2718 	__reg_bound_offset(reg);
2719 	/* Intersecting with the old var_off might have improved our bounds
2720 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2721 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2722 	 */
2723 	__update_reg_bounds(reg);
2724 }
2725 
2726 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2727 				   struct bpf_reg_state *reg, const char *ctx)
2728 {
2729 	const char *msg;
2730 
2731 	if (reg->umin_value > reg->umax_value ||
2732 	    reg->smin_value > reg->smax_value ||
2733 	    reg->u32_min_value > reg->u32_max_value ||
2734 	    reg->s32_min_value > reg->s32_max_value) {
2735 		    msg = "range bounds violation";
2736 		    goto out;
2737 	}
2738 
2739 	if (tnum_is_const(reg->var_off)) {
2740 		u64 uval = reg->var_off.value;
2741 		s64 sval = (s64)uval;
2742 
2743 		if (reg->umin_value != uval || reg->umax_value != uval ||
2744 		    reg->smin_value != sval || reg->smax_value != sval) {
2745 			msg = "const tnum out of sync with range bounds";
2746 			goto out;
2747 		}
2748 	}
2749 
2750 	if (tnum_subreg_is_const(reg->var_off)) {
2751 		u32 uval32 = tnum_subreg(reg->var_off).value;
2752 		s32 sval32 = (s32)uval32;
2753 
2754 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2755 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2756 			msg = "const subreg tnum out of sync with range bounds";
2757 			goto out;
2758 		}
2759 	}
2760 
2761 	return 0;
2762 out:
2763 	verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2764 		     "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)",
2765 		     ctx, msg, reg->umin_value, reg->umax_value,
2766 		     reg->smin_value, reg->smax_value,
2767 		     reg->u32_min_value, reg->u32_max_value,
2768 		     reg->s32_min_value, reg->s32_max_value,
2769 		     reg->var_off.value, reg->var_off.mask);
2770 	if (env->test_reg_invariants)
2771 		return -EFAULT;
2772 	__mark_reg_unbounded(reg);
2773 	return 0;
2774 }
2775 
2776 static bool __reg32_bound_s64(s32 a)
2777 {
2778 	return a >= 0 && a <= S32_MAX;
2779 }
2780 
2781 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2782 {
2783 	reg->umin_value = reg->u32_min_value;
2784 	reg->umax_value = reg->u32_max_value;
2785 
2786 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2787 	 * be positive otherwise set to worse case bounds and refine later
2788 	 * from tnum.
2789 	 */
2790 	if (__reg32_bound_s64(reg->s32_min_value) &&
2791 	    __reg32_bound_s64(reg->s32_max_value)) {
2792 		reg->smin_value = reg->s32_min_value;
2793 		reg->smax_value = reg->s32_max_value;
2794 	} else {
2795 		reg->smin_value = 0;
2796 		reg->smax_value = U32_MAX;
2797 	}
2798 }
2799 
2800 /* Mark a register as having a completely unknown (scalar) value. */
2801 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2802 {
2803 	/*
2804 	 * Clear type, off, and union(map_ptr, range) and
2805 	 * padding between 'type' and union
2806 	 */
2807 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2808 	reg->type = SCALAR_VALUE;
2809 	reg->id = 0;
2810 	reg->ref_obj_id = 0;
2811 	reg->var_off = tnum_unknown;
2812 	reg->frameno = 0;
2813 	reg->precise = false;
2814 	__mark_reg_unbounded(reg);
2815 }
2816 
2817 /* Mark a register as having a completely unknown (scalar) value,
2818  * initialize .precise as true when not bpf capable.
2819  */
2820 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2821 			       struct bpf_reg_state *reg)
2822 {
2823 	__mark_reg_unknown_imprecise(reg);
2824 	reg->precise = !env->bpf_capable;
2825 }
2826 
2827 static void mark_reg_unknown(struct bpf_verifier_env *env,
2828 			     struct bpf_reg_state *regs, u32 regno)
2829 {
2830 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2831 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2832 		/* Something bad happened, let's kill all regs except FP */
2833 		for (regno = 0; regno < BPF_REG_FP; regno++)
2834 			__mark_reg_not_init(env, regs + regno);
2835 		return;
2836 	}
2837 	__mark_reg_unknown(env, regs + regno);
2838 }
2839 
2840 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2841 				struct bpf_reg_state *regs,
2842 				u32 regno,
2843 				s32 s32_min,
2844 				s32 s32_max)
2845 {
2846 	struct bpf_reg_state *reg = regs + regno;
2847 
2848 	reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min);
2849 	reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max);
2850 
2851 	reg->smin_value = max_t(s64, reg->smin_value, s32_min);
2852 	reg->smax_value = min_t(s64, reg->smax_value, s32_max);
2853 
2854 	reg_bounds_sync(reg);
2855 
2856 	return reg_bounds_sanity_check(env, reg, "s32_range");
2857 }
2858 
2859 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2860 				struct bpf_reg_state *reg)
2861 {
2862 	__mark_reg_unknown(env, reg);
2863 	reg->type = NOT_INIT;
2864 }
2865 
2866 static void mark_reg_not_init(struct bpf_verifier_env *env,
2867 			      struct bpf_reg_state *regs, u32 regno)
2868 {
2869 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2870 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2871 		/* Something bad happened, let's kill all regs except FP */
2872 		for (regno = 0; regno < BPF_REG_FP; regno++)
2873 			__mark_reg_not_init(env, regs + regno);
2874 		return;
2875 	}
2876 	__mark_reg_not_init(env, regs + regno);
2877 }
2878 
2879 static int mark_btf_ld_reg(struct bpf_verifier_env *env,
2880 			   struct bpf_reg_state *regs, u32 regno,
2881 			   enum bpf_reg_type reg_type,
2882 			   struct btf *btf, u32 btf_id,
2883 			   enum bpf_type_flag flag)
2884 {
2885 	switch (reg_type) {
2886 	case SCALAR_VALUE:
2887 		mark_reg_unknown(env, regs, regno);
2888 		return 0;
2889 	case PTR_TO_BTF_ID:
2890 		mark_reg_known_zero(env, regs, regno);
2891 		regs[regno].type = PTR_TO_BTF_ID | flag;
2892 		regs[regno].btf = btf;
2893 		regs[regno].btf_id = btf_id;
2894 		if (type_may_be_null(flag))
2895 			regs[regno].id = ++env->id_gen;
2896 		return 0;
2897 	case PTR_TO_MEM:
2898 		mark_reg_known_zero(env, regs, regno);
2899 		regs[regno].type = PTR_TO_MEM | flag;
2900 		regs[regno].mem_size = 0;
2901 		return 0;
2902 	default:
2903 		verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__);
2904 		return -EFAULT;
2905 	}
2906 }
2907 
2908 #define DEF_NOT_SUBREG	(0)
2909 static void init_reg_state(struct bpf_verifier_env *env,
2910 			   struct bpf_func_state *state)
2911 {
2912 	struct bpf_reg_state *regs = state->regs;
2913 	int i;
2914 
2915 	for (i = 0; i < MAX_BPF_REG; i++) {
2916 		mark_reg_not_init(env, regs, i);
2917 		regs[i].subreg_def = DEF_NOT_SUBREG;
2918 	}
2919 
2920 	/* frame pointer */
2921 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2922 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2923 	regs[BPF_REG_FP].frameno = state->frameno;
2924 }
2925 
2926 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2927 {
2928 	return (struct bpf_retval_range){ minval, maxval };
2929 }
2930 
2931 #define BPF_MAIN_FUNC (-1)
2932 static void init_func_state(struct bpf_verifier_env *env,
2933 			    struct bpf_func_state *state,
2934 			    int callsite, int frameno, int subprogno)
2935 {
2936 	state->callsite = callsite;
2937 	state->frameno = frameno;
2938 	state->subprogno = subprogno;
2939 	state->callback_ret_range = retval_range(0, 0);
2940 	init_reg_state(env, state);
2941 	mark_verifier_state_scratched(env);
2942 }
2943 
2944 /* Similar to push_stack(), but for async callbacks */
2945 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2946 						int insn_idx, int prev_insn_idx,
2947 						int subprog, bool is_sleepable)
2948 {
2949 	struct bpf_verifier_stack_elem *elem;
2950 	struct bpf_func_state *frame;
2951 
2952 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
2953 	if (!elem)
2954 		return ERR_PTR(-ENOMEM);
2955 
2956 	elem->insn_idx = insn_idx;
2957 	elem->prev_insn_idx = prev_insn_idx;
2958 	elem->next = env->head;
2959 	elem->log_pos = env->log.end_pos;
2960 	env->head = elem;
2961 	env->stack_size++;
2962 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2963 		verbose(env,
2964 			"The sequence of %d jumps is too complex for async cb.\n",
2965 			env->stack_size);
2966 		return ERR_PTR(-E2BIG);
2967 	}
2968 	/* Unlike push_stack() do not copy_verifier_state().
2969 	 * The caller state doesn't matter.
2970 	 * This is async callback. It starts in a fresh stack.
2971 	 * Initialize it similar to do_check_common().
2972 	 */
2973 	elem->st.branches = 1;
2974 	elem->st.in_sleepable = is_sleepable;
2975 	frame = kzalloc(sizeof(*frame), GFP_KERNEL_ACCOUNT);
2976 	if (!frame)
2977 		return ERR_PTR(-ENOMEM);
2978 	init_func_state(env, frame,
2979 			BPF_MAIN_FUNC /* callsite */,
2980 			0 /* frameno within this callchain */,
2981 			subprog /* subprog number within this prog */);
2982 	elem->st.frame[0] = frame;
2983 	return &elem->st;
2984 }
2985 
2986 
2987 enum reg_arg_type {
2988 	SRC_OP,		/* register is used as source operand */
2989 	DST_OP,		/* register is used as destination operand */
2990 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2991 };
2992 
2993 static int cmp_subprogs(const void *a, const void *b)
2994 {
2995 	return ((struct bpf_subprog_info *)a)->start -
2996 	       ((struct bpf_subprog_info *)b)->start;
2997 }
2998 
2999 /* Find subprogram that contains instruction at 'off' */
3000 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off)
3001 {
3002 	struct bpf_subprog_info *vals = env->subprog_info;
3003 	int l, r, m;
3004 
3005 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
3006 		return NULL;
3007 
3008 	l = 0;
3009 	r = env->subprog_cnt - 1;
3010 	while (l < r) {
3011 		m = l + (r - l + 1) / 2;
3012 		if (vals[m].start <= off)
3013 			l = m;
3014 		else
3015 			r = m - 1;
3016 	}
3017 	return &vals[l];
3018 }
3019 
3020 /* Find subprogram that starts exactly at 'off' */
3021 static int find_subprog(struct bpf_verifier_env *env, int off)
3022 {
3023 	struct bpf_subprog_info *p;
3024 
3025 	p = bpf_find_containing_subprog(env, off);
3026 	if (!p || p->start != off)
3027 		return -ENOENT;
3028 	return p - env->subprog_info;
3029 }
3030 
3031 static int add_subprog(struct bpf_verifier_env *env, int off)
3032 {
3033 	int insn_cnt = env->prog->len;
3034 	int ret;
3035 
3036 	if (off >= insn_cnt || off < 0) {
3037 		verbose(env, "call to invalid destination\n");
3038 		return -EINVAL;
3039 	}
3040 	ret = find_subprog(env, off);
3041 	if (ret >= 0)
3042 		return ret;
3043 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
3044 		verbose(env, "too many subprograms\n");
3045 		return -E2BIG;
3046 	}
3047 	/* determine subprog starts. The end is one before the next starts */
3048 	env->subprog_info[env->subprog_cnt++].start = off;
3049 	sort(env->subprog_info, env->subprog_cnt,
3050 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
3051 	return env->subprog_cnt - 1;
3052 }
3053 
3054 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
3055 {
3056 	struct bpf_prog_aux *aux = env->prog->aux;
3057 	struct btf *btf = aux->btf;
3058 	const struct btf_type *t;
3059 	u32 main_btf_id, id;
3060 	const char *name;
3061 	int ret, i;
3062 
3063 	/* Non-zero func_info_cnt implies valid btf */
3064 	if (!aux->func_info_cnt)
3065 		return 0;
3066 	main_btf_id = aux->func_info[0].type_id;
3067 
3068 	t = btf_type_by_id(btf, main_btf_id);
3069 	if (!t) {
3070 		verbose(env, "invalid btf id for main subprog in func_info\n");
3071 		return -EINVAL;
3072 	}
3073 
3074 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
3075 	if (IS_ERR(name)) {
3076 		ret = PTR_ERR(name);
3077 		/* If there is no tag present, there is no exception callback */
3078 		if (ret == -ENOENT)
3079 			ret = 0;
3080 		else if (ret == -EEXIST)
3081 			verbose(env, "multiple exception callback tags for main subprog\n");
3082 		return ret;
3083 	}
3084 
3085 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
3086 	if (ret < 0) {
3087 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
3088 		return ret;
3089 	}
3090 	id = ret;
3091 	t = btf_type_by_id(btf, id);
3092 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
3093 		verbose(env, "exception callback '%s' must have global linkage\n", name);
3094 		return -EINVAL;
3095 	}
3096 	ret = 0;
3097 	for (i = 0; i < aux->func_info_cnt; i++) {
3098 		if (aux->func_info[i].type_id != id)
3099 			continue;
3100 		ret = aux->func_info[i].insn_off;
3101 		/* Further func_info and subprog checks will also happen
3102 		 * later, so assume this is the right insn_off for now.
3103 		 */
3104 		if (!ret) {
3105 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
3106 			ret = -EINVAL;
3107 		}
3108 	}
3109 	if (!ret) {
3110 		verbose(env, "exception callback type id not found in func_info\n");
3111 		ret = -EINVAL;
3112 	}
3113 	return ret;
3114 }
3115 
3116 #define MAX_KFUNC_DESCS 256
3117 #define MAX_KFUNC_BTFS	256
3118 
3119 struct bpf_kfunc_desc {
3120 	struct btf_func_model func_model;
3121 	u32 func_id;
3122 	s32 imm;
3123 	u16 offset;
3124 	unsigned long addr;
3125 };
3126 
3127 struct bpf_kfunc_btf {
3128 	struct btf *btf;
3129 	struct module *module;
3130 	u16 offset;
3131 };
3132 
3133 struct bpf_kfunc_desc_tab {
3134 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
3135 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
3136 	 * available, therefore at the end of verification do_misc_fixups()
3137 	 * sorts this by imm and offset.
3138 	 */
3139 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
3140 	u32 nr_descs;
3141 };
3142 
3143 struct bpf_kfunc_btf_tab {
3144 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
3145 	u32 nr_descs;
3146 };
3147 
3148 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc,
3149 			    int insn_idx);
3150 
3151 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
3152 {
3153 	const struct bpf_kfunc_desc *d0 = a;
3154 	const struct bpf_kfunc_desc *d1 = b;
3155 
3156 	/* func_id is not greater than BTF_MAX_TYPE */
3157 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
3158 }
3159 
3160 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
3161 {
3162 	const struct bpf_kfunc_btf *d0 = a;
3163 	const struct bpf_kfunc_btf *d1 = b;
3164 
3165 	return d0->offset - d1->offset;
3166 }
3167 
3168 static struct bpf_kfunc_desc *
3169 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
3170 {
3171 	struct bpf_kfunc_desc desc = {
3172 		.func_id = func_id,
3173 		.offset = offset,
3174 	};
3175 	struct bpf_kfunc_desc_tab *tab;
3176 
3177 	tab = prog->aux->kfunc_tab;
3178 	return bsearch(&desc, tab->descs, tab->nr_descs,
3179 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
3180 }
3181 
3182 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
3183 		       u16 btf_fd_idx, u8 **func_addr)
3184 {
3185 	const struct bpf_kfunc_desc *desc;
3186 
3187 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
3188 	if (!desc)
3189 		return -EFAULT;
3190 
3191 	*func_addr = (u8 *)desc->addr;
3192 	return 0;
3193 }
3194 
3195 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
3196 					 s16 offset)
3197 {
3198 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
3199 	struct bpf_kfunc_btf_tab *tab;
3200 	struct bpf_kfunc_btf *b;
3201 	struct module *mod;
3202 	struct btf *btf;
3203 	int btf_fd;
3204 
3205 	tab = env->prog->aux->kfunc_btf_tab;
3206 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
3207 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
3208 	if (!b) {
3209 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
3210 			verbose(env, "too many different module BTFs\n");
3211 			return ERR_PTR(-E2BIG);
3212 		}
3213 
3214 		if (bpfptr_is_null(env->fd_array)) {
3215 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
3216 			return ERR_PTR(-EPROTO);
3217 		}
3218 
3219 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
3220 					    offset * sizeof(btf_fd),
3221 					    sizeof(btf_fd)))
3222 			return ERR_PTR(-EFAULT);
3223 
3224 		btf = btf_get_by_fd(btf_fd);
3225 		if (IS_ERR(btf)) {
3226 			verbose(env, "invalid module BTF fd specified\n");
3227 			return btf;
3228 		}
3229 
3230 		if (!btf_is_module(btf)) {
3231 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
3232 			btf_put(btf);
3233 			return ERR_PTR(-EINVAL);
3234 		}
3235 
3236 		mod = btf_try_get_module(btf);
3237 		if (!mod) {
3238 			btf_put(btf);
3239 			return ERR_PTR(-ENXIO);
3240 		}
3241 
3242 		b = &tab->descs[tab->nr_descs++];
3243 		b->btf = btf;
3244 		b->module = mod;
3245 		b->offset = offset;
3246 
3247 		/* sort() reorders entries by value, so b may no longer point
3248 		 * to the right entry after this
3249 		 */
3250 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3251 		     kfunc_btf_cmp_by_off, NULL);
3252 	} else {
3253 		btf = b->btf;
3254 	}
3255 
3256 	return btf;
3257 }
3258 
3259 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
3260 {
3261 	if (!tab)
3262 		return;
3263 
3264 	while (tab->nr_descs--) {
3265 		module_put(tab->descs[tab->nr_descs].module);
3266 		btf_put(tab->descs[tab->nr_descs].btf);
3267 	}
3268 	kfree(tab);
3269 }
3270 
3271 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
3272 {
3273 	if (offset) {
3274 		if (offset < 0) {
3275 			/* In the future, this can be allowed to increase limit
3276 			 * of fd index into fd_array, interpreted as u16.
3277 			 */
3278 			verbose(env, "negative offset disallowed for kernel module function call\n");
3279 			return ERR_PTR(-EINVAL);
3280 		}
3281 
3282 		return __find_kfunc_desc_btf(env, offset);
3283 	}
3284 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
3285 }
3286 
3287 #define KF_IMPL_SUFFIX "_impl"
3288 
3289 static const struct btf_type *find_kfunc_impl_proto(struct bpf_verifier_env *env,
3290 						    struct btf *btf,
3291 						    const char *func_name)
3292 {
3293 	char *buf = env->tmp_str_buf;
3294 	const struct btf_type *func;
3295 	s32 impl_id;
3296 	int len;
3297 
3298 	len = snprintf(buf, TMP_STR_BUF_LEN, "%s%s", func_name, KF_IMPL_SUFFIX);
3299 	if (len < 0 || len >= TMP_STR_BUF_LEN) {
3300 		verbose(env, "function name %s%s is too long\n", func_name, KF_IMPL_SUFFIX);
3301 		return NULL;
3302 	}
3303 
3304 	impl_id = btf_find_by_name_kind(btf, buf, BTF_KIND_FUNC);
3305 	if (impl_id <= 0) {
3306 		verbose(env, "cannot find function %s in BTF\n", buf);
3307 		return NULL;
3308 	}
3309 
3310 	func = btf_type_by_id(btf, impl_id);
3311 
3312 	return btf_type_by_id(btf, func->type);
3313 }
3314 
3315 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
3316 			    s32 func_id,
3317 			    s16 offset,
3318 			    struct bpf_kfunc_meta *kfunc)
3319 {
3320 	const struct btf_type *func, *func_proto;
3321 	const char *func_name;
3322 	u32 *kfunc_flags;
3323 	struct btf *btf;
3324 
3325 	if (func_id <= 0) {
3326 		verbose(env, "invalid kernel function btf_id %d\n", func_id);
3327 		return -EINVAL;
3328 	}
3329 
3330 	btf = find_kfunc_desc_btf(env, offset);
3331 	if (IS_ERR(btf)) {
3332 		verbose(env, "failed to find BTF for kernel function\n");
3333 		return PTR_ERR(btf);
3334 	}
3335 
3336 	/*
3337 	 * Note that kfunc_flags may be NULL at this point, which
3338 	 * means that we couldn't find func_id in any relevant
3339 	 * kfunc_id_set. This most likely indicates an invalid kfunc
3340 	 * call.  However we don't fail with an error here,
3341 	 * and let the caller decide what to do with NULL kfunc->flags.
3342 	 */
3343 	kfunc_flags = btf_kfunc_flags(btf, func_id, env->prog);
3344 
3345 	func = btf_type_by_id(btf, func_id);
3346 	if (!func || !btf_type_is_func(func)) {
3347 		verbose(env, "kernel btf_id %d is not a function\n", func_id);
3348 		return -EINVAL;
3349 	}
3350 
3351 	func_name = btf_name_by_offset(btf, func->name_off);
3352 
3353 	/*
3354 	 * An actual prototype of a kfunc with KF_IMPLICIT_ARGS flag
3355 	 * can be found through the counterpart _impl kfunc.
3356 	 */
3357 	if (kfunc_flags && (*kfunc_flags & KF_IMPLICIT_ARGS))
3358 		func_proto = find_kfunc_impl_proto(env, btf, func_name);
3359 	else
3360 		func_proto = btf_type_by_id(btf, func->type);
3361 
3362 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
3363 		verbose(env, "kernel function btf_id %d does not have a valid func_proto\n",
3364 			func_id);
3365 		return -EINVAL;
3366 	}
3367 
3368 	memset(kfunc, 0, sizeof(*kfunc));
3369 	kfunc->btf = btf;
3370 	kfunc->id = func_id;
3371 	kfunc->name = func_name;
3372 	kfunc->proto = func_proto;
3373 	kfunc->flags = kfunc_flags;
3374 
3375 	return 0;
3376 }
3377 
3378 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
3379 {
3380 	struct bpf_kfunc_btf_tab *btf_tab;
3381 	struct btf_func_model func_model;
3382 	struct bpf_kfunc_desc_tab *tab;
3383 	struct bpf_prog_aux *prog_aux;
3384 	struct bpf_kfunc_meta kfunc;
3385 	struct bpf_kfunc_desc *desc;
3386 	unsigned long addr;
3387 	int err;
3388 
3389 	prog_aux = env->prog->aux;
3390 	tab = prog_aux->kfunc_tab;
3391 	btf_tab = prog_aux->kfunc_btf_tab;
3392 	if (!tab) {
3393 		if (!btf_vmlinux) {
3394 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
3395 			return -ENOTSUPP;
3396 		}
3397 
3398 		if (!env->prog->jit_requested) {
3399 			verbose(env, "JIT is required for calling kernel function\n");
3400 			return -ENOTSUPP;
3401 		}
3402 
3403 		if (!bpf_jit_supports_kfunc_call()) {
3404 			verbose(env, "JIT does not support calling kernel function\n");
3405 			return -ENOTSUPP;
3406 		}
3407 
3408 		if (!env->prog->gpl_compatible) {
3409 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
3410 			return -EINVAL;
3411 		}
3412 
3413 		tab = kzalloc(sizeof(*tab), GFP_KERNEL_ACCOUNT);
3414 		if (!tab)
3415 			return -ENOMEM;
3416 		prog_aux->kfunc_tab = tab;
3417 	}
3418 
3419 	/* func_id == 0 is always invalid, but instead of returning an error, be
3420 	 * conservative and wait until the code elimination pass before returning
3421 	 * error, so that invalid calls that get pruned out can be in BPF programs
3422 	 * loaded from userspace.  It is also required that offset be untouched
3423 	 * for such calls.
3424 	 */
3425 	if (!func_id && !offset)
3426 		return 0;
3427 
3428 	if (!btf_tab && offset) {
3429 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL_ACCOUNT);
3430 		if (!btf_tab)
3431 			return -ENOMEM;
3432 		prog_aux->kfunc_btf_tab = btf_tab;
3433 	}
3434 
3435 	if (find_kfunc_desc(env->prog, func_id, offset))
3436 		return 0;
3437 
3438 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
3439 		verbose(env, "too many different kernel function calls\n");
3440 		return -E2BIG;
3441 	}
3442 
3443 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
3444 	if (err)
3445 		return err;
3446 
3447 	addr = kallsyms_lookup_name(kfunc.name);
3448 	if (!addr) {
3449 		verbose(env, "cannot find address for kernel function %s\n", kfunc.name);
3450 		return -EINVAL;
3451 	}
3452 
3453 	if (bpf_dev_bound_kfunc_id(func_id)) {
3454 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3455 		if (err)
3456 			return err;
3457 	}
3458 
3459 	err = btf_distill_func_proto(&env->log, kfunc.btf, kfunc.proto, kfunc.name, &func_model);
3460 	if (err)
3461 		return err;
3462 
3463 	desc = &tab->descs[tab->nr_descs++];
3464 	desc->func_id = func_id;
3465 	desc->offset = offset;
3466 	desc->addr = addr;
3467 	desc->func_model = func_model;
3468 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3469 	     kfunc_desc_cmp_by_id_off, NULL);
3470 	return 0;
3471 }
3472 
3473 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
3474 {
3475 	const struct bpf_kfunc_desc *d0 = a;
3476 	const struct bpf_kfunc_desc *d1 = b;
3477 
3478 	if (d0->imm != d1->imm)
3479 		return d0->imm < d1->imm ? -1 : 1;
3480 	if (d0->offset != d1->offset)
3481 		return d0->offset < d1->offset ? -1 : 1;
3482 	return 0;
3483 }
3484 
3485 static int set_kfunc_desc_imm(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc)
3486 {
3487 	unsigned long call_imm;
3488 
3489 	if (bpf_jit_supports_far_kfunc_call()) {
3490 		call_imm = desc->func_id;
3491 	} else {
3492 		call_imm = BPF_CALL_IMM(desc->addr);
3493 		/* Check whether the relative offset overflows desc->imm */
3494 		if ((unsigned long)(s32)call_imm != call_imm) {
3495 			verbose(env, "address of kernel func_id %u is out of range\n",
3496 				desc->func_id);
3497 			return -EINVAL;
3498 		}
3499 	}
3500 	desc->imm = call_imm;
3501 	return 0;
3502 }
3503 
3504 static int sort_kfunc_descs_by_imm_off(struct bpf_verifier_env *env)
3505 {
3506 	struct bpf_kfunc_desc_tab *tab;
3507 	int i, err;
3508 
3509 	tab = env->prog->aux->kfunc_tab;
3510 	if (!tab)
3511 		return 0;
3512 
3513 	for (i = 0; i < tab->nr_descs; i++) {
3514 		err = set_kfunc_desc_imm(env, &tab->descs[i]);
3515 		if (err)
3516 			return err;
3517 	}
3518 
3519 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3520 	     kfunc_desc_cmp_by_imm_off, NULL);
3521 	return 0;
3522 }
3523 
3524 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
3525 {
3526 	return !!prog->aux->kfunc_tab;
3527 }
3528 
3529 const struct btf_func_model *
3530 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3531 			 const struct bpf_insn *insn)
3532 {
3533 	const struct bpf_kfunc_desc desc = {
3534 		.imm = insn->imm,
3535 		.offset = insn->off,
3536 	};
3537 	const struct bpf_kfunc_desc *res;
3538 	struct bpf_kfunc_desc_tab *tab;
3539 
3540 	tab = prog->aux->kfunc_tab;
3541 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3542 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3543 
3544 	return res ? &res->func_model : NULL;
3545 }
3546 
3547 static int add_kfunc_in_insns(struct bpf_verifier_env *env,
3548 			      struct bpf_insn *insn, int cnt)
3549 {
3550 	int i, ret;
3551 
3552 	for (i = 0; i < cnt; i++, insn++) {
3553 		if (bpf_pseudo_kfunc_call(insn)) {
3554 			ret = add_kfunc_call(env, insn->imm, insn->off);
3555 			if (ret < 0)
3556 				return ret;
3557 		}
3558 	}
3559 	return 0;
3560 }
3561 
3562 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3563 {
3564 	struct bpf_subprog_info *subprog = env->subprog_info;
3565 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3566 	struct bpf_insn *insn = env->prog->insnsi;
3567 
3568 	/* Add entry function. */
3569 	ret = add_subprog(env, 0);
3570 	if (ret)
3571 		return ret;
3572 
3573 	for (i = 0; i < insn_cnt; i++, insn++) {
3574 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3575 		    !bpf_pseudo_kfunc_call(insn))
3576 			continue;
3577 
3578 		if (!env->bpf_capable) {
3579 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3580 			return -EPERM;
3581 		}
3582 
3583 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3584 			ret = add_subprog(env, i + insn->imm + 1);
3585 		else
3586 			ret = add_kfunc_call(env, insn->imm, insn->off);
3587 
3588 		if (ret < 0)
3589 			return ret;
3590 	}
3591 
3592 	ret = bpf_find_exception_callback_insn_off(env);
3593 	if (ret < 0)
3594 		return ret;
3595 	ex_cb_insn = ret;
3596 
3597 	/* If ex_cb_insn > 0, this means that the main program has a subprog
3598 	 * marked using BTF decl tag to serve as the exception callback.
3599 	 */
3600 	if (ex_cb_insn) {
3601 		ret = add_subprog(env, ex_cb_insn);
3602 		if (ret < 0)
3603 			return ret;
3604 		for (i = 1; i < env->subprog_cnt; i++) {
3605 			if (env->subprog_info[i].start != ex_cb_insn)
3606 				continue;
3607 			env->exception_callback_subprog = i;
3608 			mark_subprog_exc_cb(env, i);
3609 			break;
3610 		}
3611 	}
3612 
3613 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3614 	 * logic. 'subprog_cnt' should not be increased.
3615 	 */
3616 	subprog[env->subprog_cnt].start = insn_cnt;
3617 
3618 	if (env->log.level & BPF_LOG_LEVEL2)
3619 		for (i = 0; i < env->subprog_cnt; i++)
3620 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3621 
3622 	return 0;
3623 }
3624 
3625 static int check_subprogs(struct bpf_verifier_env *env)
3626 {
3627 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3628 	struct bpf_subprog_info *subprog = env->subprog_info;
3629 	struct bpf_insn *insn = env->prog->insnsi;
3630 	int insn_cnt = env->prog->len;
3631 
3632 	/* now check that all jumps are within the same subprog */
3633 	subprog_start = subprog[cur_subprog].start;
3634 	subprog_end = subprog[cur_subprog + 1].start;
3635 	for (i = 0; i < insn_cnt; i++) {
3636 		u8 code = insn[i].code;
3637 
3638 		if (code == (BPF_JMP | BPF_CALL) &&
3639 		    insn[i].src_reg == 0 &&
3640 		    insn[i].imm == BPF_FUNC_tail_call) {
3641 			subprog[cur_subprog].has_tail_call = true;
3642 			subprog[cur_subprog].tail_call_reachable = true;
3643 		}
3644 		if (BPF_CLASS(code) == BPF_LD &&
3645 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3646 			subprog[cur_subprog].has_ld_abs = true;
3647 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3648 			goto next;
3649 		if (BPF_OP(code) == BPF_CALL)
3650 			goto next;
3651 		if (BPF_OP(code) == BPF_EXIT) {
3652 			subprog[cur_subprog].exit_idx = i;
3653 			goto next;
3654 		}
3655 		off = i + bpf_jmp_offset(&insn[i]) + 1;
3656 		if (off < subprog_start || off >= subprog_end) {
3657 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3658 			return -EINVAL;
3659 		}
3660 next:
3661 		if (i == subprog_end - 1) {
3662 			/* to avoid fall-through from one subprog into another
3663 			 * the last insn of the subprog should be either exit
3664 			 * or unconditional jump back or bpf_throw call
3665 			 */
3666 			if (code != (BPF_JMP | BPF_EXIT) &&
3667 			    code != (BPF_JMP32 | BPF_JA) &&
3668 			    code != (BPF_JMP | BPF_JA)) {
3669 				verbose(env, "last insn is not an exit or jmp\n");
3670 				return -EINVAL;
3671 			}
3672 			subprog_start = subprog_end;
3673 			cur_subprog++;
3674 			if (cur_subprog < env->subprog_cnt)
3675 				subprog_end = subprog[cur_subprog + 1].start;
3676 		}
3677 	}
3678 	return 0;
3679 }
3680 
3681 static int mark_stack_slot_obj_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3682 				    int spi, int nr_slots)
3683 {
3684 	int err, i;
3685 
3686 	for (i = 0; i < nr_slots; i++) {
3687 		err = bpf_mark_stack_read(env, reg->frameno, env->insn_idx, BIT(spi - i));
3688 		if (err)
3689 			return err;
3690 		mark_stack_slot_scratched(env, spi - i);
3691 	}
3692 	return 0;
3693 }
3694 
3695 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3696 {
3697 	int spi;
3698 
3699 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3700 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3701 	 * check_kfunc_call.
3702 	 */
3703 	if (reg->type == CONST_PTR_TO_DYNPTR)
3704 		return 0;
3705 	spi = dynptr_get_spi(env, reg);
3706 	if (spi < 0)
3707 		return spi;
3708 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3709 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3710 	 * read.
3711 	 */
3712 	return mark_stack_slot_obj_read(env, reg, spi, BPF_DYNPTR_NR_SLOTS);
3713 }
3714 
3715 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3716 			  int spi, int nr_slots)
3717 {
3718 	return mark_stack_slot_obj_read(env, reg, spi, nr_slots);
3719 }
3720 
3721 static int mark_irq_flag_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3722 {
3723 	int spi;
3724 
3725 	spi = irq_flag_get_spi(env, reg);
3726 	if (spi < 0)
3727 		return spi;
3728 	return mark_stack_slot_obj_read(env, reg, spi, 1);
3729 }
3730 
3731 /* This function is supposed to be used by the following 32-bit optimization
3732  * code only. It returns TRUE if the source or destination register operates
3733  * on 64-bit, otherwise return FALSE.
3734  */
3735 static bool is_reg64(struct bpf_insn *insn,
3736 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3737 {
3738 	u8 code, class, op;
3739 
3740 	code = insn->code;
3741 	class = BPF_CLASS(code);
3742 	op = BPF_OP(code);
3743 	if (class == BPF_JMP) {
3744 		/* BPF_EXIT for "main" will reach here. Return TRUE
3745 		 * conservatively.
3746 		 */
3747 		if (op == BPF_EXIT)
3748 			return true;
3749 		if (op == BPF_CALL) {
3750 			/* BPF to BPF call will reach here because of marking
3751 			 * caller saved clobber with DST_OP_NO_MARK for which we
3752 			 * don't care the register def because they are anyway
3753 			 * marked as NOT_INIT already.
3754 			 */
3755 			if (insn->src_reg == BPF_PSEUDO_CALL)
3756 				return false;
3757 			/* Helper call will reach here because of arg type
3758 			 * check, conservatively return TRUE.
3759 			 */
3760 			if (t == SRC_OP)
3761 				return true;
3762 
3763 			return false;
3764 		}
3765 	}
3766 
3767 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3768 		return false;
3769 
3770 	if (class == BPF_ALU64 || class == BPF_JMP ||
3771 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3772 		return true;
3773 
3774 	if (class == BPF_ALU || class == BPF_JMP32)
3775 		return false;
3776 
3777 	if (class == BPF_LDX) {
3778 		if (t != SRC_OP)
3779 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3780 		/* LDX source must be ptr. */
3781 		return true;
3782 	}
3783 
3784 	if (class == BPF_STX) {
3785 		/* BPF_STX (including atomic variants) has one or more source
3786 		 * operands, one of which is a ptr. Check whether the caller is
3787 		 * asking about it.
3788 		 */
3789 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3790 			return true;
3791 		return BPF_SIZE(code) == BPF_DW;
3792 	}
3793 
3794 	if (class == BPF_LD) {
3795 		u8 mode = BPF_MODE(code);
3796 
3797 		/* LD_IMM64 */
3798 		if (mode == BPF_IMM)
3799 			return true;
3800 
3801 		/* Both LD_IND and LD_ABS return 32-bit data. */
3802 		if (t != SRC_OP)
3803 			return  false;
3804 
3805 		/* Implicit ctx ptr. */
3806 		if (regno == BPF_REG_6)
3807 			return true;
3808 
3809 		/* Explicit source could be any width. */
3810 		return true;
3811 	}
3812 
3813 	if (class == BPF_ST)
3814 		/* The only source register for BPF_ST is a ptr. */
3815 		return true;
3816 
3817 	/* Conservatively return true at default. */
3818 	return true;
3819 }
3820 
3821 /* Return the regno defined by the insn, or -1. */
3822 static int insn_def_regno(const struct bpf_insn *insn)
3823 {
3824 	switch (BPF_CLASS(insn->code)) {
3825 	case BPF_JMP:
3826 	case BPF_JMP32:
3827 	case BPF_ST:
3828 		return -1;
3829 	case BPF_STX:
3830 		if (BPF_MODE(insn->code) == BPF_ATOMIC ||
3831 		    BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) {
3832 			if (insn->imm == BPF_CMPXCHG)
3833 				return BPF_REG_0;
3834 			else if (insn->imm == BPF_LOAD_ACQ)
3835 				return insn->dst_reg;
3836 			else if (insn->imm & BPF_FETCH)
3837 				return insn->src_reg;
3838 		}
3839 		return -1;
3840 	default:
3841 		return insn->dst_reg;
3842 	}
3843 }
3844 
3845 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3846 static bool insn_has_def32(struct bpf_insn *insn)
3847 {
3848 	int dst_reg = insn_def_regno(insn);
3849 
3850 	if (dst_reg == -1)
3851 		return false;
3852 
3853 	return !is_reg64(insn, dst_reg, NULL, DST_OP);
3854 }
3855 
3856 static void mark_insn_zext(struct bpf_verifier_env *env,
3857 			   struct bpf_reg_state *reg)
3858 {
3859 	s32 def_idx = reg->subreg_def;
3860 
3861 	if (def_idx == DEF_NOT_SUBREG)
3862 		return;
3863 
3864 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3865 	/* The dst will be zero extended, so won't be sub-register anymore. */
3866 	reg->subreg_def = DEF_NOT_SUBREG;
3867 }
3868 
3869 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3870 			   enum reg_arg_type t)
3871 {
3872 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3873 	struct bpf_reg_state *reg;
3874 	bool rw64;
3875 
3876 	if (regno >= MAX_BPF_REG) {
3877 		verbose(env, "R%d is invalid\n", regno);
3878 		return -EINVAL;
3879 	}
3880 
3881 	mark_reg_scratched(env, regno);
3882 
3883 	reg = &regs[regno];
3884 	rw64 = is_reg64(insn, regno, reg, t);
3885 	if (t == SRC_OP) {
3886 		/* check whether register used as source operand can be read */
3887 		if (reg->type == NOT_INIT) {
3888 			verbose(env, "R%d !read_ok\n", regno);
3889 			return -EACCES;
3890 		}
3891 		/* We don't need to worry about FP liveness because it's read-only */
3892 		if (regno == BPF_REG_FP)
3893 			return 0;
3894 
3895 		if (rw64)
3896 			mark_insn_zext(env, reg);
3897 
3898 		return 0;
3899 	} else {
3900 		/* check whether register used as dest operand can be written to */
3901 		if (regno == BPF_REG_FP) {
3902 			verbose(env, "frame pointer is read only\n");
3903 			return -EACCES;
3904 		}
3905 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3906 		if (t == DST_OP)
3907 			mark_reg_unknown(env, regs, regno);
3908 	}
3909 	return 0;
3910 }
3911 
3912 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3913 			 enum reg_arg_type t)
3914 {
3915 	struct bpf_verifier_state *vstate = env->cur_state;
3916 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3917 
3918 	return __check_reg_arg(env, state->regs, regno, t);
3919 }
3920 
3921 static int insn_stack_access_flags(int frameno, int spi)
3922 {
3923 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3924 }
3925 
3926 static int insn_stack_access_spi(int insn_flags)
3927 {
3928 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3929 }
3930 
3931 static int insn_stack_access_frameno(int insn_flags)
3932 {
3933 	return insn_flags & INSN_F_FRAMENO_MASK;
3934 }
3935 
3936 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3937 {
3938 	env->insn_aux_data[idx].jmp_point = true;
3939 }
3940 
3941 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3942 {
3943 	return env->insn_aux_data[insn_idx].jmp_point;
3944 }
3945 
3946 #define LR_FRAMENO_BITS	3
3947 #define LR_SPI_BITS	6
3948 #define LR_ENTRY_BITS	(LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3949 #define LR_SIZE_BITS	4
3950 #define LR_FRAMENO_MASK	((1ull << LR_FRAMENO_BITS) - 1)
3951 #define LR_SPI_MASK	((1ull << LR_SPI_BITS)     - 1)
3952 #define LR_SIZE_MASK	((1ull << LR_SIZE_BITS)    - 1)
3953 #define LR_SPI_OFF	LR_FRAMENO_BITS
3954 #define LR_IS_REG_OFF	(LR_SPI_BITS + LR_FRAMENO_BITS)
3955 #define LINKED_REGS_MAX	6
3956 
3957 struct linked_reg {
3958 	u8 frameno;
3959 	union {
3960 		u8 spi;
3961 		u8 regno;
3962 	};
3963 	bool is_reg;
3964 };
3965 
3966 struct linked_regs {
3967 	int cnt;
3968 	struct linked_reg entries[LINKED_REGS_MAX];
3969 };
3970 
3971 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3972 {
3973 	if (s->cnt < LINKED_REGS_MAX)
3974 		return &s->entries[s->cnt++];
3975 
3976 	return NULL;
3977 }
3978 
3979 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track
3980  * number of elements currently in stack.
3981  * Pack one history entry for linked registers as 10 bits in the following format:
3982  * - 3-bits frameno
3983  * - 6-bits spi_or_reg
3984  * - 1-bit  is_reg
3985  */
3986 static u64 linked_regs_pack(struct linked_regs *s)
3987 {
3988 	u64 val = 0;
3989 	int i;
3990 
3991 	for (i = 0; i < s->cnt; ++i) {
3992 		struct linked_reg *e = &s->entries[i];
3993 		u64 tmp = 0;
3994 
3995 		tmp |= e->frameno;
3996 		tmp |= e->spi << LR_SPI_OFF;
3997 		tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
3998 
3999 		val <<= LR_ENTRY_BITS;
4000 		val |= tmp;
4001 	}
4002 	val <<= LR_SIZE_BITS;
4003 	val |= s->cnt;
4004 	return val;
4005 }
4006 
4007 static void linked_regs_unpack(u64 val, struct linked_regs *s)
4008 {
4009 	int i;
4010 
4011 	s->cnt = val & LR_SIZE_MASK;
4012 	val >>= LR_SIZE_BITS;
4013 
4014 	for (i = 0; i < s->cnt; ++i) {
4015 		struct linked_reg *e = &s->entries[i];
4016 
4017 		e->frameno =  val & LR_FRAMENO_MASK;
4018 		e->spi     = (val >> LR_SPI_OFF) & LR_SPI_MASK;
4019 		e->is_reg  = (val >> LR_IS_REG_OFF) & 0x1;
4020 		val >>= LR_ENTRY_BITS;
4021 	}
4022 }
4023 
4024 /* for any branch, call, exit record the history of jmps in the given state */
4025 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
4026 			    int insn_flags, u64 linked_regs)
4027 {
4028 	u32 cnt = cur->jmp_history_cnt;
4029 	struct bpf_jmp_history_entry *p;
4030 	size_t alloc_size;
4031 
4032 	/* combine instruction flags if we already recorded this instruction */
4033 	if (env->cur_hist_ent) {
4034 		/* atomic instructions push insn_flags twice, for READ and
4035 		 * WRITE sides, but they should agree on stack slot
4036 		 */
4037 		verifier_bug_if((env->cur_hist_ent->flags & insn_flags) &&
4038 				(env->cur_hist_ent->flags & insn_flags) != insn_flags,
4039 				env, "insn history: insn_idx %d cur flags %x new flags %x",
4040 				env->insn_idx, env->cur_hist_ent->flags, insn_flags);
4041 		env->cur_hist_ent->flags |= insn_flags;
4042 		verifier_bug_if(env->cur_hist_ent->linked_regs != 0, env,
4043 				"insn history: insn_idx %d linked_regs: %#llx",
4044 				env->insn_idx, env->cur_hist_ent->linked_regs);
4045 		env->cur_hist_ent->linked_regs = linked_regs;
4046 		return 0;
4047 	}
4048 
4049 	cnt++;
4050 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
4051 	p = krealloc(cur->jmp_history, alloc_size, GFP_KERNEL_ACCOUNT);
4052 	if (!p)
4053 		return -ENOMEM;
4054 	cur->jmp_history = p;
4055 
4056 	p = &cur->jmp_history[cnt - 1];
4057 	p->idx = env->insn_idx;
4058 	p->prev_idx = env->prev_insn_idx;
4059 	p->flags = insn_flags;
4060 	p->linked_regs = linked_regs;
4061 	cur->jmp_history_cnt = cnt;
4062 	env->cur_hist_ent = p;
4063 
4064 	return 0;
4065 }
4066 
4067 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
4068 						        u32 hist_end, int insn_idx)
4069 {
4070 	if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
4071 		return &st->jmp_history[hist_end - 1];
4072 	return NULL;
4073 }
4074 
4075 /* Backtrack one insn at a time. If idx is not at the top of recorded
4076  * history then previous instruction came from straight line execution.
4077  * Return -ENOENT if we exhausted all instructions within given state.
4078  *
4079  * It's legal to have a bit of a looping with the same starting and ending
4080  * insn index within the same state, e.g.: 3->4->5->3, so just because current
4081  * instruction index is the same as state's first_idx doesn't mean we are
4082  * done. If there is still some jump history left, we should keep going. We
4083  * need to take into account that we might have a jump history between given
4084  * state's parent and itself, due to checkpointing. In this case, we'll have
4085  * history entry recording a jump from last instruction of parent state and
4086  * first instruction of given state.
4087  */
4088 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
4089 			     u32 *history)
4090 {
4091 	u32 cnt = *history;
4092 
4093 	if (i == st->first_insn_idx) {
4094 		if (cnt == 0)
4095 			return -ENOENT;
4096 		if (cnt == 1 && st->jmp_history[0].idx == i)
4097 			return -ENOENT;
4098 	}
4099 
4100 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
4101 		i = st->jmp_history[cnt - 1].prev_idx;
4102 		(*history)--;
4103 	} else {
4104 		i--;
4105 	}
4106 	return i;
4107 }
4108 
4109 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
4110 {
4111 	const struct btf_type *func;
4112 	struct btf *desc_btf;
4113 
4114 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
4115 		return NULL;
4116 
4117 	desc_btf = find_kfunc_desc_btf(data, insn->off);
4118 	if (IS_ERR(desc_btf))
4119 		return "<error>";
4120 
4121 	func = btf_type_by_id(desc_btf, insn->imm);
4122 	return btf_name_by_offset(desc_btf, func->name_off);
4123 }
4124 
4125 static void verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
4126 {
4127 	const struct bpf_insn_cbs cbs = {
4128 		.cb_call	= disasm_kfunc_name,
4129 		.cb_print	= verbose,
4130 		.private_data	= env,
4131 	};
4132 
4133 	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
4134 }
4135 
4136 static inline void bt_init(struct backtrack_state *bt, u32 frame)
4137 {
4138 	bt->frame = frame;
4139 }
4140 
4141 static inline void bt_reset(struct backtrack_state *bt)
4142 {
4143 	struct bpf_verifier_env *env = bt->env;
4144 
4145 	memset(bt, 0, sizeof(*bt));
4146 	bt->env = env;
4147 }
4148 
4149 static inline u32 bt_empty(struct backtrack_state *bt)
4150 {
4151 	u64 mask = 0;
4152 	int i;
4153 
4154 	for (i = 0; i <= bt->frame; i++)
4155 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
4156 
4157 	return mask == 0;
4158 }
4159 
4160 static inline int bt_subprog_enter(struct backtrack_state *bt)
4161 {
4162 	if (bt->frame == MAX_CALL_FRAMES - 1) {
4163 		verifier_bug(bt->env, "subprog enter from frame %d", bt->frame);
4164 		return -EFAULT;
4165 	}
4166 	bt->frame++;
4167 	return 0;
4168 }
4169 
4170 static inline int bt_subprog_exit(struct backtrack_state *bt)
4171 {
4172 	if (bt->frame == 0) {
4173 		verifier_bug(bt->env, "subprog exit from frame 0");
4174 		return -EFAULT;
4175 	}
4176 	bt->frame--;
4177 	return 0;
4178 }
4179 
4180 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4181 {
4182 	bt->reg_masks[frame] |= 1 << reg;
4183 }
4184 
4185 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4186 {
4187 	bt->reg_masks[frame] &= ~(1 << reg);
4188 }
4189 
4190 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
4191 {
4192 	bt_set_frame_reg(bt, bt->frame, reg);
4193 }
4194 
4195 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
4196 {
4197 	bt_clear_frame_reg(bt, bt->frame, reg);
4198 }
4199 
4200 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4201 {
4202 	bt->stack_masks[frame] |= 1ull << slot;
4203 }
4204 
4205 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4206 {
4207 	bt->stack_masks[frame] &= ~(1ull << slot);
4208 }
4209 
4210 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
4211 {
4212 	return bt->reg_masks[frame];
4213 }
4214 
4215 static inline u32 bt_reg_mask(struct backtrack_state *bt)
4216 {
4217 	return bt->reg_masks[bt->frame];
4218 }
4219 
4220 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
4221 {
4222 	return bt->stack_masks[frame];
4223 }
4224 
4225 static inline u64 bt_stack_mask(struct backtrack_state *bt)
4226 {
4227 	return bt->stack_masks[bt->frame];
4228 }
4229 
4230 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
4231 {
4232 	return bt->reg_masks[bt->frame] & (1 << reg);
4233 }
4234 
4235 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
4236 {
4237 	return bt->reg_masks[frame] & (1 << reg);
4238 }
4239 
4240 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
4241 {
4242 	return bt->stack_masks[frame] & (1ull << slot);
4243 }
4244 
4245 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
4246 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
4247 {
4248 	DECLARE_BITMAP(mask, 64);
4249 	bool first = true;
4250 	int i, n;
4251 
4252 	buf[0] = '\0';
4253 
4254 	bitmap_from_u64(mask, reg_mask);
4255 	for_each_set_bit(i, mask, 32) {
4256 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
4257 		first = false;
4258 		buf += n;
4259 		buf_sz -= n;
4260 		if (buf_sz < 0)
4261 			break;
4262 	}
4263 }
4264 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
4265 void bpf_fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
4266 {
4267 	DECLARE_BITMAP(mask, 64);
4268 	bool first = true;
4269 	int i, n;
4270 
4271 	buf[0] = '\0';
4272 
4273 	bitmap_from_u64(mask, stack_mask);
4274 	for_each_set_bit(i, mask, 64) {
4275 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
4276 		first = false;
4277 		buf += n;
4278 		buf_sz -= n;
4279 		if (buf_sz < 0)
4280 			break;
4281 	}
4282 }
4283 
4284 /* If any register R in hist->linked_regs is marked as precise in bt,
4285  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
4286  */
4287 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
4288 {
4289 	struct linked_regs linked_regs;
4290 	bool some_precise = false;
4291 	int i;
4292 
4293 	if (!hist || hist->linked_regs == 0)
4294 		return;
4295 
4296 	linked_regs_unpack(hist->linked_regs, &linked_regs);
4297 	for (i = 0; i < linked_regs.cnt; ++i) {
4298 		struct linked_reg *e = &linked_regs.entries[i];
4299 
4300 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
4301 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
4302 			some_precise = true;
4303 			break;
4304 		}
4305 	}
4306 
4307 	if (!some_precise)
4308 		return;
4309 
4310 	for (i = 0; i < linked_regs.cnt; ++i) {
4311 		struct linked_reg *e = &linked_regs.entries[i];
4312 
4313 		if (e->is_reg)
4314 			bt_set_frame_reg(bt, e->frameno, e->regno);
4315 		else
4316 			bt_set_frame_slot(bt, e->frameno, e->spi);
4317 	}
4318 }
4319 
4320 /* For given verifier state backtrack_insn() is called from the last insn to
4321  * the first insn. Its purpose is to compute a bitmask of registers and
4322  * stack slots that needs precision in the parent verifier state.
4323  *
4324  * @idx is an index of the instruction we are currently processing;
4325  * @subseq_idx is an index of the subsequent instruction that:
4326  *   - *would be* executed next, if jump history is viewed in forward order;
4327  *   - *was* processed previously during backtracking.
4328  */
4329 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
4330 			  struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
4331 {
4332 	struct bpf_insn *insn = env->prog->insnsi + idx;
4333 	u8 class = BPF_CLASS(insn->code);
4334 	u8 opcode = BPF_OP(insn->code);
4335 	u8 mode = BPF_MODE(insn->code);
4336 	u32 dreg = insn->dst_reg;
4337 	u32 sreg = insn->src_reg;
4338 	u32 spi, i, fr;
4339 
4340 	if (insn->code == 0)
4341 		return 0;
4342 	if (env->log.level & BPF_LOG_LEVEL2) {
4343 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
4344 		verbose(env, "mark_precise: frame%d: regs=%s ",
4345 			bt->frame, env->tmp_str_buf);
4346 		bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
4347 		verbose(env, "stack=%s before ", env->tmp_str_buf);
4348 		verbose(env, "%d: ", idx);
4349 		verbose_insn(env, insn);
4350 	}
4351 
4352 	/* If there is a history record that some registers gained range at this insn,
4353 	 * propagate precision marks to those registers, so that bt_is_reg_set()
4354 	 * accounts for these registers.
4355 	 */
4356 	bt_sync_linked_regs(bt, hist);
4357 
4358 	if (class == BPF_ALU || class == BPF_ALU64) {
4359 		if (!bt_is_reg_set(bt, dreg))
4360 			return 0;
4361 		if (opcode == BPF_END || opcode == BPF_NEG) {
4362 			/* sreg is reserved and unused
4363 			 * dreg still need precision before this insn
4364 			 */
4365 			return 0;
4366 		} else if (opcode == BPF_MOV) {
4367 			if (BPF_SRC(insn->code) == BPF_X) {
4368 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
4369 				 * dreg needs precision after this insn
4370 				 * sreg needs precision before this insn
4371 				 */
4372 				bt_clear_reg(bt, dreg);
4373 				if (sreg != BPF_REG_FP)
4374 					bt_set_reg(bt, sreg);
4375 			} else {
4376 				/* dreg = K
4377 				 * dreg needs precision after this insn.
4378 				 * Corresponding register is already marked
4379 				 * as precise=true in this verifier state.
4380 				 * No further markings in parent are necessary
4381 				 */
4382 				bt_clear_reg(bt, dreg);
4383 			}
4384 		} else {
4385 			if (BPF_SRC(insn->code) == BPF_X) {
4386 				/* dreg += sreg
4387 				 * both dreg and sreg need precision
4388 				 * before this insn
4389 				 */
4390 				if (sreg != BPF_REG_FP)
4391 					bt_set_reg(bt, sreg);
4392 			} /* else dreg += K
4393 			   * dreg still needs precision before this insn
4394 			   */
4395 		}
4396 	} else if (class == BPF_LDX || is_atomic_load_insn(insn)) {
4397 		if (!bt_is_reg_set(bt, dreg))
4398 			return 0;
4399 		bt_clear_reg(bt, dreg);
4400 
4401 		/* scalars can only be spilled into stack w/o losing precision.
4402 		 * Load from any other memory can be zero extended.
4403 		 * The desire to keep that precision is already indicated
4404 		 * by 'precise' mark in corresponding register of this state.
4405 		 * No further tracking necessary.
4406 		 */
4407 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4408 			return 0;
4409 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
4410 		 * that [fp - off] slot contains scalar that needs to be
4411 		 * tracked with precision
4412 		 */
4413 		spi = insn_stack_access_spi(hist->flags);
4414 		fr = insn_stack_access_frameno(hist->flags);
4415 		bt_set_frame_slot(bt, fr, spi);
4416 	} else if (class == BPF_STX || class == BPF_ST) {
4417 		if (bt_is_reg_set(bt, dreg))
4418 			/* stx & st shouldn't be using _scalar_ dst_reg
4419 			 * to access memory. It means backtracking
4420 			 * encountered a case of pointer subtraction.
4421 			 */
4422 			return -ENOTSUPP;
4423 		/* scalars can only be spilled into stack */
4424 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4425 			return 0;
4426 		spi = insn_stack_access_spi(hist->flags);
4427 		fr = insn_stack_access_frameno(hist->flags);
4428 		if (!bt_is_frame_slot_set(bt, fr, spi))
4429 			return 0;
4430 		bt_clear_frame_slot(bt, fr, spi);
4431 		if (class == BPF_STX)
4432 			bt_set_reg(bt, sreg);
4433 	} else if (class == BPF_JMP || class == BPF_JMP32) {
4434 		if (bpf_pseudo_call(insn)) {
4435 			int subprog_insn_idx, subprog;
4436 
4437 			subprog_insn_idx = idx + insn->imm + 1;
4438 			subprog = find_subprog(env, subprog_insn_idx);
4439 			if (subprog < 0)
4440 				return -EFAULT;
4441 
4442 			if (subprog_is_global(env, subprog)) {
4443 				/* check that jump history doesn't have any
4444 				 * extra instructions from subprog; the next
4445 				 * instruction after call to global subprog
4446 				 * should be literally next instruction in
4447 				 * caller program
4448 				 */
4449 				verifier_bug_if(idx + 1 != subseq_idx, env,
4450 						"extra insn from subprog");
4451 				/* r1-r5 are invalidated after subprog call,
4452 				 * so for global func call it shouldn't be set
4453 				 * anymore
4454 				 */
4455 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4456 					verifier_bug(env, "global subprog unexpected regs %x",
4457 						     bt_reg_mask(bt));
4458 					return -EFAULT;
4459 				}
4460 				/* global subprog always sets R0 */
4461 				bt_clear_reg(bt, BPF_REG_0);
4462 				return 0;
4463 			} else {
4464 				/* static subprog call instruction, which
4465 				 * means that we are exiting current subprog,
4466 				 * so only r1-r5 could be still requested as
4467 				 * precise, r0 and r6-r10 or any stack slot in
4468 				 * the current frame should be zero by now
4469 				 */
4470 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4471 					verifier_bug(env, "static subprog unexpected regs %x",
4472 						     bt_reg_mask(bt));
4473 					return -EFAULT;
4474 				}
4475 				/* we are now tracking register spills correctly,
4476 				 * so any instance of leftover slots is a bug
4477 				 */
4478 				if (bt_stack_mask(bt) != 0) {
4479 					verifier_bug(env,
4480 						     "static subprog leftover stack slots %llx",
4481 						     bt_stack_mask(bt));
4482 					return -EFAULT;
4483 				}
4484 				/* propagate r1-r5 to the caller */
4485 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
4486 					if (bt_is_reg_set(bt, i)) {
4487 						bt_clear_reg(bt, i);
4488 						bt_set_frame_reg(bt, bt->frame - 1, i);
4489 					}
4490 				}
4491 				if (bt_subprog_exit(bt))
4492 					return -EFAULT;
4493 				return 0;
4494 			}
4495 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
4496 			/* exit from callback subprog to callback-calling helper or
4497 			 * kfunc call. Use idx/subseq_idx check to discern it from
4498 			 * straight line code backtracking.
4499 			 * Unlike the subprog call handling above, we shouldn't
4500 			 * propagate precision of r1-r5 (if any requested), as they are
4501 			 * not actually arguments passed directly to callback subprogs
4502 			 */
4503 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4504 				verifier_bug(env, "callback unexpected regs %x",
4505 					     bt_reg_mask(bt));
4506 				return -EFAULT;
4507 			}
4508 			if (bt_stack_mask(bt) != 0) {
4509 				verifier_bug(env, "callback leftover stack slots %llx",
4510 					     bt_stack_mask(bt));
4511 				return -EFAULT;
4512 			}
4513 			/* clear r1-r5 in callback subprog's mask */
4514 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4515 				bt_clear_reg(bt, i);
4516 			if (bt_subprog_exit(bt))
4517 				return -EFAULT;
4518 			return 0;
4519 		} else if (opcode == BPF_CALL) {
4520 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
4521 			 * catch this error later. Make backtracking conservative
4522 			 * with ENOTSUPP.
4523 			 */
4524 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
4525 				return -ENOTSUPP;
4526 			/* regular helper call sets R0 */
4527 			bt_clear_reg(bt, BPF_REG_0);
4528 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4529 				/* if backtracking was looking for registers R1-R5
4530 				 * they should have been found already.
4531 				 */
4532 				verifier_bug(env, "backtracking call unexpected regs %x",
4533 					     bt_reg_mask(bt));
4534 				return -EFAULT;
4535 			}
4536 			if (insn->src_reg == BPF_REG_0 && insn->imm == BPF_FUNC_tail_call
4537 			    && subseq_idx - idx != 1) {
4538 				if (bt_subprog_enter(bt))
4539 					return -EFAULT;
4540 			}
4541 		} else if (opcode == BPF_EXIT) {
4542 			bool r0_precise;
4543 
4544 			/* Backtracking to a nested function call, 'idx' is a part of
4545 			 * the inner frame 'subseq_idx' is a part of the outer frame.
4546 			 * In case of a regular function call, instructions giving
4547 			 * precision to registers R1-R5 should have been found already.
4548 			 * In case of a callback, it is ok to have R1-R5 marked for
4549 			 * backtracking, as these registers are set by the function
4550 			 * invoking callback.
4551 			 */
4552 			if (subseq_idx >= 0 && bpf_calls_callback(env, subseq_idx))
4553 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4554 					bt_clear_reg(bt, i);
4555 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4556 				verifier_bug(env, "backtracking exit unexpected regs %x",
4557 					     bt_reg_mask(bt));
4558 				return -EFAULT;
4559 			}
4560 
4561 			/* BPF_EXIT in subprog or callback always returns
4562 			 * right after the call instruction, so by checking
4563 			 * whether the instruction at subseq_idx-1 is subprog
4564 			 * call or not we can distinguish actual exit from
4565 			 * *subprog* from exit from *callback*. In the former
4566 			 * case, we need to propagate r0 precision, if
4567 			 * necessary. In the former we never do that.
4568 			 */
4569 			r0_precise = subseq_idx - 1 >= 0 &&
4570 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
4571 				     bt_is_reg_set(bt, BPF_REG_0);
4572 
4573 			bt_clear_reg(bt, BPF_REG_0);
4574 			if (bt_subprog_enter(bt))
4575 				return -EFAULT;
4576 
4577 			if (r0_precise)
4578 				bt_set_reg(bt, BPF_REG_0);
4579 			/* r6-r9 and stack slots will stay set in caller frame
4580 			 * bitmasks until we return back from callee(s)
4581 			 */
4582 			return 0;
4583 		} else if (BPF_SRC(insn->code) == BPF_X) {
4584 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
4585 				return 0;
4586 			/* dreg <cond> sreg
4587 			 * Both dreg and sreg need precision before
4588 			 * this insn. If only sreg was marked precise
4589 			 * before it would be equally necessary to
4590 			 * propagate it to dreg.
4591 			 */
4592 			if (!hist || !(hist->flags & INSN_F_SRC_REG_STACK))
4593 				bt_set_reg(bt, sreg);
4594 			if (!hist || !(hist->flags & INSN_F_DST_REG_STACK))
4595 				bt_set_reg(bt, dreg);
4596 		} else if (BPF_SRC(insn->code) == BPF_K) {
4597 			 /* dreg <cond> K
4598 			  * Only dreg still needs precision before
4599 			  * this insn, so for the K-based conditional
4600 			  * there is nothing new to be marked.
4601 			  */
4602 		}
4603 	} else if (class == BPF_LD) {
4604 		if (!bt_is_reg_set(bt, dreg))
4605 			return 0;
4606 		bt_clear_reg(bt, dreg);
4607 		/* It's ld_imm64 or ld_abs or ld_ind.
4608 		 * For ld_imm64 no further tracking of precision
4609 		 * into parent is necessary
4610 		 */
4611 		if (mode == BPF_IND || mode == BPF_ABS)
4612 			/* to be analyzed */
4613 			return -ENOTSUPP;
4614 	}
4615 	/* Propagate precision marks to linked registers, to account for
4616 	 * registers marked as precise in this function.
4617 	 */
4618 	bt_sync_linked_regs(bt, hist);
4619 	return 0;
4620 }
4621 
4622 /* the scalar precision tracking algorithm:
4623  * . at the start all registers have precise=false.
4624  * . scalar ranges are tracked as normal through alu and jmp insns.
4625  * . once precise value of the scalar register is used in:
4626  *   .  ptr + scalar alu
4627  *   . if (scalar cond K|scalar)
4628  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
4629  *   backtrack through the verifier states and mark all registers and
4630  *   stack slots with spilled constants that these scalar registers
4631  *   should be precise.
4632  * . during state pruning two registers (or spilled stack slots)
4633  *   are equivalent if both are not precise.
4634  *
4635  * Note the verifier cannot simply walk register parentage chain,
4636  * since many different registers and stack slots could have been
4637  * used to compute single precise scalar.
4638  *
4639  * The approach of starting with precise=true for all registers and then
4640  * backtrack to mark a register as not precise when the verifier detects
4641  * that program doesn't care about specific value (e.g., when helper
4642  * takes register as ARG_ANYTHING parameter) is not safe.
4643  *
4644  * It's ok to walk single parentage chain of the verifier states.
4645  * It's possible that this backtracking will go all the way till 1st insn.
4646  * All other branches will be explored for needing precision later.
4647  *
4648  * The backtracking needs to deal with cases like:
4649  *   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)
4650  * r9 -= r8
4651  * r5 = r9
4652  * if r5 > 0x79f goto pc+7
4653  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4654  * r5 += 1
4655  * ...
4656  * call bpf_perf_event_output#25
4657  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4658  *
4659  * and this case:
4660  * r6 = 1
4661  * call foo // uses callee's r6 inside to compute r0
4662  * r0 += r6
4663  * if r0 == 0 goto
4664  *
4665  * to track above reg_mask/stack_mask needs to be independent for each frame.
4666  *
4667  * Also if parent's curframe > frame where backtracking started,
4668  * the verifier need to mark registers in both frames, otherwise callees
4669  * may incorrectly prune callers. This is similar to
4670  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4671  *
4672  * For now backtracking falls back into conservative marking.
4673  */
4674 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4675 				     struct bpf_verifier_state *st)
4676 {
4677 	struct bpf_func_state *func;
4678 	struct bpf_reg_state *reg;
4679 	int i, j;
4680 
4681 	if (env->log.level & BPF_LOG_LEVEL2) {
4682 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4683 			st->curframe);
4684 	}
4685 
4686 	/* big hammer: mark all scalars precise in this path.
4687 	 * pop_stack may still get !precise scalars.
4688 	 * We also skip current state and go straight to first parent state,
4689 	 * because precision markings in current non-checkpointed state are
4690 	 * not needed. See why in the comment in __mark_chain_precision below.
4691 	 */
4692 	for (st = st->parent; st; st = st->parent) {
4693 		for (i = 0; i <= st->curframe; i++) {
4694 			func = st->frame[i];
4695 			for (j = 0; j < BPF_REG_FP; j++) {
4696 				reg = &func->regs[j];
4697 				if (reg->type != SCALAR_VALUE || reg->precise)
4698 					continue;
4699 				reg->precise = true;
4700 				if (env->log.level & BPF_LOG_LEVEL2) {
4701 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4702 						i, j);
4703 				}
4704 			}
4705 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4706 				if (!is_spilled_reg(&func->stack[j]))
4707 					continue;
4708 				reg = &func->stack[j].spilled_ptr;
4709 				if (reg->type != SCALAR_VALUE || reg->precise)
4710 					continue;
4711 				reg->precise = true;
4712 				if (env->log.level & BPF_LOG_LEVEL2) {
4713 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4714 						i, -(j + 1) * 8);
4715 				}
4716 			}
4717 		}
4718 	}
4719 }
4720 
4721 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4722 {
4723 	struct bpf_func_state *func;
4724 	struct bpf_reg_state *reg;
4725 	int i, j;
4726 
4727 	for (i = 0; i <= st->curframe; i++) {
4728 		func = st->frame[i];
4729 		for (j = 0; j < BPF_REG_FP; j++) {
4730 			reg = &func->regs[j];
4731 			if (reg->type != SCALAR_VALUE)
4732 				continue;
4733 			reg->precise = false;
4734 		}
4735 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4736 			if (!is_spilled_reg(&func->stack[j]))
4737 				continue;
4738 			reg = &func->stack[j].spilled_ptr;
4739 			if (reg->type != SCALAR_VALUE)
4740 				continue;
4741 			reg->precise = false;
4742 		}
4743 	}
4744 }
4745 
4746 /*
4747  * __mark_chain_precision() backtracks BPF program instruction sequence and
4748  * chain of verifier states making sure that register *regno* (if regno >= 0)
4749  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4750  * SCALARS, as well as any other registers and slots that contribute to
4751  * a tracked state of given registers/stack slots, depending on specific BPF
4752  * assembly instructions (see backtrack_insns() for exact instruction handling
4753  * logic). This backtracking relies on recorded jmp_history and is able to
4754  * traverse entire chain of parent states. This process ends only when all the
4755  * necessary registers/slots and their transitive dependencies are marked as
4756  * precise.
4757  *
4758  * One important and subtle aspect is that precise marks *do not matter* in
4759  * the currently verified state (current state). It is important to understand
4760  * why this is the case.
4761  *
4762  * First, note that current state is the state that is not yet "checkpointed",
4763  * i.e., it is not yet put into env->explored_states, and it has no children
4764  * states as well. It's ephemeral, and can end up either a) being discarded if
4765  * compatible explored state is found at some point or BPF_EXIT instruction is
4766  * reached or b) checkpointed and put into env->explored_states, branching out
4767  * into one or more children states.
4768  *
4769  * In the former case, precise markings in current state are completely
4770  * ignored by state comparison code (see regsafe() for details). Only
4771  * checkpointed ("old") state precise markings are important, and if old
4772  * state's register/slot is precise, regsafe() assumes current state's
4773  * register/slot as precise and checks value ranges exactly and precisely. If
4774  * states turn out to be compatible, current state's necessary precise
4775  * markings and any required parent states' precise markings are enforced
4776  * after the fact with propagate_precision() logic, after the fact. But it's
4777  * important to realize that in this case, even after marking current state
4778  * registers/slots as precise, we immediately discard current state. So what
4779  * actually matters is any of the precise markings propagated into current
4780  * state's parent states, which are always checkpointed (due to b) case above).
4781  * As such, for scenario a) it doesn't matter if current state has precise
4782  * markings set or not.
4783  *
4784  * Now, for the scenario b), checkpointing and forking into child(ren)
4785  * state(s). Note that before current state gets to checkpointing step, any
4786  * processed instruction always assumes precise SCALAR register/slot
4787  * knowledge: if precise value or range is useful to prune jump branch, BPF
4788  * verifier takes this opportunity enthusiastically. Similarly, when
4789  * register's value is used to calculate offset or memory address, exact
4790  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4791  * what we mentioned above about state comparison ignoring precise markings
4792  * during state comparison, BPF verifier ignores and also assumes precise
4793  * markings *at will* during instruction verification process. But as verifier
4794  * assumes precision, it also propagates any precision dependencies across
4795  * parent states, which are not yet finalized, so can be further restricted
4796  * based on new knowledge gained from restrictions enforced by their children
4797  * states. This is so that once those parent states are finalized, i.e., when
4798  * they have no more active children state, state comparison logic in
4799  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4800  * required for correctness.
4801  *
4802  * To build a bit more intuition, note also that once a state is checkpointed,
4803  * the path we took to get to that state is not important. This is crucial
4804  * property for state pruning. When state is checkpointed and finalized at
4805  * some instruction index, it can be correctly and safely used to "short
4806  * circuit" any *compatible* state that reaches exactly the same instruction
4807  * index. I.e., if we jumped to that instruction from a completely different
4808  * code path than original finalized state was derived from, it doesn't
4809  * matter, current state can be discarded because from that instruction
4810  * forward having a compatible state will ensure we will safely reach the
4811  * exit. States describe preconditions for further exploration, but completely
4812  * forget the history of how we got here.
4813  *
4814  * This also means that even if we needed precise SCALAR range to get to
4815  * finalized state, but from that point forward *that same* SCALAR register is
4816  * never used in a precise context (i.e., it's precise value is not needed for
4817  * correctness), it's correct and safe to mark such register as "imprecise"
4818  * (i.e., precise marking set to false). This is what we rely on when we do
4819  * not set precise marking in current state. If no child state requires
4820  * precision for any given SCALAR register, it's safe to dictate that it can
4821  * be imprecise. If any child state does require this register to be precise,
4822  * we'll mark it precise later retroactively during precise markings
4823  * propagation from child state to parent states.
4824  *
4825  * Skipping precise marking setting in current state is a mild version of
4826  * relying on the above observation. But we can utilize this property even
4827  * more aggressively by proactively forgetting any precise marking in the
4828  * current state (which we inherited from the parent state), right before we
4829  * checkpoint it and branch off into new child state. This is done by
4830  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4831  * finalized states which help in short circuiting more future states.
4832  */
4833 static int __mark_chain_precision(struct bpf_verifier_env *env,
4834 				  struct bpf_verifier_state *starting_state,
4835 				  int regno,
4836 				  bool *changed)
4837 {
4838 	struct bpf_verifier_state *st = starting_state;
4839 	struct backtrack_state *bt = &env->bt;
4840 	int first_idx = st->first_insn_idx;
4841 	int last_idx = starting_state->insn_idx;
4842 	int subseq_idx = -1;
4843 	struct bpf_func_state *func;
4844 	bool tmp, skip_first = true;
4845 	struct bpf_reg_state *reg;
4846 	int i, fr, err;
4847 
4848 	if (!env->bpf_capable)
4849 		return 0;
4850 
4851 	changed = changed ?: &tmp;
4852 	/* set frame number from which we are starting to backtrack */
4853 	bt_init(bt, starting_state->curframe);
4854 
4855 	/* Do sanity checks against current state of register and/or stack
4856 	 * slot, but don't set precise flag in current state, as precision
4857 	 * tracking in the current state is unnecessary.
4858 	 */
4859 	func = st->frame[bt->frame];
4860 	if (regno >= 0) {
4861 		reg = &func->regs[regno];
4862 		if (reg->type != SCALAR_VALUE) {
4863 			verifier_bug(env, "backtracking misuse");
4864 			return -EFAULT;
4865 		}
4866 		bt_set_reg(bt, regno);
4867 	}
4868 
4869 	if (bt_empty(bt))
4870 		return 0;
4871 
4872 	for (;;) {
4873 		DECLARE_BITMAP(mask, 64);
4874 		u32 history = st->jmp_history_cnt;
4875 		struct bpf_jmp_history_entry *hist;
4876 
4877 		if (env->log.level & BPF_LOG_LEVEL2) {
4878 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4879 				bt->frame, last_idx, first_idx, subseq_idx);
4880 		}
4881 
4882 		if (last_idx < 0) {
4883 			/* we are at the entry into subprog, which
4884 			 * is expected for global funcs, but only if
4885 			 * requested precise registers are R1-R5
4886 			 * (which are global func's input arguments)
4887 			 */
4888 			if (st->curframe == 0 &&
4889 			    st->frame[0]->subprogno > 0 &&
4890 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4891 			    bt_stack_mask(bt) == 0 &&
4892 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4893 				bitmap_from_u64(mask, bt_reg_mask(bt));
4894 				for_each_set_bit(i, mask, 32) {
4895 					reg = &st->frame[0]->regs[i];
4896 					bt_clear_reg(bt, i);
4897 					if (reg->type == SCALAR_VALUE) {
4898 						reg->precise = true;
4899 						*changed = true;
4900 					}
4901 				}
4902 				return 0;
4903 			}
4904 
4905 			verifier_bug(env, "backtracking func entry subprog %d reg_mask %x stack_mask %llx",
4906 				     st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4907 			return -EFAULT;
4908 		}
4909 
4910 		for (i = last_idx;;) {
4911 			if (skip_first) {
4912 				err = 0;
4913 				skip_first = false;
4914 			} else {
4915 				hist = get_jmp_hist_entry(st, history, i);
4916 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4917 			}
4918 			if (err == -ENOTSUPP) {
4919 				mark_all_scalars_precise(env, starting_state);
4920 				bt_reset(bt);
4921 				return 0;
4922 			} else if (err) {
4923 				return err;
4924 			}
4925 			if (bt_empty(bt))
4926 				/* Found assignment(s) into tracked register in this state.
4927 				 * Since this state is already marked, just return.
4928 				 * Nothing to be tracked further in the parent state.
4929 				 */
4930 				return 0;
4931 			subseq_idx = i;
4932 			i = get_prev_insn_idx(st, i, &history);
4933 			if (i == -ENOENT)
4934 				break;
4935 			if (i >= env->prog->len) {
4936 				/* This can happen if backtracking reached insn 0
4937 				 * and there are still reg_mask or stack_mask
4938 				 * to backtrack.
4939 				 * It means the backtracking missed the spot where
4940 				 * particular register was initialized with a constant.
4941 				 */
4942 				verifier_bug(env, "backtracking idx %d", i);
4943 				return -EFAULT;
4944 			}
4945 		}
4946 		st = st->parent;
4947 		if (!st)
4948 			break;
4949 
4950 		for (fr = bt->frame; fr >= 0; fr--) {
4951 			func = st->frame[fr];
4952 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4953 			for_each_set_bit(i, mask, 32) {
4954 				reg = &func->regs[i];
4955 				if (reg->type != SCALAR_VALUE) {
4956 					bt_clear_frame_reg(bt, fr, i);
4957 					continue;
4958 				}
4959 				if (reg->precise) {
4960 					bt_clear_frame_reg(bt, fr, i);
4961 				} else {
4962 					reg->precise = true;
4963 					*changed = true;
4964 				}
4965 			}
4966 
4967 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4968 			for_each_set_bit(i, mask, 64) {
4969 				if (verifier_bug_if(i >= func->allocated_stack / BPF_REG_SIZE,
4970 						    env, "stack slot %d, total slots %d",
4971 						    i, func->allocated_stack / BPF_REG_SIZE))
4972 					return -EFAULT;
4973 
4974 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4975 					bt_clear_frame_slot(bt, fr, i);
4976 					continue;
4977 				}
4978 				reg = &func->stack[i].spilled_ptr;
4979 				if (reg->precise) {
4980 					bt_clear_frame_slot(bt, fr, i);
4981 				} else {
4982 					reg->precise = true;
4983 					*changed = true;
4984 				}
4985 			}
4986 			if (env->log.level & BPF_LOG_LEVEL2) {
4987 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4988 					     bt_frame_reg_mask(bt, fr));
4989 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4990 					fr, env->tmp_str_buf);
4991 				bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4992 					       bt_frame_stack_mask(bt, fr));
4993 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4994 				print_verifier_state(env, st, fr, true);
4995 			}
4996 		}
4997 
4998 		if (bt_empty(bt))
4999 			return 0;
5000 
5001 		subseq_idx = first_idx;
5002 		last_idx = st->last_insn_idx;
5003 		first_idx = st->first_insn_idx;
5004 	}
5005 
5006 	/* if we still have requested precise regs or slots, we missed
5007 	 * something (e.g., stack access through non-r10 register), so
5008 	 * fallback to marking all precise
5009 	 */
5010 	if (!bt_empty(bt)) {
5011 		mark_all_scalars_precise(env, starting_state);
5012 		bt_reset(bt);
5013 	}
5014 
5015 	return 0;
5016 }
5017 
5018 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
5019 {
5020 	return __mark_chain_precision(env, env->cur_state, regno, NULL);
5021 }
5022 
5023 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
5024  * desired reg and stack masks across all relevant frames
5025  */
5026 static int mark_chain_precision_batch(struct bpf_verifier_env *env,
5027 				      struct bpf_verifier_state *starting_state)
5028 {
5029 	return __mark_chain_precision(env, starting_state, -1, NULL);
5030 }
5031 
5032 static bool is_spillable_regtype(enum bpf_reg_type type)
5033 {
5034 	switch (base_type(type)) {
5035 	case PTR_TO_MAP_VALUE:
5036 	case PTR_TO_STACK:
5037 	case PTR_TO_CTX:
5038 	case PTR_TO_PACKET:
5039 	case PTR_TO_PACKET_META:
5040 	case PTR_TO_PACKET_END:
5041 	case PTR_TO_FLOW_KEYS:
5042 	case CONST_PTR_TO_MAP:
5043 	case PTR_TO_SOCKET:
5044 	case PTR_TO_SOCK_COMMON:
5045 	case PTR_TO_TCP_SOCK:
5046 	case PTR_TO_XDP_SOCK:
5047 	case PTR_TO_BTF_ID:
5048 	case PTR_TO_BUF:
5049 	case PTR_TO_MEM:
5050 	case PTR_TO_FUNC:
5051 	case PTR_TO_MAP_KEY:
5052 	case PTR_TO_ARENA:
5053 		return true;
5054 	default:
5055 		return false;
5056 	}
5057 }
5058 
5059 /* Does this register contain a constant zero? */
5060 static bool register_is_null(struct bpf_reg_state *reg)
5061 {
5062 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
5063 }
5064 
5065 /* check if register is a constant scalar value */
5066 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
5067 {
5068 	return reg->type == SCALAR_VALUE &&
5069 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
5070 }
5071 
5072 /* assuming is_reg_const() is true, return constant value of a register */
5073 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
5074 {
5075 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
5076 }
5077 
5078 static bool __is_pointer_value(bool allow_ptr_leaks,
5079 			       const struct bpf_reg_state *reg)
5080 {
5081 	if (allow_ptr_leaks)
5082 		return false;
5083 
5084 	return reg->type != SCALAR_VALUE;
5085 }
5086 
5087 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
5088 					struct bpf_reg_state *src_reg)
5089 {
5090 	if (src_reg->type != SCALAR_VALUE)
5091 		return;
5092 
5093 	if (src_reg->id & BPF_ADD_CONST) {
5094 		/*
5095 		 * The verifier is processing rX = rY insn and
5096 		 * rY->id has special linked register already.
5097 		 * Cleared it, since multiple rX += const are not supported.
5098 		 */
5099 		src_reg->id = 0;
5100 		src_reg->off = 0;
5101 	}
5102 
5103 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
5104 		/* Ensure that src_reg has a valid ID that will be copied to
5105 		 * dst_reg and then will be used by sync_linked_regs() to
5106 		 * propagate min/max range.
5107 		 */
5108 		src_reg->id = ++env->id_gen;
5109 }
5110 
5111 /* Copy src state preserving dst->parent and dst->live fields */
5112 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
5113 {
5114 	*dst = *src;
5115 }
5116 
5117 static void save_register_state(struct bpf_verifier_env *env,
5118 				struct bpf_func_state *state,
5119 				int spi, struct bpf_reg_state *reg,
5120 				int size)
5121 {
5122 	int i;
5123 
5124 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
5125 
5126 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
5127 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
5128 
5129 	/* size < 8 bytes spill */
5130 	for (; i; i--)
5131 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
5132 }
5133 
5134 static bool is_bpf_st_mem(struct bpf_insn *insn)
5135 {
5136 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
5137 }
5138 
5139 static int get_reg_width(struct bpf_reg_state *reg)
5140 {
5141 	return fls64(reg->umax_value);
5142 }
5143 
5144 /* See comment for mark_fastcall_pattern_for_call() */
5145 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
5146 					  struct bpf_func_state *state, int insn_idx, int off)
5147 {
5148 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
5149 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
5150 	int i;
5151 
5152 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
5153 		return;
5154 	/* access to the region [max_stack_depth .. fastcall_stack_off)
5155 	 * from something that is not a part of the fastcall pattern,
5156 	 * disable fastcall rewrites for current subprogram by setting
5157 	 * fastcall_stack_off to a value smaller than any possible offset.
5158 	 */
5159 	subprog->fastcall_stack_off = S16_MIN;
5160 	/* reset fastcall aux flags within subprogram,
5161 	 * happens at most once per subprogram
5162 	 */
5163 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
5164 		aux[i].fastcall_spills_num = 0;
5165 		aux[i].fastcall_pattern = 0;
5166 	}
5167 }
5168 
5169 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
5170  * stack boundary and alignment are checked in check_mem_access()
5171  */
5172 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
5173 				       /* stack frame we're writing to */
5174 				       struct bpf_func_state *state,
5175 				       int off, int size, int value_regno,
5176 				       int insn_idx)
5177 {
5178 	struct bpf_func_state *cur; /* state of the current function */
5179 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
5180 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5181 	struct bpf_reg_state *reg = NULL;
5182 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
5183 
5184 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
5185 	 * so it's aligned access and [off, off + size) are within stack limits
5186 	 */
5187 	if (!env->allow_ptr_leaks &&
5188 	    is_spilled_reg(&state->stack[spi]) &&
5189 	    !is_spilled_scalar_reg(&state->stack[spi]) &&
5190 	    size != BPF_REG_SIZE) {
5191 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
5192 		return -EACCES;
5193 	}
5194 
5195 	cur = env->cur_state->frame[env->cur_state->curframe];
5196 	if (value_regno >= 0)
5197 		reg = &cur->regs[value_regno];
5198 	if (!env->bypass_spec_v4) {
5199 		bool sanitize = reg && is_spillable_regtype(reg->type);
5200 
5201 		for (i = 0; i < size; i++) {
5202 			u8 type = state->stack[spi].slot_type[i];
5203 
5204 			if (type != STACK_MISC && type != STACK_ZERO) {
5205 				sanitize = true;
5206 				break;
5207 			}
5208 		}
5209 
5210 		if (sanitize)
5211 			env->insn_aux_data[insn_idx].nospec_result = true;
5212 	}
5213 
5214 	err = destroy_if_dynptr_stack_slot(env, state, spi);
5215 	if (err)
5216 		return err;
5217 
5218 	if (!(off % BPF_REG_SIZE) && size == BPF_REG_SIZE) {
5219 		/* only mark the slot as written if all 8 bytes were written
5220 		 * otherwise read propagation may incorrectly stop too soon
5221 		 * when stack slots are partially written.
5222 		 * This heuristic means that read propagation will be
5223 		 * conservative, since it will add reg_live_read marks
5224 		 * to stack slots all the way to first state when programs
5225 		 * writes+reads less than 8 bytes
5226 		 */
5227 		bpf_mark_stack_write(env, state->frameno, BIT(spi));
5228 	}
5229 
5230 	check_fastcall_stack_contract(env, state, insn_idx, off);
5231 	mark_stack_slot_scratched(env, spi);
5232 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
5233 		bool reg_value_fits;
5234 
5235 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
5236 		/* Make sure that reg had an ID to build a relation on spill. */
5237 		if (reg_value_fits)
5238 			assign_scalar_id_before_mov(env, reg);
5239 		save_register_state(env, state, spi, reg, size);
5240 		/* Break the relation on a narrowing spill. */
5241 		if (!reg_value_fits)
5242 			state->stack[spi].spilled_ptr.id = 0;
5243 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
5244 		   env->bpf_capable) {
5245 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
5246 
5247 		memset(tmp_reg, 0, sizeof(*tmp_reg));
5248 		__mark_reg_known(tmp_reg, insn->imm);
5249 		tmp_reg->type = SCALAR_VALUE;
5250 		save_register_state(env, state, spi, tmp_reg, size);
5251 	} else if (reg && is_spillable_regtype(reg->type)) {
5252 		/* register containing pointer is being spilled into stack */
5253 		if (size != BPF_REG_SIZE) {
5254 			verbose_linfo(env, insn_idx, "; ");
5255 			verbose(env, "invalid size of register spill\n");
5256 			return -EACCES;
5257 		}
5258 		if (state != cur && reg->type == PTR_TO_STACK) {
5259 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
5260 			return -EINVAL;
5261 		}
5262 		save_register_state(env, state, spi, reg, size);
5263 	} else {
5264 		u8 type = STACK_MISC;
5265 
5266 		/* regular write of data into stack destroys any spilled ptr */
5267 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5268 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
5269 		if (is_stack_slot_special(&state->stack[spi]))
5270 			for (i = 0; i < BPF_REG_SIZE; i++)
5271 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
5272 
5273 		/* when we zero initialize stack slots mark them as such */
5274 		if ((reg && register_is_null(reg)) ||
5275 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
5276 			/* STACK_ZERO case happened because register spill
5277 			 * wasn't properly aligned at the stack slot boundary,
5278 			 * so it's not a register spill anymore; force
5279 			 * originating register to be precise to make
5280 			 * STACK_ZERO correct for subsequent states
5281 			 */
5282 			err = mark_chain_precision(env, value_regno);
5283 			if (err)
5284 				return err;
5285 			type = STACK_ZERO;
5286 		}
5287 
5288 		/* Mark slots affected by this stack write. */
5289 		for (i = 0; i < size; i++)
5290 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
5291 		insn_flags = 0; /* not a register spill */
5292 	}
5293 
5294 	if (insn_flags)
5295 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5296 	return 0;
5297 }
5298 
5299 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
5300  * known to contain a variable offset.
5301  * This function checks whether the write is permitted and conservatively
5302  * tracks the effects of the write, considering that each stack slot in the
5303  * dynamic range is potentially written to.
5304  *
5305  * 'off' includes 'regno->off'.
5306  * 'value_regno' can be -1, meaning that an unknown value is being written to
5307  * the stack.
5308  *
5309  * Spilled pointers in range are not marked as written because we don't know
5310  * what's going to be actually written. This means that read propagation for
5311  * future reads cannot be terminated by this write.
5312  *
5313  * For privileged programs, uninitialized stack slots are considered
5314  * initialized by this write (even though we don't know exactly what offsets
5315  * are going to be written to). The idea is that we don't want the verifier to
5316  * reject future reads that access slots written to through variable offsets.
5317  */
5318 static int check_stack_write_var_off(struct bpf_verifier_env *env,
5319 				     /* func where register points to */
5320 				     struct bpf_func_state *state,
5321 				     int ptr_regno, int off, int size,
5322 				     int value_regno, int insn_idx)
5323 {
5324 	struct bpf_func_state *cur; /* state of the current function */
5325 	int min_off, max_off;
5326 	int i, err;
5327 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
5328 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5329 	bool writing_zero = false;
5330 	/* set if the fact that we're writing a zero is used to let any
5331 	 * stack slots remain STACK_ZERO
5332 	 */
5333 	bool zero_used = false;
5334 
5335 	cur = env->cur_state->frame[env->cur_state->curframe];
5336 	ptr_reg = &cur->regs[ptr_regno];
5337 	min_off = ptr_reg->smin_value + off;
5338 	max_off = ptr_reg->smax_value + off + size;
5339 	if (value_regno >= 0)
5340 		value_reg = &cur->regs[value_regno];
5341 	if ((value_reg && register_is_null(value_reg)) ||
5342 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
5343 		writing_zero = true;
5344 
5345 	for (i = min_off; i < max_off; i++) {
5346 		int spi;
5347 
5348 		spi = __get_spi(i);
5349 		err = destroy_if_dynptr_stack_slot(env, state, spi);
5350 		if (err)
5351 			return err;
5352 	}
5353 
5354 	check_fastcall_stack_contract(env, state, insn_idx, min_off);
5355 	/* Variable offset writes destroy any spilled pointers in range. */
5356 	for (i = min_off; i < max_off; i++) {
5357 		u8 new_type, *stype;
5358 		int slot, spi;
5359 
5360 		slot = -i - 1;
5361 		spi = slot / BPF_REG_SIZE;
5362 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5363 		mark_stack_slot_scratched(env, spi);
5364 
5365 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
5366 			/* Reject the write if range we may write to has not
5367 			 * been initialized beforehand. If we didn't reject
5368 			 * here, the ptr status would be erased below (even
5369 			 * though not all slots are actually overwritten),
5370 			 * possibly opening the door to leaks.
5371 			 *
5372 			 * We do however catch STACK_INVALID case below, and
5373 			 * only allow reading possibly uninitialized memory
5374 			 * later for CAP_PERFMON, as the write may not happen to
5375 			 * that slot.
5376 			 */
5377 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
5378 				insn_idx, i);
5379 			return -EINVAL;
5380 		}
5381 
5382 		/* If writing_zero and the spi slot contains a spill of value 0,
5383 		 * maintain the spill type.
5384 		 */
5385 		if (writing_zero && *stype == STACK_SPILL &&
5386 		    is_spilled_scalar_reg(&state->stack[spi])) {
5387 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
5388 
5389 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
5390 				zero_used = true;
5391 				continue;
5392 			}
5393 		}
5394 
5395 		/* Erase all other spilled pointers. */
5396 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5397 
5398 		/* Update the slot type. */
5399 		new_type = STACK_MISC;
5400 		if (writing_zero && *stype == STACK_ZERO) {
5401 			new_type = STACK_ZERO;
5402 			zero_used = true;
5403 		}
5404 		/* If the slot is STACK_INVALID, we check whether it's OK to
5405 		 * pretend that it will be initialized by this write. The slot
5406 		 * might not actually be written to, and so if we mark it as
5407 		 * initialized future reads might leak uninitialized memory.
5408 		 * For privileged programs, we will accept such reads to slots
5409 		 * that may or may not be written because, if we're reject
5410 		 * them, the error would be too confusing.
5411 		 */
5412 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
5413 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
5414 					insn_idx, i);
5415 			return -EINVAL;
5416 		}
5417 		*stype = new_type;
5418 	}
5419 	if (zero_used) {
5420 		/* backtracking doesn't work for STACK_ZERO yet. */
5421 		err = mark_chain_precision(env, value_regno);
5422 		if (err)
5423 			return err;
5424 	}
5425 	return 0;
5426 }
5427 
5428 /* When register 'dst_regno' is assigned some values from stack[min_off,
5429  * max_off), we set the register's type according to the types of the
5430  * respective stack slots. If all the stack values are known to be zeros, then
5431  * so is the destination reg. Otherwise, the register is considered to be
5432  * SCALAR. This function does not deal with register filling; the caller must
5433  * ensure that all spilled registers in the stack range have been marked as
5434  * read.
5435  */
5436 static void mark_reg_stack_read(struct bpf_verifier_env *env,
5437 				/* func where src register points to */
5438 				struct bpf_func_state *ptr_state,
5439 				int min_off, int max_off, int dst_regno)
5440 {
5441 	struct bpf_verifier_state *vstate = env->cur_state;
5442 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5443 	int i, slot, spi;
5444 	u8 *stype;
5445 	int zeros = 0;
5446 
5447 	for (i = min_off; i < max_off; i++) {
5448 		slot = -i - 1;
5449 		spi = slot / BPF_REG_SIZE;
5450 		mark_stack_slot_scratched(env, spi);
5451 		stype = ptr_state->stack[spi].slot_type;
5452 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
5453 			break;
5454 		zeros++;
5455 	}
5456 	if (zeros == max_off - min_off) {
5457 		/* Any access_size read into register is zero extended,
5458 		 * so the whole register == const_zero.
5459 		 */
5460 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
5461 	} else {
5462 		/* have read misc data from the stack */
5463 		mark_reg_unknown(env, state->regs, dst_regno);
5464 	}
5465 }
5466 
5467 /* Read the stack at 'off' and put the results into the register indicated by
5468  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
5469  * spilled reg.
5470  *
5471  * 'dst_regno' can be -1, meaning that the read value is not going to a
5472  * register.
5473  *
5474  * The access is assumed to be within the current stack bounds.
5475  */
5476 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
5477 				      /* func where src register points to */
5478 				      struct bpf_func_state *reg_state,
5479 				      int off, int size, int dst_regno)
5480 {
5481 	struct bpf_verifier_state *vstate = env->cur_state;
5482 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5483 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
5484 	struct bpf_reg_state *reg;
5485 	u8 *stype, type;
5486 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
5487 	int err;
5488 
5489 	stype = reg_state->stack[spi].slot_type;
5490 	reg = &reg_state->stack[spi].spilled_ptr;
5491 
5492 	mark_stack_slot_scratched(env, spi);
5493 	check_fastcall_stack_contract(env, state, env->insn_idx, off);
5494 	err = bpf_mark_stack_read(env, reg_state->frameno, env->insn_idx, BIT(spi));
5495 	if (err)
5496 		return err;
5497 
5498 	if (is_spilled_reg(&reg_state->stack[spi])) {
5499 		u8 spill_size = 1;
5500 
5501 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
5502 			spill_size++;
5503 
5504 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
5505 			if (reg->type != SCALAR_VALUE) {
5506 				verbose_linfo(env, env->insn_idx, "; ");
5507 				verbose(env, "invalid size of register fill\n");
5508 				return -EACCES;
5509 			}
5510 
5511 			if (dst_regno < 0)
5512 				return 0;
5513 
5514 			if (size <= spill_size &&
5515 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
5516 				/* The earlier check_reg_arg() has decided the
5517 				 * subreg_def for this insn.  Save it first.
5518 				 */
5519 				s32 subreg_def = state->regs[dst_regno].subreg_def;
5520 
5521 				if (env->bpf_capable && size == 4 && spill_size == 4 &&
5522 				    get_reg_width(reg) <= 32)
5523 					/* Ensure stack slot has an ID to build a relation
5524 					 * with the destination register on fill.
5525 					 */
5526 					assign_scalar_id_before_mov(env, reg);
5527 				copy_register_state(&state->regs[dst_regno], reg);
5528 				state->regs[dst_regno].subreg_def = subreg_def;
5529 
5530 				/* Break the relation on a narrowing fill.
5531 				 * coerce_reg_to_size will adjust the boundaries.
5532 				 */
5533 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
5534 					state->regs[dst_regno].id = 0;
5535 			} else {
5536 				int spill_cnt = 0, zero_cnt = 0;
5537 
5538 				for (i = 0; i < size; i++) {
5539 					type = stype[(slot - i) % BPF_REG_SIZE];
5540 					if (type == STACK_SPILL) {
5541 						spill_cnt++;
5542 						continue;
5543 					}
5544 					if (type == STACK_MISC)
5545 						continue;
5546 					if (type == STACK_ZERO) {
5547 						zero_cnt++;
5548 						continue;
5549 					}
5550 					if (type == STACK_INVALID && env->allow_uninit_stack)
5551 						continue;
5552 					verbose(env, "invalid read from stack off %d+%d size %d\n",
5553 						off, i, size);
5554 					return -EACCES;
5555 				}
5556 
5557 				if (spill_cnt == size &&
5558 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
5559 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5560 					/* this IS register fill, so keep insn_flags */
5561 				} else if (zero_cnt == size) {
5562 					/* similarly to mark_reg_stack_read(), preserve zeroes */
5563 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5564 					insn_flags = 0; /* not restoring original register state */
5565 				} else {
5566 					mark_reg_unknown(env, state->regs, dst_regno);
5567 					insn_flags = 0; /* not restoring original register state */
5568 				}
5569 			}
5570 		} else if (dst_regno >= 0) {
5571 			/* restore register state from stack */
5572 			if (env->bpf_capable)
5573 				/* Ensure stack slot has an ID to build a relation
5574 				 * with the destination register on fill.
5575 				 */
5576 				assign_scalar_id_before_mov(env, reg);
5577 			copy_register_state(&state->regs[dst_regno], reg);
5578 			/* mark reg as written since spilled pointer state likely
5579 			 * has its liveness marks cleared by is_state_visited()
5580 			 * which resets stack/reg liveness for state transitions
5581 			 */
5582 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
5583 			/* If dst_regno==-1, the caller is asking us whether
5584 			 * it is acceptable to use this value as a SCALAR_VALUE
5585 			 * (e.g. for XADD).
5586 			 * We must not allow unprivileged callers to do that
5587 			 * with spilled pointers.
5588 			 */
5589 			verbose(env, "leaking pointer from stack off %d\n",
5590 				off);
5591 			return -EACCES;
5592 		}
5593 	} else {
5594 		for (i = 0; i < size; i++) {
5595 			type = stype[(slot - i) % BPF_REG_SIZE];
5596 			if (type == STACK_MISC)
5597 				continue;
5598 			if (type == STACK_ZERO)
5599 				continue;
5600 			if (type == STACK_INVALID && env->allow_uninit_stack)
5601 				continue;
5602 			verbose(env, "invalid read from stack off %d+%d size %d\n",
5603 				off, i, size);
5604 			return -EACCES;
5605 		}
5606 		if (dst_regno >= 0)
5607 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
5608 		insn_flags = 0; /* we are not restoring spilled register */
5609 	}
5610 	if (insn_flags)
5611 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5612 	return 0;
5613 }
5614 
5615 enum bpf_access_src {
5616 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
5617 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
5618 };
5619 
5620 static int check_stack_range_initialized(struct bpf_verifier_env *env,
5621 					 int regno, int off, int access_size,
5622 					 bool zero_size_allowed,
5623 					 enum bpf_access_type type,
5624 					 struct bpf_call_arg_meta *meta);
5625 
5626 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5627 {
5628 	return cur_regs(env) + regno;
5629 }
5630 
5631 /* Read the stack at 'ptr_regno + off' and put the result into the register
5632  * 'dst_regno'.
5633  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5634  * but not its variable offset.
5635  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5636  *
5637  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5638  * filling registers (i.e. reads of spilled register cannot be detected when
5639  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5640  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5641  * offset; for a fixed offset check_stack_read_fixed_off should be used
5642  * instead.
5643  */
5644 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5645 				    int ptr_regno, int off, int size, int dst_regno)
5646 {
5647 	/* The state of the source register. */
5648 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5649 	struct bpf_func_state *ptr_state = func(env, reg);
5650 	int err;
5651 	int min_off, max_off;
5652 
5653 	/* Note that we pass a NULL meta, so raw access will not be permitted.
5654 	 */
5655 	err = check_stack_range_initialized(env, ptr_regno, off, size,
5656 					    false, BPF_READ, NULL);
5657 	if (err)
5658 		return err;
5659 
5660 	min_off = reg->smin_value + off;
5661 	max_off = reg->smax_value + off;
5662 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5663 	check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
5664 	return 0;
5665 }
5666 
5667 /* check_stack_read dispatches to check_stack_read_fixed_off or
5668  * check_stack_read_var_off.
5669  *
5670  * The caller must ensure that the offset falls within the allocated stack
5671  * bounds.
5672  *
5673  * 'dst_regno' is a register which will receive the value from the stack. It
5674  * can be -1, meaning that the read value is not going to a register.
5675  */
5676 static int check_stack_read(struct bpf_verifier_env *env,
5677 			    int ptr_regno, int off, int size,
5678 			    int dst_regno)
5679 {
5680 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5681 	struct bpf_func_state *state = func(env, reg);
5682 	int err;
5683 	/* Some accesses are only permitted with a static offset. */
5684 	bool var_off = !tnum_is_const(reg->var_off);
5685 
5686 	/* The offset is required to be static when reads don't go to a
5687 	 * register, in order to not leak pointers (see
5688 	 * check_stack_read_fixed_off).
5689 	 */
5690 	if (dst_regno < 0 && var_off) {
5691 		char tn_buf[48];
5692 
5693 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5694 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5695 			tn_buf, off, size);
5696 		return -EACCES;
5697 	}
5698 	/* Variable offset is prohibited for unprivileged mode for simplicity
5699 	 * since it requires corresponding support in Spectre masking for stack
5700 	 * ALU. See also retrieve_ptr_limit(). The check in
5701 	 * check_stack_access_for_ptr_arithmetic() called by
5702 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5703 	 * with variable offsets, therefore no check is required here. Further,
5704 	 * just checking it here would be insufficient as speculative stack
5705 	 * writes could still lead to unsafe speculative behaviour.
5706 	 */
5707 	if (!var_off) {
5708 		off += reg->var_off.value;
5709 		err = check_stack_read_fixed_off(env, state, off, size,
5710 						 dst_regno);
5711 	} else {
5712 		/* Variable offset stack reads need more conservative handling
5713 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5714 		 * branch.
5715 		 */
5716 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5717 					       dst_regno);
5718 	}
5719 	return err;
5720 }
5721 
5722 
5723 /* check_stack_write dispatches to check_stack_write_fixed_off or
5724  * check_stack_write_var_off.
5725  *
5726  * 'ptr_regno' is the register used as a pointer into the stack.
5727  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5728  * 'value_regno' is the register whose value we're writing to the stack. It can
5729  * be -1, meaning that we're not writing from a register.
5730  *
5731  * The caller must ensure that the offset falls within the maximum stack size.
5732  */
5733 static int check_stack_write(struct bpf_verifier_env *env,
5734 			     int ptr_regno, int off, int size,
5735 			     int value_regno, int insn_idx)
5736 {
5737 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5738 	struct bpf_func_state *state = func(env, reg);
5739 	int err;
5740 
5741 	if (tnum_is_const(reg->var_off)) {
5742 		off += reg->var_off.value;
5743 		err = check_stack_write_fixed_off(env, state, off, size,
5744 						  value_regno, insn_idx);
5745 	} else {
5746 		/* Variable offset stack reads need more conservative handling
5747 		 * than fixed offset ones.
5748 		 */
5749 		err = check_stack_write_var_off(env, state,
5750 						ptr_regno, off, size,
5751 						value_regno, insn_idx);
5752 	}
5753 	return err;
5754 }
5755 
5756 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5757 				 int off, int size, enum bpf_access_type type)
5758 {
5759 	struct bpf_reg_state *reg = reg_state(env, regno);
5760 	struct bpf_map *map = reg->map_ptr;
5761 	u32 cap = bpf_map_flags_to_cap(map);
5762 
5763 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5764 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5765 			map->value_size, off, size);
5766 		return -EACCES;
5767 	}
5768 
5769 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5770 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5771 			map->value_size, off, size);
5772 		return -EACCES;
5773 	}
5774 
5775 	return 0;
5776 }
5777 
5778 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5779 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5780 			      int off, int size, u32 mem_size,
5781 			      bool zero_size_allowed)
5782 {
5783 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5784 	struct bpf_reg_state *reg;
5785 
5786 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5787 		return 0;
5788 
5789 	reg = &cur_regs(env)[regno];
5790 	switch (reg->type) {
5791 	case PTR_TO_MAP_KEY:
5792 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5793 			mem_size, off, size);
5794 		break;
5795 	case PTR_TO_MAP_VALUE:
5796 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5797 			mem_size, off, size);
5798 		break;
5799 	case PTR_TO_PACKET:
5800 	case PTR_TO_PACKET_META:
5801 	case PTR_TO_PACKET_END:
5802 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5803 			off, size, regno, reg->id, off, mem_size);
5804 		break;
5805 	case PTR_TO_MEM:
5806 	default:
5807 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5808 			mem_size, off, size);
5809 	}
5810 
5811 	return -EACCES;
5812 }
5813 
5814 /* check read/write into a memory region with possible variable offset */
5815 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5816 				   int off, int size, u32 mem_size,
5817 				   bool zero_size_allowed)
5818 {
5819 	struct bpf_verifier_state *vstate = env->cur_state;
5820 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5821 	struct bpf_reg_state *reg = &state->regs[regno];
5822 	int err;
5823 
5824 	/* We may have adjusted the register pointing to memory region, so we
5825 	 * need to try adding each of min_value and max_value to off
5826 	 * to make sure our theoretical access will be safe.
5827 	 *
5828 	 * The minimum value is only important with signed
5829 	 * comparisons where we can't assume the floor of a
5830 	 * value is 0.  If we are using signed variables for our
5831 	 * index'es we need to make sure that whatever we use
5832 	 * will have a set floor within our range.
5833 	 */
5834 	if (reg->smin_value < 0 &&
5835 	    (reg->smin_value == S64_MIN ||
5836 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5837 	      reg->smin_value + off < 0)) {
5838 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5839 			regno);
5840 		return -EACCES;
5841 	}
5842 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5843 				 mem_size, zero_size_allowed);
5844 	if (err) {
5845 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5846 			regno);
5847 		return err;
5848 	}
5849 
5850 	/* If we haven't set a max value then we need to bail since we can't be
5851 	 * sure we won't do bad things.
5852 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5853 	 */
5854 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5855 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5856 			regno);
5857 		return -EACCES;
5858 	}
5859 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5860 				 mem_size, zero_size_allowed);
5861 	if (err) {
5862 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5863 			regno);
5864 		return err;
5865 	}
5866 
5867 	return 0;
5868 }
5869 
5870 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5871 			       const struct bpf_reg_state *reg, int regno,
5872 			       bool fixed_off_ok)
5873 {
5874 	/* Access to this pointer-typed register or passing it to a helper
5875 	 * is only allowed in its original, unmodified form.
5876 	 */
5877 
5878 	if (reg->off < 0) {
5879 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5880 			reg_type_str(env, reg->type), regno, reg->off);
5881 		return -EACCES;
5882 	}
5883 
5884 	if (!fixed_off_ok && reg->off) {
5885 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5886 			reg_type_str(env, reg->type), regno, reg->off);
5887 		return -EACCES;
5888 	}
5889 
5890 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5891 		char tn_buf[48];
5892 
5893 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5894 		verbose(env, "variable %s access var_off=%s disallowed\n",
5895 			reg_type_str(env, reg->type), tn_buf);
5896 		return -EACCES;
5897 	}
5898 
5899 	return 0;
5900 }
5901 
5902 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5903 		             const struct bpf_reg_state *reg, int regno)
5904 {
5905 	return __check_ptr_off_reg(env, reg, regno, false);
5906 }
5907 
5908 static int map_kptr_match_type(struct bpf_verifier_env *env,
5909 			       struct btf_field *kptr_field,
5910 			       struct bpf_reg_state *reg, u32 regno)
5911 {
5912 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5913 	int perm_flags;
5914 	const char *reg_name = "";
5915 
5916 	if (btf_is_kernel(reg->btf)) {
5917 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5918 
5919 		/* Only unreferenced case accepts untrusted pointers */
5920 		if (kptr_field->type == BPF_KPTR_UNREF)
5921 			perm_flags |= PTR_UNTRUSTED;
5922 	} else {
5923 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5924 		if (kptr_field->type == BPF_KPTR_PERCPU)
5925 			perm_flags |= MEM_PERCPU;
5926 	}
5927 
5928 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5929 		goto bad_type;
5930 
5931 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5932 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5933 
5934 	/* For ref_ptr case, release function check should ensure we get one
5935 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5936 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5937 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5938 	 * reg->off and reg->ref_obj_id are not needed here.
5939 	 */
5940 	if (__check_ptr_off_reg(env, reg, regno, true))
5941 		return -EACCES;
5942 
5943 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5944 	 * we also need to take into account the reg->off.
5945 	 *
5946 	 * We want to support cases like:
5947 	 *
5948 	 * struct foo {
5949 	 *         struct bar br;
5950 	 *         struct baz bz;
5951 	 * };
5952 	 *
5953 	 * struct foo *v;
5954 	 * v = func();	      // PTR_TO_BTF_ID
5955 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5956 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5957 	 *                    // first member type of struct after comparison fails
5958 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5959 	 *                    // to match type
5960 	 *
5961 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5962 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5963 	 * the struct to match type against first member of struct, i.e. reject
5964 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5965 	 * strict mode to true for type match.
5966 	 */
5967 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5968 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5969 				  kptr_field->type != BPF_KPTR_UNREF))
5970 		goto bad_type;
5971 	return 0;
5972 bad_type:
5973 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5974 		reg_type_str(env, reg->type), reg_name);
5975 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5976 	if (kptr_field->type == BPF_KPTR_UNREF)
5977 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5978 			targ_name);
5979 	else
5980 		verbose(env, "\n");
5981 	return -EINVAL;
5982 }
5983 
5984 static bool in_sleepable(struct bpf_verifier_env *env)
5985 {
5986 	return env->cur_state->in_sleepable;
5987 }
5988 
5989 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5990  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5991  */
5992 static bool in_rcu_cs(struct bpf_verifier_env *env)
5993 {
5994 	return env->cur_state->active_rcu_locks ||
5995 	       env->cur_state->active_locks ||
5996 	       !in_sleepable(env);
5997 }
5998 
5999 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
6000 BTF_SET_START(rcu_protected_types)
6001 #ifdef CONFIG_NET
6002 BTF_ID(struct, prog_test_ref_kfunc)
6003 #endif
6004 #ifdef CONFIG_CGROUPS
6005 BTF_ID(struct, cgroup)
6006 #endif
6007 #ifdef CONFIG_BPF_JIT
6008 BTF_ID(struct, bpf_cpumask)
6009 #endif
6010 BTF_ID(struct, task_struct)
6011 #ifdef CONFIG_CRYPTO
6012 BTF_ID(struct, bpf_crypto_ctx)
6013 #endif
6014 BTF_SET_END(rcu_protected_types)
6015 
6016 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
6017 {
6018 	if (!btf_is_kernel(btf))
6019 		return true;
6020 	return btf_id_set_contains(&rcu_protected_types, btf_id);
6021 }
6022 
6023 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
6024 {
6025 	struct btf_struct_meta *meta;
6026 
6027 	if (btf_is_kernel(kptr_field->kptr.btf))
6028 		return NULL;
6029 
6030 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
6031 				    kptr_field->kptr.btf_id);
6032 
6033 	return meta ? meta->record : NULL;
6034 }
6035 
6036 static bool rcu_safe_kptr(const struct btf_field *field)
6037 {
6038 	const struct btf_field_kptr *kptr = &field->kptr;
6039 
6040 	return field->type == BPF_KPTR_PERCPU ||
6041 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
6042 }
6043 
6044 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
6045 {
6046 	struct btf_record *rec;
6047 	u32 ret;
6048 
6049 	ret = PTR_MAYBE_NULL;
6050 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
6051 		ret |= MEM_RCU;
6052 		if (kptr_field->type == BPF_KPTR_PERCPU)
6053 			ret |= MEM_PERCPU;
6054 		else if (!btf_is_kernel(kptr_field->kptr.btf))
6055 			ret |= MEM_ALLOC;
6056 
6057 		rec = kptr_pointee_btf_record(kptr_field);
6058 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
6059 			ret |= NON_OWN_REF;
6060 	} else {
6061 		ret |= PTR_UNTRUSTED;
6062 	}
6063 
6064 	return ret;
6065 }
6066 
6067 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
6068 			    struct btf_field *field)
6069 {
6070 	struct bpf_reg_state *reg;
6071 	const struct btf_type *t;
6072 
6073 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
6074 	mark_reg_known_zero(env, cur_regs(env), regno);
6075 	reg = reg_state(env, regno);
6076 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
6077 	reg->mem_size = t->size;
6078 	reg->id = ++env->id_gen;
6079 
6080 	return 0;
6081 }
6082 
6083 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
6084 				 int value_regno, int insn_idx,
6085 				 struct btf_field *kptr_field)
6086 {
6087 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
6088 	int class = BPF_CLASS(insn->code);
6089 	struct bpf_reg_state *val_reg;
6090 	int ret;
6091 
6092 	/* Things we already checked for in check_map_access and caller:
6093 	 *  - Reject cases where variable offset may touch kptr
6094 	 *  - size of access (must be BPF_DW)
6095 	 *  - tnum_is_const(reg->var_off)
6096 	 *  - kptr_field->offset == off + reg->var_off.value
6097 	 */
6098 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
6099 	if (BPF_MODE(insn->code) != BPF_MEM) {
6100 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
6101 		return -EACCES;
6102 	}
6103 
6104 	/* We only allow loading referenced kptr, since it will be marked as
6105 	 * untrusted, similar to unreferenced kptr.
6106 	 */
6107 	if (class != BPF_LDX &&
6108 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
6109 		verbose(env, "store to referenced kptr disallowed\n");
6110 		return -EACCES;
6111 	}
6112 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
6113 		verbose(env, "store to uptr disallowed\n");
6114 		return -EACCES;
6115 	}
6116 
6117 	if (class == BPF_LDX) {
6118 		if (kptr_field->type == BPF_UPTR)
6119 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
6120 
6121 		/* We can simply mark the value_regno receiving the pointer
6122 		 * value from map as PTR_TO_BTF_ID, with the correct type.
6123 		 */
6124 		ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID,
6125 				      kptr_field->kptr.btf, kptr_field->kptr.btf_id,
6126 				      btf_ld_kptr_type(env, kptr_field));
6127 		if (ret < 0)
6128 			return ret;
6129 	} else if (class == BPF_STX) {
6130 		val_reg = reg_state(env, value_regno);
6131 		if (!register_is_null(val_reg) &&
6132 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
6133 			return -EACCES;
6134 	} else if (class == BPF_ST) {
6135 		if (insn->imm) {
6136 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
6137 				kptr_field->offset);
6138 			return -EACCES;
6139 		}
6140 	} else {
6141 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
6142 		return -EACCES;
6143 	}
6144 	return 0;
6145 }
6146 
6147 /*
6148  * Return the size of the memory region accessible from a pointer to map value.
6149  * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible.
6150  */
6151 static u32 map_mem_size(const struct bpf_map *map)
6152 {
6153 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY)
6154 		return map->max_entries * sizeof(long);
6155 
6156 	return map->value_size;
6157 }
6158 
6159 /* check read/write into a map element with possible variable offset */
6160 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
6161 			    int off, int size, bool zero_size_allowed,
6162 			    enum bpf_access_src src)
6163 {
6164 	struct bpf_verifier_state *vstate = env->cur_state;
6165 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6166 	struct bpf_reg_state *reg = &state->regs[regno];
6167 	struct bpf_map *map = reg->map_ptr;
6168 	u32 mem_size = map_mem_size(map);
6169 	struct btf_record *rec;
6170 	int err, i;
6171 
6172 	err = check_mem_region_access(env, regno, off, size, mem_size, zero_size_allowed);
6173 	if (err)
6174 		return err;
6175 
6176 	if (IS_ERR_OR_NULL(map->record))
6177 		return 0;
6178 	rec = map->record;
6179 	for (i = 0; i < rec->cnt; i++) {
6180 		struct btf_field *field = &rec->fields[i];
6181 		u32 p = field->offset;
6182 
6183 		/* If any part of a field  can be touched by load/store, reject
6184 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
6185 		 * it is sufficient to check x1 < y2 && y1 < x2.
6186 		 */
6187 		if (reg->smin_value + off < p + field->size &&
6188 		    p < reg->umax_value + off + size) {
6189 			switch (field->type) {
6190 			case BPF_KPTR_UNREF:
6191 			case BPF_KPTR_REF:
6192 			case BPF_KPTR_PERCPU:
6193 			case BPF_UPTR:
6194 				if (src != ACCESS_DIRECT) {
6195 					verbose(env, "%s cannot be accessed indirectly by helper\n",
6196 						btf_field_type_name(field->type));
6197 					return -EACCES;
6198 				}
6199 				if (!tnum_is_const(reg->var_off)) {
6200 					verbose(env, "%s access cannot have variable offset\n",
6201 						btf_field_type_name(field->type));
6202 					return -EACCES;
6203 				}
6204 				if (p != off + reg->var_off.value) {
6205 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
6206 						btf_field_type_name(field->type),
6207 						p, off + reg->var_off.value);
6208 					return -EACCES;
6209 				}
6210 				if (size != bpf_size_to_bytes(BPF_DW)) {
6211 					verbose(env, "%s access size must be BPF_DW\n",
6212 						btf_field_type_name(field->type));
6213 					return -EACCES;
6214 				}
6215 				break;
6216 			default:
6217 				verbose(env, "%s cannot be accessed directly by load/store\n",
6218 					btf_field_type_name(field->type));
6219 				return -EACCES;
6220 			}
6221 		}
6222 	}
6223 	return 0;
6224 }
6225 
6226 #define MAX_PACKET_OFF 0xffff
6227 
6228 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
6229 				       const struct bpf_call_arg_meta *meta,
6230 				       enum bpf_access_type t)
6231 {
6232 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
6233 
6234 	switch (prog_type) {
6235 	/* Program types only with direct read access go here! */
6236 	case BPF_PROG_TYPE_LWT_IN:
6237 	case BPF_PROG_TYPE_LWT_OUT:
6238 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
6239 	case BPF_PROG_TYPE_SK_REUSEPORT:
6240 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6241 	case BPF_PROG_TYPE_CGROUP_SKB:
6242 		if (t == BPF_WRITE)
6243 			return false;
6244 		fallthrough;
6245 
6246 	/* Program types with direct read + write access go here! */
6247 	case BPF_PROG_TYPE_SCHED_CLS:
6248 	case BPF_PROG_TYPE_SCHED_ACT:
6249 	case BPF_PROG_TYPE_XDP:
6250 	case BPF_PROG_TYPE_LWT_XMIT:
6251 	case BPF_PROG_TYPE_SK_SKB:
6252 	case BPF_PROG_TYPE_SK_MSG:
6253 		if (meta)
6254 			return meta->pkt_access;
6255 
6256 		env->seen_direct_write = true;
6257 		return true;
6258 
6259 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
6260 		if (t == BPF_WRITE)
6261 			env->seen_direct_write = true;
6262 
6263 		return true;
6264 
6265 	default:
6266 		return false;
6267 	}
6268 }
6269 
6270 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
6271 			       int size, bool zero_size_allowed)
6272 {
6273 	struct bpf_reg_state *reg = reg_state(env, regno);
6274 	int err;
6275 
6276 	/* We may have added a variable offset to the packet pointer; but any
6277 	 * reg->range we have comes after that.  We are only checking the fixed
6278 	 * offset.
6279 	 */
6280 
6281 	/* We don't allow negative numbers, because we aren't tracking enough
6282 	 * detail to prove they're safe.
6283 	 */
6284 	if (reg->smin_value < 0) {
6285 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6286 			regno);
6287 		return -EACCES;
6288 	}
6289 
6290 	err = reg->range < 0 ? -EINVAL :
6291 	      __check_mem_access(env, regno, off, size, reg->range,
6292 				 zero_size_allowed);
6293 	if (err) {
6294 		verbose(env, "R%d offset is outside of the packet\n", regno);
6295 		return err;
6296 	}
6297 
6298 	/* __check_mem_access has made sure "off + size - 1" is within u16.
6299 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
6300 	 * otherwise find_good_pkt_pointers would have refused to set range info
6301 	 * that __check_mem_access would have rejected this pkt access.
6302 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
6303 	 */
6304 	env->prog->aux->max_pkt_offset =
6305 		max_t(u32, env->prog->aux->max_pkt_offset,
6306 		      off + reg->umax_value + size - 1);
6307 
6308 	return err;
6309 }
6310 
6311 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
6312 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
6313 			    enum bpf_access_type t, struct bpf_insn_access_aux *info)
6314 {
6315 	if (env->ops->is_valid_access &&
6316 	    env->ops->is_valid_access(off, size, t, env->prog, info)) {
6317 		/* A non zero info.ctx_field_size indicates that this field is a
6318 		 * candidate for later verifier transformation to load the whole
6319 		 * field and then apply a mask when accessed with a narrower
6320 		 * access than actual ctx access size. A zero info.ctx_field_size
6321 		 * will only allow for whole field access and rejects any other
6322 		 * type of narrower access.
6323 		 */
6324 		if (base_type(info->reg_type) == PTR_TO_BTF_ID) {
6325 			if (info->ref_obj_id &&
6326 			    !find_reference_state(env->cur_state, info->ref_obj_id)) {
6327 				verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n",
6328 					off);
6329 				return -EACCES;
6330 			}
6331 		} else {
6332 			env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size;
6333 		}
6334 		/* remember the offset of last byte accessed in ctx */
6335 		if (env->prog->aux->max_ctx_offset < off + size)
6336 			env->prog->aux->max_ctx_offset = off + size;
6337 		return 0;
6338 	}
6339 
6340 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
6341 	return -EACCES;
6342 }
6343 
6344 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
6345 				  int size)
6346 {
6347 	if (size < 0 || off < 0 ||
6348 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
6349 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
6350 			off, size);
6351 		return -EACCES;
6352 	}
6353 	return 0;
6354 }
6355 
6356 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
6357 			     u32 regno, int off, int size,
6358 			     enum bpf_access_type t)
6359 {
6360 	struct bpf_reg_state *reg = reg_state(env, regno);
6361 	struct bpf_insn_access_aux info = {};
6362 	bool valid;
6363 
6364 	if (reg->smin_value < 0) {
6365 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6366 			regno);
6367 		return -EACCES;
6368 	}
6369 
6370 	switch (reg->type) {
6371 	case PTR_TO_SOCK_COMMON:
6372 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
6373 		break;
6374 	case PTR_TO_SOCKET:
6375 		valid = bpf_sock_is_valid_access(off, size, t, &info);
6376 		break;
6377 	case PTR_TO_TCP_SOCK:
6378 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
6379 		break;
6380 	case PTR_TO_XDP_SOCK:
6381 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
6382 		break;
6383 	default:
6384 		valid = false;
6385 	}
6386 
6387 
6388 	if (valid) {
6389 		env->insn_aux_data[insn_idx].ctx_field_size =
6390 			info.ctx_field_size;
6391 		return 0;
6392 	}
6393 
6394 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
6395 		regno, reg_type_str(env, reg->type), off, size);
6396 
6397 	return -EACCES;
6398 }
6399 
6400 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
6401 {
6402 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
6403 }
6404 
6405 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
6406 {
6407 	const struct bpf_reg_state *reg = reg_state(env, regno);
6408 
6409 	return reg->type == PTR_TO_CTX;
6410 }
6411 
6412 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
6413 {
6414 	const struct bpf_reg_state *reg = reg_state(env, regno);
6415 
6416 	return type_is_sk_pointer(reg->type);
6417 }
6418 
6419 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
6420 {
6421 	const struct bpf_reg_state *reg = reg_state(env, regno);
6422 
6423 	return type_is_pkt_pointer(reg->type);
6424 }
6425 
6426 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
6427 {
6428 	const struct bpf_reg_state *reg = reg_state(env, regno);
6429 
6430 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
6431 	return reg->type == PTR_TO_FLOW_KEYS;
6432 }
6433 
6434 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
6435 {
6436 	const struct bpf_reg_state *reg = reg_state(env, regno);
6437 
6438 	return reg->type == PTR_TO_ARENA;
6439 }
6440 
6441 /* Return false if @regno contains a pointer whose type isn't supported for
6442  * atomic instruction @insn.
6443  */
6444 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno,
6445 			       struct bpf_insn *insn)
6446 {
6447 	if (is_ctx_reg(env, regno))
6448 		return false;
6449 	if (is_pkt_reg(env, regno))
6450 		return false;
6451 	if (is_flow_key_reg(env, regno))
6452 		return false;
6453 	if (is_sk_reg(env, regno))
6454 		return false;
6455 	if (is_arena_reg(env, regno))
6456 		return bpf_jit_supports_insn(insn, true);
6457 
6458 	return true;
6459 }
6460 
6461 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
6462 #ifdef CONFIG_NET
6463 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
6464 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6465 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
6466 #endif
6467 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
6468 };
6469 
6470 static bool is_trusted_reg(const struct bpf_reg_state *reg)
6471 {
6472 	/* A referenced register is always trusted. */
6473 	if (reg->ref_obj_id)
6474 		return true;
6475 
6476 	/* Types listed in the reg2btf_ids are always trusted */
6477 	if (reg2btf_ids[base_type(reg->type)] &&
6478 	    !bpf_type_has_unsafe_modifiers(reg->type))
6479 		return true;
6480 
6481 	/* If a register is not referenced, it is trusted if it has the
6482 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
6483 	 * other type modifiers may be safe, but we elect to take an opt-in
6484 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
6485 	 * not.
6486 	 *
6487 	 * Eventually, we should make PTR_TRUSTED the single source of truth
6488 	 * for whether a register is trusted.
6489 	 */
6490 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
6491 	       !bpf_type_has_unsafe_modifiers(reg->type);
6492 }
6493 
6494 static bool is_rcu_reg(const struct bpf_reg_state *reg)
6495 {
6496 	return reg->type & MEM_RCU;
6497 }
6498 
6499 static void clear_trusted_flags(enum bpf_type_flag *flag)
6500 {
6501 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
6502 }
6503 
6504 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
6505 				   const struct bpf_reg_state *reg,
6506 				   int off, int size, bool strict)
6507 {
6508 	struct tnum reg_off;
6509 	int ip_align;
6510 
6511 	/* Byte size accesses are always allowed. */
6512 	if (!strict || size == 1)
6513 		return 0;
6514 
6515 	/* For platforms that do not have a Kconfig enabling
6516 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
6517 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
6518 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
6519 	 * to this code only in strict mode where we want to emulate
6520 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
6521 	 * unconditional IP align value of '2'.
6522 	 */
6523 	ip_align = 2;
6524 
6525 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
6526 	if (!tnum_is_aligned(reg_off, size)) {
6527 		char tn_buf[48];
6528 
6529 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6530 		verbose(env,
6531 			"misaligned packet access off %d+%s+%d+%d size %d\n",
6532 			ip_align, tn_buf, reg->off, off, size);
6533 		return -EACCES;
6534 	}
6535 
6536 	return 0;
6537 }
6538 
6539 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
6540 				       const struct bpf_reg_state *reg,
6541 				       const char *pointer_desc,
6542 				       int off, int size, bool strict)
6543 {
6544 	struct tnum reg_off;
6545 
6546 	/* Byte size accesses are always allowed. */
6547 	if (!strict || size == 1)
6548 		return 0;
6549 
6550 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
6551 	if (!tnum_is_aligned(reg_off, size)) {
6552 		char tn_buf[48];
6553 
6554 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6555 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
6556 			pointer_desc, tn_buf, reg->off, off, size);
6557 		return -EACCES;
6558 	}
6559 
6560 	return 0;
6561 }
6562 
6563 static int check_ptr_alignment(struct bpf_verifier_env *env,
6564 			       const struct bpf_reg_state *reg, int off,
6565 			       int size, bool strict_alignment_once)
6566 {
6567 	bool strict = env->strict_alignment || strict_alignment_once;
6568 	const char *pointer_desc = "";
6569 
6570 	switch (reg->type) {
6571 	case PTR_TO_PACKET:
6572 	case PTR_TO_PACKET_META:
6573 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
6574 		 * right in front, treat it the very same way.
6575 		 */
6576 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
6577 	case PTR_TO_FLOW_KEYS:
6578 		pointer_desc = "flow keys ";
6579 		break;
6580 	case PTR_TO_MAP_KEY:
6581 		pointer_desc = "key ";
6582 		break;
6583 	case PTR_TO_MAP_VALUE:
6584 		pointer_desc = "value ";
6585 		if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY)
6586 			strict = true;
6587 		break;
6588 	case PTR_TO_CTX:
6589 		pointer_desc = "context ";
6590 		break;
6591 	case PTR_TO_STACK:
6592 		pointer_desc = "stack ";
6593 		/* The stack spill tracking logic in check_stack_write_fixed_off()
6594 		 * and check_stack_read_fixed_off() relies on stack accesses being
6595 		 * aligned.
6596 		 */
6597 		strict = true;
6598 		break;
6599 	case PTR_TO_SOCKET:
6600 		pointer_desc = "sock ";
6601 		break;
6602 	case PTR_TO_SOCK_COMMON:
6603 		pointer_desc = "sock_common ";
6604 		break;
6605 	case PTR_TO_TCP_SOCK:
6606 		pointer_desc = "tcp_sock ";
6607 		break;
6608 	case PTR_TO_XDP_SOCK:
6609 		pointer_desc = "xdp_sock ";
6610 		break;
6611 	case PTR_TO_ARENA:
6612 		return 0;
6613 	default:
6614 		break;
6615 	}
6616 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
6617 					   strict);
6618 }
6619 
6620 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
6621 {
6622 	if (!bpf_jit_supports_private_stack())
6623 		return NO_PRIV_STACK;
6624 
6625 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
6626 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
6627 	 * explicitly.
6628 	 */
6629 	switch (prog->type) {
6630 	case BPF_PROG_TYPE_KPROBE:
6631 	case BPF_PROG_TYPE_TRACEPOINT:
6632 	case BPF_PROG_TYPE_PERF_EVENT:
6633 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6634 		return PRIV_STACK_ADAPTIVE;
6635 	case BPF_PROG_TYPE_TRACING:
6636 	case BPF_PROG_TYPE_LSM:
6637 	case BPF_PROG_TYPE_STRUCT_OPS:
6638 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
6639 			return PRIV_STACK_ADAPTIVE;
6640 		fallthrough;
6641 	default:
6642 		break;
6643 	}
6644 
6645 	return NO_PRIV_STACK;
6646 }
6647 
6648 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
6649 {
6650 	if (env->prog->jit_requested)
6651 		return round_up(stack_depth, 16);
6652 
6653 	/* round up to 32-bytes, since this is granularity
6654 	 * of interpreter stack size
6655 	 */
6656 	return round_up(max_t(u32, stack_depth, 1), 32);
6657 }
6658 
6659 /* starting from main bpf function walk all instructions of the function
6660  * and recursively walk all callees that given function can call.
6661  * Ignore jump and exit insns.
6662  * Since recursion is prevented by check_cfg() this algorithm
6663  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
6664  */
6665 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
6666 					 bool priv_stack_supported)
6667 {
6668 	struct bpf_subprog_info *subprog = env->subprog_info;
6669 	struct bpf_insn *insn = env->prog->insnsi;
6670 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
6671 	bool tail_call_reachable = false;
6672 	int ret_insn[MAX_CALL_FRAMES];
6673 	int ret_prog[MAX_CALL_FRAMES];
6674 	int j;
6675 
6676 	i = subprog[idx].start;
6677 	if (!priv_stack_supported)
6678 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6679 process_func:
6680 	/* protect against potential stack overflow that might happen when
6681 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
6682 	 * depth for such case down to 256 so that the worst case scenario
6683 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
6684 	 * 8k).
6685 	 *
6686 	 * To get the idea what might happen, see an example:
6687 	 * func1 -> sub rsp, 128
6688 	 *  subfunc1 -> sub rsp, 256
6689 	 *  tailcall1 -> add rsp, 256
6690 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
6691 	 *   subfunc2 -> sub rsp, 64
6692 	 *   subfunc22 -> sub rsp, 128
6693 	 *   tailcall2 -> add rsp, 128
6694 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
6695 	 *
6696 	 * tailcall will unwind the current stack frame but it will not get rid
6697 	 * of caller's stack as shown on the example above.
6698 	 */
6699 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
6700 		verbose(env,
6701 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
6702 			depth);
6703 		return -EACCES;
6704 	}
6705 
6706 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
6707 	if (priv_stack_supported) {
6708 		/* Request private stack support only if the subprog stack
6709 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
6710 		 * avoid jit penalty if the stack usage is small.
6711 		 */
6712 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
6713 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
6714 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
6715 	}
6716 
6717 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6718 		if (subprog_depth > MAX_BPF_STACK) {
6719 			verbose(env, "stack size of subprog %d is %d. Too large\n",
6720 				idx, subprog_depth);
6721 			return -EACCES;
6722 		}
6723 	} else {
6724 		depth += subprog_depth;
6725 		if (depth > MAX_BPF_STACK) {
6726 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
6727 				frame + 1, depth);
6728 			return -EACCES;
6729 		}
6730 	}
6731 continue_func:
6732 	subprog_end = subprog[idx + 1].start;
6733 	for (; i < subprog_end; i++) {
6734 		int next_insn, sidx;
6735 
6736 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
6737 			bool err = false;
6738 
6739 			if (!is_bpf_throw_kfunc(insn + i))
6740 				continue;
6741 			if (subprog[idx].is_cb)
6742 				err = true;
6743 			for (int c = 0; c < frame && !err; c++) {
6744 				if (subprog[ret_prog[c]].is_cb) {
6745 					err = true;
6746 					break;
6747 				}
6748 			}
6749 			if (!err)
6750 				continue;
6751 			verbose(env,
6752 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
6753 				i, idx);
6754 			return -EINVAL;
6755 		}
6756 
6757 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
6758 			continue;
6759 		/* remember insn and function to return to */
6760 		ret_insn[frame] = i + 1;
6761 		ret_prog[frame] = idx;
6762 
6763 		/* find the callee */
6764 		next_insn = i + insn[i].imm + 1;
6765 		sidx = find_subprog(env, next_insn);
6766 		if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn))
6767 			return -EFAULT;
6768 		if (subprog[sidx].is_async_cb) {
6769 			if (subprog[sidx].has_tail_call) {
6770 				verifier_bug(env, "subprog has tail_call and async cb");
6771 				return -EFAULT;
6772 			}
6773 			/* async callbacks don't increase bpf prog stack size unless called directly */
6774 			if (!bpf_pseudo_call(insn + i))
6775 				continue;
6776 			if (subprog[sidx].is_exception_cb) {
6777 				verbose(env, "insn %d cannot call exception cb directly", i);
6778 				return -EINVAL;
6779 			}
6780 		}
6781 		i = next_insn;
6782 		idx = sidx;
6783 		if (!priv_stack_supported)
6784 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6785 
6786 		if (subprog[idx].has_tail_call)
6787 			tail_call_reachable = true;
6788 
6789 		frame++;
6790 		if (frame >= MAX_CALL_FRAMES) {
6791 			verbose(env, "the call stack of %d frames is too deep !\n",
6792 				frame);
6793 			return -E2BIG;
6794 		}
6795 		goto process_func;
6796 	}
6797 	/* if tail call got detected across bpf2bpf calls then mark each of the
6798 	 * currently present subprog frames as tail call reachable subprogs;
6799 	 * this info will be utilized by JIT so that we will be preserving the
6800 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
6801 	 */
6802 	if (tail_call_reachable)
6803 		for (j = 0; j < frame; j++) {
6804 			if (subprog[ret_prog[j]].is_exception_cb) {
6805 				verbose(env, "cannot tail call within exception cb\n");
6806 				return -EINVAL;
6807 			}
6808 			subprog[ret_prog[j]].tail_call_reachable = true;
6809 		}
6810 	if (subprog[0].tail_call_reachable)
6811 		env->prog->aux->tail_call_reachable = true;
6812 
6813 	/* end of for() loop means the last insn of the 'subprog'
6814 	 * was reached. Doesn't matter whether it was JA or EXIT
6815 	 */
6816 	if (frame == 0)
6817 		return 0;
6818 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
6819 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6820 	frame--;
6821 	i = ret_insn[frame];
6822 	idx = ret_prog[frame];
6823 	goto continue_func;
6824 }
6825 
6826 static int check_max_stack_depth(struct bpf_verifier_env *env)
6827 {
6828 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
6829 	struct bpf_subprog_info *si = env->subprog_info;
6830 	bool priv_stack_supported;
6831 	int ret;
6832 
6833 	for (int i = 0; i < env->subprog_cnt; i++) {
6834 		if (si[i].has_tail_call) {
6835 			priv_stack_mode = NO_PRIV_STACK;
6836 			break;
6837 		}
6838 	}
6839 
6840 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
6841 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
6842 
6843 	/* All async_cb subprogs use normal kernel stack. If a particular
6844 	 * subprog appears in both main prog and async_cb subtree, that
6845 	 * subprog will use normal kernel stack to avoid potential nesting.
6846 	 * The reverse subprog traversal ensures when main prog subtree is
6847 	 * checked, the subprogs appearing in async_cb subtrees are already
6848 	 * marked as using normal kernel stack, so stack size checking can
6849 	 * be done properly.
6850 	 */
6851 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
6852 		if (!i || si[i].is_async_cb) {
6853 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
6854 			ret = check_max_stack_depth_subprog(env, i, priv_stack_supported);
6855 			if (ret < 0)
6856 				return ret;
6857 		}
6858 	}
6859 
6860 	for (int i = 0; i < env->subprog_cnt; i++) {
6861 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6862 			env->prog->aux->jits_use_priv_stack = true;
6863 			break;
6864 		}
6865 	}
6866 
6867 	return 0;
6868 }
6869 
6870 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6871 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6872 				  const struct bpf_insn *insn, int idx)
6873 {
6874 	int start = idx + insn->imm + 1, subprog;
6875 
6876 	subprog = find_subprog(env, start);
6877 	if (verifier_bug_if(subprog < 0, env, "get stack depth: no program at insn %d", start))
6878 		return -EFAULT;
6879 	return env->subprog_info[subprog].stack_depth;
6880 }
6881 #endif
6882 
6883 static int __check_buffer_access(struct bpf_verifier_env *env,
6884 				 const char *buf_info,
6885 				 const struct bpf_reg_state *reg,
6886 				 int regno, int off, int size)
6887 {
6888 	if (off < 0) {
6889 		verbose(env,
6890 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6891 			regno, buf_info, off, size);
6892 		return -EACCES;
6893 	}
6894 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6895 		char tn_buf[48];
6896 
6897 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6898 		verbose(env,
6899 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6900 			regno, off, tn_buf);
6901 		return -EACCES;
6902 	}
6903 
6904 	return 0;
6905 }
6906 
6907 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6908 				  const struct bpf_reg_state *reg,
6909 				  int regno, int off, int size)
6910 {
6911 	int err;
6912 
6913 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6914 	if (err)
6915 		return err;
6916 
6917 	if (off + size > env->prog->aux->max_tp_access)
6918 		env->prog->aux->max_tp_access = off + size;
6919 
6920 	return 0;
6921 }
6922 
6923 static int check_buffer_access(struct bpf_verifier_env *env,
6924 			       const struct bpf_reg_state *reg,
6925 			       int regno, int off, int size,
6926 			       bool zero_size_allowed,
6927 			       u32 *max_access)
6928 {
6929 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6930 	int err;
6931 
6932 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6933 	if (err)
6934 		return err;
6935 
6936 	if (off + size > *max_access)
6937 		*max_access = off + size;
6938 
6939 	return 0;
6940 }
6941 
6942 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6943 static void zext_32_to_64(struct bpf_reg_state *reg)
6944 {
6945 	reg->var_off = tnum_subreg(reg->var_off);
6946 	__reg_assign_32_into_64(reg);
6947 }
6948 
6949 /* truncate register to smaller size (in bytes)
6950  * must be called with size < BPF_REG_SIZE
6951  */
6952 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6953 {
6954 	u64 mask;
6955 
6956 	/* clear high bits in bit representation */
6957 	reg->var_off = tnum_cast(reg->var_off, size);
6958 
6959 	/* fix arithmetic bounds */
6960 	mask = ((u64)1 << (size * 8)) - 1;
6961 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6962 		reg->umin_value &= mask;
6963 		reg->umax_value &= mask;
6964 	} else {
6965 		reg->umin_value = 0;
6966 		reg->umax_value = mask;
6967 	}
6968 	reg->smin_value = reg->umin_value;
6969 	reg->smax_value = reg->umax_value;
6970 
6971 	/* If size is smaller than 32bit register the 32bit register
6972 	 * values are also truncated so we push 64-bit bounds into
6973 	 * 32-bit bounds. Above were truncated < 32-bits already.
6974 	 */
6975 	if (size < 4)
6976 		__mark_reg32_unbounded(reg);
6977 
6978 	reg_bounds_sync(reg);
6979 }
6980 
6981 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6982 {
6983 	if (size == 1) {
6984 		reg->smin_value = reg->s32_min_value = S8_MIN;
6985 		reg->smax_value = reg->s32_max_value = S8_MAX;
6986 	} else if (size == 2) {
6987 		reg->smin_value = reg->s32_min_value = S16_MIN;
6988 		reg->smax_value = reg->s32_max_value = S16_MAX;
6989 	} else {
6990 		/* size == 4 */
6991 		reg->smin_value = reg->s32_min_value = S32_MIN;
6992 		reg->smax_value = reg->s32_max_value = S32_MAX;
6993 	}
6994 	reg->umin_value = reg->u32_min_value = 0;
6995 	reg->umax_value = U64_MAX;
6996 	reg->u32_max_value = U32_MAX;
6997 	reg->var_off = tnum_unknown;
6998 }
6999 
7000 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
7001 {
7002 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
7003 	u64 top_smax_value, top_smin_value;
7004 	u64 num_bits = size * 8;
7005 
7006 	if (tnum_is_const(reg->var_off)) {
7007 		u64_cval = reg->var_off.value;
7008 		if (size == 1)
7009 			reg->var_off = tnum_const((s8)u64_cval);
7010 		else if (size == 2)
7011 			reg->var_off = tnum_const((s16)u64_cval);
7012 		else
7013 			/* size == 4 */
7014 			reg->var_off = tnum_const((s32)u64_cval);
7015 
7016 		u64_cval = reg->var_off.value;
7017 		reg->smax_value = reg->smin_value = u64_cval;
7018 		reg->umax_value = reg->umin_value = u64_cval;
7019 		reg->s32_max_value = reg->s32_min_value = u64_cval;
7020 		reg->u32_max_value = reg->u32_min_value = u64_cval;
7021 		return;
7022 	}
7023 
7024 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
7025 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
7026 
7027 	if (top_smax_value != top_smin_value)
7028 		goto out;
7029 
7030 	/* find the s64_min and s64_min after sign extension */
7031 	if (size == 1) {
7032 		init_s64_max = (s8)reg->smax_value;
7033 		init_s64_min = (s8)reg->smin_value;
7034 	} else if (size == 2) {
7035 		init_s64_max = (s16)reg->smax_value;
7036 		init_s64_min = (s16)reg->smin_value;
7037 	} else {
7038 		init_s64_max = (s32)reg->smax_value;
7039 		init_s64_min = (s32)reg->smin_value;
7040 	}
7041 
7042 	s64_max = max(init_s64_max, init_s64_min);
7043 	s64_min = min(init_s64_max, init_s64_min);
7044 
7045 	/* both of s64_max/s64_min positive or negative */
7046 	if ((s64_max >= 0) == (s64_min >= 0)) {
7047 		reg->s32_min_value = reg->smin_value = s64_min;
7048 		reg->s32_max_value = reg->smax_value = s64_max;
7049 		reg->u32_min_value = reg->umin_value = s64_min;
7050 		reg->u32_max_value = reg->umax_value = s64_max;
7051 		reg->var_off = tnum_range(s64_min, s64_max);
7052 		return;
7053 	}
7054 
7055 out:
7056 	set_sext64_default_val(reg, size);
7057 }
7058 
7059 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
7060 {
7061 	if (size == 1) {
7062 		reg->s32_min_value = S8_MIN;
7063 		reg->s32_max_value = S8_MAX;
7064 	} else {
7065 		/* size == 2 */
7066 		reg->s32_min_value = S16_MIN;
7067 		reg->s32_max_value = S16_MAX;
7068 	}
7069 	reg->u32_min_value = 0;
7070 	reg->u32_max_value = U32_MAX;
7071 	reg->var_off = tnum_subreg(tnum_unknown);
7072 }
7073 
7074 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
7075 {
7076 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
7077 	u32 top_smax_value, top_smin_value;
7078 	u32 num_bits = size * 8;
7079 
7080 	if (tnum_is_const(reg->var_off)) {
7081 		u32_val = reg->var_off.value;
7082 		if (size == 1)
7083 			reg->var_off = tnum_const((s8)u32_val);
7084 		else
7085 			reg->var_off = tnum_const((s16)u32_val);
7086 
7087 		u32_val = reg->var_off.value;
7088 		reg->s32_min_value = reg->s32_max_value = u32_val;
7089 		reg->u32_min_value = reg->u32_max_value = u32_val;
7090 		return;
7091 	}
7092 
7093 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
7094 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
7095 
7096 	if (top_smax_value != top_smin_value)
7097 		goto out;
7098 
7099 	/* find the s32_min and s32_min after sign extension */
7100 	if (size == 1) {
7101 		init_s32_max = (s8)reg->s32_max_value;
7102 		init_s32_min = (s8)reg->s32_min_value;
7103 	} else {
7104 		/* size == 2 */
7105 		init_s32_max = (s16)reg->s32_max_value;
7106 		init_s32_min = (s16)reg->s32_min_value;
7107 	}
7108 	s32_max = max(init_s32_max, init_s32_min);
7109 	s32_min = min(init_s32_max, init_s32_min);
7110 
7111 	if ((s32_min >= 0) == (s32_max >= 0)) {
7112 		reg->s32_min_value = s32_min;
7113 		reg->s32_max_value = s32_max;
7114 		reg->u32_min_value = (u32)s32_min;
7115 		reg->u32_max_value = (u32)s32_max;
7116 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
7117 		return;
7118 	}
7119 
7120 out:
7121 	set_sext32_default_val(reg, size);
7122 }
7123 
7124 static bool bpf_map_is_rdonly(const struct bpf_map *map)
7125 {
7126 	/* A map is considered read-only if the following condition are true:
7127 	 *
7128 	 * 1) BPF program side cannot change any of the map content. The
7129 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
7130 	 *    and was set at map creation time.
7131 	 * 2) The map value(s) have been initialized from user space by a
7132 	 *    loader and then "frozen", such that no new map update/delete
7133 	 *    operations from syscall side are possible for the rest of
7134 	 *    the map's lifetime from that point onwards.
7135 	 * 3) Any parallel/pending map update/delete operations from syscall
7136 	 *    side have been completed. Only after that point, it's safe to
7137 	 *    assume that map value(s) are immutable.
7138 	 */
7139 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
7140 	       READ_ONCE(map->frozen) &&
7141 	       !bpf_map_write_active(map);
7142 }
7143 
7144 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
7145 			       bool is_ldsx)
7146 {
7147 	void *ptr;
7148 	u64 addr;
7149 	int err;
7150 
7151 	err = map->ops->map_direct_value_addr(map, &addr, off);
7152 	if (err)
7153 		return err;
7154 	ptr = (void *)(long)addr + off;
7155 
7156 	switch (size) {
7157 	case sizeof(u8):
7158 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
7159 		break;
7160 	case sizeof(u16):
7161 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
7162 		break;
7163 	case sizeof(u32):
7164 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
7165 		break;
7166 	case sizeof(u64):
7167 		*val = *(u64 *)ptr;
7168 		break;
7169 	default:
7170 		return -EINVAL;
7171 	}
7172 	return 0;
7173 }
7174 
7175 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
7176 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
7177 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
7178 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
7179 
7180 /*
7181  * Allow list few fields as RCU trusted or full trusted.
7182  * This logic doesn't allow mix tagging and will be removed once GCC supports
7183  * btf_type_tag.
7184  */
7185 
7186 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
7187 BTF_TYPE_SAFE_RCU(struct task_struct) {
7188 	const cpumask_t *cpus_ptr;
7189 	struct css_set __rcu *cgroups;
7190 	struct task_struct __rcu *real_parent;
7191 	struct task_struct *group_leader;
7192 };
7193 
7194 BTF_TYPE_SAFE_RCU(struct cgroup) {
7195 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
7196 	struct kernfs_node *kn;
7197 };
7198 
7199 BTF_TYPE_SAFE_RCU(struct css_set) {
7200 	struct cgroup *dfl_cgrp;
7201 };
7202 
7203 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) {
7204 	struct cgroup *cgroup;
7205 };
7206 
7207 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
7208 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
7209 	struct file __rcu *exe_file;
7210 #ifdef CONFIG_MEMCG
7211 	struct task_struct __rcu *owner;
7212 #endif
7213 };
7214 
7215 /* skb->sk, req->sk are not RCU protected, but we mark them as such
7216  * because bpf prog accessible sockets are SOCK_RCU_FREE.
7217  */
7218 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
7219 	struct sock *sk;
7220 };
7221 
7222 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
7223 	struct sock *sk;
7224 };
7225 
7226 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
7227 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
7228 	struct seq_file *seq;
7229 };
7230 
7231 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
7232 	struct bpf_iter_meta *meta;
7233 	struct task_struct *task;
7234 };
7235 
7236 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
7237 	struct file *file;
7238 };
7239 
7240 BTF_TYPE_SAFE_TRUSTED(struct file) {
7241 	struct inode *f_inode;
7242 };
7243 
7244 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {
7245 	struct inode *d_inode;
7246 };
7247 
7248 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
7249 	struct sock *sk;
7250 };
7251 
7252 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) {
7253 	struct mm_struct *vm_mm;
7254 	struct file *vm_file;
7255 };
7256 
7257 static bool type_is_rcu(struct bpf_verifier_env *env,
7258 			struct bpf_reg_state *reg,
7259 			const char *field_name, u32 btf_id)
7260 {
7261 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
7262 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
7263 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
7264 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state));
7265 
7266 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
7267 }
7268 
7269 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
7270 				struct bpf_reg_state *reg,
7271 				const char *field_name, u32 btf_id)
7272 {
7273 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
7274 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
7275 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
7276 
7277 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
7278 }
7279 
7280 static bool type_is_trusted(struct bpf_verifier_env *env,
7281 			    struct bpf_reg_state *reg,
7282 			    const char *field_name, u32 btf_id)
7283 {
7284 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
7285 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
7286 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
7287 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
7288 
7289 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
7290 }
7291 
7292 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
7293 				    struct bpf_reg_state *reg,
7294 				    const char *field_name, u32 btf_id)
7295 {
7296 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
7297 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
7298 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct));
7299 
7300 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
7301 					  "__safe_trusted_or_null");
7302 }
7303 
7304 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
7305 				   struct bpf_reg_state *regs,
7306 				   int regno, int off, int size,
7307 				   enum bpf_access_type atype,
7308 				   int value_regno)
7309 {
7310 	struct bpf_reg_state *reg = regs + regno;
7311 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
7312 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
7313 	const char *field_name = NULL;
7314 	enum bpf_type_flag flag = 0;
7315 	u32 btf_id = 0;
7316 	int ret;
7317 
7318 	if (!env->allow_ptr_leaks) {
7319 		verbose(env,
7320 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7321 			tname);
7322 		return -EPERM;
7323 	}
7324 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
7325 		verbose(env,
7326 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
7327 			tname);
7328 		return -EINVAL;
7329 	}
7330 	if (off < 0) {
7331 		verbose(env,
7332 			"R%d is ptr_%s invalid negative access: off=%d\n",
7333 			regno, tname, off);
7334 		return -EACCES;
7335 	}
7336 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
7337 		char tn_buf[48];
7338 
7339 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7340 		verbose(env,
7341 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
7342 			regno, tname, off, tn_buf);
7343 		return -EACCES;
7344 	}
7345 
7346 	if (reg->type & MEM_USER) {
7347 		verbose(env,
7348 			"R%d is ptr_%s access user memory: off=%d\n",
7349 			regno, tname, off);
7350 		return -EACCES;
7351 	}
7352 
7353 	if (reg->type & MEM_PERCPU) {
7354 		verbose(env,
7355 			"R%d is ptr_%s access percpu memory: off=%d\n",
7356 			regno, tname, off);
7357 		return -EACCES;
7358 	}
7359 
7360 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
7361 		if (!btf_is_kernel(reg->btf)) {
7362 			verifier_bug(env, "reg->btf must be kernel btf");
7363 			return -EFAULT;
7364 		}
7365 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
7366 	} else {
7367 		/* Writes are permitted with default btf_struct_access for
7368 		 * program allocated objects (which always have ref_obj_id > 0),
7369 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
7370 		 */
7371 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
7372 			verbose(env, "only read is supported\n");
7373 			return -EACCES;
7374 		}
7375 
7376 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
7377 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
7378 			verifier_bug(env, "ref_obj_id for allocated object must be non-zero");
7379 			return -EFAULT;
7380 		}
7381 
7382 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
7383 	}
7384 
7385 	if (ret < 0)
7386 		return ret;
7387 
7388 	if (ret != PTR_TO_BTF_ID) {
7389 		/* just mark; */
7390 
7391 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
7392 		/* If this is an untrusted pointer, all pointers formed by walking it
7393 		 * also inherit the untrusted flag.
7394 		 */
7395 		flag = PTR_UNTRUSTED;
7396 
7397 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
7398 		/* By default any pointer obtained from walking a trusted pointer is no
7399 		 * longer trusted, unless the field being accessed has explicitly been
7400 		 * marked as inheriting its parent's state of trust (either full or RCU).
7401 		 * For example:
7402 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
7403 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
7404 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
7405 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
7406 		 *
7407 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
7408 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
7409 		 */
7410 		if (type_is_trusted(env, reg, field_name, btf_id)) {
7411 			flag |= PTR_TRUSTED;
7412 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
7413 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
7414 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
7415 			if (type_is_rcu(env, reg, field_name, btf_id)) {
7416 				/* ignore __rcu tag and mark it MEM_RCU */
7417 				flag |= MEM_RCU;
7418 			} else if (flag & MEM_RCU ||
7419 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
7420 				/* __rcu tagged pointers can be NULL */
7421 				flag |= MEM_RCU | PTR_MAYBE_NULL;
7422 
7423 				/* We always trust them */
7424 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
7425 				    flag & PTR_UNTRUSTED)
7426 					flag &= ~PTR_UNTRUSTED;
7427 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
7428 				/* keep as-is */
7429 			} else {
7430 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
7431 				clear_trusted_flags(&flag);
7432 			}
7433 		} else {
7434 			/*
7435 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
7436 			 * aggressively mark as untrusted otherwise such
7437 			 * pointers will be plain PTR_TO_BTF_ID without flags
7438 			 * and will be allowed to be passed into helpers for
7439 			 * compat reasons.
7440 			 */
7441 			flag = PTR_UNTRUSTED;
7442 		}
7443 	} else {
7444 		/* Old compat. Deprecated */
7445 		clear_trusted_flags(&flag);
7446 	}
7447 
7448 	if (atype == BPF_READ && value_regno >= 0) {
7449 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
7450 		if (ret < 0)
7451 			return ret;
7452 	}
7453 
7454 	return 0;
7455 }
7456 
7457 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
7458 				   struct bpf_reg_state *regs,
7459 				   int regno, int off, int size,
7460 				   enum bpf_access_type atype,
7461 				   int value_regno)
7462 {
7463 	struct bpf_reg_state *reg = regs + regno;
7464 	struct bpf_map *map = reg->map_ptr;
7465 	struct bpf_reg_state map_reg;
7466 	enum bpf_type_flag flag = 0;
7467 	const struct btf_type *t;
7468 	const char *tname;
7469 	u32 btf_id;
7470 	int ret;
7471 
7472 	if (!btf_vmlinux) {
7473 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
7474 		return -ENOTSUPP;
7475 	}
7476 
7477 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
7478 		verbose(env, "map_ptr access not supported for map type %d\n",
7479 			map->map_type);
7480 		return -ENOTSUPP;
7481 	}
7482 
7483 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
7484 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
7485 
7486 	if (!env->allow_ptr_leaks) {
7487 		verbose(env,
7488 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7489 			tname);
7490 		return -EPERM;
7491 	}
7492 
7493 	if (off < 0) {
7494 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
7495 			regno, tname, off);
7496 		return -EACCES;
7497 	}
7498 
7499 	if (atype != BPF_READ) {
7500 		verbose(env, "only read from %s is supported\n", tname);
7501 		return -EACCES;
7502 	}
7503 
7504 	/* Simulate access to a PTR_TO_BTF_ID */
7505 	memset(&map_reg, 0, sizeof(map_reg));
7506 	ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID,
7507 			      btf_vmlinux, *map->ops->map_btf_id, 0);
7508 	if (ret < 0)
7509 		return ret;
7510 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
7511 	if (ret < 0)
7512 		return ret;
7513 
7514 	if (value_regno >= 0) {
7515 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
7516 		if (ret < 0)
7517 			return ret;
7518 	}
7519 
7520 	return 0;
7521 }
7522 
7523 /* Check that the stack access at the given offset is within bounds. The
7524  * maximum valid offset is -1.
7525  *
7526  * The minimum valid offset is -MAX_BPF_STACK for writes, and
7527  * -state->allocated_stack for reads.
7528  */
7529 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
7530                                           s64 off,
7531                                           struct bpf_func_state *state,
7532                                           enum bpf_access_type t)
7533 {
7534 	int min_valid_off;
7535 
7536 	if (t == BPF_WRITE || env->allow_uninit_stack)
7537 		min_valid_off = -MAX_BPF_STACK;
7538 	else
7539 		min_valid_off = -state->allocated_stack;
7540 
7541 	if (off < min_valid_off || off > -1)
7542 		return -EACCES;
7543 	return 0;
7544 }
7545 
7546 /* Check that the stack access at 'regno + off' falls within the maximum stack
7547  * bounds.
7548  *
7549  * 'off' includes `regno->offset`, but not its dynamic part (if any).
7550  */
7551 static int check_stack_access_within_bounds(
7552 		struct bpf_verifier_env *env,
7553 		int regno, int off, int access_size,
7554 		enum bpf_access_type type)
7555 {
7556 	struct bpf_reg_state *reg = reg_state(env, regno);
7557 	struct bpf_func_state *state = func(env, reg);
7558 	s64 min_off, max_off;
7559 	int err;
7560 	char *err_extra;
7561 
7562 	if (type == BPF_READ)
7563 		err_extra = " read from";
7564 	else
7565 		err_extra = " write to";
7566 
7567 	if (tnum_is_const(reg->var_off)) {
7568 		min_off = (s64)reg->var_off.value + off;
7569 		max_off = min_off + access_size;
7570 	} else {
7571 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
7572 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
7573 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
7574 				err_extra, regno);
7575 			return -EACCES;
7576 		}
7577 		min_off = reg->smin_value + off;
7578 		max_off = reg->smax_value + off + access_size;
7579 	}
7580 
7581 	err = check_stack_slot_within_bounds(env, min_off, state, type);
7582 	if (!err && max_off > 0)
7583 		err = -EINVAL; /* out of stack access into non-negative offsets */
7584 	if (!err && access_size < 0)
7585 		/* access_size should not be negative (or overflow an int); others checks
7586 		 * along the way should have prevented such an access.
7587 		 */
7588 		err = -EFAULT; /* invalid negative access size; integer overflow? */
7589 
7590 	if (err) {
7591 		if (tnum_is_const(reg->var_off)) {
7592 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
7593 				err_extra, regno, off, access_size);
7594 		} else {
7595 			char tn_buf[48];
7596 
7597 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7598 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
7599 				err_extra, regno, tn_buf, off, access_size);
7600 		}
7601 		return err;
7602 	}
7603 
7604 	/* Note that there is no stack access with offset zero, so the needed stack
7605 	 * size is -min_off, not -min_off+1.
7606 	 */
7607 	return grow_stack_state(env, state, -min_off /* size */);
7608 }
7609 
7610 static bool get_func_retval_range(struct bpf_prog *prog,
7611 				  struct bpf_retval_range *range)
7612 {
7613 	if (prog->type == BPF_PROG_TYPE_LSM &&
7614 		prog->expected_attach_type == BPF_LSM_MAC &&
7615 		!bpf_lsm_get_retval_range(prog, range)) {
7616 		return true;
7617 	}
7618 	return false;
7619 }
7620 
7621 /* check whether memory at (regno + off) is accessible for t = (read | write)
7622  * if t==write, value_regno is a register which value is stored into memory
7623  * if t==read, value_regno is a register which will receive the value from memory
7624  * if t==write && value_regno==-1, some unknown value is stored into memory
7625  * if t==read && value_regno==-1, don't care what we read from memory
7626  */
7627 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
7628 			    int off, int bpf_size, enum bpf_access_type t,
7629 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
7630 {
7631 	struct bpf_reg_state *regs = cur_regs(env);
7632 	struct bpf_reg_state *reg = regs + regno;
7633 	int size, err = 0;
7634 
7635 	size = bpf_size_to_bytes(bpf_size);
7636 	if (size < 0)
7637 		return size;
7638 
7639 	/* alignment checks will add in reg->off themselves */
7640 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
7641 	if (err)
7642 		return err;
7643 
7644 	/* for access checks, reg->off is just part of off */
7645 	off += reg->off;
7646 
7647 	if (reg->type == PTR_TO_MAP_KEY) {
7648 		if (t == BPF_WRITE) {
7649 			verbose(env, "write to change key R%d not allowed\n", regno);
7650 			return -EACCES;
7651 		}
7652 
7653 		err = check_mem_region_access(env, regno, off, size,
7654 					      reg->map_ptr->key_size, false);
7655 		if (err)
7656 			return err;
7657 		if (value_regno >= 0)
7658 			mark_reg_unknown(env, regs, value_regno);
7659 	} else if (reg->type == PTR_TO_MAP_VALUE) {
7660 		struct btf_field *kptr_field = NULL;
7661 
7662 		if (t == BPF_WRITE && value_regno >= 0 &&
7663 		    is_pointer_value(env, value_regno)) {
7664 			verbose(env, "R%d leaks addr into map\n", value_regno);
7665 			return -EACCES;
7666 		}
7667 		err = check_map_access_type(env, regno, off, size, t);
7668 		if (err)
7669 			return err;
7670 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
7671 		if (err)
7672 			return err;
7673 		if (tnum_is_const(reg->var_off))
7674 			kptr_field = btf_record_find(reg->map_ptr->record,
7675 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
7676 		if (kptr_field) {
7677 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
7678 		} else if (t == BPF_READ && value_regno >= 0) {
7679 			struct bpf_map *map = reg->map_ptr;
7680 
7681 			/*
7682 			 * If map is read-only, track its contents as scalars,
7683 			 * unless it is an insn array (see the special case below)
7684 			 */
7685 			if (tnum_is_const(reg->var_off) &&
7686 			    bpf_map_is_rdonly(map) &&
7687 			    map->ops->map_direct_value_addr &&
7688 			    map->map_type != BPF_MAP_TYPE_INSN_ARRAY) {
7689 				int map_off = off + reg->var_off.value;
7690 				u64 val = 0;
7691 
7692 				err = bpf_map_direct_read(map, map_off, size,
7693 							  &val, is_ldsx);
7694 				if (err)
7695 					return err;
7696 
7697 				regs[value_regno].type = SCALAR_VALUE;
7698 				__mark_reg_known(&regs[value_regno], val);
7699 			} else if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
7700 				if (bpf_size != BPF_DW) {
7701 					verbose(env, "Invalid read of %d bytes from insn_array\n",
7702 						     size);
7703 					return -EACCES;
7704 				}
7705 				copy_register_state(&regs[value_regno], reg);
7706 				regs[value_regno].type = PTR_TO_INSN;
7707 			} else {
7708 				mark_reg_unknown(env, regs, value_regno);
7709 			}
7710 		}
7711 	} else if (base_type(reg->type) == PTR_TO_MEM) {
7712 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7713 		bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED);
7714 
7715 		if (type_may_be_null(reg->type)) {
7716 			verbose(env, "R%d invalid mem access '%s'\n", regno,
7717 				reg_type_str(env, reg->type));
7718 			return -EACCES;
7719 		}
7720 
7721 		if (t == BPF_WRITE && rdonly_mem) {
7722 			verbose(env, "R%d cannot write into %s\n",
7723 				regno, reg_type_str(env, reg->type));
7724 			return -EACCES;
7725 		}
7726 
7727 		if (t == BPF_WRITE && value_regno >= 0 &&
7728 		    is_pointer_value(env, value_regno)) {
7729 			verbose(env, "R%d leaks addr into mem\n", value_regno);
7730 			return -EACCES;
7731 		}
7732 
7733 		/*
7734 		 * Accesses to untrusted PTR_TO_MEM are done through probe
7735 		 * instructions, hence no need to check bounds in that case.
7736 		 */
7737 		if (!rdonly_untrusted)
7738 			err = check_mem_region_access(env, regno, off, size,
7739 						      reg->mem_size, false);
7740 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7741 			mark_reg_unknown(env, regs, value_regno);
7742 	} else if (reg->type == PTR_TO_CTX) {
7743 		struct bpf_retval_range range;
7744 		struct bpf_insn_access_aux info = {
7745 			.reg_type = SCALAR_VALUE,
7746 			.is_ldsx = is_ldsx,
7747 			.log = &env->log,
7748 		};
7749 
7750 		if (t == BPF_WRITE && value_regno >= 0 &&
7751 		    is_pointer_value(env, value_regno)) {
7752 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
7753 			return -EACCES;
7754 		}
7755 
7756 		err = check_ptr_off_reg(env, reg, regno);
7757 		if (err < 0)
7758 			return err;
7759 
7760 		err = check_ctx_access(env, insn_idx, off, size, t, &info);
7761 		if (err)
7762 			verbose_linfo(env, insn_idx, "; ");
7763 		if (!err && t == BPF_READ && value_regno >= 0) {
7764 			/* ctx access returns either a scalar, or a
7765 			 * PTR_TO_PACKET[_META,_END]. In the latter
7766 			 * case, we know the offset is zero.
7767 			 */
7768 			if (info.reg_type == SCALAR_VALUE) {
7769 				if (info.is_retval && get_func_retval_range(env->prog, &range)) {
7770 					err = __mark_reg_s32_range(env, regs, value_regno,
7771 								   range.minval, range.maxval);
7772 					if (err)
7773 						return err;
7774 				} else {
7775 					mark_reg_unknown(env, regs, value_regno);
7776 				}
7777 			} else {
7778 				mark_reg_known_zero(env, regs,
7779 						    value_regno);
7780 				if (type_may_be_null(info.reg_type))
7781 					regs[value_regno].id = ++env->id_gen;
7782 				/* A load of ctx field could have different
7783 				 * actual load size with the one encoded in the
7784 				 * insn. When the dst is PTR, it is for sure not
7785 				 * a sub-register.
7786 				 */
7787 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
7788 				if (base_type(info.reg_type) == PTR_TO_BTF_ID) {
7789 					regs[value_regno].btf = info.btf;
7790 					regs[value_regno].btf_id = info.btf_id;
7791 					regs[value_regno].ref_obj_id = info.ref_obj_id;
7792 				}
7793 			}
7794 			regs[value_regno].type = info.reg_type;
7795 		}
7796 
7797 	} else if (reg->type == PTR_TO_STACK) {
7798 		/* Basic bounds checks. */
7799 		err = check_stack_access_within_bounds(env, regno, off, size, t);
7800 		if (err)
7801 			return err;
7802 
7803 		if (t == BPF_READ)
7804 			err = check_stack_read(env, regno, off, size,
7805 					       value_regno);
7806 		else
7807 			err = check_stack_write(env, regno, off, size,
7808 						value_regno, insn_idx);
7809 	} else if (reg_is_pkt_pointer(reg)) {
7810 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7811 			verbose(env, "cannot write into packet\n");
7812 			return -EACCES;
7813 		}
7814 		if (t == BPF_WRITE && value_regno >= 0 &&
7815 		    is_pointer_value(env, value_regno)) {
7816 			verbose(env, "R%d leaks addr into packet\n",
7817 				value_regno);
7818 			return -EACCES;
7819 		}
7820 		err = check_packet_access(env, regno, off, size, false);
7821 		if (!err && t == BPF_READ && value_regno >= 0)
7822 			mark_reg_unknown(env, regs, value_regno);
7823 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
7824 		if (t == BPF_WRITE && value_regno >= 0 &&
7825 		    is_pointer_value(env, value_regno)) {
7826 			verbose(env, "R%d leaks addr into flow keys\n",
7827 				value_regno);
7828 			return -EACCES;
7829 		}
7830 
7831 		err = check_flow_keys_access(env, off, size);
7832 		if (!err && t == BPF_READ && value_regno >= 0)
7833 			mark_reg_unknown(env, regs, value_regno);
7834 	} else if (type_is_sk_pointer(reg->type)) {
7835 		if (t == BPF_WRITE) {
7836 			verbose(env, "R%d cannot write into %s\n",
7837 				regno, reg_type_str(env, reg->type));
7838 			return -EACCES;
7839 		}
7840 		err = check_sock_access(env, insn_idx, regno, off, size, t);
7841 		if (!err && value_regno >= 0)
7842 			mark_reg_unknown(env, regs, value_regno);
7843 	} else if (reg->type == PTR_TO_TP_BUFFER) {
7844 		err = check_tp_buffer_access(env, reg, regno, off, size);
7845 		if (!err && t == BPF_READ && value_regno >= 0)
7846 			mark_reg_unknown(env, regs, value_regno);
7847 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7848 		   !type_may_be_null(reg->type)) {
7849 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
7850 					      value_regno);
7851 	} else if (reg->type == CONST_PTR_TO_MAP) {
7852 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7853 					      value_regno);
7854 	} else if (base_type(reg->type) == PTR_TO_BUF) {
7855 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7856 		u32 *max_access;
7857 
7858 		if (rdonly_mem) {
7859 			if (t == BPF_WRITE) {
7860 				verbose(env, "R%d cannot write into %s\n",
7861 					regno, reg_type_str(env, reg->type));
7862 				return -EACCES;
7863 			}
7864 			max_access = &env->prog->aux->max_rdonly_access;
7865 		} else {
7866 			max_access = &env->prog->aux->max_rdwr_access;
7867 		}
7868 
7869 		err = check_buffer_access(env, reg, regno, off, size, false,
7870 					  max_access);
7871 
7872 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7873 			mark_reg_unknown(env, regs, value_regno);
7874 	} else if (reg->type == PTR_TO_ARENA) {
7875 		if (t == BPF_READ && value_regno >= 0)
7876 			mark_reg_unknown(env, regs, value_regno);
7877 	} else {
7878 		verbose(env, "R%d invalid mem access '%s'\n", regno,
7879 			reg_type_str(env, reg->type));
7880 		return -EACCES;
7881 	}
7882 
7883 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7884 	    regs[value_regno].type == SCALAR_VALUE) {
7885 		if (!is_ldsx)
7886 			/* b/h/w load zero-extends, mark upper bits as known 0 */
7887 			coerce_reg_to_size(&regs[value_regno], size);
7888 		else
7889 			coerce_reg_to_size_sx(&regs[value_regno], size);
7890 	}
7891 	return err;
7892 }
7893 
7894 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7895 			     bool allow_trust_mismatch);
7896 
7897 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
7898 			  bool strict_alignment_once, bool is_ldsx,
7899 			  bool allow_trust_mismatch, const char *ctx)
7900 {
7901 	struct bpf_reg_state *regs = cur_regs(env);
7902 	enum bpf_reg_type src_reg_type;
7903 	int err;
7904 
7905 	/* check src operand */
7906 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7907 	if (err)
7908 		return err;
7909 
7910 	/* check dst operand */
7911 	err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7912 	if (err)
7913 		return err;
7914 
7915 	src_reg_type = regs[insn->src_reg].type;
7916 
7917 	/* Check if (src_reg + off) is readable. The state of dst_reg will be
7918 	 * updated by this call.
7919 	 */
7920 	err = check_mem_access(env, env->insn_idx, insn->src_reg, insn->off,
7921 			       BPF_SIZE(insn->code), BPF_READ, insn->dst_reg,
7922 			       strict_alignment_once, is_ldsx);
7923 	err = err ?: save_aux_ptr_type(env, src_reg_type,
7924 				       allow_trust_mismatch);
7925 	err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], ctx);
7926 
7927 	return err;
7928 }
7929 
7930 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,
7931 			   bool strict_alignment_once)
7932 {
7933 	struct bpf_reg_state *regs = cur_regs(env);
7934 	enum bpf_reg_type dst_reg_type;
7935 	int err;
7936 
7937 	/* check src1 operand */
7938 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7939 	if (err)
7940 		return err;
7941 
7942 	/* check src2 operand */
7943 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7944 	if (err)
7945 		return err;
7946 
7947 	dst_reg_type = regs[insn->dst_reg].type;
7948 
7949 	/* Check if (dst_reg + off) is writeable. */
7950 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7951 			       BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg,
7952 			       strict_alignment_once, false);
7953 	err = err ?: save_aux_ptr_type(env, dst_reg_type, false);
7954 
7955 	return err;
7956 }
7957 
7958 static int check_atomic_rmw(struct bpf_verifier_env *env,
7959 			    struct bpf_insn *insn)
7960 {
7961 	int load_reg;
7962 	int err;
7963 
7964 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7965 		verbose(env, "invalid atomic operand size\n");
7966 		return -EINVAL;
7967 	}
7968 
7969 	/* check src1 operand */
7970 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7971 	if (err)
7972 		return err;
7973 
7974 	/* check src2 operand */
7975 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7976 	if (err)
7977 		return err;
7978 
7979 	if (insn->imm == BPF_CMPXCHG) {
7980 		/* Check comparison of R0 with memory location */
7981 		const u32 aux_reg = BPF_REG_0;
7982 
7983 		err = check_reg_arg(env, aux_reg, SRC_OP);
7984 		if (err)
7985 			return err;
7986 
7987 		if (is_pointer_value(env, aux_reg)) {
7988 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7989 			return -EACCES;
7990 		}
7991 	}
7992 
7993 	if (is_pointer_value(env, insn->src_reg)) {
7994 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7995 		return -EACCES;
7996 	}
7997 
7998 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7999 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
8000 			insn->dst_reg,
8001 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
8002 		return -EACCES;
8003 	}
8004 
8005 	if (insn->imm & BPF_FETCH) {
8006 		if (insn->imm == BPF_CMPXCHG)
8007 			load_reg = BPF_REG_0;
8008 		else
8009 			load_reg = insn->src_reg;
8010 
8011 		/* check and record load of old value */
8012 		err = check_reg_arg(env, load_reg, DST_OP);
8013 		if (err)
8014 			return err;
8015 	} else {
8016 		/* This instruction accesses a memory location but doesn't
8017 		 * actually load it into a register.
8018 		 */
8019 		load_reg = -1;
8020 	}
8021 
8022 	/* Check whether we can read the memory, with second call for fetch
8023 	 * case to simulate the register fill.
8024 	 */
8025 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
8026 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
8027 	if (!err && load_reg >= 0)
8028 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
8029 				       insn->off, BPF_SIZE(insn->code),
8030 				       BPF_READ, load_reg, true, false);
8031 	if (err)
8032 		return err;
8033 
8034 	if (is_arena_reg(env, insn->dst_reg)) {
8035 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
8036 		if (err)
8037 			return err;
8038 	}
8039 	/* Check whether we can write into the same memory. */
8040 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
8041 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
8042 	if (err)
8043 		return err;
8044 	return 0;
8045 }
8046 
8047 static int check_atomic_load(struct bpf_verifier_env *env,
8048 			     struct bpf_insn *insn)
8049 {
8050 	int err;
8051 
8052 	err = check_load_mem(env, insn, true, false, false, "atomic_load");
8053 	if (err)
8054 		return err;
8055 
8056 	if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) {
8057 		verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n",
8058 			insn->src_reg,
8059 			reg_type_str(env, reg_state(env, insn->src_reg)->type));
8060 		return -EACCES;
8061 	}
8062 
8063 	return 0;
8064 }
8065 
8066 static int check_atomic_store(struct bpf_verifier_env *env,
8067 			      struct bpf_insn *insn)
8068 {
8069 	int err;
8070 
8071 	err = check_store_reg(env, insn, true);
8072 	if (err)
8073 		return err;
8074 
8075 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
8076 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
8077 			insn->dst_reg,
8078 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
8079 		return -EACCES;
8080 	}
8081 
8082 	return 0;
8083 }
8084 
8085 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn)
8086 {
8087 	switch (insn->imm) {
8088 	case BPF_ADD:
8089 	case BPF_ADD | BPF_FETCH:
8090 	case BPF_AND:
8091 	case BPF_AND | BPF_FETCH:
8092 	case BPF_OR:
8093 	case BPF_OR | BPF_FETCH:
8094 	case BPF_XOR:
8095 	case BPF_XOR | BPF_FETCH:
8096 	case BPF_XCHG:
8097 	case BPF_CMPXCHG:
8098 		return check_atomic_rmw(env, insn);
8099 	case BPF_LOAD_ACQ:
8100 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
8101 			verbose(env,
8102 				"64-bit load-acquires are only supported on 64-bit arches\n");
8103 			return -EOPNOTSUPP;
8104 		}
8105 		return check_atomic_load(env, insn);
8106 	case BPF_STORE_REL:
8107 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
8108 			verbose(env,
8109 				"64-bit store-releases are only supported on 64-bit arches\n");
8110 			return -EOPNOTSUPP;
8111 		}
8112 		return check_atomic_store(env, insn);
8113 	default:
8114 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n",
8115 			insn->imm);
8116 		return -EINVAL;
8117 	}
8118 }
8119 
8120 /* When register 'regno' is used to read the stack (either directly or through
8121  * a helper function) make sure that it's within stack boundary and, depending
8122  * on the access type and privileges, that all elements of the stack are
8123  * initialized.
8124  *
8125  * 'off' includes 'regno->off', but not its dynamic part (if any).
8126  *
8127  * All registers that have been spilled on the stack in the slots within the
8128  * read offsets are marked as read.
8129  */
8130 static int check_stack_range_initialized(
8131 		struct bpf_verifier_env *env, int regno, int off,
8132 		int access_size, bool zero_size_allowed,
8133 		enum bpf_access_type type, struct bpf_call_arg_meta *meta)
8134 {
8135 	struct bpf_reg_state *reg = reg_state(env, regno);
8136 	struct bpf_func_state *state = func(env, reg);
8137 	int err, min_off, max_off, i, j, slot, spi;
8138 	/* Some accesses can write anything into the stack, others are
8139 	 * read-only.
8140 	 */
8141 	bool clobber = false;
8142 
8143 	if (access_size == 0 && !zero_size_allowed) {
8144 		verbose(env, "invalid zero-sized read\n");
8145 		return -EACCES;
8146 	}
8147 
8148 	if (type == BPF_WRITE)
8149 		clobber = true;
8150 
8151 	err = check_stack_access_within_bounds(env, regno, off, access_size, type);
8152 	if (err)
8153 		return err;
8154 
8155 
8156 	if (tnum_is_const(reg->var_off)) {
8157 		min_off = max_off = reg->var_off.value + off;
8158 	} else {
8159 		/* Variable offset is prohibited for unprivileged mode for
8160 		 * simplicity since it requires corresponding support in
8161 		 * Spectre masking for stack ALU.
8162 		 * See also retrieve_ptr_limit().
8163 		 */
8164 		if (!env->bypass_spec_v1) {
8165 			char tn_buf[48];
8166 
8167 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8168 			verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
8169 				regno, tn_buf);
8170 			return -EACCES;
8171 		}
8172 		/* Only initialized buffer on stack is allowed to be accessed
8173 		 * with variable offset. With uninitialized buffer it's hard to
8174 		 * guarantee that whole memory is marked as initialized on
8175 		 * helper return since specific bounds are unknown what may
8176 		 * cause uninitialized stack leaking.
8177 		 */
8178 		if (meta && meta->raw_mode)
8179 			meta = NULL;
8180 
8181 		min_off = reg->smin_value + off;
8182 		max_off = reg->smax_value + off;
8183 	}
8184 
8185 	if (meta && meta->raw_mode) {
8186 		/* Ensure we won't be overwriting dynptrs when simulating byte
8187 		 * by byte access in check_helper_call using meta.access_size.
8188 		 * This would be a problem if we have a helper in the future
8189 		 * which takes:
8190 		 *
8191 		 *	helper(uninit_mem, len, dynptr)
8192 		 *
8193 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
8194 		 * may end up writing to dynptr itself when touching memory from
8195 		 * arg 1. This can be relaxed on a case by case basis for known
8196 		 * safe cases, but reject due to the possibilitiy of aliasing by
8197 		 * default.
8198 		 */
8199 		for (i = min_off; i < max_off + access_size; i++) {
8200 			int stack_off = -i - 1;
8201 
8202 			spi = __get_spi(i);
8203 			/* raw_mode may write past allocated_stack */
8204 			if (state->allocated_stack <= stack_off)
8205 				continue;
8206 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
8207 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
8208 				return -EACCES;
8209 			}
8210 		}
8211 		meta->access_size = access_size;
8212 		meta->regno = regno;
8213 		return 0;
8214 	}
8215 
8216 	for (i = min_off; i < max_off + access_size; i++) {
8217 		u8 *stype;
8218 
8219 		slot = -i - 1;
8220 		spi = slot / BPF_REG_SIZE;
8221 		if (state->allocated_stack <= slot) {
8222 			verbose(env, "allocated_stack too small\n");
8223 			return -EFAULT;
8224 		}
8225 
8226 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
8227 		if (*stype == STACK_MISC)
8228 			goto mark;
8229 		if ((*stype == STACK_ZERO) ||
8230 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
8231 			if (clobber) {
8232 				/* helper can write anything into the stack */
8233 				*stype = STACK_MISC;
8234 			}
8235 			goto mark;
8236 		}
8237 
8238 		if (is_spilled_reg(&state->stack[spi]) &&
8239 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
8240 		     env->allow_ptr_leaks)) {
8241 			if (clobber) {
8242 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
8243 				for (j = 0; j < BPF_REG_SIZE; j++)
8244 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
8245 			}
8246 			goto mark;
8247 		}
8248 
8249 		if (tnum_is_const(reg->var_off)) {
8250 			verbose(env, "invalid read from stack R%d off %d+%d size %d\n",
8251 				regno, min_off, i - min_off, access_size);
8252 		} else {
8253 			char tn_buf[48];
8254 
8255 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8256 			verbose(env, "invalid read from stack R%d var_off %s+%d size %d\n",
8257 				regno, tn_buf, i - min_off, access_size);
8258 		}
8259 		return -EACCES;
8260 mark:
8261 		/* reading any byte out of 8-byte 'spill_slot' will cause
8262 		 * the whole slot to be marked as 'read'
8263 		 */
8264 		err = bpf_mark_stack_read(env, reg->frameno, env->insn_idx, BIT(spi));
8265 		if (err)
8266 			return err;
8267 		/* We do not call bpf_mark_stack_write(), as we can not
8268 		 * be sure that whether stack slot is written to or not. Hence,
8269 		 * we must still conservatively propagate reads upwards even if
8270 		 * helper may write to the entire memory range.
8271 		 */
8272 	}
8273 	return 0;
8274 }
8275 
8276 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
8277 				   int access_size, enum bpf_access_type access_type,
8278 				   bool zero_size_allowed,
8279 				   struct bpf_call_arg_meta *meta)
8280 {
8281 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8282 	u32 *max_access;
8283 
8284 	switch (base_type(reg->type)) {
8285 	case PTR_TO_PACKET:
8286 	case PTR_TO_PACKET_META:
8287 		return check_packet_access(env, regno, reg->off, access_size,
8288 					   zero_size_allowed);
8289 	case PTR_TO_MAP_KEY:
8290 		if (access_type == BPF_WRITE) {
8291 			verbose(env, "R%d cannot write into %s\n", regno,
8292 				reg_type_str(env, reg->type));
8293 			return -EACCES;
8294 		}
8295 		return check_mem_region_access(env, regno, reg->off, access_size,
8296 					       reg->map_ptr->key_size, false);
8297 	case PTR_TO_MAP_VALUE:
8298 		if (check_map_access_type(env, regno, reg->off, access_size, access_type))
8299 			return -EACCES;
8300 		return check_map_access(env, regno, reg->off, access_size,
8301 					zero_size_allowed, ACCESS_HELPER);
8302 	case PTR_TO_MEM:
8303 		if (type_is_rdonly_mem(reg->type)) {
8304 			if (access_type == BPF_WRITE) {
8305 				verbose(env, "R%d cannot write into %s\n", regno,
8306 					reg_type_str(env, reg->type));
8307 				return -EACCES;
8308 			}
8309 		}
8310 		return check_mem_region_access(env, regno, reg->off,
8311 					       access_size, reg->mem_size,
8312 					       zero_size_allowed);
8313 	case PTR_TO_BUF:
8314 		if (type_is_rdonly_mem(reg->type)) {
8315 			if (access_type == BPF_WRITE) {
8316 				verbose(env, "R%d cannot write into %s\n", regno,
8317 					reg_type_str(env, reg->type));
8318 				return -EACCES;
8319 			}
8320 
8321 			max_access = &env->prog->aux->max_rdonly_access;
8322 		} else {
8323 			max_access = &env->prog->aux->max_rdwr_access;
8324 		}
8325 		return check_buffer_access(env, reg, regno, reg->off,
8326 					   access_size, zero_size_allowed,
8327 					   max_access);
8328 	case PTR_TO_STACK:
8329 		return check_stack_range_initialized(
8330 				env,
8331 				regno, reg->off, access_size,
8332 				zero_size_allowed, access_type, meta);
8333 	case PTR_TO_BTF_ID:
8334 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
8335 					       access_size, BPF_READ, -1);
8336 	case PTR_TO_CTX:
8337 		/* in case the function doesn't know how to access the context,
8338 		 * (because we are in a program of type SYSCALL for example), we
8339 		 * can not statically check its size.
8340 		 * Dynamically check it now.
8341 		 */
8342 		if (!env->ops->convert_ctx_access) {
8343 			int offset = access_size - 1;
8344 
8345 			/* Allow zero-byte read from PTR_TO_CTX */
8346 			if (access_size == 0)
8347 				return zero_size_allowed ? 0 : -EACCES;
8348 
8349 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
8350 						access_type, -1, false, false);
8351 		}
8352 
8353 		fallthrough;
8354 	default: /* scalar_value or invalid ptr */
8355 		/* Allow zero-byte read from NULL, regardless of pointer type */
8356 		if (zero_size_allowed && access_size == 0 &&
8357 		    register_is_null(reg))
8358 			return 0;
8359 
8360 		verbose(env, "R%d type=%s ", regno,
8361 			reg_type_str(env, reg->type));
8362 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
8363 		return -EACCES;
8364 	}
8365 }
8366 
8367 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
8368  * size.
8369  *
8370  * @regno is the register containing the access size. regno-1 is the register
8371  * containing the pointer.
8372  */
8373 static int check_mem_size_reg(struct bpf_verifier_env *env,
8374 			      struct bpf_reg_state *reg, u32 regno,
8375 			      enum bpf_access_type access_type,
8376 			      bool zero_size_allowed,
8377 			      struct bpf_call_arg_meta *meta)
8378 {
8379 	int err;
8380 
8381 	/* This is used to refine r0 return value bounds for helpers
8382 	 * that enforce this value as an upper bound on return values.
8383 	 * See do_refine_retval_range() for helpers that can refine
8384 	 * the return value. C type of helper is u32 so we pull register
8385 	 * bound from umax_value however, if negative verifier errors
8386 	 * out. Only upper bounds can be learned because retval is an
8387 	 * int type and negative retvals are allowed.
8388 	 */
8389 	meta->msize_max_value = reg->umax_value;
8390 
8391 	/* The register is SCALAR_VALUE; the access check happens using
8392 	 * its boundaries. For unprivileged variable accesses, disable
8393 	 * raw mode so that the program is required to initialize all
8394 	 * the memory that the helper could just partially fill up.
8395 	 */
8396 	if (!tnum_is_const(reg->var_off))
8397 		meta = NULL;
8398 
8399 	if (reg->smin_value < 0) {
8400 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
8401 			regno);
8402 		return -EACCES;
8403 	}
8404 
8405 	if (reg->umin_value == 0 && !zero_size_allowed) {
8406 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
8407 			regno, reg->umin_value, reg->umax_value);
8408 		return -EACCES;
8409 	}
8410 
8411 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
8412 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
8413 			regno);
8414 		return -EACCES;
8415 	}
8416 	err = check_helper_mem_access(env, regno - 1, reg->umax_value,
8417 				      access_type, zero_size_allowed, meta);
8418 	if (!err)
8419 		err = mark_chain_precision(env, regno);
8420 	return err;
8421 }
8422 
8423 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8424 			 u32 regno, u32 mem_size)
8425 {
8426 	bool may_be_null = type_may_be_null(reg->type);
8427 	struct bpf_reg_state saved_reg;
8428 	int err;
8429 
8430 	if (register_is_null(reg))
8431 		return 0;
8432 
8433 	/* Assuming that the register contains a value check if the memory
8434 	 * access is safe. Temporarily save and restore the register's state as
8435 	 * the conversion shouldn't be visible to a caller.
8436 	 */
8437 	if (may_be_null) {
8438 		saved_reg = *reg;
8439 		mark_ptr_not_null_reg(reg);
8440 	}
8441 
8442 	err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL);
8443 	err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL);
8444 
8445 	if (may_be_null)
8446 		*reg = saved_reg;
8447 
8448 	return err;
8449 }
8450 
8451 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8452 				    u32 regno)
8453 {
8454 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
8455 	bool may_be_null = type_may_be_null(mem_reg->type);
8456 	struct bpf_reg_state saved_reg;
8457 	struct bpf_call_arg_meta meta;
8458 	int err;
8459 
8460 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
8461 
8462 	memset(&meta, 0, sizeof(meta));
8463 
8464 	if (may_be_null) {
8465 		saved_reg = *mem_reg;
8466 		mark_ptr_not_null_reg(mem_reg);
8467 	}
8468 
8469 	err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta);
8470 	err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta);
8471 
8472 	if (may_be_null)
8473 		*mem_reg = saved_reg;
8474 
8475 	return err;
8476 }
8477 
8478 enum {
8479 	PROCESS_SPIN_LOCK = (1 << 0),
8480 	PROCESS_RES_LOCK  = (1 << 1),
8481 	PROCESS_LOCK_IRQ  = (1 << 2),
8482 };
8483 
8484 /* Implementation details:
8485  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
8486  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
8487  * Two bpf_map_lookups (even with the same key) will have different reg->id.
8488  * Two separate bpf_obj_new will also have different reg->id.
8489  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
8490  * clears reg->id after value_or_null->value transition, since the verifier only
8491  * cares about the range of access to valid map value pointer and doesn't care
8492  * about actual address of the map element.
8493  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
8494  * reg->id > 0 after value_or_null->value transition. By doing so
8495  * two bpf_map_lookups will be considered two different pointers that
8496  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
8497  * returned from bpf_obj_new.
8498  * The verifier allows taking only one bpf_spin_lock at a time to avoid
8499  * dead-locks.
8500  * Since only one bpf_spin_lock is allowed the checks are simpler than
8501  * reg_is_refcounted() logic. The verifier needs to remember only
8502  * one spin_lock instead of array of acquired_refs.
8503  * env->cur_state->active_locks remembers which map value element or allocated
8504  * object got locked and clears it after bpf_spin_unlock.
8505  */
8506 static int process_spin_lock(struct bpf_verifier_env *env, int regno, int flags)
8507 {
8508 	bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK;
8509 	const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin";
8510 	struct bpf_reg_state *reg = reg_state(env, regno);
8511 	struct bpf_verifier_state *cur = env->cur_state;
8512 	bool is_const = tnum_is_const(reg->var_off);
8513 	bool is_irq = flags & PROCESS_LOCK_IRQ;
8514 	u64 val = reg->var_off.value;
8515 	struct bpf_map *map = NULL;
8516 	struct btf *btf = NULL;
8517 	struct btf_record *rec;
8518 	u32 spin_lock_off;
8519 	int err;
8520 
8521 	if (!is_const) {
8522 		verbose(env,
8523 			"R%d doesn't have constant offset. %s_lock has to be at the constant offset\n",
8524 			regno, lock_str);
8525 		return -EINVAL;
8526 	}
8527 	if (reg->type == PTR_TO_MAP_VALUE) {
8528 		map = reg->map_ptr;
8529 		if (!map->btf) {
8530 			verbose(env,
8531 				"map '%s' has to have BTF in order to use %s_lock\n",
8532 				map->name, lock_str);
8533 			return -EINVAL;
8534 		}
8535 	} else {
8536 		btf = reg->btf;
8537 	}
8538 
8539 	rec = reg_btf_record(reg);
8540 	if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) {
8541 		verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local",
8542 			map ? map->name : "kptr", lock_str);
8543 		return -EINVAL;
8544 	}
8545 	spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off;
8546 	if (spin_lock_off != val + reg->off) {
8547 		verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n",
8548 			val + reg->off, lock_str, spin_lock_off);
8549 		return -EINVAL;
8550 	}
8551 	if (is_lock) {
8552 		void *ptr;
8553 		int type;
8554 
8555 		if (map)
8556 			ptr = map;
8557 		else
8558 			ptr = btf;
8559 
8560 		if (!is_res_lock && cur->active_locks) {
8561 			if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) {
8562 				verbose(env,
8563 					"Locking two bpf_spin_locks are not allowed\n");
8564 				return -EINVAL;
8565 			}
8566 		} else if (is_res_lock && cur->active_locks) {
8567 			if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) {
8568 				verbose(env, "Acquiring the same lock again, AA deadlock detected\n");
8569 				return -EINVAL;
8570 			}
8571 		}
8572 
8573 		if (is_res_lock && is_irq)
8574 			type = REF_TYPE_RES_LOCK_IRQ;
8575 		else if (is_res_lock)
8576 			type = REF_TYPE_RES_LOCK;
8577 		else
8578 			type = REF_TYPE_LOCK;
8579 		err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr);
8580 		if (err < 0) {
8581 			verbose(env, "Failed to acquire lock state\n");
8582 			return err;
8583 		}
8584 	} else {
8585 		void *ptr;
8586 		int type;
8587 
8588 		if (map)
8589 			ptr = map;
8590 		else
8591 			ptr = btf;
8592 
8593 		if (!cur->active_locks) {
8594 			verbose(env, "%s_unlock without taking a lock\n", lock_str);
8595 			return -EINVAL;
8596 		}
8597 
8598 		if (is_res_lock && is_irq)
8599 			type = REF_TYPE_RES_LOCK_IRQ;
8600 		else if (is_res_lock)
8601 			type = REF_TYPE_RES_LOCK;
8602 		else
8603 			type = REF_TYPE_LOCK;
8604 		if (!find_lock_state(cur, type, reg->id, ptr)) {
8605 			verbose(env, "%s_unlock of different lock\n", lock_str);
8606 			return -EINVAL;
8607 		}
8608 		if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) {
8609 			verbose(env, "%s_unlock cannot be out of order\n", lock_str);
8610 			return -EINVAL;
8611 		}
8612 		if (release_lock_state(cur, type, reg->id, ptr)) {
8613 			verbose(env, "%s_unlock of different lock\n", lock_str);
8614 			return -EINVAL;
8615 		}
8616 
8617 		invalidate_non_owning_refs(env);
8618 	}
8619 	return 0;
8620 }
8621 
8622 /* Check if @regno is a pointer to a specific field in a map value */
8623 static int check_map_field_pointer(struct bpf_verifier_env *env, u32 regno,
8624 				   enum btf_field_type field_type,
8625 				   struct bpf_map_desc *map_desc)
8626 {
8627 	struct bpf_reg_state *reg = reg_state(env, regno);
8628 	bool is_const = tnum_is_const(reg->var_off);
8629 	struct bpf_map *map = reg->map_ptr;
8630 	u64 val = reg->var_off.value;
8631 	const char *struct_name = btf_field_type_name(field_type);
8632 	int field_off = -1;
8633 
8634 	if (!is_const) {
8635 		verbose(env,
8636 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
8637 			regno, struct_name);
8638 		return -EINVAL;
8639 	}
8640 	if (!map->btf) {
8641 		verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name,
8642 			struct_name);
8643 		return -EINVAL;
8644 	}
8645 	if (!btf_record_has_field(map->record, field_type)) {
8646 		verbose(env, "map '%s' has no valid %s\n", map->name, struct_name);
8647 		return -EINVAL;
8648 	}
8649 	switch (field_type) {
8650 	case BPF_TIMER:
8651 		field_off = map->record->timer_off;
8652 		break;
8653 	case BPF_TASK_WORK:
8654 		field_off = map->record->task_work_off;
8655 		break;
8656 	case BPF_WORKQUEUE:
8657 		field_off = map->record->wq_off;
8658 		break;
8659 	default:
8660 		verifier_bug(env, "unsupported BTF field type: %s\n", struct_name);
8661 		return -EINVAL;
8662 	}
8663 	if (field_off != val + reg->off) {
8664 		verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n",
8665 			val + reg->off, struct_name, field_off);
8666 		return -EINVAL;
8667 	}
8668 	if (map_desc->ptr) {
8669 		verifier_bug(env, "Two map pointers in a %s helper", struct_name);
8670 		return -EFAULT;
8671 	}
8672 	map_desc->uid = reg->map_uid;
8673 	map_desc->ptr = map;
8674 	return 0;
8675 }
8676 
8677 static int process_timer_func(struct bpf_verifier_env *env, int regno,
8678 			      struct bpf_map_desc *map)
8679 {
8680 	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
8681 		verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n");
8682 		return -EOPNOTSUPP;
8683 	}
8684 	return check_map_field_pointer(env, regno, BPF_TIMER, map);
8685 }
8686 
8687 static int process_timer_helper(struct bpf_verifier_env *env, int regno,
8688 				struct bpf_call_arg_meta *meta)
8689 {
8690 	return process_timer_func(env, regno, &meta->map);
8691 }
8692 
8693 static int process_timer_kfunc(struct bpf_verifier_env *env, int regno,
8694 			       struct bpf_kfunc_call_arg_meta *meta)
8695 {
8696 	return process_timer_func(env, regno, &meta->map);
8697 }
8698 
8699 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
8700 			     struct bpf_call_arg_meta *meta)
8701 {
8702 	struct bpf_reg_state *reg = reg_state(env, regno);
8703 	struct btf_field *kptr_field;
8704 	struct bpf_map *map_ptr;
8705 	struct btf_record *rec;
8706 	u32 kptr_off;
8707 
8708 	if (type_is_ptr_alloc_obj(reg->type)) {
8709 		rec = reg_btf_record(reg);
8710 	} else { /* PTR_TO_MAP_VALUE */
8711 		map_ptr = reg->map_ptr;
8712 		if (!map_ptr->btf) {
8713 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
8714 				map_ptr->name);
8715 			return -EINVAL;
8716 		}
8717 		rec = map_ptr->record;
8718 		meta->map.ptr = map_ptr;
8719 	}
8720 
8721 	if (!tnum_is_const(reg->var_off)) {
8722 		verbose(env,
8723 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
8724 			regno);
8725 		return -EINVAL;
8726 	}
8727 
8728 	if (!btf_record_has_field(rec, BPF_KPTR)) {
8729 		verbose(env, "R%d has no valid kptr\n", regno);
8730 		return -EINVAL;
8731 	}
8732 
8733 	kptr_off = reg->off + reg->var_off.value;
8734 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
8735 	if (!kptr_field) {
8736 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
8737 		return -EACCES;
8738 	}
8739 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
8740 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
8741 		return -EACCES;
8742 	}
8743 	meta->kptr_field = kptr_field;
8744 	return 0;
8745 }
8746 
8747 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
8748  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
8749  *
8750  * In both cases we deal with the first 8 bytes, but need to mark the next 8
8751  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
8752  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
8753  *
8754  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
8755  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
8756  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
8757  * mutate the view of the dynptr and also possibly destroy it. In the latter
8758  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
8759  * memory that dynptr points to.
8760  *
8761  * The verifier will keep track both levels of mutation (bpf_dynptr's in
8762  * reg->type and the memory's in reg->dynptr.type), but there is no support for
8763  * readonly dynptr view yet, hence only the first case is tracked and checked.
8764  *
8765  * This is consistent with how C applies the const modifier to a struct object,
8766  * where the pointer itself inside bpf_dynptr becomes const but not what it
8767  * points to.
8768  *
8769  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
8770  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
8771  */
8772 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
8773 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
8774 {
8775 	struct bpf_reg_state *reg = reg_state(env, regno);
8776 	int err;
8777 
8778 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
8779 		verbose(env,
8780 			"arg#%d expected pointer to stack or const struct bpf_dynptr\n",
8781 			regno - 1);
8782 		return -EINVAL;
8783 	}
8784 
8785 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
8786 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
8787 	 */
8788 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
8789 		verifier_bug(env, "misconfigured dynptr helper type flags");
8790 		return -EFAULT;
8791 	}
8792 
8793 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
8794 	 *		 constructing a mutable bpf_dynptr object.
8795 	 *
8796 	 *		 Currently, this is only possible with PTR_TO_STACK
8797 	 *		 pointing to a region of at least 16 bytes which doesn't
8798 	 *		 contain an existing bpf_dynptr.
8799 	 *
8800 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
8801 	 *		 mutated or destroyed. However, the memory it points to
8802 	 *		 may be mutated.
8803 	 *
8804 	 *  None       - Points to a initialized dynptr that can be mutated and
8805 	 *		 destroyed, including mutation of the memory it points
8806 	 *		 to.
8807 	 */
8808 	if (arg_type & MEM_UNINIT) {
8809 		int i;
8810 
8811 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
8812 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
8813 			return -EINVAL;
8814 		}
8815 
8816 		/* we write BPF_DW bits (8 bytes) at a time */
8817 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8818 			err = check_mem_access(env, insn_idx, regno,
8819 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8820 			if (err)
8821 				return err;
8822 		}
8823 
8824 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
8825 	} else /* MEM_RDONLY and None case from above */ {
8826 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
8827 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
8828 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
8829 			return -EINVAL;
8830 		}
8831 
8832 		if (!is_dynptr_reg_valid_init(env, reg)) {
8833 			verbose(env,
8834 				"Expected an initialized dynptr as arg #%d\n",
8835 				regno - 1);
8836 			return -EINVAL;
8837 		}
8838 
8839 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
8840 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
8841 			verbose(env,
8842 				"Expected a dynptr of type %s as arg #%d\n",
8843 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1);
8844 			return -EINVAL;
8845 		}
8846 
8847 		err = mark_dynptr_read(env, reg);
8848 	}
8849 	return err;
8850 }
8851 
8852 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
8853 {
8854 	struct bpf_func_state *state = func(env, reg);
8855 
8856 	return state->stack[spi].spilled_ptr.ref_obj_id;
8857 }
8858 
8859 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8860 {
8861 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8862 }
8863 
8864 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8865 {
8866 	return meta->kfunc_flags & KF_ITER_NEW;
8867 }
8868 
8869 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8870 {
8871 	return meta->kfunc_flags & KF_ITER_NEXT;
8872 }
8873 
8874 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8875 {
8876 	return meta->kfunc_flags & KF_ITER_DESTROY;
8877 }
8878 
8879 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
8880 			      const struct btf_param *arg)
8881 {
8882 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
8883 	 * kfunc is iter state pointer
8884 	 */
8885 	if (is_iter_kfunc(meta))
8886 		return arg_idx == 0;
8887 
8888 	/* iter passed as an argument to a generic kfunc */
8889 	return btf_param_match_suffix(meta->btf, arg, "__iter");
8890 }
8891 
8892 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
8893 			    struct bpf_kfunc_call_arg_meta *meta)
8894 {
8895 	struct bpf_reg_state *reg = reg_state(env, regno);
8896 	const struct btf_type *t;
8897 	int spi, err, i, nr_slots, btf_id;
8898 
8899 	if (reg->type != PTR_TO_STACK) {
8900 		verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1);
8901 		return -EINVAL;
8902 	}
8903 
8904 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8905 	 * ensures struct convention, so we wouldn't need to do any BTF
8906 	 * validation here. But given iter state can be passed as a parameter
8907 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8908 	 * conservative here.
8909 	 */
8910 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1);
8911 	if (btf_id < 0) {
8912 		verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1);
8913 		return -EINVAL;
8914 	}
8915 	t = btf_type_by_id(meta->btf, btf_id);
8916 	nr_slots = t->size / BPF_REG_SIZE;
8917 
8918 	if (is_iter_new_kfunc(meta)) {
8919 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
8920 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8921 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
8922 				iter_type_str(meta->btf, btf_id), regno - 1);
8923 			return -EINVAL;
8924 		}
8925 
8926 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8927 			err = check_mem_access(env, insn_idx, regno,
8928 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8929 			if (err)
8930 				return err;
8931 		}
8932 
8933 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8934 		if (err)
8935 			return err;
8936 	} else {
8937 		/* iter_next() or iter_destroy(), as well as any kfunc
8938 		 * accepting iter argument, expect initialized iter state
8939 		 */
8940 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8941 		switch (err) {
8942 		case 0:
8943 			break;
8944 		case -EINVAL:
8945 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
8946 				iter_type_str(meta->btf, btf_id), regno - 1);
8947 			return err;
8948 		case -EPROTO:
8949 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8950 			return err;
8951 		default:
8952 			return err;
8953 		}
8954 
8955 		spi = iter_get_spi(env, reg, nr_slots);
8956 		if (spi < 0)
8957 			return spi;
8958 
8959 		err = mark_iter_read(env, reg, spi, nr_slots);
8960 		if (err)
8961 			return err;
8962 
8963 		/* remember meta->iter info for process_iter_next_call() */
8964 		meta->iter.spi = spi;
8965 		meta->iter.frameno = reg->frameno;
8966 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
8967 
8968 		if (is_iter_destroy_kfunc(meta)) {
8969 			err = unmark_stack_slots_iter(env, reg, nr_slots);
8970 			if (err)
8971 				return err;
8972 		}
8973 	}
8974 
8975 	return 0;
8976 }
8977 
8978 /* Look for a previous loop entry at insn_idx: nearest parent state
8979  * stopped at insn_idx with callsites matching those in cur->frame.
8980  */
8981 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
8982 						  struct bpf_verifier_state *cur,
8983 						  int insn_idx)
8984 {
8985 	struct bpf_verifier_state_list *sl;
8986 	struct bpf_verifier_state *st;
8987 	struct list_head *pos, *head;
8988 
8989 	/* Explored states are pushed in stack order, most recent states come first */
8990 	head = explored_state(env, insn_idx);
8991 	list_for_each(pos, head) {
8992 		sl = container_of(pos, struct bpf_verifier_state_list, node);
8993 		/* If st->branches != 0 state is a part of current DFS verification path,
8994 		 * hence cur & st for a loop.
8995 		 */
8996 		st = &sl->state;
8997 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
8998 		    st->dfs_depth < cur->dfs_depth)
8999 			return st;
9000 	}
9001 
9002 	return NULL;
9003 }
9004 
9005 static void reset_idmap_scratch(struct bpf_verifier_env *env);
9006 static bool regs_exact(const struct bpf_reg_state *rold,
9007 		       const struct bpf_reg_state *rcur,
9008 		       struct bpf_idmap *idmap);
9009 
9010 /*
9011  * Check if scalar registers are exact for the purpose of not widening.
9012  * More lenient than regs_exact()
9013  */
9014 static bool scalars_exact_for_widen(const struct bpf_reg_state *rold,
9015 				    const struct bpf_reg_state *rcur)
9016 {
9017 	return !memcmp(rold, rcur, offsetof(struct bpf_reg_state, id));
9018 }
9019 
9020 static void maybe_widen_reg(struct bpf_verifier_env *env,
9021 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur)
9022 {
9023 	if (rold->type != SCALAR_VALUE)
9024 		return;
9025 	if (rold->type != rcur->type)
9026 		return;
9027 	if (rold->precise || rcur->precise || scalars_exact_for_widen(rold, rcur))
9028 		return;
9029 	__mark_reg_unknown(env, rcur);
9030 }
9031 
9032 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
9033 				   struct bpf_verifier_state *old,
9034 				   struct bpf_verifier_state *cur)
9035 {
9036 	struct bpf_func_state *fold, *fcur;
9037 	int i, fr, num_slots;
9038 
9039 	for (fr = old->curframe; fr >= 0; fr--) {
9040 		fold = old->frame[fr];
9041 		fcur = cur->frame[fr];
9042 
9043 		for (i = 0; i < MAX_BPF_REG; i++)
9044 			maybe_widen_reg(env,
9045 					&fold->regs[i],
9046 					&fcur->regs[i]);
9047 
9048 		num_slots = min(fold->allocated_stack / BPF_REG_SIZE,
9049 				fcur->allocated_stack / BPF_REG_SIZE);
9050 		for (i = 0; i < num_slots; i++) {
9051 			if (!is_spilled_reg(&fold->stack[i]) ||
9052 			    !is_spilled_reg(&fcur->stack[i]))
9053 				continue;
9054 
9055 			maybe_widen_reg(env,
9056 					&fold->stack[i].spilled_ptr,
9057 					&fcur->stack[i].spilled_ptr);
9058 		}
9059 	}
9060 	return 0;
9061 }
9062 
9063 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
9064 						 struct bpf_kfunc_call_arg_meta *meta)
9065 {
9066 	int iter_frameno = meta->iter.frameno;
9067 	int iter_spi = meta->iter.spi;
9068 
9069 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
9070 }
9071 
9072 /* process_iter_next_call() is called when verifier gets to iterator's next
9073  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
9074  * to it as just "iter_next()" in comments below.
9075  *
9076  * BPF verifier relies on a crucial contract for any iter_next()
9077  * implementation: it should *eventually* return NULL, and once that happens
9078  * it should keep returning NULL. That is, once iterator exhausts elements to
9079  * iterate, it should never reset or spuriously return new elements.
9080  *
9081  * With the assumption of such contract, process_iter_next_call() simulates
9082  * a fork in the verifier state to validate loop logic correctness and safety
9083  * without having to simulate infinite amount of iterations.
9084  *
9085  * In current state, we first assume that iter_next() returned NULL and
9086  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
9087  * conditions we should not form an infinite loop and should eventually reach
9088  * exit.
9089  *
9090  * Besides that, we also fork current state and enqueue it for later
9091  * verification. In a forked state we keep iterator state as ACTIVE
9092  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
9093  * also bump iteration depth to prevent erroneous infinite loop detection
9094  * later on (see iter_active_depths_differ() comment for details). In this
9095  * state we assume that we'll eventually loop back to another iter_next()
9096  * calls (it could be in exactly same location or in some other instruction,
9097  * it doesn't matter, we don't make any unnecessary assumptions about this,
9098  * everything revolves around iterator state in a stack slot, not which
9099  * instruction is calling iter_next()). When that happens, we either will come
9100  * to iter_next() with equivalent state and can conclude that next iteration
9101  * will proceed in exactly the same way as we just verified, so it's safe to
9102  * assume that loop converges. If not, we'll go on another iteration
9103  * simulation with a different input state, until all possible starting states
9104  * are validated or we reach maximum number of instructions limit.
9105  *
9106  * This way, we will either exhaustively discover all possible input states
9107  * that iterator loop can start with and eventually will converge, or we'll
9108  * effectively regress into bounded loop simulation logic and either reach
9109  * maximum number of instructions if loop is not provably convergent, or there
9110  * is some statically known limit on number of iterations (e.g., if there is
9111  * an explicit `if n > 100 then break;` statement somewhere in the loop).
9112  *
9113  * Iteration convergence logic in is_state_visited() relies on exact
9114  * states comparison, which ignores read and precision marks.
9115  * This is necessary because read and precision marks are not finalized
9116  * while in the loop. Exact comparison might preclude convergence for
9117  * simple programs like below:
9118  *
9119  *     i = 0;
9120  *     while(iter_next(&it))
9121  *       i++;
9122  *
9123  * At each iteration step i++ would produce a new distinct state and
9124  * eventually instruction processing limit would be reached.
9125  *
9126  * To avoid such behavior speculatively forget (widen) range for
9127  * imprecise scalar registers, if those registers were not precise at the
9128  * end of the previous iteration and do not match exactly.
9129  *
9130  * This is a conservative heuristic that allows to verify wide range of programs,
9131  * however it precludes verification of programs that conjure an
9132  * imprecise value on the first loop iteration and use it as precise on a second.
9133  * For example, the following safe program would fail to verify:
9134  *
9135  *     struct bpf_num_iter it;
9136  *     int arr[10];
9137  *     int i = 0, a = 0;
9138  *     bpf_iter_num_new(&it, 0, 10);
9139  *     while (bpf_iter_num_next(&it)) {
9140  *       if (a == 0) {
9141  *         a = 1;
9142  *         i = 7; // Because i changed verifier would forget
9143  *                // it's range on second loop entry.
9144  *       } else {
9145  *         arr[i] = 42; // This would fail to verify.
9146  *       }
9147  *     }
9148  *     bpf_iter_num_destroy(&it);
9149  */
9150 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
9151 				  struct bpf_kfunc_call_arg_meta *meta)
9152 {
9153 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
9154 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
9155 	struct bpf_reg_state *cur_iter, *queued_iter;
9156 
9157 	BTF_TYPE_EMIT(struct bpf_iter);
9158 
9159 	cur_iter = get_iter_from_state(cur_st, meta);
9160 
9161 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
9162 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
9163 		verifier_bug(env, "unexpected iterator state %d (%s)",
9164 			     cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
9165 		return -EFAULT;
9166 	}
9167 
9168 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
9169 		/* Because iter_next() call is a checkpoint is_state_visitied()
9170 		 * should guarantee parent state with same call sites and insn_idx.
9171 		 */
9172 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
9173 		    !same_callsites(cur_st->parent, cur_st)) {
9174 			verifier_bug(env, "bad parent state for iter next call");
9175 			return -EFAULT;
9176 		}
9177 		/* Note cur_st->parent in the call below, it is necessary to skip
9178 		 * checkpoint created for cur_st by is_state_visited()
9179 		 * right at this instruction.
9180 		 */
9181 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
9182 		/* branch out active iter state */
9183 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
9184 		if (IS_ERR(queued_st))
9185 			return PTR_ERR(queued_st);
9186 
9187 		queued_iter = get_iter_from_state(queued_st, meta);
9188 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
9189 		queued_iter->iter.depth++;
9190 		if (prev_st)
9191 			widen_imprecise_scalars(env, prev_st, queued_st);
9192 
9193 		queued_fr = queued_st->frame[queued_st->curframe];
9194 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
9195 	}
9196 
9197 	/* switch to DRAINED state, but keep the depth unchanged */
9198 	/* mark current iter state as drained and assume returned NULL */
9199 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
9200 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
9201 
9202 	return 0;
9203 }
9204 
9205 static bool arg_type_is_mem_size(enum bpf_arg_type type)
9206 {
9207 	return type == ARG_CONST_SIZE ||
9208 	       type == ARG_CONST_SIZE_OR_ZERO;
9209 }
9210 
9211 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
9212 {
9213 	return base_type(type) == ARG_PTR_TO_MEM &&
9214 	       type & MEM_UNINIT;
9215 }
9216 
9217 static bool arg_type_is_release(enum bpf_arg_type type)
9218 {
9219 	return type & OBJ_RELEASE;
9220 }
9221 
9222 static bool arg_type_is_dynptr(enum bpf_arg_type type)
9223 {
9224 	return base_type(type) == ARG_PTR_TO_DYNPTR;
9225 }
9226 
9227 static int resolve_map_arg_type(struct bpf_verifier_env *env,
9228 				 const struct bpf_call_arg_meta *meta,
9229 				 enum bpf_arg_type *arg_type)
9230 {
9231 	if (!meta->map.ptr) {
9232 		/* kernel subsystem misconfigured verifier */
9233 		verifier_bug(env, "invalid map_ptr to access map->type");
9234 		return -EFAULT;
9235 	}
9236 
9237 	switch (meta->map.ptr->map_type) {
9238 	case BPF_MAP_TYPE_SOCKMAP:
9239 	case BPF_MAP_TYPE_SOCKHASH:
9240 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
9241 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
9242 		} else {
9243 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
9244 			return -EINVAL;
9245 		}
9246 		break;
9247 	case BPF_MAP_TYPE_BLOOM_FILTER:
9248 		if (meta->func_id == BPF_FUNC_map_peek_elem)
9249 			*arg_type = ARG_PTR_TO_MAP_VALUE;
9250 		break;
9251 	default:
9252 		break;
9253 	}
9254 	return 0;
9255 }
9256 
9257 struct bpf_reg_types {
9258 	const enum bpf_reg_type types[10];
9259 	u32 *btf_id;
9260 };
9261 
9262 static const struct bpf_reg_types sock_types = {
9263 	.types = {
9264 		PTR_TO_SOCK_COMMON,
9265 		PTR_TO_SOCKET,
9266 		PTR_TO_TCP_SOCK,
9267 		PTR_TO_XDP_SOCK,
9268 	},
9269 };
9270 
9271 #ifdef CONFIG_NET
9272 static const struct bpf_reg_types btf_id_sock_common_types = {
9273 	.types = {
9274 		PTR_TO_SOCK_COMMON,
9275 		PTR_TO_SOCKET,
9276 		PTR_TO_TCP_SOCK,
9277 		PTR_TO_XDP_SOCK,
9278 		PTR_TO_BTF_ID,
9279 		PTR_TO_BTF_ID | PTR_TRUSTED,
9280 	},
9281 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9282 };
9283 #endif
9284 
9285 static const struct bpf_reg_types mem_types = {
9286 	.types = {
9287 		PTR_TO_STACK,
9288 		PTR_TO_PACKET,
9289 		PTR_TO_PACKET_META,
9290 		PTR_TO_MAP_KEY,
9291 		PTR_TO_MAP_VALUE,
9292 		PTR_TO_MEM,
9293 		PTR_TO_MEM | MEM_RINGBUF,
9294 		PTR_TO_BUF,
9295 		PTR_TO_BTF_ID | PTR_TRUSTED,
9296 	},
9297 };
9298 
9299 static const struct bpf_reg_types spin_lock_types = {
9300 	.types = {
9301 		PTR_TO_MAP_VALUE,
9302 		PTR_TO_BTF_ID | MEM_ALLOC,
9303 	}
9304 };
9305 
9306 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
9307 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
9308 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
9309 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
9310 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
9311 static const struct bpf_reg_types btf_ptr_types = {
9312 	.types = {
9313 		PTR_TO_BTF_ID,
9314 		PTR_TO_BTF_ID | PTR_TRUSTED,
9315 		PTR_TO_BTF_ID | MEM_RCU,
9316 	},
9317 };
9318 static const struct bpf_reg_types percpu_btf_ptr_types = {
9319 	.types = {
9320 		PTR_TO_BTF_ID | MEM_PERCPU,
9321 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
9322 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
9323 	}
9324 };
9325 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
9326 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
9327 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
9328 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
9329 static const struct bpf_reg_types kptr_xchg_dest_types = {
9330 	.types = {
9331 		PTR_TO_MAP_VALUE,
9332 		PTR_TO_BTF_ID | MEM_ALLOC
9333 	}
9334 };
9335 static const struct bpf_reg_types dynptr_types = {
9336 	.types = {
9337 		PTR_TO_STACK,
9338 		CONST_PTR_TO_DYNPTR,
9339 	}
9340 };
9341 
9342 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
9343 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
9344 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
9345 	[ARG_CONST_SIZE]		= &scalar_types,
9346 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
9347 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
9348 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
9349 	[ARG_PTR_TO_CTX]		= &context_types,
9350 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
9351 #ifdef CONFIG_NET
9352 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
9353 #endif
9354 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
9355 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
9356 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
9357 	[ARG_PTR_TO_MEM]		= &mem_types,
9358 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
9359 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
9360 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
9361 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
9362 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
9363 	[ARG_PTR_TO_TIMER]		= &timer_types,
9364 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
9365 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
9366 };
9367 
9368 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
9369 			  enum bpf_arg_type arg_type,
9370 			  const u32 *arg_btf_id,
9371 			  struct bpf_call_arg_meta *meta)
9372 {
9373 	struct bpf_reg_state *reg = reg_state(env, regno);
9374 	enum bpf_reg_type expected, type = reg->type;
9375 	const struct bpf_reg_types *compatible;
9376 	int i, j;
9377 
9378 	compatible = compatible_reg_types[base_type(arg_type)];
9379 	if (!compatible) {
9380 		verifier_bug(env, "unsupported arg type %d", arg_type);
9381 		return -EFAULT;
9382 	}
9383 
9384 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
9385 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
9386 	 *
9387 	 * Same for MAYBE_NULL:
9388 	 *
9389 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
9390 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
9391 	 *
9392 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
9393 	 *
9394 	 * Therefore we fold these flags depending on the arg_type before comparison.
9395 	 */
9396 	if (arg_type & MEM_RDONLY)
9397 		type &= ~MEM_RDONLY;
9398 	if (arg_type & PTR_MAYBE_NULL)
9399 		type &= ~PTR_MAYBE_NULL;
9400 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
9401 		type &= ~DYNPTR_TYPE_FLAG_MASK;
9402 
9403 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
9404 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) {
9405 		type &= ~MEM_ALLOC;
9406 		type &= ~MEM_PERCPU;
9407 	}
9408 
9409 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
9410 		expected = compatible->types[i];
9411 		if (expected == NOT_INIT)
9412 			break;
9413 
9414 		if (type == expected)
9415 			goto found;
9416 	}
9417 
9418 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
9419 	for (j = 0; j + 1 < i; j++)
9420 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
9421 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
9422 	return -EACCES;
9423 
9424 found:
9425 	if (base_type(reg->type) != PTR_TO_BTF_ID)
9426 		return 0;
9427 
9428 	if (compatible == &mem_types) {
9429 		if (!(arg_type & MEM_RDONLY)) {
9430 			verbose(env,
9431 				"%s() may write into memory pointed by R%d type=%s\n",
9432 				func_id_name(meta->func_id),
9433 				regno, reg_type_str(env, reg->type));
9434 			return -EACCES;
9435 		}
9436 		return 0;
9437 	}
9438 
9439 	switch ((int)reg->type) {
9440 	case PTR_TO_BTF_ID:
9441 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9442 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
9443 	case PTR_TO_BTF_ID | MEM_RCU:
9444 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
9445 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
9446 	{
9447 		/* For bpf_sk_release, it needs to match against first member
9448 		 * 'struct sock_common', hence make an exception for it. This
9449 		 * allows bpf_sk_release to work for multiple socket types.
9450 		 */
9451 		bool strict_type_match = arg_type_is_release(arg_type) &&
9452 					 meta->func_id != BPF_FUNC_sk_release;
9453 
9454 		if (type_may_be_null(reg->type) &&
9455 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
9456 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
9457 			return -EACCES;
9458 		}
9459 
9460 		if (!arg_btf_id) {
9461 			if (!compatible->btf_id) {
9462 				verifier_bug(env, "missing arg compatible BTF ID");
9463 				return -EFAULT;
9464 			}
9465 			arg_btf_id = compatible->btf_id;
9466 		}
9467 
9468 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
9469 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9470 				return -EACCES;
9471 		} else {
9472 			if (arg_btf_id == BPF_PTR_POISON) {
9473 				verbose(env, "verifier internal error:");
9474 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
9475 					regno);
9476 				return -EACCES;
9477 			}
9478 
9479 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
9480 						  btf_vmlinux, *arg_btf_id,
9481 						  strict_type_match)) {
9482 				verbose(env, "R%d is of type %s but %s is expected\n",
9483 					regno, btf_type_name(reg->btf, reg->btf_id),
9484 					btf_type_name(btf_vmlinux, *arg_btf_id));
9485 				return -EACCES;
9486 			}
9487 		}
9488 		break;
9489 	}
9490 	case PTR_TO_BTF_ID | MEM_ALLOC:
9491 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
9492 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
9493 		    meta->func_id != BPF_FUNC_kptr_xchg) {
9494 			verifier_bug(env, "unimplemented handling of MEM_ALLOC");
9495 			return -EFAULT;
9496 		}
9497 		/* Check if local kptr in src arg matches kptr in dst arg */
9498 		if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) {
9499 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9500 				return -EACCES;
9501 		}
9502 		break;
9503 	case PTR_TO_BTF_ID | MEM_PERCPU:
9504 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
9505 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
9506 		/* Handled by helper specific checks */
9507 		break;
9508 	default:
9509 		verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match");
9510 		return -EFAULT;
9511 	}
9512 	return 0;
9513 }
9514 
9515 static struct btf_field *
9516 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
9517 {
9518 	struct btf_field *field;
9519 	struct btf_record *rec;
9520 
9521 	rec = reg_btf_record(reg);
9522 	if (!rec)
9523 		return NULL;
9524 
9525 	field = btf_record_find(rec, off, fields);
9526 	if (!field)
9527 		return NULL;
9528 
9529 	return field;
9530 }
9531 
9532 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
9533 				  const struct bpf_reg_state *reg, int regno,
9534 				  enum bpf_arg_type arg_type)
9535 {
9536 	u32 type = reg->type;
9537 
9538 	/* When referenced register is passed to release function, its fixed
9539 	 * offset must be 0.
9540 	 *
9541 	 * We will check arg_type_is_release reg has ref_obj_id when storing
9542 	 * meta->release_regno.
9543 	 */
9544 	if (arg_type_is_release(arg_type)) {
9545 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
9546 		 * may not directly point to the object being released, but to
9547 		 * dynptr pointing to such object, which might be at some offset
9548 		 * on the stack. In that case, we simply to fallback to the
9549 		 * default handling.
9550 		 */
9551 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
9552 			return 0;
9553 
9554 		/* Doing check_ptr_off_reg check for the offset will catch this
9555 		 * because fixed_off_ok is false, but checking here allows us
9556 		 * to give the user a better error message.
9557 		 */
9558 		if (reg->off) {
9559 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
9560 				regno);
9561 			return -EINVAL;
9562 		}
9563 		return __check_ptr_off_reg(env, reg, regno, false);
9564 	}
9565 
9566 	switch (type) {
9567 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
9568 	case PTR_TO_STACK:
9569 	case PTR_TO_PACKET:
9570 	case PTR_TO_PACKET_META:
9571 	case PTR_TO_MAP_KEY:
9572 	case PTR_TO_MAP_VALUE:
9573 	case PTR_TO_MEM:
9574 	case PTR_TO_MEM | MEM_RDONLY:
9575 	case PTR_TO_MEM | MEM_RINGBUF:
9576 	case PTR_TO_BUF:
9577 	case PTR_TO_BUF | MEM_RDONLY:
9578 	case PTR_TO_ARENA:
9579 	case SCALAR_VALUE:
9580 		return 0;
9581 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
9582 	 * fixed offset.
9583 	 */
9584 	case PTR_TO_BTF_ID:
9585 	case PTR_TO_BTF_ID | MEM_ALLOC:
9586 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9587 	case PTR_TO_BTF_ID | MEM_RCU:
9588 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
9589 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
9590 		/* When referenced PTR_TO_BTF_ID is passed to release function,
9591 		 * its fixed offset must be 0. In the other cases, fixed offset
9592 		 * can be non-zero. This was already checked above. So pass
9593 		 * fixed_off_ok as true to allow fixed offset for all other
9594 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
9595 		 * still need to do checks instead of returning.
9596 		 */
9597 		return __check_ptr_off_reg(env, reg, regno, true);
9598 	default:
9599 		return __check_ptr_off_reg(env, reg, regno, false);
9600 	}
9601 }
9602 
9603 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
9604 						const struct bpf_func_proto *fn,
9605 						struct bpf_reg_state *regs)
9606 {
9607 	struct bpf_reg_state *state = NULL;
9608 	int i;
9609 
9610 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
9611 		if (arg_type_is_dynptr(fn->arg_type[i])) {
9612 			if (state) {
9613 				verbose(env, "verifier internal error: multiple dynptr args\n");
9614 				return NULL;
9615 			}
9616 			state = &regs[BPF_REG_1 + i];
9617 		}
9618 
9619 	if (!state)
9620 		verbose(env, "verifier internal error: no dynptr arg found\n");
9621 
9622 	return state;
9623 }
9624 
9625 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9626 {
9627 	struct bpf_func_state *state = func(env, reg);
9628 	int spi;
9629 
9630 	if (reg->type == CONST_PTR_TO_DYNPTR)
9631 		return reg->id;
9632 	spi = dynptr_get_spi(env, reg);
9633 	if (spi < 0)
9634 		return spi;
9635 	return state->stack[spi].spilled_ptr.id;
9636 }
9637 
9638 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9639 {
9640 	struct bpf_func_state *state = func(env, reg);
9641 	int spi;
9642 
9643 	if (reg->type == CONST_PTR_TO_DYNPTR)
9644 		return reg->ref_obj_id;
9645 	spi = dynptr_get_spi(env, reg);
9646 	if (spi < 0)
9647 		return spi;
9648 	return state->stack[spi].spilled_ptr.ref_obj_id;
9649 }
9650 
9651 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
9652 					    struct bpf_reg_state *reg)
9653 {
9654 	struct bpf_func_state *state = func(env, reg);
9655 	int spi;
9656 
9657 	if (reg->type == CONST_PTR_TO_DYNPTR)
9658 		return reg->dynptr.type;
9659 
9660 	spi = __get_spi(reg->off);
9661 	if (spi < 0) {
9662 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
9663 		return BPF_DYNPTR_TYPE_INVALID;
9664 	}
9665 
9666 	return state->stack[spi].spilled_ptr.dynptr.type;
9667 }
9668 
9669 static int check_reg_const_str(struct bpf_verifier_env *env,
9670 			       struct bpf_reg_state *reg, u32 regno)
9671 {
9672 	struct bpf_map *map = reg->map_ptr;
9673 	int err;
9674 	int map_off;
9675 	u64 map_addr;
9676 	char *str_ptr;
9677 
9678 	if (reg->type != PTR_TO_MAP_VALUE)
9679 		return -EINVAL;
9680 
9681 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
9682 		verbose(env, "R%d points to insn_array map which cannot be used as const string\n", regno);
9683 		return -EACCES;
9684 	}
9685 
9686 	if (!bpf_map_is_rdonly(map)) {
9687 		verbose(env, "R%d does not point to a readonly map'\n", regno);
9688 		return -EACCES;
9689 	}
9690 
9691 	if (!tnum_is_const(reg->var_off)) {
9692 		verbose(env, "R%d is not a constant address'\n", regno);
9693 		return -EACCES;
9694 	}
9695 
9696 	if (!map->ops->map_direct_value_addr) {
9697 		verbose(env, "no direct value access support for this map type\n");
9698 		return -EACCES;
9699 	}
9700 
9701 	err = check_map_access(env, regno, reg->off,
9702 			       map->value_size - reg->off, false,
9703 			       ACCESS_HELPER);
9704 	if (err)
9705 		return err;
9706 
9707 	map_off = reg->off + reg->var_off.value;
9708 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
9709 	if (err) {
9710 		verbose(env, "direct value access on string failed\n");
9711 		return err;
9712 	}
9713 
9714 	str_ptr = (char *)(long)(map_addr);
9715 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
9716 		verbose(env, "string is not zero-terminated\n");
9717 		return -EINVAL;
9718 	}
9719 	return 0;
9720 }
9721 
9722 /* Returns constant key value in `value` if possible, else negative error */
9723 static int get_constant_map_key(struct bpf_verifier_env *env,
9724 				struct bpf_reg_state *key,
9725 				u32 key_size,
9726 				s64 *value)
9727 {
9728 	struct bpf_func_state *state = func(env, key);
9729 	struct bpf_reg_state *reg;
9730 	int slot, spi, off;
9731 	int spill_size = 0;
9732 	int zero_size = 0;
9733 	int stack_off;
9734 	int i, err;
9735 	u8 *stype;
9736 
9737 	if (!env->bpf_capable)
9738 		return -EOPNOTSUPP;
9739 	if (key->type != PTR_TO_STACK)
9740 		return -EOPNOTSUPP;
9741 	if (!tnum_is_const(key->var_off))
9742 		return -EOPNOTSUPP;
9743 
9744 	stack_off = key->off + key->var_off.value;
9745 	slot = -stack_off - 1;
9746 	spi = slot / BPF_REG_SIZE;
9747 	off = slot % BPF_REG_SIZE;
9748 	stype = state->stack[spi].slot_type;
9749 
9750 	/* First handle precisely tracked STACK_ZERO */
9751 	for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
9752 		zero_size++;
9753 	if (zero_size >= key_size) {
9754 		*value = 0;
9755 		return 0;
9756 	}
9757 
9758 	/* Check that stack contains a scalar spill of expected size */
9759 	if (!is_spilled_scalar_reg(&state->stack[spi]))
9760 		return -EOPNOTSUPP;
9761 	for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
9762 		spill_size++;
9763 	if (spill_size != key_size)
9764 		return -EOPNOTSUPP;
9765 
9766 	reg = &state->stack[spi].spilled_ptr;
9767 	if (!tnum_is_const(reg->var_off))
9768 		/* Stack value not statically known */
9769 		return -EOPNOTSUPP;
9770 
9771 	/* We are relying on a constant value. So mark as precise
9772 	 * to prevent pruning on it.
9773 	 */
9774 	bt_set_frame_slot(&env->bt, key->frameno, spi);
9775 	err = mark_chain_precision_batch(env, env->cur_state);
9776 	if (err < 0)
9777 		return err;
9778 
9779 	*value = reg->var_off.value;
9780 	return 0;
9781 }
9782 
9783 static bool can_elide_value_nullness(enum bpf_map_type type);
9784 
9785 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
9786 			  struct bpf_call_arg_meta *meta,
9787 			  const struct bpf_func_proto *fn,
9788 			  int insn_idx)
9789 {
9790 	u32 regno = BPF_REG_1 + arg;
9791 	struct bpf_reg_state *reg = reg_state(env, regno);
9792 	enum bpf_arg_type arg_type = fn->arg_type[arg];
9793 	enum bpf_reg_type type = reg->type;
9794 	u32 *arg_btf_id = NULL;
9795 	u32 key_size;
9796 	int err = 0;
9797 
9798 	if (arg_type == ARG_DONTCARE)
9799 		return 0;
9800 
9801 	err = check_reg_arg(env, regno, SRC_OP);
9802 	if (err)
9803 		return err;
9804 
9805 	if (arg_type == ARG_ANYTHING) {
9806 		if (is_pointer_value(env, regno)) {
9807 			verbose(env, "R%d leaks addr into helper function\n",
9808 				regno);
9809 			return -EACCES;
9810 		}
9811 		return 0;
9812 	}
9813 
9814 	if (type_is_pkt_pointer(type) &&
9815 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
9816 		verbose(env, "helper access to the packet is not allowed\n");
9817 		return -EACCES;
9818 	}
9819 
9820 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
9821 		err = resolve_map_arg_type(env, meta, &arg_type);
9822 		if (err)
9823 			return err;
9824 	}
9825 
9826 	if (register_is_null(reg) && type_may_be_null(arg_type))
9827 		/* A NULL register has a SCALAR_VALUE type, so skip
9828 		 * type checking.
9829 		 */
9830 		goto skip_type_check;
9831 
9832 	/* arg_btf_id and arg_size are in a union. */
9833 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
9834 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
9835 		arg_btf_id = fn->arg_btf_id[arg];
9836 
9837 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
9838 	if (err)
9839 		return err;
9840 
9841 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
9842 	if (err)
9843 		return err;
9844 
9845 skip_type_check:
9846 	if (arg_type_is_release(arg_type)) {
9847 		if (arg_type_is_dynptr(arg_type)) {
9848 			struct bpf_func_state *state = func(env, reg);
9849 			int spi;
9850 
9851 			/* Only dynptr created on stack can be released, thus
9852 			 * the get_spi and stack state checks for spilled_ptr
9853 			 * should only be done before process_dynptr_func for
9854 			 * PTR_TO_STACK.
9855 			 */
9856 			if (reg->type == PTR_TO_STACK) {
9857 				spi = dynptr_get_spi(env, reg);
9858 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
9859 					verbose(env, "arg %d is an unacquired reference\n", regno);
9860 					return -EINVAL;
9861 				}
9862 			} else {
9863 				verbose(env, "cannot release unowned const bpf_dynptr\n");
9864 				return -EINVAL;
9865 			}
9866 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
9867 			verbose(env, "R%d must be referenced when passed to release function\n",
9868 				regno);
9869 			return -EINVAL;
9870 		}
9871 		if (meta->release_regno) {
9872 			verifier_bug(env, "more than one release argument");
9873 			return -EFAULT;
9874 		}
9875 		meta->release_regno = regno;
9876 	}
9877 
9878 	if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) {
9879 		if (meta->ref_obj_id) {
9880 			verbose(env, "more than one arg with ref_obj_id R%d %u %u",
9881 				regno, reg->ref_obj_id,
9882 				meta->ref_obj_id);
9883 			return -EACCES;
9884 		}
9885 		meta->ref_obj_id = reg->ref_obj_id;
9886 	}
9887 
9888 	switch (base_type(arg_type)) {
9889 	case ARG_CONST_MAP_PTR:
9890 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
9891 		if (meta->map.ptr) {
9892 			/* Use map_uid (which is unique id of inner map) to reject:
9893 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
9894 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
9895 			 * if (inner_map1 && inner_map2) {
9896 			 *     timer = bpf_map_lookup_elem(inner_map1);
9897 			 *     if (timer)
9898 			 *         // mismatch would have been allowed
9899 			 *         bpf_timer_init(timer, inner_map2);
9900 			 * }
9901 			 *
9902 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
9903 			 */
9904 			if (meta->map.ptr != reg->map_ptr ||
9905 			    meta->map.uid != reg->map_uid) {
9906 				verbose(env,
9907 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
9908 					meta->map.uid, reg->map_uid);
9909 				return -EINVAL;
9910 			}
9911 		}
9912 		meta->map.ptr = reg->map_ptr;
9913 		meta->map.uid = reg->map_uid;
9914 		break;
9915 	case ARG_PTR_TO_MAP_KEY:
9916 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
9917 		 * check that [key, key + map->key_size) are within
9918 		 * stack limits and initialized
9919 		 */
9920 		if (!meta->map.ptr) {
9921 			/* in function declaration map_ptr must come before
9922 			 * map_key, so that it's verified and known before
9923 			 * we have to check map_key here. Otherwise it means
9924 			 * that kernel subsystem misconfigured verifier
9925 			 */
9926 			verifier_bug(env, "invalid map_ptr to access map->key");
9927 			return -EFAULT;
9928 		}
9929 		key_size = meta->map.ptr->key_size;
9930 		err = check_helper_mem_access(env, regno, key_size, BPF_READ, false, NULL);
9931 		if (err)
9932 			return err;
9933 		if (can_elide_value_nullness(meta->map.ptr->map_type)) {
9934 			err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
9935 			if (err < 0) {
9936 				meta->const_map_key = -1;
9937 				if (err == -EOPNOTSUPP)
9938 					err = 0;
9939 				else
9940 					return err;
9941 			}
9942 		}
9943 		break;
9944 	case ARG_PTR_TO_MAP_VALUE:
9945 		if (type_may_be_null(arg_type) && register_is_null(reg))
9946 			return 0;
9947 
9948 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
9949 		 * check [value, value + map->value_size) validity
9950 		 */
9951 		if (!meta->map.ptr) {
9952 			/* kernel subsystem misconfigured verifier */
9953 			verifier_bug(env, "invalid map_ptr to access map->value");
9954 			return -EFAULT;
9955 		}
9956 		meta->raw_mode = arg_type & MEM_UNINIT;
9957 		err = check_helper_mem_access(env, regno, meta->map.ptr->value_size,
9958 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9959 					      false, meta);
9960 		break;
9961 	case ARG_PTR_TO_PERCPU_BTF_ID:
9962 		if (!reg->btf_id) {
9963 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
9964 			return -EACCES;
9965 		}
9966 		meta->ret_btf = reg->btf;
9967 		meta->ret_btf_id = reg->btf_id;
9968 		break;
9969 	case ARG_PTR_TO_SPIN_LOCK:
9970 		if (in_rbtree_lock_required_cb(env)) {
9971 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
9972 			return -EACCES;
9973 		}
9974 		if (meta->func_id == BPF_FUNC_spin_lock) {
9975 			err = process_spin_lock(env, regno, PROCESS_SPIN_LOCK);
9976 			if (err)
9977 				return err;
9978 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
9979 			err = process_spin_lock(env, regno, 0);
9980 			if (err)
9981 				return err;
9982 		} else {
9983 			verifier_bug(env, "spin lock arg on unexpected helper");
9984 			return -EFAULT;
9985 		}
9986 		break;
9987 	case ARG_PTR_TO_TIMER:
9988 		err = process_timer_helper(env, regno, meta);
9989 		if (err)
9990 			return err;
9991 		break;
9992 	case ARG_PTR_TO_FUNC:
9993 		meta->subprogno = reg->subprogno;
9994 		break;
9995 	case ARG_PTR_TO_MEM:
9996 		/* The access to this pointer is only checked when we hit the
9997 		 * next is_mem_size argument below.
9998 		 */
9999 		meta->raw_mode = arg_type & MEM_UNINIT;
10000 		if (arg_type & MEM_FIXED_SIZE) {
10001 			err = check_helper_mem_access(env, regno, fn->arg_size[arg],
10002 						      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
10003 						      false, meta);
10004 			if (err)
10005 				return err;
10006 			if (arg_type & MEM_ALIGNED)
10007 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
10008 		}
10009 		break;
10010 	case ARG_CONST_SIZE:
10011 		err = check_mem_size_reg(env, reg, regno,
10012 					 fn->arg_type[arg - 1] & MEM_WRITE ?
10013 					 BPF_WRITE : BPF_READ,
10014 					 false, meta);
10015 		break;
10016 	case ARG_CONST_SIZE_OR_ZERO:
10017 		err = check_mem_size_reg(env, reg, regno,
10018 					 fn->arg_type[arg - 1] & MEM_WRITE ?
10019 					 BPF_WRITE : BPF_READ,
10020 					 true, meta);
10021 		break;
10022 	case ARG_PTR_TO_DYNPTR:
10023 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
10024 		if (err)
10025 			return err;
10026 		break;
10027 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
10028 		if (!tnum_is_const(reg->var_off)) {
10029 			verbose(env, "R%d is not a known constant'\n",
10030 				regno);
10031 			return -EACCES;
10032 		}
10033 		meta->mem_size = reg->var_off.value;
10034 		err = mark_chain_precision(env, regno);
10035 		if (err)
10036 			return err;
10037 		break;
10038 	case ARG_PTR_TO_CONST_STR:
10039 	{
10040 		err = check_reg_const_str(env, reg, regno);
10041 		if (err)
10042 			return err;
10043 		break;
10044 	}
10045 	case ARG_KPTR_XCHG_DEST:
10046 		err = process_kptr_func(env, regno, meta);
10047 		if (err)
10048 			return err;
10049 		break;
10050 	}
10051 
10052 	return err;
10053 }
10054 
10055 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
10056 {
10057 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
10058 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10059 
10060 	if (func_id != BPF_FUNC_map_update_elem &&
10061 	    func_id != BPF_FUNC_map_delete_elem)
10062 		return false;
10063 
10064 	/* It's not possible to get access to a locked struct sock in these
10065 	 * contexts, so updating is safe.
10066 	 */
10067 	switch (type) {
10068 	case BPF_PROG_TYPE_TRACING:
10069 		if (eatype == BPF_TRACE_ITER)
10070 			return true;
10071 		break;
10072 	case BPF_PROG_TYPE_SOCK_OPS:
10073 		/* map_update allowed only via dedicated helpers with event type checks */
10074 		if (func_id == BPF_FUNC_map_delete_elem)
10075 			return true;
10076 		break;
10077 	case BPF_PROG_TYPE_SOCKET_FILTER:
10078 	case BPF_PROG_TYPE_SCHED_CLS:
10079 	case BPF_PROG_TYPE_SCHED_ACT:
10080 	case BPF_PROG_TYPE_XDP:
10081 	case BPF_PROG_TYPE_SK_REUSEPORT:
10082 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
10083 	case BPF_PROG_TYPE_SK_LOOKUP:
10084 		return true;
10085 	default:
10086 		break;
10087 	}
10088 
10089 	verbose(env, "cannot update sockmap in this context\n");
10090 	return false;
10091 }
10092 
10093 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
10094 {
10095 	return env->prog->jit_requested &&
10096 	       bpf_jit_supports_subprog_tailcalls();
10097 }
10098 
10099 static int check_map_func_compatibility(struct bpf_verifier_env *env,
10100 					struct bpf_map *map, int func_id)
10101 {
10102 	if (!map)
10103 		return 0;
10104 
10105 	/* We need a two way check, first is from map perspective ... */
10106 	switch (map->map_type) {
10107 	case BPF_MAP_TYPE_PROG_ARRAY:
10108 		if (func_id != BPF_FUNC_tail_call)
10109 			goto error;
10110 		break;
10111 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
10112 		if (func_id != BPF_FUNC_perf_event_read &&
10113 		    func_id != BPF_FUNC_perf_event_output &&
10114 		    func_id != BPF_FUNC_skb_output &&
10115 		    func_id != BPF_FUNC_perf_event_read_value &&
10116 		    func_id != BPF_FUNC_xdp_output)
10117 			goto error;
10118 		break;
10119 	case BPF_MAP_TYPE_RINGBUF:
10120 		if (func_id != BPF_FUNC_ringbuf_output &&
10121 		    func_id != BPF_FUNC_ringbuf_reserve &&
10122 		    func_id != BPF_FUNC_ringbuf_query &&
10123 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
10124 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
10125 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
10126 			goto error;
10127 		break;
10128 	case BPF_MAP_TYPE_USER_RINGBUF:
10129 		if (func_id != BPF_FUNC_user_ringbuf_drain)
10130 			goto error;
10131 		break;
10132 	case BPF_MAP_TYPE_STACK_TRACE:
10133 		if (func_id != BPF_FUNC_get_stackid)
10134 			goto error;
10135 		break;
10136 	case BPF_MAP_TYPE_CGROUP_ARRAY:
10137 		if (func_id != BPF_FUNC_skb_under_cgroup &&
10138 		    func_id != BPF_FUNC_current_task_under_cgroup)
10139 			goto error;
10140 		break;
10141 	case BPF_MAP_TYPE_CGROUP_STORAGE:
10142 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
10143 		if (func_id != BPF_FUNC_get_local_storage)
10144 			goto error;
10145 		break;
10146 	case BPF_MAP_TYPE_DEVMAP:
10147 	case BPF_MAP_TYPE_DEVMAP_HASH:
10148 		if (func_id != BPF_FUNC_redirect_map &&
10149 		    func_id != BPF_FUNC_map_lookup_elem)
10150 			goto error;
10151 		break;
10152 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
10153 	 * appear.
10154 	 */
10155 	case BPF_MAP_TYPE_CPUMAP:
10156 		if (func_id != BPF_FUNC_redirect_map)
10157 			goto error;
10158 		break;
10159 	case BPF_MAP_TYPE_XSKMAP:
10160 		if (func_id != BPF_FUNC_redirect_map &&
10161 		    func_id != BPF_FUNC_map_lookup_elem)
10162 			goto error;
10163 		break;
10164 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10165 	case BPF_MAP_TYPE_HASH_OF_MAPS:
10166 		if (func_id != BPF_FUNC_map_lookup_elem)
10167 			goto error;
10168 		break;
10169 	case BPF_MAP_TYPE_SOCKMAP:
10170 		if (func_id != BPF_FUNC_sk_redirect_map &&
10171 		    func_id != BPF_FUNC_sock_map_update &&
10172 		    func_id != BPF_FUNC_msg_redirect_map &&
10173 		    func_id != BPF_FUNC_sk_select_reuseport &&
10174 		    func_id != BPF_FUNC_map_lookup_elem &&
10175 		    !may_update_sockmap(env, func_id))
10176 			goto error;
10177 		break;
10178 	case BPF_MAP_TYPE_SOCKHASH:
10179 		if (func_id != BPF_FUNC_sk_redirect_hash &&
10180 		    func_id != BPF_FUNC_sock_hash_update &&
10181 		    func_id != BPF_FUNC_msg_redirect_hash &&
10182 		    func_id != BPF_FUNC_sk_select_reuseport &&
10183 		    func_id != BPF_FUNC_map_lookup_elem &&
10184 		    !may_update_sockmap(env, func_id))
10185 			goto error;
10186 		break;
10187 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
10188 		if (func_id != BPF_FUNC_sk_select_reuseport)
10189 			goto error;
10190 		break;
10191 	case BPF_MAP_TYPE_QUEUE:
10192 	case BPF_MAP_TYPE_STACK:
10193 		if (func_id != BPF_FUNC_map_peek_elem &&
10194 		    func_id != BPF_FUNC_map_pop_elem &&
10195 		    func_id != BPF_FUNC_map_push_elem)
10196 			goto error;
10197 		break;
10198 	case BPF_MAP_TYPE_SK_STORAGE:
10199 		if (func_id != BPF_FUNC_sk_storage_get &&
10200 		    func_id != BPF_FUNC_sk_storage_delete &&
10201 		    func_id != BPF_FUNC_kptr_xchg)
10202 			goto error;
10203 		break;
10204 	case BPF_MAP_TYPE_INODE_STORAGE:
10205 		if (func_id != BPF_FUNC_inode_storage_get &&
10206 		    func_id != BPF_FUNC_inode_storage_delete &&
10207 		    func_id != BPF_FUNC_kptr_xchg)
10208 			goto error;
10209 		break;
10210 	case BPF_MAP_TYPE_TASK_STORAGE:
10211 		if (func_id != BPF_FUNC_task_storage_get &&
10212 		    func_id != BPF_FUNC_task_storage_delete &&
10213 		    func_id != BPF_FUNC_kptr_xchg)
10214 			goto error;
10215 		break;
10216 	case BPF_MAP_TYPE_CGRP_STORAGE:
10217 		if (func_id != BPF_FUNC_cgrp_storage_get &&
10218 		    func_id != BPF_FUNC_cgrp_storage_delete &&
10219 		    func_id != BPF_FUNC_kptr_xchg)
10220 			goto error;
10221 		break;
10222 	case BPF_MAP_TYPE_BLOOM_FILTER:
10223 		if (func_id != BPF_FUNC_map_peek_elem &&
10224 		    func_id != BPF_FUNC_map_push_elem)
10225 			goto error;
10226 		break;
10227 	case BPF_MAP_TYPE_INSN_ARRAY:
10228 		goto error;
10229 	default:
10230 		break;
10231 	}
10232 
10233 	/* ... and second from the function itself. */
10234 	switch (func_id) {
10235 	case BPF_FUNC_tail_call:
10236 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
10237 			goto error;
10238 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
10239 			verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n");
10240 			return -EINVAL;
10241 		}
10242 		break;
10243 	case BPF_FUNC_perf_event_read:
10244 	case BPF_FUNC_perf_event_output:
10245 	case BPF_FUNC_perf_event_read_value:
10246 	case BPF_FUNC_skb_output:
10247 	case BPF_FUNC_xdp_output:
10248 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
10249 			goto error;
10250 		break;
10251 	case BPF_FUNC_ringbuf_output:
10252 	case BPF_FUNC_ringbuf_reserve:
10253 	case BPF_FUNC_ringbuf_query:
10254 	case BPF_FUNC_ringbuf_reserve_dynptr:
10255 	case BPF_FUNC_ringbuf_submit_dynptr:
10256 	case BPF_FUNC_ringbuf_discard_dynptr:
10257 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
10258 			goto error;
10259 		break;
10260 	case BPF_FUNC_user_ringbuf_drain:
10261 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
10262 			goto error;
10263 		break;
10264 	case BPF_FUNC_get_stackid:
10265 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
10266 			goto error;
10267 		break;
10268 	case BPF_FUNC_current_task_under_cgroup:
10269 	case BPF_FUNC_skb_under_cgroup:
10270 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
10271 			goto error;
10272 		break;
10273 	case BPF_FUNC_redirect_map:
10274 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
10275 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
10276 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
10277 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
10278 			goto error;
10279 		break;
10280 	case BPF_FUNC_sk_redirect_map:
10281 	case BPF_FUNC_msg_redirect_map:
10282 	case BPF_FUNC_sock_map_update:
10283 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
10284 			goto error;
10285 		break;
10286 	case BPF_FUNC_sk_redirect_hash:
10287 	case BPF_FUNC_msg_redirect_hash:
10288 	case BPF_FUNC_sock_hash_update:
10289 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
10290 			goto error;
10291 		break;
10292 	case BPF_FUNC_get_local_storage:
10293 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
10294 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
10295 			goto error;
10296 		break;
10297 	case BPF_FUNC_sk_select_reuseport:
10298 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
10299 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
10300 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
10301 			goto error;
10302 		break;
10303 	case BPF_FUNC_map_pop_elem:
10304 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10305 		    map->map_type != BPF_MAP_TYPE_STACK)
10306 			goto error;
10307 		break;
10308 	case BPF_FUNC_map_peek_elem:
10309 	case BPF_FUNC_map_push_elem:
10310 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10311 		    map->map_type != BPF_MAP_TYPE_STACK &&
10312 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
10313 			goto error;
10314 		break;
10315 	case BPF_FUNC_map_lookup_percpu_elem:
10316 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
10317 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10318 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
10319 			goto error;
10320 		break;
10321 	case BPF_FUNC_sk_storage_get:
10322 	case BPF_FUNC_sk_storage_delete:
10323 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
10324 			goto error;
10325 		break;
10326 	case BPF_FUNC_inode_storage_get:
10327 	case BPF_FUNC_inode_storage_delete:
10328 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
10329 			goto error;
10330 		break;
10331 	case BPF_FUNC_task_storage_get:
10332 	case BPF_FUNC_task_storage_delete:
10333 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
10334 			goto error;
10335 		break;
10336 	case BPF_FUNC_cgrp_storage_get:
10337 	case BPF_FUNC_cgrp_storage_delete:
10338 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
10339 			goto error;
10340 		break;
10341 	default:
10342 		break;
10343 	}
10344 
10345 	return 0;
10346 error:
10347 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
10348 		map->map_type, func_id_name(func_id), func_id);
10349 	return -EINVAL;
10350 }
10351 
10352 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
10353 {
10354 	int count = 0;
10355 
10356 	if (arg_type_is_raw_mem(fn->arg1_type))
10357 		count++;
10358 	if (arg_type_is_raw_mem(fn->arg2_type))
10359 		count++;
10360 	if (arg_type_is_raw_mem(fn->arg3_type))
10361 		count++;
10362 	if (arg_type_is_raw_mem(fn->arg4_type))
10363 		count++;
10364 	if (arg_type_is_raw_mem(fn->arg5_type))
10365 		count++;
10366 
10367 	/* We only support one arg being in raw mode at the moment,
10368 	 * which is sufficient for the helper functions we have
10369 	 * right now.
10370 	 */
10371 	return count <= 1;
10372 }
10373 
10374 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
10375 {
10376 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
10377 	bool has_size = fn->arg_size[arg] != 0;
10378 	bool is_next_size = false;
10379 
10380 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
10381 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
10382 
10383 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
10384 		return is_next_size;
10385 
10386 	return has_size == is_next_size || is_next_size == is_fixed;
10387 }
10388 
10389 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
10390 {
10391 	/* bpf_xxx(..., buf, len) call will access 'len'
10392 	 * bytes from memory 'buf'. Both arg types need
10393 	 * to be paired, so make sure there's no buggy
10394 	 * helper function specification.
10395 	 */
10396 	if (arg_type_is_mem_size(fn->arg1_type) ||
10397 	    check_args_pair_invalid(fn, 0) ||
10398 	    check_args_pair_invalid(fn, 1) ||
10399 	    check_args_pair_invalid(fn, 2) ||
10400 	    check_args_pair_invalid(fn, 3) ||
10401 	    check_args_pair_invalid(fn, 4))
10402 		return false;
10403 
10404 	return true;
10405 }
10406 
10407 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
10408 {
10409 	int i;
10410 
10411 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10412 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
10413 			return !!fn->arg_btf_id[i];
10414 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
10415 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
10416 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
10417 		    /* arg_btf_id and arg_size are in a union. */
10418 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
10419 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
10420 			return false;
10421 	}
10422 
10423 	return true;
10424 }
10425 
10426 static bool check_mem_arg_rw_flag_ok(const struct bpf_func_proto *fn)
10427 {
10428 	int i;
10429 
10430 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10431 		enum bpf_arg_type arg_type = fn->arg_type[i];
10432 
10433 		if (base_type(arg_type) != ARG_PTR_TO_MEM)
10434 			continue;
10435 		if (!(arg_type & (MEM_WRITE | MEM_RDONLY)))
10436 			return false;
10437 	}
10438 
10439 	return true;
10440 }
10441 
10442 static int check_func_proto(const struct bpf_func_proto *fn)
10443 {
10444 	return check_raw_mode_ok(fn) &&
10445 	       check_arg_pair_ok(fn) &&
10446 	       check_mem_arg_rw_flag_ok(fn) &&
10447 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
10448 }
10449 
10450 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
10451  * are now invalid, so turn them into unknown SCALAR_VALUE.
10452  *
10453  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
10454  * since these slices point to packet data.
10455  */
10456 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
10457 {
10458 	struct bpf_func_state *state;
10459 	struct bpf_reg_state *reg;
10460 
10461 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10462 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
10463 			mark_reg_invalid(env, reg);
10464 	}));
10465 }
10466 
10467 enum {
10468 	AT_PKT_END = -1,
10469 	BEYOND_PKT_END = -2,
10470 };
10471 
10472 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
10473 {
10474 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10475 	struct bpf_reg_state *reg = &state->regs[regn];
10476 
10477 	if (reg->type != PTR_TO_PACKET)
10478 		/* PTR_TO_PACKET_META is not supported yet */
10479 		return;
10480 
10481 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
10482 	 * How far beyond pkt_end it goes is unknown.
10483 	 * if (!range_open) it's the case of pkt >= pkt_end
10484 	 * if (range_open) it's the case of pkt > pkt_end
10485 	 * hence this pointer is at least 1 byte bigger than pkt_end
10486 	 */
10487 	if (range_open)
10488 		reg->range = BEYOND_PKT_END;
10489 	else
10490 		reg->range = AT_PKT_END;
10491 }
10492 
10493 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id)
10494 {
10495 	int i;
10496 
10497 	for (i = 0; i < state->acquired_refs; i++) {
10498 		if (state->refs[i].type != REF_TYPE_PTR)
10499 			continue;
10500 		if (state->refs[i].id == ref_obj_id) {
10501 			release_reference_state(state, i);
10502 			return 0;
10503 		}
10504 	}
10505 	return -EINVAL;
10506 }
10507 
10508 /* The pointer with the specified id has released its reference to kernel
10509  * resources. Identify all copies of the same pointer and clear the reference.
10510  *
10511  * This is the release function corresponding to acquire_reference(). Idempotent.
10512  */
10513 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id)
10514 {
10515 	struct bpf_verifier_state *vstate = env->cur_state;
10516 	struct bpf_func_state *state;
10517 	struct bpf_reg_state *reg;
10518 	int err;
10519 
10520 	err = release_reference_nomark(vstate, ref_obj_id);
10521 	if (err)
10522 		return err;
10523 
10524 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10525 		if (reg->ref_obj_id == ref_obj_id)
10526 			mark_reg_invalid(env, reg);
10527 	}));
10528 
10529 	return 0;
10530 }
10531 
10532 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
10533 {
10534 	struct bpf_func_state *unused;
10535 	struct bpf_reg_state *reg;
10536 
10537 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10538 		if (type_is_non_owning_ref(reg->type))
10539 			mark_reg_invalid(env, reg);
10540 	}));
10541 }
10542 
10543 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
10544 				    struct bpf_reg_state *regs)
10545 {
10546 	int i;
10547 
10548 	/* after the call registers r0 - r5 were scratched */
10549 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10550 		mark_reg_not_init(env, regs, caller_saved[i]);
10551 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
10552 	}
10553 }
10554 
10555 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
10556 				   struct bpf_func_state *caller,
10557 				   struct bpf_func_state *callee,
10558 				   int insn_idx);
10559 
10560 static int set_callee_state(struct bpf_verifier_env *env,
10561 			    struct bpf_func_state *caller,
10562 			    struct bpf_func_state *callee, int insn_idx);
10563 
10564 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
10565 			    set_callee_state_fn set_callee_state_cb,
10566 			    struct bpf_verifier_state *state)
10567 {
10568 	struct bpf_func_state *caller, *callee;
10569 	int err;
10570 
10571 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
10572 		verbose(env, "the call stack of %d frames is too deep\n",
10573 			state->curframe + 2);
10574 		return -E2BIG;
10575 	}
10576 
10577 	if (state->frame[state->curframe + 1]) {
10578 		verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
10579 		return -EFAULT;
10580 	}
10581 
10582 	caller = state->frame[state->curframe];
10583 	callee = kzalloc(sizeof(*callee), GFP_KERNEL_ACCOUNT);
10584 	if (!callee)
10585 		return -ENOMEM;
10586 	state->frame[state->curframe + 1] = callee;
10587 
10588 	/* callee cannot access r0, r6 - r9 for reading and has to write
10589 	 * into its own stack before reading from it.
10590 	 * callee can read/write into caller's stack
10591 	 */
10592 	init_func_state(env, callee,
10593 			/* remember the callsite, it will be used by bpf_exit */
10594 			callsite,
10595 			state->curframe + 1 /* frameno within this callchain */,
10596 			subprog /* subprog number within this prog */);
10597 	err = set_callee_state_cb(env, caller, callee, callsite);
10598 	if (err)
10599 		goto err_out;
10600 
10601 	/* only increment it after check_reg_arg() finished */
10602 	state->curframe++;
10603 
10604 	return 0;
10605 
10606 err_out:
10607 	free_func_state(callee);
10608 	state->frame[state->curframe + 1] = NULL;
10609 	return err;
10610 }
10611 
10612 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
10613 				    const struct btf *btf,
10614 				    struct bpf_reg_state *regs)
10615 {
10616 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
10617 	struct bpf_verifier_log *log = &env->log;
10618 	u32 i;
10619 	int ret;
10620 
10621 	ret = btf_prepare_func_args(env, subprog);
10622 	if (ret)
10623 		return ret;
10624 
10625 	/* check that BTF function arguments match actual types that the
10626 	 * verifier sees.
10627 	 */
10628 	for (i = 0; i < sub->arg_cnt; i++) {
10629 		u32 regno = i + 1;
10630 		struct bpf_reg_state *reg = &regs[regno];
10631 		struct bpf_subprog_arg_info *arg = &sub->args[i];
10632 
10633 		if (arg->arg_type == ARG_ANYTHING) {
10634 			if (reg->type != SCALAR_VALUE) {
10635 				bpf_log(log, "R%d is not a scalar\n", regno);
10636 				return -EINVAL;
10637 			}
10638 		} else if (arg->arg_type & PTR_UNTRUSTED) {
10639 			/*
10640 			 * Anything is allowed for untrusted arguments, as these are
10641 			 * read-only and probe read instructions would protect against
10642 			 * invalid memory access.
10643 			 */
10644 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
10645 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10646 			if (ret < 0)
10647 				return ret;
10648 			/* If function expects ctx type in BTF check that caller
10649 			 * is passing PTR_TO_CTX.
10650 			 */
10651 			if (reg->type != PTR_TO_CTX) {
10652 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
10653 				return -EINVAL;
10654 			}
10655 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
10656 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10657 			if (ret < 0)
10658 				return ret;
10659 			if (check_mem_reg(env, reg, regno, arg->mem_size))
10660 				return -EINVAL;
10661 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
10662 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
10663 				return -EINVAL;
10664 			}
10665 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
10666 			/*
10667 			 * Can pass any value and the kernel won't crash, but
10668 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
10669 			 * else is a bug in the bpf program. Point it out to
10670 			 * the user at the verification time instead of
10671 			 * run-time debug nightmare.
10672 			 */
10673 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
10674 				bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
10675 				return -EINVAL;
10676 			}
10677 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
10678 			ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
10679 			if (ret)
10680 				return ret;
10681 
10682 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
10683 			if (ret)
10684 				return ret;
10685 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
10686 			struct bpf_call_arg_meta meta;
10687 			int err;
10688 
10689 			if (register_is_null(reg) && type_may_be_null(arg->arg_type))
10690 				continue;
10691 
10692 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
10693 			err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
10694 			err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
10695 			if (err)
10696 				return err;
10697 		} else {
10698 			verifier_bug(env, "unrecognized arg#%d type %d", i, arg->arg_type);
10699 			return -EFAULT;
10700 		}
10701 	}
10702 
10703 	return 0;
10704 }
10705 
10706 /* Compare BTF of a function call with given bpf_reg_state.
10707  * Returns:
10708  * EFAULT - there is a verifier bug. Abort verification.
10709  * EINVAL - there is a type mismatch or BTF is not available.
10710  * 0 - BTF matches with what bpf_reg_state expects.
10711  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
10712  */
10713 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
10714 				  struct bpf_reg_state *regs)
10715 {
10716 	struct bpf_prog *prog = env->prog;
10717 	struct btf *btf = prog->aux->btf;
10718 	u32 btf_id;
10719 	int err;
10720 
10721 	if (!prog->aux->func_info)
10722 		return -EINVAL;
10723 
10724 	btf_id = prog->aux->func_info[subprog].type_id;
10725 	if (!btf_id)
10726 		return -EFAULT;
10727 
10728 	if (prog->aux->func_info_aux[subprog].unreliable)
10729 		return -EINVAL;
10730 
10731 	err = btf_check_func_arg_match(env, subprog, btf, regs);
10732 	/* Compiler optimizations can remove arguments from static functions
10733 	 * or mismatched type can be passed into a global function.
10734 	 * In such cases mark the function as unreliable from BTF point of view.
10735 	 */
10736 	if (err)
10737 		prog->aux->func_info_aux[subprog].unreliable = true;
10738 	return err;
10739 }
10740 
10741 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10742 			      int insn_idx, int subprog,
10743 			      set_callee_state_fn set_callee_state_cb)
10744 {
10745 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
10746 	struct bpf_func_state *caller, *callee;
10747 	int err;
10748 
10749 	caller = state->frame[state->curframe];
10750 	err = btf_check_subprog_call(env, subprog, caller->regs);
10751 	if (err == -EFAULT)
10752 		return err;
10753 
10754 	/* set_callee_state is used for direct subprog calls, but we are
10755 	 * interested in validating only BPF helpers that can call subprogs as
10756 	 * callbacks
10757 	 */
10758 	env->subprog_info[subprog].is_cb = true;
10759 	if (bpf_pseudo_kfunc_call(insn) &&
10760 	    !is_callback_calling_kfunc(insn->imm)) {
10761 		verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
10762 			     func_id_name(insn->imm), insn->imm);
10763 		return -EFAULT;
10764 	} else if (!bpf_pseudo_kfunc_call(insn) &&
10765 		   !is_callback_calling_function(insn->imm)) { /* helper */
10766 		verifier_bug(env, "helper %s#%d not marked as callback-calling",
10767 			     func_id_name(insn->imm), insn->imm);
10768 		return -EFAULT;
10769 	}
10770 
10771 	if (is_async_callback_calling_insn(insn)) {
10772 		struct bpf_verifier_state *async_cb;
10773 
10774 		/* there is no real recursion here. timer and workqueue callbacks are async */
10775 		env->subprog_info[subprog].is_async_cb = true;
10776 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
10777 					 insn_idx, subprog,
10778 					 is_async_cb_sleepable(env, insn));
10779 		if (IS_ERR(async_cb))
10780 			return PTR_ERR(async_cb);
10781 		callee = async_cb->frame[0];
10782 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
10783 
10784 		/* Convert bpf_timer_set_callback() args into timer callback args */
10785 		err = set_callee_state_cb(env, caller, callee, insn_idx);
10786 		if (err)
10787 			return err;
10788 
10789 		return 0;
10790 	}
10791 
10792 	/* for callback functions enqueue entry to callback and
10793 	 * proceed with next instruction within current frame.
10794 	 */
10795 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
10796 	if (IS_ERR(callback_state))
10797 		return PTR_ERR(callback_state);
10798 
10799 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
10800 			       callback_state);
10801 	if (err)
10802 		return err;
10803 
10804 	callback_state->callback_unroll_depth++;
10805 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
10806 	caller->callback_depth = 0;
10807 	return 0;
10808 }
10809 
10810 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10811 			   int *insn_idx)
10812 {
10813 	struct bpf_verifier_state *state = env->cur_state;
10814 	struct bpf_func_state *caller;
10815 	int err, subprog, target_insn;
10816 
10817 	target_insn = *insn_idx + insn->imm + 1;
10818 	subprog = find_subprog(env, target_insn);
10819 	if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program",
10820 			    target_insn))
10821 		return -EFAULT;
10822 
10823 	caller = state->frame[state->curframe];
10824 	err = btf_check_subprog_call(env, subprog, caller->regs);
10825 	if (err == -EFAULT)
10826 		return err;
10827 	if (subprog_is_global(env, subprog)) {
10828 		const char *sub_name = subprog_name(env, subprog);
10829 
10830 		if (env->cur_state->active_locks) {
10831 			verbose(env, "global function calls are not allowed while holding a lock,\n"
10832 				     "use static function instead\n");
10833 			return -EINVAL;
10834 		}
10835 
10836 		if (env->subprog_info[subprog].might_sleep &&
10837 		    (env->cur_state->active_rcu_locks || env->cur_state->active_preempt_locks ||
10838 		     env->cur_state->active_irq_id || !in_sleepable(env))) {
10839 			verbose(env, "global functions that may sleep are not allowed in non-sleepable context,\n"
10840 				     "i.e., in a RCU/IRQ/preempt-disabled section, or in\n"
10841 				     "a non-sleepable BPF program context\n");
10842 			return -EINVAL;
10843 		}
10844 
10845 		if (err) {
10846 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
10847 				subprog, sub_name);
10848 			return err;
10849 		}
10850 
10851 		if (env->log.level & BPF_LOG_LEVEL)
10852 			verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
10853 				subprog, sub_name);
10854 		if (env->subprog_info[subprog].changes_pkt_data)
10855 			clear_all_pkt_pointers(env);
10856 		/* mark global subprog for verifying after main prog */
10857 		subprog_aux(env, subprog)->called = true;
10858 		clear_caller_saved_regs(env, caller->regs);
10859 
10860 		/* All global functions return a 64-bit SCALAR_VALUE */
10861 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
10862 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10863 
10864 		/* continue with next insn after call */
10865 		return 0;
10866 	}
10867 
10868 	/* for regular function entry setup new frame and continue
10869 	 * from that frame.
10870 	 */
10871 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
10872 	if (err)
10873 		return err;
10874 
10875 	clear_caller_saved_regs(env, caller->regs);
10876 
10877 	/* and go analyze first insn of the callee */
10878 	*insn_idx = env->subprog_info[subprog].start - 1;
10879 
10880 	bpf_reset_live_stack_callchain(env);
10881 
10882 	if (env->log.level & BPF_LOG_LEVEL) {
10883 		verbose(env, "caller:\n");
10884 		print_verifier_state(env, state, caller->frameno, true);
10885 		verbose(env, "callee:\n");
10886 		print_verifier_state(env, state, state->curframe, true);
10887 	}
10888 
10889 	return 0;
10890 }
10891 
10892 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
10893 				   struct bpf_func_state *caller,
10894 				   struct bpf_func_state *callee)
10895 {
10896 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
10897 	 *      void *callback_ctx, u64 flags);
10898 	 * callback_fn(struct bpf_map *map, void *key, void *value,
10899 	 *      void *callback_ctx);
10900 	 */
10901 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10902 
10903 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10904 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10905 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10906 
10907 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10908 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10909 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10910 
10911 	/* pointer to stack or null */
10912 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
10913 
10914 	/* unused */
10915 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10916 	return 0;
10917 }
10918 
10919 static int set_callee_state(struct bpf_verifier_env *env,
10920 			    struct bpf_func_state *caller,
10921 			    struct bpf_func_state *callee, int insn_idx)
10922 {
10923 	int i;
10924 
10925 	/* copy r1 - r5 args that callee can access.  The copy includes parent
10926 	 * pointers, which connects us up to the liveness chain
10927 	 */
10928 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
10929 		callee->regs[i] = caller->regs[i];
10930 	return 0;
10931 }
10932 
10933 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
10934 				       struct bpf_func_state *caller,
10935 				       struct bpf_func_state *callee,
10936 				       int insn_idx)
10937 {
10938 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
10939 	struct bpf_map *map;
10940 	int err;
10941 
10942 	/* valid map_ptr and poison value does not matter */
10943 	map = insn_aux->map_ptr_state.map_ptr;
10944 	if (!map->ops->map_set_for_each_callback_args ||
10945 	    !map->ops->map_for_each_callback) {
10946 		verbose(env, "callback function not allowed for map\n");
10947 		return -ENOTSUPP;
10948 	}
10949 
10950 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
10951 	if (err)
10952 		return err;
10953 
10954 	callee->in_callback_fn = true;
10955 	callee->callback_ret_range = retval_range(0, 1);
10956 	return 0;
10957 }
10958 
10959 static int set_loop_callback_state(struct bpf_verifier_env *env,
10960 				   struct bpf_func_state *caller,
10961 				   struct bpf_func_state *callee,
10962 				   int insn_idx)
10963 {
10964 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
10965 	 *	    u64 flags);
10966 	 * callback_fn(u64 index, void *callback_ctx);
10967 	 */
10968 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
10969 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10970 
10971 	/* unused */
10972 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10973 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10974 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10975 
10976 	callee->in_callback_fn = true;
10977 	callee->callback_ret_range = retval_range(0, 1);
10978 	return 0;
10979 }
10980 
10981 static int set_timer_callback_state(struct bpf_verifier_env *env,
10982 				    struct bpf_func_state *caller,
10983 				    struct bpf_func_state *callee,
10984 				    int insn_idx)
10985 {
10986 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
10987 
10988 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
10989 	 * callback_fn(struct bpf_map *map, void *key, void *value);
10990 	 */
10991 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10992 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10993 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
10994 
10995 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10996 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10997 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
10998 
10999 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
11000 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
11001 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
11002 
11003 	/* unused */
11004 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11005 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11006 	callee->in_async_callback_fn = true;
11007 	callee->callback_ret_range = retval_range(0, 0);
11008 	return 0;
11009 }
11010 
11011 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
11012 				       struct bpf_func_state *caller,
11013 				       struct bpf_func_state *callee,
11014 				       int insn_idx)
11015 {
11016 	/* bpf_find_vma(struct task_struct *task, u64 addr,
11017 	 *               void *callback_fn, void *callback_ctx, u64 flags)
11018 	 * (callback_fn)(struct task_struct *task,
11019 	 *               struct vm_area_struct *vma, void *callback_ctx);
11020 	 */
11021 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
11022 
11023 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
11024 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11025 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
11026 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
11027 
11028 	/* pointer to stack or null */
11029 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
11030 
11031 	/* unused */
11032 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11033 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11034 	callee->in_callback_fn = true;
11035 	callee->callback_ret_range = retval_range(0, 1);
11036 	return 0;
11037 }
11038 
11039 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
11040 					   struct bpf_func_state *caller,
11041 					   struct bpf_func_state *callee,
11042 					   int insn_idx)
11043 {
11044 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
11045 	 *			  callback_ctx, u64 flags);
11046 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
11047 	 */
11048 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
11049 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
11050 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
11051 
11052 	/* unused */
11053 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
11054 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11055 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11056 
11057 	callee->in_callback_fn = true;
11058 	callee->callback_ret_range = retval_range(0, 1);
11059 	return 0;
11060 }
11061 
11062 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
11063 					 struct bpf_func_state *caller,
11064 					 struct bpf_func_state *callee,
11065 					 int insn_idx)
11066 {
11067 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
11068 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
11069 	 *
11070 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
11071 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
11072 	 * by this point, so look at 'root'
11073 	 */
11074 	struct btf_field *field;
11075 
11076 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
11077 				      BPF_RB_ROOT);
11078 	if (!field || !field->graph_root.value_btf_id)
11079 		return -EFAULT;
11080 
11081 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
11082 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
11083 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
11084 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
11085 
11086 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
11087 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11088 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11089 	callee->in_callback_fn = true;
11090 	callee->callback_ret_range = retval_range(0, 1);
11091 	return 0;
11092 }
11093 
11094 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env,
11095 						 struct bpf_func_state *caller,
11096 						 struct bpf_func_state *callee,
11097 						 int insn_idx)
11098 {
11099 	struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr;
11100 
11101 	/*
11102 	 * callback_fn(struct bpf_map *map, void *key, void *value);
11103 	 */
11104 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
11105 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
11106 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
11107 
11108 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
11109 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11110 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
11111 
11112 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
11113 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
11114 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
11115 
11116 	/* unused */
11117 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11118 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11119 	callee->in_async_callback_fn = true;
11120 	callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
11121 	return 0;
11122 }
11123 
11124 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
11125 
11126 /* Are we currently verifying the callback for a rbtree helper that must
11127  * be called with lock held? If so, no need to complain about unreleased
11128  * lock
11129  */
11130 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
11131 {
11132 	struct bpf_verifier_state *state = env->cur_state;
11133 	struct bpf_insn *insn = env->prog->insnsi;
11134 	struct bpf_func_state *callee;
11135 	int kfunc_btf_id;
11136 
11137 	if (!state->curframe)
11138 		return false;
11139 
11140 	callee = state->frame[state->curframe];
11141 
11142 	if (!callee->in_callback_fn)
11143 		return false;
11144 
11145 	kfunc_btf_id = insn[callee->callsite].imm;
11146 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
11147 }
11148 
11149 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg,
11150 				bool return_32bit)
11151 {
11152 	if (return_32bit)
11153 		return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval;
11154 	else
11155 		return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
11156 }
11157 
11158 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
11159 {
11160 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
11161 	struct bpf_func_state *caller, *callee;
11162 	struct bpf_reg_state *r0;
11163 	bool in_callback_fn;
11164 	int err;
11165 
11166 	err = bpf_update_live_stack(env);
11167 	if (err)
11168 		return err;
11169 
11170 	callee = state->frame[state->curframe];
11171 	r0 = &callee->regs[BPF_REG_0];
11172 	if (r0->type == PTR_TO_STACK) {
11173 		/* technically it's ok to return caller's stack pointer
11174 		 * (or caller's caller's pointer) back to the caller,
11175 		 * since these pointers are valid. Only current stack
11176 		 * pointer will be invalid as soon as function exits,
11177 		 * but let's be conservative
11178 		 */
11179 		verbose(env, "cannot return stack pointer to the caller\n");
11180 		return -EINVAL;
11181 	}
11182 
11183 	caller = state->frame[state->curframe - 1];
11184 	if (callee->in_callback_fn) {
11185 		if (r0->type != SCALAR_VALUE) {
11186 			verbose(env, "R0 not a scalar value\n");
11187 			return -EACCES;
11188 		}
11189 
11190 		/* we are going to rely on register's precise value */
11191 		err = mark_chain_precision(env, BPF_REG_0);
11192 		if (err)
11193 			return err;
11194 
11195 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
11196 		if (!retval_range_within(callee->callback_ret_range, r0, false)) {
11197 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
11198 					       "At callback return", "R0");
11199 			return -EINVAL;
11200 		}
11201 		if (!bpf_calls_callback(env, callee->callsite)) {
11202 			verifier_bug(env, "in callback at %d, callsite %d !calls_callback",
11203 				     *insn_idx, callee->callsite);
11204 			return -EFAULT;
11205 		}
11206 	} else {
11207 		/* return to the caller whatever r0 had in the callee */
11208 		caller->regs[BPF_REG_0] = *r0;
11209 	}
11210 
11211 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
11212 	 * there function call logic would reschedule callback visit. If iteration
11213 	 * converges is_state_visited() would prune that visit eventually.
11214 	 */
11215 	in_callback_fn = callee->in_callback_fn;
11216 	if (in_callback_fn)
11217 		*insn_idx = callee->callsite;
11218 	else
11219 		*insn_idx = callee->callsite + 1;
11220 
11221 	if (env->log.level & BPF_LOG_LEVEL) {
11222 		verbose(env, "returning from callee:\n");
11223 		print_verifier_state(env, state, callee->frameno, true);
11224 		verbose(env, "to caller at %d:\n", *insn_idx);
11225 		print_verifier_state(env, state, caller->frameno, true);
11226 	}
11227 	/* clear everything in the callee. In case of exceptional exits using
11228 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
11229 	free_func_state(callee);
11230 	state->frame[state->curframe--] = NULL;
11231 
11232 	/* for callbacks widen imprecise scalars to make programs like below verify:
11233 	 *
11234 	 *   struct ctx { int i; }
11235 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
11236 	 *   ...
11237 	 *   struct ctx = { .i = 0; }
11238 	 *   bpf_loop(100, cb, &ctx, 0);
11239 	 *
11240 	 * This is similar to what is done in process_iter_next_call() for open
11241 	 * coded iterators.
11242 	 */
11243 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
11244 	if (prev_st) {
11245 		err = widen_imprecise_scalars(env, prev_st, state);
11246 		if (err)
11247 			return err;
11248 	}
11249 	return 0;
11250 }
11251 
11252 static int do_refine_retval_range(struct bpf_verifier_env *env,
11253 				  struct bpf_reg_state *regs, int ret_type,
11254 				  int func_id,
11255 				  struct bpf_call_arg_meta *meta)
11256 {
11257 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
11258 
11259 	if (ret_type != RET_INTEGER)
11260 		return 0;
11261 
11262 	switch (func_id) {
11263 	case BPF_FUNC_get_stack:
11264 	case BPF_FUNC_get_task_stack:
11265 	case BPF_FUNC_probe_read_str:
11266 	case BPF_FUNC_probe_read_kernel_str:
11267 	case BPF_FUNC_probe_read_user_str:
11268 		ret_reg->smax_value = meta->msize_max_value;
11269 		ret_reg->s32_max_value = meta->msize_max_value;
11270 		ret_reg->smin_value = -MAX_ERRNO;
11271 		ret_reg->s32_min_value = -MAX_ERRNO;
11272 		reg_bounds_sync(ret_reg);
11273 		break;
11274 	case BPF_FUNC_get_smp_processor_id:
11275 		ret_reg->umax_value = nr_cpu_ids - 1;
11276 		ret_reg->u32_max_value = nr_cpu_ids - 1;
11277 		ret_reg->smax_value = nr_cpu_ids - 1;
11278 		ret_reg->s32_max_value = nr_cpu_ids - 1;
11279 		ret_reg->umin_value = 0;
11280 		ret_reg->u32_min_value = 0;
11281 		ret_reg->smin_value = 0;
11282 		ret_reg->s32_min_value = 0;
11283 		reg_bounds_sync(ret_reg);
11284 		break;
11285 	}
11286 
11287 	return reg_bounds_sanity_check(env, ret_reg, "retval");
11288 }
11289 
11290 static int
11291 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11292 		int func_id, int insn_idx)
11293 {
11294 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11295 	struct bpf_map *map = meta->map.ptr;
11296 
11297 	if (func_id != BPF_FUNC_tail_call &&
11298 	    func_id != BPF_FUNC_map_lookup_elem &&
11299 	    func_id != BPF_FUNC_map_update_elem &&
11300 	    func_id != BPF_FUNC_map_delete_elem &&
11301 	    func_id != BPF_FUNC_map_push_elem &&
11302 	    func_id != BPF_FUNC_map_pop_elem &&
11303 	    func_id != BPF_FUNC_map_peek_elem &&
11304 	    func_id != BPF_FUNC_for_each_map_elem &&
11305 	    func_id != BPF_FUNC_redirect_map &&
11306 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
11307 		return 0;
11308 
11309 	if (map == NULL) {
11310 		verifier_bug(env, "expected map for helper call");
11311 		return -EFAULT;
11312 	}
11313 
11314 	/* In case of read-only, some additional restrictions
11315 	 * need to be applied in order to prevent altering the
11316 	 * state of the map from program side.
11317 	 */
11318 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
11319 	    (func_id == BPF_FUNC_map_delete_elem ||
11320 	     func_id == BPF_FUNC_map_update_elem ||
11321 	     func_id == BPF_FUNC_map_push_elem ||
11322 	     func_id == BPF_FUNC_map_pop_elem)) {
11323 		verbose(env, "write into map forbidden\n");
11324 		return -EACCES;
11325 	}
11326 
11327 	if (!aux->map_ptr_state.map_ptr)
11328 		bpf_map_ptr_store(aux, meta->map.ptr,
11329 				  !meta->map.ptr->bypass_spec_v1, false);
11330 	else if (aux->map_ptr_state.map_ptr != meta->map.ptr)
11331 		bpf_map_ptr_store(aux, meta->map.ptr,
11332 				  !meta->map.ptr->bypass_spec_v1, true);
11333 	return 0;
11334 }
11335 
11336 static int
11337 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11338 		int func_id, int insn_idx)
11339 {
11340 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11341 	struct bpf_reg_state *reg;
11342 	struct bpf_map *map = meta->map.ptr;
11343 	u64 val, max;
11344 	int err;
11345 
11346 	if (func_id != BPF_FUNC_tail_call)
11347 		return 0;
11348 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
11349 		verbose(env, "expected prog array map for tail call");
11350 		return -EINVAL;
11351 	}
11352 
11353 	reg = reg_state(env, BPF_REG_3);
11354 	val = reg->var_off.value;
11355 	max = map->max_entries;
11356 
11357 	if (!(is_reg_const(reg, false) && val < max)) {
11358 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11359 		return 0;
11360 	}
11361 
11362 	err = mark_chain_precision(env, BPF_REG_3);
11363 	if (err)
11364 		return err;
11365 	if (bpf_map_key_unseen(aux))
11366 		bpf_map_key_store(aux, val);
11367 	else if (!bpf_map_key_poisoned(aux) &&
11368 		  bpf_map_key_immediate(aux) != val)
11369 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11370 	return 0;
11371 }
11372 
11373 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
11374 {
11375 	struct bpf_verifier_state *state = env->cur_state;
11376 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11377 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
11378 	bool refs_lingering = false;
11379 	int i;
11380 
11381 	if (!exception_exit && cur_func(env)->frameno)
11382 		return 0;
11383 
11384 	for (i = 0; i < state->acquired_refs; i++) {
11385 		if (state->refs[i].type != REF_TYPE_PTR)
11386 			continue;
11387 		/* Allow struct_ops programs to return a referenced kptr back to
11388 		 * kernel. Type checks are performed later in check_return_code.
11389 		 */
11390 		if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
11391 		    reg->ref_obj_id == state->refs[i].id)
11392 			continue;
11393 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
11394 			state->refs[i].id, state->refs[i].insn_idx);
11395 		refs_lingering = true;
11396 	}
11397 	return refs_lingering ? -EINVAL : 0;
11398 }
11399 
11400 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
11401 {
11402 	int err;
11403 
11404 	if (check_lock && env->cur_state->active_locks) {
11405 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
11406 		return -EINVAL;
11407 	}
11408 
11409 	err = check_reference_leak(env, exception_exit);
11410 	if (err) {
11411 		verbose(env, "%s would lead to reference leak\n", prefix);
11412 		return err;
11413 	}
11414 
11415 	if (check_lock && env->cur_state->active_irq_id) {
11416 		verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
11417 		return -EINVAL;
11418 	}
11419 
11420 	if (check_lock && env->cur_state->active_rcu_locks) {
11421 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
11422 		return -EINVAL;
11423 	}
11424 
11425 	if (check_lock && env->cur_state->active_preempt_locks) {
11426 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
11427 		return -EINVAL;
11428 	}
11429 
11430 	return 0;
11431 }
11432 
11433 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
11434 				   struct bpf_reg_state *regs)
11435 {
11436 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
11437 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
11438 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
11439 	struct bpf_bprintf_data data = {};
11440 	int err, fmt_map_off, num_args;
11441 	u64 fmt_addr;
11442 	char *fmt;
11443 
11444 	/* data must be an array of u64 */
11445 	if (data_len_reg->var_off.value % 8)
11446 		return -EINVAL;
11447 	num_args = data_len_reg->var_off.value / 8;
11448 
11449 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
11450 	 * and map_direct_value_addr is set.
11451 	 */
11452 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
11453 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
11454 						  fmt_map_off);
11455 	if (err) {
11456 		verbose(env, "failed to retrieve map value address\n");
11457 		return -EFAULT;
11458 	}
11459 	fmt = (char *)(long)fmt_addr + fmt_map_off;
11460 
11461 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
11462 	 * can focus on validating the format specifiers.
11463 	 */
11464 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
11465 	if (err < 0)
11466 		verbose(env, "Invalid format string\n");
11467 
11468 	return err;
11469 }
11470 
11471 static int check_get_func_ip(struct bpf_verifier_env *env)
11472 {
11473 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11474 	int func_id = BPF_FUNC_get_func_ip;
11475 
11476 	if (type == BPF_PROG_TYPE_TRACING) {
11477 		if (!bpf_prog_has_trampoline(env->prog)) {
11478 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
11479 				func_id_name(func_id), func_id);
11480 			return -ENOTSUPP;
11481 		}
11482 		return 0;
11483 	} else if (type == BPF_PROG_TYPE_KPROBE) {
11484 		return 0;
11485 	}
11486 
11487 	verbose(env, "func %s#%d not supported for program type %d\n",
11488 		func_id_name(func_id), func_id, type);
11489 	return -ENOTSUPP;
11490 }
11491 
11492 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env)
11493 {
11494 	return &env->insn_aux_data[env->insn_idx];
11495 }
11496 
11497 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
11498 {
11499 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_4);
11500 	bool reg_is_null = register_is_null(reg);
11501 
11502 	if (reg_is_null)
11503 		mark_chain_precision(env, BPF_REG_4);
11504 
11505 	return reg_is_null;
11506 }
11507 
11508 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
11509 {
11510 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
11511 
11512 	if (!state->initialized) {
11513 		state->initialized = 1;
11514 		state->fit_for_inline = loop_flag_is_zero(env);
11515 		state->callback_subprogno = subprogno;
11516 		return;
11517 	}
11518 
11519 	if (!state->fit_for_inline)
11520 		return;
11521 
11522 	state->fit_for_inline = (loop_flag_is_zero(env) &&
11523 				 state->callback_subprogno == subprogno);
11524 }
11525 
11526 /* Returns whether or not the given map type can potentially elide
11527  * lookup return value nullness check. This is possible if the key
11528  * is statically known.
11529  */
11530 static bool can_elide_value_nullness(enum bpf_map_type type)
11531 {
11532 	switch (type) {
11533 	case BPF_MAP_TYPE_ARRAY:
11534 	case BPF_MAP_TYPE_PERCPU_ARRAY:
11535 		return true;
11536 	default:
11537 		return false;
11538 	}
11539 }
11540 
11541 static int get_helper_proto(struct bpf_verifier_env *env, int func_id,
11542 			    const struct bpf_func_proto **ptr)
11543 {
11544 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
11545 		return -ERANGE;
11546 
11547 	if (!env->ops->get_func_proto)
11548 		return -EINVAL;
11549 
11550 	*ptr = env->ops->get_func_proto(func_id, env->prog);
11551 	return *ptr && (*ptr)->func ? 0 : -EINVAL;
11552 }
11553 
11554 /* Check if we're in a sleepable context. */
11555 static inline bool in_sleepable_context(struct bpf_verifier_env *env)
11556 {
11557 	return !env->cur_state->active_rcu_locks &&
11558 	       !env->cur_state->active_preempt_locks &&
11559 	       !env->cur_state->active_locks &&
11560 	       !env->cur_state->active_irq_id &&
11561 	       in_sleepable(env);
11562 }
11563 
11564 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11565 			     int *insn_idx_p)
11566 {
11567 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11568 	bool returns_cpu_specific_alloc_ptr = false;
11569 	const struct bpf_func_proto *fn = NULL;
11570 	enum bpf_return_type ret_type;
11571 	enum bpf_type_flag ret_flag;
11572 	struct bpf_reg_state *regs;
11573 	struct bpf_call_arg_meta meta;
11574 	int insn_idx = *insn_idx_p;
11575 	bool changes_data;
11576 	int i, err, func_id;
11577 
11578 	/* find function prototype */
11579 	func_id = insn->imm;
11580 	err = get_helper_proto(env, insn->imm, &fn);
11581 	if (err == -ERANGE) {
11582 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
11583 		return -EINVAL;
11584 	}
11585 
11586 	if (err) {
11587 		verbose(env, "program of this type cannot use helper %s#%d\n",
11588 			func_id_name(func_id), func_id);
11589 		return err;
11590 	}
11591 
11592 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
11593 	if (!env->prog->gpl_compatible && fn->gpl_only) {
11594 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
11595 		return -EINVAL;
11596 	}
11597 
11598 	if (fn->allowed && !fn->allowed(env->prog)) {
11599 		verbose(env, "helper call is not allowed in probe\n");
11600 		return -EINVAL;
11601 	}
11602 
11603 	if (!in_sleepable(env) && fn->might_sleep) {
11604 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
11605 		return -EINVAL;
11606 	}
11607 
11608 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
11609 	changes_data = bpf_helper_changes_pkt_data(func_id);
11610 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
11611 		verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id);
11612 		return -EFAULT;
11613 	}
11614 
11615 	memset(&meta, 0, sizeof(meta));
11616 	meta.pkt_access = fn->pkt_access;
11617 
11618 	err = check_func_proto(fn);
11619 	if (err) {
11620 		verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id);
11621 		return err;
11622 	}
11623 
11624 	if (env->cur_state->active_rcu_locks) {
11625 		if (fn->might_sleep) {
11626 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
11627 				func_id_name(func_id), func_id);
11628 			return -EINVAL;
11629 		}
11630 	}
11631 
11632 	if (env->cur_state->active_preempt_locks) {
11633 		if (fn->might_sleep) {
11634 			verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
11635 				func_id_name(func_id), func_id);
11636 			return -EINVAL;
11637 		}
11638 	}
11639 
11640 	if (env->cur_state->active_irq_id) {
11641 		if (fn->might_sleep) {
11642 			verbose(env, "sleepable helper %s#%d in IRQ-disabled region\n",
11643 				func_id_name(func_id), func_id);
11644 			return -EINVAL;
11645 		}
11646 	}
11647 
11648 	/* Track non-sleepable context for helpers. */
11649 	if (!in_sleepable_context(env))
11650 		env->insn_aux_data[insn_idx].non_sleepable = true;
11651 
11652 	meta.func_id = func_id;
11653 	/* check args */
11654 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
11655 		err = check_func_arg(env, i, &meta, fn, insn_idx);
11656 		if (err)
11657 			return err;
11658 	}
11659 
11660 	err = record_func_map(env, &meta, func_id, insn_idx);
11661 	if (err)
11662 		return err;
11663 
11664 	err = record_func_key(env, &meta, func_id, insn_idx);
11665 	if (err)
11666 		return err;
11667 
11668 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
11669 	 * is inferred from register state.
11670 	 */
11671 	for (i = 0; i < meta.access_size; i++) {
11672 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
11673 				       BPF_WRITE, -1, false, false);
11674 		if (err)
11675 			return err;
11676 	}
11677 
11678 	regs = cur_regs(env);
11679 
11680 	if (meta.release_regno) {
11681 		err = -EINVAL;
11682 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
11683 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
11684 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
11685 			u32 ref_obj_id = meta.ref_obj_id;
11686 			bool in_rcu = in_rcu_cs(env);
11687 			struct bpf_func_state *state;
11688 			struct bpf_reg_state *reg;
11689 
11690 			err = release_reference_nomark(env->cur_state, ref_obj_id);
11691 			if (!err) {
11692 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11693 					if (reg->ref_obj_id == ref_obj_id) {
11694 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
11695 							reg->ref_obj_id = 0;
11696 							reg->type &= ~MEM_ALLOC;
11697 							reg->type |= MEM_RCU;
11698 						} else {
11699 							mark_reg_invalid(env, reg);
11700 						}
11701 					}
11702 				}));
11703 			}
11704 		} else if (meta.ref_obj_id) {
11705 			err = release_reference(env, meta.ref_obj_id);
11706 		} else if (register_is_null(&regs[meta.release_regno])) {
11707 			/* meta.ref_obj_id can only be 0 if register that is meant to be
11708 			 * released is NULL, which must be > R0.
11709 			 */
11710 			err = 0;
11711 		}
11712 		if (err) {
11713 			verbose(env, "func %s#%d reference has not been acquired before\n",
11714 				func_id_name(func_id), func_id);
11715 			return err;
11716 		}
11717 	}
11718 
11719 	switch (func_id) {
11720 	case BPF_FUNC_tail_call:
11721 		err = check_resource_leak(env, false, true, "tail_call");
11722 		if (err)
11723 			return err;
11724 		break;
11725 	case BPF_FUNC_get_local_storage:
11726 		/* check that flags argument in get_local_storage(map, flags) is 0,
11727 		 * this is required because get_local_storage() can't return an error.
11728 		 */
11729 		if (!register_is_null(&regs[BPF_REG_2])) {
11730 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
11731 			return -EINVAL;
11732 		}
11733 		break;
11734 	case BPF_FUNC_for_each_map_elem:
11735 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11736 					 set_map_elem_callback_state);
11737 		break;
11738 	case BPF_FUNC_timer_set_callback:
11739 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11740 					 set_timer_callback_state);
11741 		break;
11742 	case BPF_FUNC_find_vma:
11743 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11744 					 set_find_vma_callback_state);
11745 		break;
11746 	case BPF_FUNC_snprintf:
11747 		err = check_bpf_snprintf_call(env, regs);
11748 		break;
11749 	case BPF_FUNC_loop:
11750 		update_loop_inline_state(env, meta.subprogno);
11751 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
11752 		 * is finished, thus mark it precise.
11753 		 */
11754 		err = mark_chain_precision(env, BPF_REG_1);
11755 		if (err)
11756 			return err;
11757 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
11758 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11759 						 set_loop_callback_state);
11760 		} else {
11761 			cur_func(env)->callback_depth = 0;
11762 			if (env->log.level & BPF_LOG_LEVEL2)
11763 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
11764 					env->cur_state->curframe);
11765 		}
11766 		break;
11767 	case BPF_FUNC_dynptr_from_mem:
11768 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
11769 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
11770 				reg_type_str(env, regs[BPF_REG_1].type));
11771 			return -EACCES;
11772 		}
11773 		break;
11774 	case BPF_FUNC_set_retval:
11775 		if (prog_type == BPF_PROG_TYPE_LSM &&
11776 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
11777 			if (!env->prog->aux->attach_func_proto->type) {
11778 				/* Make sure programs that attach to void
11779 				 * hooks don't try to modify return value.
11780 				 */
11781 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
11782 				return -EINVAL;
11783 			}
11784 		}
11785 		break;
11786 	case BPF_FUNC_dynptr_data:
11787 	{
11788 		struct bpf_reg_state *reg;
11789 		int id, ref_obj_id;
11790 
11791 		reg = get_dynptr_arg_reg(env, fn, regs);
11792 		if (!reg)
11793 			return -EFAULT;
11794 
11795 
11796 		if (meta.dynptr_id) {
11797 			verifier_bug(env, "meta.dynptr_id already set");
11798 			return -EFAULT;
11799 		}
11800 		if (meta.ref_obj_id) {
11801 			verifier_bug(env, "meta.ref_obj_id already set");
11802 			return -EFAULT;
11803 		}
11804 
11805 		id = dynptr_id(env, reg);
11806 		if (id < 0) {
11807 			verifier_bug(env, "failed to obtain dynptr id");
11808 			return id;
11809 		}
11810 
11811 		ref_obj_id = dynptr_ref_obj_id(env, reg);
11812 		if (ref_obj_id < 0) {
11813 			verifier_bug(env, "failed to obtain dynptr ref_obj_id");
11814 			return ref_obj_id;
11815 		}
11816 
11817 		meta.dynptr_id = id;
11818 		meta.ref_obj_id = ref_obj_id;
11819 
11820 		break;
11821 	}
11822 	case BPF_FUNC_dynptr_write:
11823 	{
11824 		enum bpf_dynptr_type dynptr_type;
11825 		struct bpf_reg_state *reg;
11826 
11827 		reg = get_dynptr_arg_reg(env, fn, regs);
11828 		if (!reg)
11829 			return -EFAULT;
11830 
11831 		dynptr_type = dynptr_get_type(env, reg);
11832 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
11833 			return -EFAULT;
11834 
11835 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB ||
11836 		    dynptr_type == BPF_DYNPTR_TYPE_SKB_META)
11837 			/* this will trigger clear_all_pkt_pointers(), which will
11838 			 * invalidate all dynptr slices associated with the skb
11839 			 */
11840 			changes_data = true;
11841 
11842 		break;
11843 	}
11844 	case BPF_FUNC_per_cpu_ptr:
11845 	case BPF_FUNC_this_cpu_ptr:
11846 	{
11847 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
11848 		const struct btf_type *type;
11849 
11850 		if (reg->type & MEM_RCU) {
11851 			type = btf_type_by_id(reg->btf, reg->btf_id);
11852 			if (!type || !btf_type_is_struct(type)) {
11853 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
11854 				return -EFAULT;
11855 			}
11856 			returns_cpu_specific_alloc_ptr = true;
11857 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
11858 		}
11859 		break;
11860 	}
11861 	case BPF_FUNC_user_ringbuf_drain:
11862 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11863 					 set_user_ringbuf_callback_state);
11864 		break;
11865 	}
11866 
11867 	if (err)
11868 		return err;
11869 
11870 	/* reset caller saved regs */
11871 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
11872 		mark_reg_not_init(env, regs, caller_saved[i]);
11873 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11874 	}
11875 
11876 	/* helper call returns 64-bit value. */
11877 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
11878 
11879 	/* update return register (already marked as written above) */
11880 	ret_type = fn->ret_type;
11881 	ret_flag = type_flag(ret_type);
11882 
11883 	switch (base_type(ret_type)) {
11884 	case RET_INTEGER:
11885 		/* sets type to SCALAR_VALUE */
11886 		mark_reg_unknown(env, regs, BPF_REG_0);
11887 		break;
11888 	case RET_VOID:
11889 		regs[BPF_REG_0].type = NOT_INIT;
11890 		break;
11891 	case RET_PTR_TO_MAP_VALUE:
11892 		/* There is no offset yet applied, variable or fixed */
11893 		mark_reg_known_zero(env, regs, BPF_REG_0);
11894 		/* remember map_ptr, so that check_map_access()
11895 		 * can check 'value_size' boundary of memory access
11896 		 * to map element returned from bpf_map_lookup_elem()
11897 		 */
11898 		if (meta.map.ptr == NULL) {
11899 			verifier_bug(env, "unexpected null map_ptr");
11900 			return -EFAULT;
11901 		}
11902 
11903 		if (func_id == BPF_FUNC_map_lookup_elem &&
11904 		    can_elide_value_nullness(meta.map.ptr->map_type) &&
11905 		    meta.const_map_key >= 0 &&
11906 		    meta.const_map_key < meta.map.ptr->max_entries)
11907 			ret_flag &= ~PTR_MAYBE_NULL;
11908 
11909 		regs[BPF_REG_0].map_ptr = meta.map.ptr;
11910 		regs[BPF_REG_0].map_uid = meta.map.uid;
11911 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
11912 		if (!type_may_be_null(ret_flag) &&
11913 		    btf_record_has_field(meta.map.ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
11914 			regs[BPF_REG_0].id = ++env->id_gen;
11915 		}
11916 		break;
11917 	case RET_PTR_TO_SOCKET:
11918 		mark_reg_known_zero(env, regs, BPF_REG_0);
11919 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
11920 		break;
11921 	case RET_PTR_TO_SOCK_COMMON:
11922 		mark_reg_known_zero(env, regs, BPF_REG_0);
11923 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
11924 		break;
11925 	case RET_PTR_TO_TCP_SOCK:
11926 		mark_reg_known_zero(env, regs, BPF_REG_0);
11927 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
11928 		break;
11929 	case RET_PTR_TO_MEM:
11930 		mark_reg_known_zero(env, regs, BPF_REG_0);
11931 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11932 		regs[BPF_REG_0].mem_size = meta.mem_size;
11933 		break;
11934 	case RET_PTR_TO_MEM_OR_BTF_ID:
11935 	{
11936 		const struct btf_type *t;
11937 
11938 		mark_reg_known_zero(env, regs, BPF_REG_0);
11939 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
11940 		if (!btf_type_is_struct(t)) {
11941 			u32 tsize;
11942 			const struct btf_type *ret;
11943 			const char *tname;
11944 
11945 			/* resolve the type size of ksym. */
11946 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
11947 			if (IS_ERR(ret)) {
11948 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
11949 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
11950 					tname, PTR_ERR(ret));
11951 				return -EINVAL;
11952 			}
11953 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11954 			regs[BPF_REG_0].mem_size = tsize;
11955 		} else {
11956 			if (returns_cpu_specific_alloc_ptr) {
11957 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
11958 			} else {
11959 				/* MEM_RDONLY may be carried from ret_flag, but it
11960 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
11961 				 * it will confuse the check of PTR_TO_BTF_ID in
11962 				 * check_mem_access().
11963 				 */
11964 				ret_flag &= ~MEM_RDONLY;
11965 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11966 			}
11967 
11968 			regs[BPF_REG_0].btf = meta.ret_btf;
11969 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11970 		}
11971 		break;
11972 	}
11973 	case RET_PTR_TO_BTF_ID:
11974 	{
11975 		struct btf *ret_btf;
11976 		int ret_btf_id;
11977 
11978 		mark_reg_known_zero(env, regs, BPF_REG_0);
11979 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11980 		if (func_id == BPF_FUNC_kptr_xchg) {
11981 			ret_btf = meta.kptr_field->kptr.btf;
11982 			ret_btf_id = meta.kptr_field->kptr.btf_id;
11983 			if (!btf_is_kernel(ret_btf)) {
11984 				regs[BPF_REG_0].type |= MEM_ALLOC;
11985 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
11986 					regs[BPF_REG_0].type |= MEM_PERCPU;
11987 			}
11988 		} else {
11989 			if (fn->ret_btf_id == BPF_PTR_POISON) {
11990 				verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type",
11991 					     func_id_name(func_id));
11992 				return -EFAULT;
11993 			}
11994 			ret_btf = btf_vmlinux;
11995 			ret_btf_id = *fn->ret_btf_id;
11996 		}
11997 		if (ret_btf_id == 0) {
11998 			verbose(env, "invalid return type %u of func %s#%d\n",
11999 				base_type(ret_type), func_id_name(func_id),
12000 				func_id);
12001 			return -EINVAL;
12002 		}
12003 		regs[BPF_REG_0].btf = ret_btf;
12004 		regs[BPF_REG_0].btf_id = ret_btf_id;
12005 		break;
12006 	}
12007 	default:
12008 		verbose(env, "unknown return type %u of func %s#%d\n",
12009 			base_type(ret_type), func_id_name(func_id), func_id);
12010 		return -EINVAL;
12011 	}
12012 
12013 	if (type_may_be_null(regs[BPF_REG_0].type))
12014 		regs[BPF_REG_0].id = ++env->id_gen;
12015 
12016 	if (helper_multiple_ref_obj_use(func_id, meta.map.ptr)) {
12017 		verifier_bug(env, "func %s#%d sets ref_obj_id more than once",
12018 			     func_id_name(func_id), func_id);
12019 		return -EFAULT;
12020 	}
12021 
12022 	if (is_dynptr_ref_function(func_id))
12023 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
12024 
12025 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
12026 		/* For release_reference() */
12027 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12028 	} else if (is_acquire_function(func_id, meta.map.ptr)) {
12029 		int id = acquire_reference(env, insn_idx);
12030 
12031 		if (id < 0)
12032 			return id;
12033 		/* For mark_ptr_or_null_reg() */
12034 		regs[BPF_REG_0].id = id;
12035 		/* For release_reference() */
12036 		regs[BPF_REG_0].ref_obj_id = id;
12037 	}
12038 
12039 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
12040 	if (err)
12041 		return err;
12042 
12043 	err = check_map_func_compatibility(env, meta.map.ptr, func_id);
12044 	if (err)
12045 		return err;
12046 
12047 	if ((func_id == BPF_FUNC_get_stack ||
12048 	     func_id == BPF_FUNC_get_task_stack) &&
12049 	    !env->prog->has_callchain_buf) {
12050 		const char *err_str;
12051 
12052 #ifdef CONFIG_PERF_EVENTS
12053 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
12054 		err_str = "cannot get callchain buffer for func %s#%d\n";
12055 #else
12056 		err = -ENOTSUPP;
12057 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
12058 #endif
12059 		if (err) {
12060 			verbose(env, err_str, func_id_name(func_id), func_id);
12061 			return err;
12062 		}
12063 
12064 		env->prog->has_callchain_buf = true;
12065 	}
12066 
12067 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
12068 		env->prog->call_get_stack = true;
12069 
12070 	if (func_id == BPF_FUNC_get_func_ip) {
12071 		if (check_get_func_ip(env))
12072 			return -ENOTSUPP;
12073 		env->prog->call_get_func_ip = true;
12074 	}
12075 
12076 	if (func_id == BPF_FUNC_tail_call) {
12077 		if (env->cur_state->curframe) {
12078 			struct bpf_verifier_state *branch;
12079 
12080 			mark_reg_scratched(env, BPF_REG_0);
12081 			branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
12082 			if (IS_ERR(branch))
12083 				return PTR_ERR(branch);
12084 			clear_all_pkt_pointers(env);
12085 			mark_reg_unknown(env, regs, BPF_REG_0);
12086 			err = prepare_func_exit(env, &env->insn_idx);
12087 			if (err)
12088 				return err;
12089 			env->insn_idx--;
12090 		} else {
12091 			changes_data = false;
12092 		}
12093 	}
12094 
12095 	if (changes_data)
12096 		clear_all_pkt_pointers(env);
12097 	return 0;
12098 }
12099 
12100 /* mark_btf_func_reg_size() is used when the reg size is determined by
12101  * the BTF func_proto's return value size and argument.
12102  */
12103 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
12104 				     u32 regno, size_t reg_size)
12105 {
12106 	struct bpf_reg_state *reg = &regs[regno];
12107 
12108 	if (regno == BPF_REG_0) {
12109 		/* Function return value */
12110 		reg->subreg_def = reg_size == sizeof(u64) ?
12111 			DEF_NOT_SUBREG : env->insn_idx + 1;
12112 	} else if (reg_size == sizeof(u64)) {
12113 		/* Function argument */
12114 		mark_insn_zext(env, reg);
12115 	}
12116 }
12117 
12118 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
12119 				   size_t reg_size)
12120 {
12121 	return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size);
12122 }
12123 
12124 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
12125 {
12126 	return meta->kfunc_flags & KF_ACQUIRE;
12127 }
12128 
12129 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
12130 {
12131 	return meta->kfunc_flags & KF_RELEASE;
12132 }
12133 
12134 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
12135 {
12136 	return meta->kfunc_flags & KF_SLEEPABLE;
12137 }
12138 
12139 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
12140 {
12141 	return meta->kfunc_flags & KF_DESTRUCTIVE;
12142 }
12143 
12144 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
12145 {
12146 	return meta->kfunc_flags & KF_RCU;
12147 }
12148 
12149 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
12150 {
12151 	return meta->kfunc_flags & KF_RCU_PROTECTED;
12152 }
12153 
12154 static bool is_kfunc_arg_mem_size(const struct btf *btf,
12155 				  const struct btf_param *arg,
12156 				  const struct bpf_reg_state *reg)
12157 {
12158 	const struct btf_type *t;
12159 
12160 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12161 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
12162 		return false;
12163 
12164 	return btf_param_match_suffix(btf, arg, "__sz");
12165 }
12166 
12167 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
12168 					const struct btf_param *arg,
12169 					const struct bpf_reg_state *reg)
12170 {
12171 	const struct btf_type *t;
12172 
12173 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12174 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
12175 		return false;
12176 
12177 	return btf_param_match_suffix(btf, arg, "__szk");
12178 }
12179 
12180 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
12181 {
12182 	return btf_param_match_suffix(btf, arg, "__k");
12183 }
12184 
12185 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
12186 {
12187 	return btf_param_match_suffix(btf, arg, "__ign");
12188 }
12189 
12190 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
12191 {
12192 	return btf_param_match_suffix(btf, arg, "__map");
12193 }
12194 
12195 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
12196 {
12197 	return btf_param_match_suffix(btf, arg, "__alloc");
12198 }
12199 
12200 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
12201 {
12202 	return btf_param_match_suffix(btf, arg, "__uninit");
12203 }
12204 
12205 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
12206 {
12207 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
12208 }
12209 
12210 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
12211 {
12212 	return btf_param_match_suffix(btf, arg, "__nullable");
12213 }
12214 
12215 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
12216 {
12217 	return btf_param_match_suffix(btf, arg, "__str");
12218 }
12219 
12220 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
12221 {
12222 	return btf_param_match_suffix(btf, arg, "__irq_flag");
12223 }
12224 
12225 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
12226 					  const struct btf_param *arg,
12227 					  const char *name)
12228 {
12229 	int len, target_len = strlen(name);
12230 	const char *param_name;
12231 
12232 	param_name = btf_name_by_offset(btf, arg->name_off);
12233 	if (str_is_empty(param_name))
12234 		return false;
12235 	len = strlen(param_name);
12236 	if (len != target_len)
12237 		return false;
12238 	if (strcmp(param_name, name))
12239 		return false;
12240 
12241 	return true;
12242 }
12243 
12244 enum {
12245 	KF_ARG_DYNPTR_ID,
12246 	KF_ARG_LIST_HEAD_ID,
12247 	KF_ARG_LIST_NODE_ID,
12248 	KF_ARG_RB_ROOT_ID,
12249 	KF_ARG_RB_NODE_ID,
12250 	KF_ARG_WORKQUEUE_ID,
12251 	KF_ARG_RES_SPIN_LOCK_ID,
12252 	KF_ARG_TASK_WORK_ID,
12253 	KF_ARG_PROG_AUX_ID,
12254 	KF_ARG_TIMER_ID
12255 };
12256 
12257 BTF_ID_LIST(kf_arg_btf_ids)
12258 BTF_ID(struct, bpf_dynptr)
12259 BTF_ID(struct, bpf_list_head)
12260 BTF_ID(struct, bpf_list_node)
12261 BTF_ID(struct, bpf_rb_root)
12262 BTF_ID(struct, bpf_rb_node)
12263 BTF_ID(struct, bpf_wq)
12264 BTF_ID(struct, bpf_res_spin_lock)
12265 BTF_ID(struct, bpf_task_work)
12266 BTF_ID(struct, bpf_prog_aux)
12267 BTF_ID(struct, bpf_timer)
12268 
12269 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
12270 				    const struct btf_param *arg, int type)
12271 {
12272 	const struct btf_type *t;
12273 	u32 res_id;
12274 
12275 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12276 	if (!t)
12277 		return false;
12278 	if (!btf_type_is_ptr(t))
12279 		return false;
12280 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
12281 	if (!t)
12282 		return false;
12283 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
12284 }
12285 
12286 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
12287 {
12288 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
12289 }
12290 
12291 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
12292 {
12293 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
12294 }
12295 
12296 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
12297 {
12298 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
12299 }
12300 
12301 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
12302 {
12303 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
12304 }
12305 
12306 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
12307 {
12308 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
12309 }
12310 
12311 static bool is_kfunc_arg_timer(const struct btf *btf, const struct btf_param *arg)
12312 {
12313 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TIMER_ID);
12314 }
12315 
12316 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
12317 {
12318 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
12319 }
12320 
12321 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg)
12322 {
12323 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID);
12324 }
12325 
12326 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg)
12327 {
12328 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID);
12329 }
12330 
12331 static bool is_rbtree_node_type(const struct btf_type *t)
12332 {
12333 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]);
12334 }
12335 
12336 static bool is_list_node_type(const struct btf_type *t)
12337 {
12338 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]);
12339 }
12340 
12341 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
12342 				  const struct btf_param *arg)
12343 {
12344 	const struct btf_type *t;
12345 
12346 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
12347 	if (!t)
12348 		return false;
12349 
12350 	return true;
12351 }
12352 
12353 static bool is_kfunc_arg_prog_aux(const struct btf *btf, const struct btf_param *arg)
12354 {
12355 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_PROG_AUX_ID);
12356 }
12357 
12358 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
12359 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
12360 					const struct btf *btf,
12361 					const struct btf_type *t, int rec)
12362 {
12363 	const struct btf_type *member_type;
12364 	const struct btf_member *member;
12365 	u32 i;
12366 
12367 	if (!btf_type_is_struct(t))
12368 		return false;
12369 
12370 	for_each_member(i, t, member) {
12371 		const struct btf_array *array;
12372 
12373 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
12374 		if (btf_type_is_struct(member_type)) {
12375 			if (rec >= 3) {
12376 				verbose(env, "max struct nesting depth exceeded\n");
12377 				return false;
12378 			}
12379 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
12380 				return false;
12381 			continue;
12382 		}
12383 		if (btf_type_is_array(member_type)) {
12384 			array = btf_array(member_type);
12385 			if (!array->nelems)
12386 				return false;
12387 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
12388 			if (!btf_type_is_scalar(member_type))
12389 				return false;
12390 			continue;
12391 		}
12392 		if (!btf_type_is_scalar(member_type))
12393 			return false;
12394 	}
12395 	return true;
12396 }
12397 
12398 enum kfunc_ptr_arg_type {
12399 	KF_ARG_PTR_TO_CTX,
12400 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
12401 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
12402 	KF_ARG_PTR_TO_DYNPTR,
12403 	KF_ARG_PTR_TO_ITER,
12404 	KF_ARG_PTR_TO_LIST_HEAD,
12405 	KF_ARG_PTR_TO_LIST_NODE,
12406 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
12407 	KF_ARG_PTR_TO_MEM,
12408 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
12409 	KF_ARG_PTR_TO_CALLBACK,
12410 	KF_ARG_PTR_TO_RB_ROOT,
12411 	KF_ARG_PTR_TO_RB_NODE,
12412 	KF_ARG_PTR_TO_NULL,
12413 	KF_ARG_PTR_TO_CONST_STR,
12414 	KF_ARG_PTR_TO_MAP,
12415 	KF_ARG_PTR_TO_TIMER,
12416 	KF_ARG_PTR_TO_WORKQUEUE,
12417 	KF_ARG_PTR_TO_IRQ_FLAG,
12418 	KF_ARG_PTR_TO_RES_SPIN_LOCK,
12419 	KF_ARG_PTR_TO_TASK_WORK,
12420 };
12421 
12422 enum special_kfunc_type {
12423 	KF_bpf_obj_new_impl,
12424 	KF_bpf_obj_drop_impl,
12425 	KF_bpf_refcount_acquire_impl,
12426 	KF_bpf_list_push_front_impl,
12427 	KF_bpf_list_push_back_impl,
12428 	KF_bpf_list_pop_front,
12429 	KF_bpf_list_pop_back,
12430 	KF_bpf_list_front,
12431 	KF_bpf_list_back,
12432 	KF_bpf_cast_to_kern_ctx,
12433 	KF_bpf_rdonly_cast,
12434 	KF_bpf_rcu_read_lock,
12435 	KF_bpf_rcu_read_unlock,
12436 	KF_bpf_rbtree_remove,
12437 	KF_bpf_rbtree_add_impl,
12438 	KF_bpf_rbtree_first,
12439 	KF_bpf_rbtree_root,
12440 	KF_bpf_rbtree_left,
12441 	KF_bpf_rbtree_right,
12442 	KF_bpf_dynptr_from_skb,
12443 	KF_bpf_dynptr_from_xdp,
12444 	KF_bpf_dynptr_from_skb_meta,
12445 	KF_bpf_xdp_pull_data,
12446 	KF_bpf_dynptr_slice,
12447 	KF_bpf_dynptr_slice_rdwr,
12448 	KF_bpf_dynptr_clone,
12449 	KF_bpf_percpu_obj_new_impl,
12450 	KF_bpf_percpu_obj_drop_impl,
12451 	KF_bpf_throw,
12452 	KF_bpf_wq_set_callback,
12453 	KF_bpf_preempt_disable,
12454 	KF_bpf_preempt_enable,
12455 	KF_bpf_iter_css_task_new,
12456 	KF_bpf_session_cookie,
12457 	KF_bpf_get_kmem_cache,
12458 	KF_bpf_local_irq_save,
12459 	KF_bpf_local_irq_restore,
12460 	KF_bpf_iter_num_new,
12461 	KF_bpf_iter_num_next,
12462 	KF_bpf_iter_num_destroy,
12463 	KF_bpf_set_dentry_xattr,
12464 	KF_bpf_remove_dentry_xattr,
12465 	KF_bpf_res_spin_lock,
12466 	KF_bpf_res_spin_unlock,
12467 	KF_bpf_res_spin_lock_irqsave,
12468 	KF_bpf_res_spin_unlock_irqrestore,
12469 	KF_bpf_dynptr_from_file,
12470 	KF_bpf_dynptr_file_discard,
12471 	KF___bpf_trap,
12472 	KF_bpf_task_work_schedule_signal,
12473 	KF_bpf_task_work_schedule_resume,
12474 	KF_bpf_arena_alloc_pages,
12475 	KF_bpf_arena_free_pages,
12476 	KF_bpf_arena_reserve_pages,
12477 	KF_bpf_session_is_return,
12478 	KF_bpf_stream_vprintk,
12479 	KF_bpf_stream_print_stack,
12480 };
12481 
12482 BTF_ID_LIST(special_kfunc_list)
12483 BTF_ID(func, bpf_obj_new_impl)
12484 BTF_ID(func, bpf_obj_drop_impl)
12485 BTF_ID(func, bpf_refcount_acquire_impl)
12486 BTF_ID(func, bpf_list_push_front_impl)
12487 BTF_ID(func, bpf_list_push_back_impl)
12488 BTF_ID(func, bpf_list_pop_front)
12489 BTF_ID(func, bpf_list_pop_back)
12490 BTF_ID(func, bpf_list_front)
12491 BTF_ID(func, bpf_list_back)
12492 BTF_ID(func, bpf_cast_to_kern_ctx)
12493 BTF_ID(func, bpf_rdonly_cast)
12494 BTF_ID(func, bpf_rcu_read_lock)
12495 BTF_ID(func, bpf_rcu_read_unlock)
12496 BTF_ID(func, bpf_rbtree_remove)
12497 BTF_ID(func, bpf_rbtree_add_impl)
12498 BTF_ID(func, bpf_rbtree_first)
12499 BTF_ID(func, bpf_rbtree_root)
12500 BTF_ID(func, bpf_rbtree_left)
12501 BTF_ID(func, bpf_rbtree_right)
12502 #ifdef CONFIG_NET
12503 BTF_ID(func, bpf_dynptr_from_skb)
12504 BTF_ID(func, bpf_dynptr_from_xdp)
12505 BTF_ID(func, bpf_dynptr_from_skb_meta)
12506 BTF_ID(func, bpf_xdp_pull_data)
12507 #else
12508 BTF_ID_UNUSED
12509 BTF_ID_UNUSED
12510 BTF_ID_UNUSED
12511 BTF_ID_UNUSED
12512 #endif
12513 BTF_ID(func, bpf_dynptr_slice)
12514 BTF_ID(func, bpf_dynptr_slice_rdwr)
12515 BTF_ID(func, bpf_dynptr_clone)
12516 BTF_ID(func, bpf_percpu_obj_new_impl)
12517 BTF_ID(func, bpf_percpu_obj_drop_impl)
12518 BTF_ID(func, bpf_throw)
12519 BTF_ID(func, bpf_wq_set_callback)
12520 BTF_ID(func, bpf_preempt_disable)
12521 BTF_ID(func, bpf_preempt_enable)
12522 #ifdef CONFIG_CGROUPS
12523 BTF_ID(func, bpf_iter_css_task_new)
12524 #else
12525 BTF_ID_UNUSED
12526 #endif
12527 #ifdef CONFIG_BPF_EVENTS
12528 BTF_ID(func, bpf_session_cookie)
12529 #else
12530 BTF_ID_UNUSED
12531 #endif
12532 BTF_ID(func, bpf_get_kmem_cache)
12533 BTF_ID(func, bpf_local_irq_save)
12534 BTF_ID(func, bpf_local_irq_restore)
12535 BTF_ID(func, bpf_iter_num_new)
12536 BTF_ID(func, bpf_iter_num_next)
12537 BTF_ID(func, bpf_iter_num_destroy)
12538 #ifdef CONFIG_BPF_LSM
12539 BTF_ID(func, bpf_set_dentry_xattr)
12540 BTF_ID(func, bpf_remove_dentry_xattr)
12541 #else
12542 BTF_ID_UNUSED
12543 BTF_ID_UNUSED
12544 #endif
12545 BTF_ID(func, bpf_res_spin_lock)
12546 BTF_ID(func, bpf_res_spin_unlock)
12547 BTF_ID(func, bpf_res_spin_lock_irqsave)
12548 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
12549 BTF_ID(func, bpf_dynptr_from_file)
12550 BTF_ID(func, bpf_dynptr_file_discard)
12551 BTF_ID(func, __bpf_trap)
12552 BTF_ID(func, bpf_task_work_schedule_signal)
12553 BTF_ID(func, bpf_task_work_schedule_resume)
12554 BTF_ID(func, bpf_arena_alloc_pages)
12555 BTF_ID(func, bpf_arena_free_pages)
12556 BTF_ID(func, bpf_arena_reserve_pages)
12557 BTF_ID(func, bpf_session_is_return)
12558 BTF_ID(func, bpf_stream_vprintk)
12559 BTF_ID(func, bpf_stream_print_stack)
12560 
12561 static bool is_task_work_add_kfunc(u32 func_id)
12562 {
12563 	return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal] ||
12564 	       func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume];
12565 }
12566 
12567 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
12568 {
12569 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
12570 	    meta->arg_owning_ref) {
12571 		return false;
12572 	}
12573 
12574 	return meta->kfunc_flags & KF_RET_NULL;
12575 }
12576 
12577 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
12578 {
12579 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
12580 }
12581 
12582 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
12583 {
12584 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
12585 }
12586 
12587 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
12588 {
12589 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
12590 }
12591 
12592 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
12593 {
12594 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
12595 }
12596 
12597 static bool is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta *meta)
12598 {
12599 	return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data];
12600 }
12601 
12602 static enum kfunc_ptr_arg_type
12603 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
12604 		       struct bpf_kfunc_call_arg_meta *meta,
12605 		       const struct btf_type *t, const struct btf_type *ref_t,
12606 		       const char *ref_tname, const struct btf_param *args,
12607 		       int argno, int nargs)
12608 {
12609 	u32 regno = argno + 1;
12610 	struct bpf_reg_state *regs = cur_regs(env);
12611 	struct bpf_reg_state *reg = &regs[regno];
12612 	bool arg_mem_size = false;
12613 
12614 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
12615 	    meta->func_id == special_kfunc_list[KF_bpf_session_is_return] ||
12616 	    meta->func_id == special_kfunc_list[KF_bpf_session_cookie])
12617 		return KF_ARG_PTR_TO_CTX;
12618 
12619 	if (argno + 1 < nargs &&
12620 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
12621 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
12622 		arg_mem_size = true;
12623 
12624 	/* In this function, we verify the kfunc's BTF as per the argument type,
12625 	 * leaving the rest of the verification with respect to the register
12626 	 * type to our caller. When a set of conditions hold in the BTF type of
12627 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
12628 	 */
12629 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
12630 		return KF_ARG_PTR_TO_CTX;
12631 
12632 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg) &&
12633 	    !arg_mem_size)
12634 		return KF_ARG_PTR_TO_NULL;
12635 
12636 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
12637 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
12638 
12639 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
12640 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
12641 
12642 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
12643 		return KF_ARG_PTR_TO_DYNPTR;
12644 
12645 	if (is_kfunc_arg_iter(meta, argno, &args[argno]))
12646 		return KF_ARG_PTR_TO_ITER;
12647 
12648 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
12649 		return KF_ARG_PTR_TO_LIST_HEAD;
12650 
12651 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
12652 		return KF_ARG_PTR_TO_LIST_NODE;
12653 
12654 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
12655 		return KF_ARG_PTR_TO_RB_ROOT;
12656 
12657 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
12658 		return KF_ARG_PTR_TO_RB_NODE;
12659 
12660 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
12661 		return KF_ARG_PTR_TO_CONST_STR;
12662 
12663 	if (is_kfunc_arg_map(meta->btf, &args[argno]))
12664 		return KF_ARG_PTR_TO_MAP;
12665 
12666 	if (is_kfunc_arg_wq(meta->btf, &args[argno]))
12667 		return KF_ARG_PTR_TO_WORKQUEUE;
12668 
12669 	if (is_kfunc_arg_timer(meta->btf, &args[argno]))
12670 		return KF_ARG_PTR_TO_TIMER;
12671 
12672 	if (is_kfunc_arg_task_work(meta->btf, &args[argno]))
12673 		return KF_ARG_PTR_TO_TASK_WORK;
12674 
12675 	if (is_kfunc_arg_irq_flag(meta->btf, &args[argno]))
12676 		return KF_ARG_PTR_TO_IRQ_FLAG;
12677 
12678 	if (is_kfunc_arg_res_spin_lock(meta->btf, &args[argno]))
12679 		return KF_ARG_PTR_TO_RES_SPIN_LOCK;
12680 
12681 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
12682 		if (!btf_type_is_struct(ref_t)) {
12683 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
12684 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
12685 			return -EINVAL;
12686 		}
12687 		return KF_ARG_PTR_TO_BTF_ID;
12688 	}
12689 
12690 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
12691 		return KF_ARG_PTR_TO_CALLBACK;
12692 
12693 	/* This is the catch all argument type of register types supported by
12694 	 * check_helper_mem_access. However, we only allow when argument type is
12695 	 * pointer to scalar, or struct composed (recursively) of scalars. When
12696 	 * arg_mem_size is true, the pointer can be void *.
12697 	 */
12698 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
12699 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
12700 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
12701 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
12702 		return -EINVAL;
12703 	}
12704 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
12705 }
12706 
12707 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
12708 					struct bpf_reg_state *reg,
12709 					const struct btf_type *ref_t,
12710 					const char *ref_tname, u32 ref_id,
12711 					struct bpf_kfunc_call_arg_meta *meta,
12712 					int argno)
12713 {
12714 	const struct btf_type *reg_ref_t;
12715 	bool strict_type_match = false;
12716 	const struct btf *reg_btf;
12717 	const char *reg_ref_tname;
12718 	bool taking_projection;
12719 	bool struct_same;
12720 	u32 reg_ref_id;
12721 
12722 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
12723 		reg_btf = reg->btf;
12724 		reg_ref_id = reg->btf_id;
12725 	} else {
12726 		reg_btf = btf_vmlinux;
12727 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
12728 	}
12729 
12730 	/* Enforce strict type matching for calls to kfuncs that are acquiring
12731 	 * or releasing a reference, or are no-cast aliases. We do _not_
12732 	 * enforce strict matching for kfuncs by default,
12733 	 * as we want to enable BPF programs to pass types that are bitwise
12734 	 * equivalent without forcing them to explicitly cast with something
12735 	 * like bpf_cast_to_kern_ctx().
12736 	 *
12737 	 * For example, say we had a type like the following:
12738 	 *
12739 	 * struct bpf_cpumask {
12740 	 *	cpumask_t cpumask;
12741 	 *	refcount_t usage;
12742 	 * };
12743 	 *
12744 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
12745 	 * to a struct cpumask, so it would be safe to pass a struct
12746 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
12747 	 *
12748 	 * The philosophy here is similar to how we allow scalars of different
12749 	 * types to be passed to kfuncs as long as the size is the same. The
12750 	 * only difference here is that we're simply allowing
12751 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
12752 	 * resolve types.
12753 	 */
12754 	if ((is_kfunc_release(meta) && reg->ref_obj_id) ||
12755 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
12756 		strict_type_match = true;
12757 
12758 	WARN_ON_ONCE(is_kfunc_release(meta) &&
12759 		     (reg->off || !tnum_is_const(reg->var_off) ||
12760 		      reg->var_off.value));
12761 
12762 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
12763 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
12764 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
12765 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
12766 	 * actually use it -- it must cast to the underlying type. So we allow
12767 	 * caller to pass in the underlying type.
12768 	 */
12769 	taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
12770 	if (!taking_projection && !struct_same) {
12771 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
12772 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
12773 			btf_type_str(reg_ref_t), reg_ref_tname);
12774 		return -EINVAL;
12775 	}
12776 	return 0;
12777 }
12778 
12779 static int process_irq_flag(struct bpf_verifier_env *env, int regno,
12780 			     struct bpf_kfunc_call_arg_meta *meta)
12781 {
12782 	struct bpf_reg_state *reg = reg_state(env, regno);
12783 	int err, kfunc_class = IRQ_NATIVE_KFUNC;
12784 	bool irq_save;
12785 
12786 	if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] ||
12787 	    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) {
12788 		irq_save = true;
12789 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
12790 			kfunc_class = IRQ_LOCK_KFUNC;
12791 	} else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] ||
12792 		   meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) {
12793 		irq_save = false;
12794 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
12795 			kfunc_class = IRQ_LOCK_KFUNC;
12796 	} else {
12797 		verifier_bug(env, "unknown irq flags kfunc");
12798 		return -EFAULT;
12799 	}
12800 
12801 	if (irq_save) {
12802 		if (!is_irq_flag_reg_valid_uninit(env, reg)) {
12803 			verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1);
12804 			return -EINVAL;
12805 		}
12806 
12807 		err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false);
12808 		if (err)
12809 			return err;
12810 
12811 		err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class);
12812 		if (err)
12813 			return err;
12814 	} else {
12815 		err = is_irq_flag_reg_valid_init(env, reg);
12816 		if (err) {
12817 			verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1);
12818 			return err;
12819 		}
12820 
12821 		err = mark_irq_flag_read(env, reg);
12822 		if (err)
12823 			return err;
12824 
12825 		err = unmark_stack_slot_irq_flag(env, reg, kfunc_class);
12826 		if (err)
12827 			return err;
12828 	}
12829 	return 0;
12830 }
12831 
12832 
12833 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12834 {
12835 	struct btf_record *rec = reg_btf_record(reg);
12836 
12837 	if (!env->cur_state->active_locks) {
12838 		verifier_bug(env, "%s w/o active lock", __func__);
12839 		return -EFAULT;
12840 	}
12841 
12842 	if (type_flag(reg->type) & NON_OWN_REF) {
12843 		verifier_bug(env, "NON_OWN_REF already set");
12844 		return -EFAULT;
12845 	}
12846 
12847 	reg->type |= NON_OWN_REF;
12848 	if (rec->refcount_off >= 0)
12849 		reg->type |= MEM_RCU;
12850 
12851 	return 0;
12852 }
12853 
12854 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
12855 {
12856 	struct bpf_verifier_state *state = env->cur_state;
12857 	struct bpf_func_state *unused;
12858 	struct bpf_reg_state *reg;
12859 	int i;
12860 
12861 	if (!ref_obj_id) {
12862 		verifier_bug(env, "ref_obj_id is zero for owning -> non-owning conversion");
12863 		return -EFAULT;
12864 	}
12865 
12866 	for (i = 0; i < state->acquired_refs; i++) {
12867 		if (state->refs[i].id != ref_obj_id)
12868 			continue;
12869 
12870 		/* Clear ref_obj_id here so release_reference doesn't clobber
12871 		 * the whole reg
12872 		 */
12873 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
12874 			if (reg->ref_obj_id == ref_obj_id) {
12875 				reg->ref_obj_id = 0;
12876 				ref_set_non_owning(env, reg);
12877 			}
12878 		}));
12879 		return 0;
12880 	}
12881 
12882 	verifier_bug(env, "ref state missing for ref_obj_id");
12883 	return -EFAULT;
12884 }
12885 
12886 /* Implementation details:
12887  *
12888  * Each register points to some region of memory, which we define as an
12889  * allocation. Each allocation may embed a bpf_spin_lock which protects any
12890  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
12891  * allocation. The lock and the data it protects are colocated in the same
12892  * memory region.
12893  *
12894  * Hence, everytime a register holds a pointer value pointing to such
12895  * allocation, the verifier preserves a unique reg->id for it.
12896  *
12897  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
12898  * bpf_spin_lock is called.
12899  *
12900  * To enable this, lock state in the verifier captures two values:
12901  *	active_lock.ptr = Register's type specific pointer
12902  *	active_lock.id  = A unique ID for each register pointer value
12903  *
12904  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
12905  * supported register types.
12906  *
12907  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
12908  * allocated objects is the reg->btf pointer.
12909  *
12910  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
12911  * can establish the provenance of the map value statically for each distinct
12912  * lookup into such maps. They always contain a single map value hence unique
12913  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
12914  *
12915  * So, in case of global variables, they use array maps with max_entries = 1,
12916  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
12917  * into the same map value as max_entries is 1, as described above).
12918  *
12919  * In case of inner map lookups, the inner map pointer has same map_ptr as the
12920  * outer map pointer (in verifier context), but each lookup into an inner map
12921  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
12922  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
12923  * will get different reg->id assigned to each lookup, hence different
12924  * active_lock.id.
12925  *
12926  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
12927  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
12928  * returned from bpf_obj_new. Each allocation receives a new reg->id.
12929  */
12930 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12931 {
12932 	struct bpf_reference_state *s;
12933 	void *ptr;
12934 	u32 id;
12935 
12936 	switch ((int)reg->type) {
12937 	case PTR_TO_MAP_VALUE:
12938 		ptr = reg->map_ptr;
12939 		break;
12940 	case PTR_TO_BTF_ID | MEM_ALLOC:
12941 		ptr = reg->btf;
12942 		break;
12943 	default:
12944 		verifier_bug(env, "unknown reg type for lock check");
12945 		return -EFAULT;
12946 	}
12947 	id = reg->id;
12948 
12949 	if (!env->cur_state->active_locks)
12950 		return -EINVAL;
12951 	s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr);
12952 	if (!s) {
12953 		verbose(env, "held lock and object are not in the same allocation\n");
12954 		return -EINVAL;
12955 	}
12956 	return 0;
12957 }
12958 
12959 static bool is_bpf_list_api_kfunc(u32 btf_id)
12960 {
12961 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12962 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12963 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12964 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back] ||
12965 	       btf_id == special_kfunc_list[KF_bpf_list_front] ||
12966 	       btf_id == special_kfunc_list[KF_bpf_list_back];
12967 }
12968 
12969 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
12970 {
12971 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12972 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12973 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first] ||
12974 	       btf_id == special_kfunc_list[KF_bpf_rbtree_root] ||
12975 	       btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12976 	       btf_id == special_kfunc_list[KF_bpf_rbtree_right];
12977 }
12978 
12979 static bool is_bpf_iter_num_api_kfunc(u32 btf_id)
12980 {
12981 	return btf_id == special_kfunc_list[KF_bpf_iter_num_new] ||
12982 	       btf_id == special_kfunc_list[KF_bpf_iter_num_next] ||
12983 	       btf_id == special_kfunc_list[KF_bpf_iter_num_destroy];
12984 }
12985 
12986 static bool is_bpf_graph_api_kfunc(u32 btf_id)
12987 {
12988 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
12989 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
12990 }
12991 
12992 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id)
12993 {
12994 	return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
12995 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
12996 	       btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
12997 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore];
12998 }
12999 
13000 static bool is_bpf_arena_kfunc(u32 btf_id)
13001 {
13002 	return btf_id == special_kfunc_list[KF_bpf_arena_alloc_pages] ||
13003 	       btf_id == special_kfunc_list[KF_bpf_arena_free_pages] ||
13004 	       btf_id == special_kfunc_list[KF_bpf_arena_reserve_pages];
13005 }
13006 
13007 static bool is_bpf_stream_kfunc(u32 btf_id)
13008 {
13009 	return btf_id == special_kfunc_list[KF_bpf_stream_vprintk] ||
13010 	       btf_id == special_kfunc_list[KF_bpf_stream_print_stack];
13011 }
13012 
13013 static bool kfunc_spin_allowed(u32 btf_id)
13014 {
13015 	return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) ||
13016 	       is_bpf_res_spin_lock_kfunc(btf_id) || is_bpf_arena_kfunc(btf_id) ||
13017 	       is_bpf_stream_kfunc(btf_id);
13018 }
13019 
13020 static bool is_sync_callback_calling_kfunc(u32 btf_id)
13021 {
13022 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
13023 }
13024 
13025 static bool is_async_callback_calling_kfunc(u32 btf_id)
13026 {
13027 	return is_bpf_wq_set_callback_kfunc(btf_id) ||
13028 	       is_task_work_add_kfunc(btf_id);
13029 }
13030 
13031 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
13032 {
13033 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
13034 	       insn->imm == special_kfunc_list[KF_bpf_throw];
13035 }
13036 
13037 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id)
13038 {
13039 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback];
13040 }
13041 
13042 static bool is_callback_calling_kfunc(u32 btf_id)
13043 {
13044 	return is_sync_callback_calling_kfunc(btf_id) ||
13045 	       is_async_callback_calling_kfunc(btf_id);
13046 }
13047 
13048 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
13049 {
13050 	return is_bpf_rbtree_api_kfunc(btf_id);
13051 }
13052 
13053 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
13054 					  enum btf_field_type head_field_type,
13055 					  u32 kfunc_btf_id)
13056 {
13057 	bool ret;
13058 
13059 	switch (head_field_type) {
13060 	case BPF_LIST_HEAD:
13061 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
13062 		break;
13063 	case BPF_RB_ROOT:
13064 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
13065 		break;
13066 	default:
13067 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
13068 			btf_field_type_name(head_field_type));
13069 		return false;
13070 	}
13071 
13072 	if (!ret)
13073 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
13074 			btf_field_type_name(head_field_type));
13075 	return ret;
13076 }
13077 
13078 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
13079 					  enum btf_field_type node_field_type,
13080 					  u32 kfunc_btf_id)
13081 {
13082 	bool ret;
13083 
13084 	switch (node_field_type) {
13085 	case BPF_LIST_NODE:
13086 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
13087 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
13088 		break;
13089 	case BPF_RB_NODE:
13090 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
13091 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
13092 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
13093 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
13094 		break;
13095 	default:
13096 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
13097 			btf_field_type_name(node_field_type));
13098 		return false;
13099 	}
13100 
13101 	if (!ret)
13102 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
13103 			btf_field_type_name(node_field_type));
13104 	return ret;
13105 }
13106 
13107 static int
13108 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
13109 				   struct bpf_reg_state *reg, u32 regno,
13110 				   struct bpf_kfunc_call_arg_meta *meta,
13111 				   enum btf_field_type head_field_type,
13112 				   struct btf_field **head_field)
13113 {
13114 	const char *head_type_name;
13115 	struct btf_field *field;
13116 	struct btf_record *rec;
13117 	u32 head_off;
13118 
13119 	if (meta->btf != btf_vmlinux) {
13120 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
13121 		return -EFAULT;
13122 	}
13123 
13124 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
13125 		return -EFAULT;
13126 
13127 	head_type_name = btf_field_type_name(head_field_type);
13128 	if (!tnum_is_const(reg->var_off)) {
13129 		verbose(env,
13130 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
13131 			regno, head_type_name);
13132 		return -EINVAL;
13133 	}
13134 
13135 	rec = reg_btf_record(reg);
13136 	head_off = reg->off + reg->var_off.value;
13137 	field = btf_record_find(rec, head_off, head_field_type);
13138 	if (!field) {
13139 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
13140 		return -EINVAL;
13141 	}
13142 
13143 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
13144 	if (check_reg_allocation_locked(env, reg)) {
13145 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
13146 			rec->spin_lock_off, head_type_name);
13147 		return -EINVAL;
13148 	}
13149 
13150 	if (*head_field) {
13151 		verifier_bug(env, "repeating %s arg", head_type_name);
13152 		return -EFAULT;
13153 	}
13154 	*head_field = field;
13155 	return 0;
13156 }
13157 
13158 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
13159 					   struct bpf_reg_state *reg, u32 regno,
13160 					   struct bpf_kfunc_call_arg_meta *meta)
13161 {
13162 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
13163 							  &meta->arg_list_head.field);
13164 }
13165 
13166 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
13167 					     struct bpf_reg_state *reg, u32 regno,
13168 					     struct bpf_kfunc_call_arg_meta *meta)
13169 {
13170 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
13171 							  &meta->arg_rbtree_root.field);
13172 }
13173 
13174 static int
13175 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
13176 				   struct bpf_reg_state *reg, u32 regno,
13177 				   struct bpf_kfunc_call_arg_meta *meta,
13178 				   enum btf_field_type head_field_type,
13179 				   enum btf_field_type node_field_type,
13180 				   struct btf_field **node_field)
13181 {
13182 	const char *node_type_name;
13183 	const struct btf_type *et, *t;
13184 	struct btf_field *field;
13185 	u32 node_off;
13186 
13187 	if (meta->btf != btf_vmlinux) {
13188 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
13189 		return -EFAULT;
13190 	}
13191 
13192 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
13193 		return -EFAULT;
13194 
13195 	node_type_name = btf_field_type_name(node_field_type);
13196 	if (!tnum_is_const(reg->var_off)) {
13197 		verbose(env,
13198 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
13199 			regno, node_type_name);
13200 		return -EINVAL;
13201 	}
13202 
13203 	node_off = reg->off + reg->var_off.value;
13204 	field = reg_find_field_offset(reg, node_off, node_field_type);
13205 	if (!field) {
13206 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
13207 		return -EINVAL;
13208 	}
13209 
13210 	field = *node_field;
13211 
13212 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
13213 	t = btf_type_by_id(reg->btf, reg->btf_id);
13214 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
13215 				  field->graph_root.value_btf_id, true)) {
13216 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
13217 			"in struct %s, but arg is at offset=%d in struct %s\n",
13218 			btf_field_type_name(head_field_type),
13219 			btf_field_type_name(node_field_type),
13220 			field->graph_root.node_offset,
13221 			btf_name_by_offset(field->graph_root.btf, et->name_off),
13222 			node_off, btf_name_by_offset(reg->btf, t->name_off));
13223 		return -EINVAL;
13224 	}
13225 	meta->arg_btf = reg->btf;
13226 	meta->arg_btf_id = reg->btf_id;
13227 
13228 	if (node_off != field->graph_root.node_offset) {
13229 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
13230 			node_off, btf_field_type_name(node_field_type),
13231 			field->graph_root.node_offset,
13232 			btf_name_by_offset(field->graph_root.btf, et->name_off));
13233 		return -EINVAL;
13234 	}
13235 
13236 	return 0;
13237 }
13238 
13239 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
13240 					   struct bpf_reg_state *reg, u32 regno,
13241 					   struct bpf_kfunc_call_arg_meta *meta)
13242 {
13243 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
13244 						  BPF_LIST_HEAD, BPF_LIST_NODE,
13245 						  &meta->arg_list_head.field);
13246 }
13247 
13248 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
13249 					     struct bpf_reg_state *reg, u32 regno,
13250 					     struct bpf_kfunc_call_arg_meta *meta)
13251 {
13252 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
13253 						  BPF_RB_ROOT, BPF_RB_NODE,
13254 						  &meta->arg_rbtree_root.field);
13255 }
13256 
13257 /*
13258  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
13259  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
13260  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
13261  * them can only be attached to some specific hook points.
13262  */
13263 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
13264 {
13265 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
13266 
13267 	switch (prog_type) {
13268 	case BPF_PROG_TYPE_LSM:
13269 		return true;
13270 	case BPF_PROG_TYPE_TRACING:
13271 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
13272 			return true;
13273 		fallthrough;
13274 	default:
13275 		return in_sleepable(env);
13276 	}
13277 }
13278 
13279 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13280 			    int insn_idx)
13281 {
13282 	const char *func_name = meta->func_name, *ref_tname;
13283 	const struct btf *btf = meta->btf;
13284 	const struct btf_param *args;
13285 	struct btf_record *rec;
13286 	u32 i, nargs;
13287 	int ret;
13288 
13289 	args = (const struct btf_param *)(meta->func_proto + 1);
13290 	nargs = btf_type_vlen(meta->func_proto);
13291 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
13292 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
13293 			MAX_BPF_FUNC_REG_ARGS);
13294 		return -EINVAL;
13295 	}
13296 
13297 	/* Check that BTF function arguments match actual types that the
13298 	 * verifier sees.
13299 	 */
13300 	for (i = 0; i < nargs; i++) {
13301 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
13302 		const struct btf_type *t, *ref_t, *resolve_ret;
13303 		enum bpf_arg_type arg_type = ARG_DONTCARE;
13304 		u32 regno = i + 1, ref_id, type_size;
13305 		bool is_ret_buf_sz = false;
13306 		int kf_arg_type;
13307 
13308 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
13309 
13310 		if (is_kfunc_arg_ignore(btf, &args[i]))
13311 			continue;
13312 
13313 		if (is_kfunc_arg_prog_aux(btf, &args[i])) {
13314 			/* Reject repeated use bpf_prog_aux */
13315 			if (meta->arg_prog) {
13316 				verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc");
13317 				return -EFAULT;
13318 			}
13319 			meta->arg_prog = true;
13320 			cur_aux(env)->arg_prog = regno;
13321 			continue;
13322 		}
13323 
13324 		if (btf_type_is_scalar(t)) {
13325 			if (reg->type != SCALAR_VALUE) {
13326 				verbose(env, "R%d is not a scalar\n", regno);
13327 				return -EINVAL;
13328 			}
13329 
13330 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
13331 				if (meta->arg_constant.found) {
13332 					verifier_bug(env, "only one constant argument permitted");
13333 					return -EFAULT;
13334 				}
13335 				if (!tnum_is_const(reg->var_off)) {
13336 					verbose(env, "R%d must be a known constant\n", regno);
13337 					return -EINVAL;
13338 				}
13339 				ret = mark_chain_precision(env, regno);
13340 				if (ret < 0)
13341 					return ret;
13342 				meta->arg_constant.found = true;
13343 				meta->arg_constant.value = reg->var_off.value;
13344 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
13345 				meta->r0_rdonly = true;
13346 				is_ret_buf_sz = true;
13347 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
13348 				is_ret_buf_sz = true;
13349 			}
13350 
13351 			if (is_ret_buf_sz) {
13352 				if (meta->r0_size) {
13353 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
13354 					return -EINVAL;
13355 				}
13356 
13357 				if (!tnum_is_const(reg->var_off)) {
13358 					verbose(env, "R%d is not a const\n", regno);
13359 					return -EINVAL;
13360 				}
13361 
13362 				meta->r0_size = reg->var_off.value;
13363 				ret = mark_chain_precision(env, regno);
13364 				if (ret)
13365 					return ret;
13366 			}
13367 			continue;
13368 		}
13369 
13370 		if (!btf_type_is_ptr(t)) {
13371 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
13372 			return -EINVAL;
13373 		}
13374 
13375 		if ((register_is_null(reg) || type_may_be_null(reg->type)) &&
13376 		    !is_kfunc_arg_nullable(meta->btf, &args[i])) {
13377 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
13378 			return -EACCES;
13379 		}
13380 
13381 		if (reg->ref_obj_id) {
13382 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
13383 				verifier_bug(env, "more than one arg with ref_obj_id R%d %u %u",
13384 					     regno, reg->ref_obj_id,
13385 					     meta->ref_obj_id);
13386 				return -EFAULT;
13387 			}
13388 			meta->ref_obj_id = reg->ref_obj_id;
13389 			if (is_kfunc_release(meta))
13390 				meta->release_regno = regno;
13391 		}
13392 
13393 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
13394 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13395 
13396 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
13397 		if (kf_arg_type < 0)
13398 			return kf_arg_type;
13399 
13400 		switch (kf_arg_type) {
13401 		case KF_ARG_PTR_TO_NULL:
13402 			continue;
13403 		case KF_ARG_PTR_TO_MAP:
13404 			if (!reg->map_ptr) {
13405 				verbose(env, "pointer in R%d isn't map pointer\n", regno);
13406 				return -EINVAL;
13407 			}
13408 			if (meta->map.ptr && (reg->map_ptr->record->wq_off >= 0 ||
13409 					      reg->map_ptr->record->task_work_off >= 0)) {
13410 				/* Use map_uid (which is unique id of inner map) to reject:
13411 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
13412 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
13413 				 * if (inner_map1 && inner_map2) {
13414 				 *     wq = bpf_map_lookup_elem(inner_map1);
13415 				 *     if (wq)
13416 				 *         // mismatch would have been allowed
13417 				 *         bpf_wq_init(wq, inner_map2);
13418 				 * }
13419 				 *
13420 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
13421 				 */
13422 				if (meta->map.ptr != reg->map_ptr ||
13423 				    meta->map.uid != reg->map_uid) {
13424 					if (reg->map_ptr->record->task_work_off >= 0) {
13425 						verbose(env,
13426 							"bpf_task_work pointer in R2 map_uid=%d doesn't match map pointer in R3 map_uid=%d\n",
13427 							meta->map.uid, reg->map_uid);
13428 						return -EINVAL;
13429 					}
13430 					verbose(env,
13431 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
13432 						meta->map.uid, reg->map_uid);
13433 					return -EINVAL;
13434 				}
13435 			}
13436 			meta->map.ptr = reg->map_ptr;
13437 			meta->map.uid = reg->map_uid;
13438 			fallthrough;
13439 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13440 		case KF_ARG_PTR_TO_BTF_ID:
13441 			if (!is_trusted_reg(reg)) {
13442 				if (!is_kfunc_rcu(meta)) {
13443 					verbose(env, "R%d must be referenced or trusted\n", regno);
13444 					return -EINVAL;
13445 				}
13446 				if (!is_rcu_reg(reg)) {
13447 					verbose(env, "R%d must be a rcu pointer\n", regno);
13448 					return -EINVAL;
13449 				}
13450 			}
13451 			fallthrough;
13452 		case KF_ARG_PTR_TO_CTX:
13453 		case KF_ARG_PTR_TO_DYNPTR:
13454 		case KF_ARG_PTR_TO_ITER:
13455 		case KF_ARG_PTR_TO_LIST_HEAD:
13456 		case KF_ARG_PTR_TO_LIST_NODE:
13457 		case KF_ARG_PTR_TO_RB_ROOT:
13458 		case KF_ARG_PTR_TO_RB_NODE:
13459 		case KF_ARG_PTR_TO_MEM:
13460 		case KF_ARG_PTR_TO_MEM_SIZE:
13461 		case KF_ARG_PTR_TO_CALLBACK:
13462 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13463 		case KF_ARG_PTR_TO_CONST_STR:
13464 		case KF_ARG_PTR_TO_WORKQUEUE:
13465 		case KF_ARG_PTR_TO_TIMER:
13466 		case KF_ARG_PTR_TO_TASK_WORK:
13467 		case KF_ARG_PTR_TO_IRQ_FLAG:
13468 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13469 			break;
13470 		default:
13471 			verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type);
13472 			return -EFAULT;
13473 		}
13474 
13475 		if (is_kfunc_release(meta) && reg->ref_obj_id)
13476 			arg_type |= OBJ_RELEASE;
13477 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
13478 		if (ret < 0)
13479 			return ret;
13480 
13481 		switch (kf_arg_type) {
13482 		case KF_ARG_PTR_TO_CTX:
13483 			if (reg->type != PTR_TO_CTX) {
13484 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n",
13485 					i, reg_type_str(env, reg->type));
13486 				return -EINVAL;
13487 			}
13488 
13489 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13490 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
13491 				if (ret < 0)
13492 					return -EINVAL;
13493 				meta->ret_btf_id  = ret;
13494 			}
13495 			break;
13496 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13497 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
13498 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
13499 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
13500 					return -EINVAL;
13501 				}
13502 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
13503 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
13504 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
13505 					return -EINVAL;
13506 				}
13507 			} else {
13508 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13509 				return -EINVAL;
13510 			}
13511 			if (!reg->ref_obj_id) {
13512 				verbose(env, "allocated object must be referenced\n");
13513 				return -EINVAL;
13514 			}
13515 			if (meta->btf == btf_vmlinux) {
13516 				meta->arg_btf = reg->btf;
13517 				meta->arg_btf_id = reg->btf_id;
13518 			}
13519 			break;
13520 		case KF_ARG_PTR_TO_DYNPTR:
13521 		{
13522 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
13523 			int clone_ref_obj_id = 0;
13524 
13525 			if (reg->type == CONST_PTR_TO_DYNPTR)
13526 				dynptr_arg_type |= MEM_RDONLY;
13527 
13528 			if (is_kfunc_arg_uninit(btf, &args[i]))
13529 				dynptr_arg_type |= MEM_UNINIT;
13530 
13531 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
13532 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
13533 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
13534 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
13535 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) {
13536 				dynptr_arg_type |= DYNPTR_TYPE_SKB_META;
13537 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
13538 				dynptr_arg_type |= DYNPTR_TYPE_FILE;
13539 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_file_discard]) {
13540 				dynptr_arg_type |= DYNPTR_TYPE_FILE;
13541 				meta->release_regno = regno;
13542 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
13543 				   (dynptr_arg_type & MEM_UNINIT)) {
13544 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
13545 
13546 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
13547 					verifier_bug(env, "no dynptr type for parent of clone");
13548 					return -EFAULT;
13549 				}
13550 
13551 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
13552 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
13553 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
13554 					verifier_bug(env, "missing ref obj id for parent of clone");
13555 					return -EFAULT;
13556 				}
13557 			}
13558 
13559 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
13560 			if (ret < 0)
13561 				return ret;
13562 
13563 			if (!(dynptr_arg_type & MEM_UNINIT)) {
13564 				int id = dynptr_id(env, reg);
13565 
13566 				if (id < 0) {
13567 					verifier_bug(env, "failed to obtain dynptr id");
13568 					return id;
13569 				}
13570 				meta->initialized_dynptr.id = id;
13571 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
13572 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
13573 			}
13574 
13575 			break;
13576 		}
13577 		case KF_ARG_PTR_TO_ITER:
13578 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
13579 				if (!check_css_task_iter_allowlist(env)) {
13580 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
13581 					return -EINVAL;
13582 				}
13583 			}
13584 			ret = process_iter_arg(env, regno, insn_idx, meta);
13585 			if (ret < 0)
13586 				return ret;
13587 			break;
13588 		case KF_ARG_PTR_TO_LIST_HEAD:
13589 			if (reg->type != PTR_TO_MAP_VALUE &&
13590 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13591 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13592 				return -EINVAL;
13593 			}
13594 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13595 				verbose(env, "allocated object must be referenced\n");
13596 				return -EINVAL;
13597 			}
13598 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
13599 			if (ret < 0)
13600 				return ret;
13601 			break;
13602 		case KF_ARG_PTR_TO_RB_ROOT:
13603 			if (reg->type != PTR_TO_MAP_VALUE &&
13604 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13605 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13606 				return -EINVAL;
13607 			}
13608 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13609 				verbose(env, "allocated object must be referenced\n");
13610 				return -EINVAL;
13611 			}
13612 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
13613 			if (ret < 0)
13614 				return ret;
13615 			break;
13616 		case KF_ARG_PTR_TO_LIST_NODE:
13617 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13618 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13619 				return -EINVAL;
13620 			}
13621 			if (!reg->ref_obj_id) {
13622 				verbose(env, "allocated object must be referenced\n");
13623 				return -EINVAL;
13624 			}
13625 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
13626 			if (ret < 0)
13627 				return ret;
13628 			break;
13629 		case KF_ARG_PTR_TO_RB_NODE:
13630 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13631 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13632 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
13633 					return -EINVAL;
13634 				}
13635 				if (!reg->ref_obj_id) {
13636 					verbose(env, "allocated object must be referenced\n");
13637 					return -EINVAL;
13638 				}
13639 			} else {
13640 				if (!type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) {
13641 					verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name);
13642 					return -EINVAL;
13643 				}
13644 				if (in_rbtree_lock_required_cb(env)) {
13645 					verbose(env, "%s not allowed in rbtree cb\n", func_name);
13646 					return -EINVAL;
13647 				}
13648 			}
13649 
13650 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
13651 			if (ret < 0)
13652 				return ret;
13653 			break;
13654 		case KF_ARG_PTR_TO_MAP:
13655 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
13656 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
13657 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
13658 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13659 			fallthrough;
13660 		case KF_ARG_PTR_TO_BTF_ID:
13661 			/* Only base_type is checked, further checks are done here */
13662 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
13663 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
13664 			    !reg2btf_ids[base_type(reg->type)]) {
13665 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
13666 				verbose(env, "expected %s or socket\n",
13667 					reg_type_str(env, base_type(reg->type) |
13668 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
13669 				return -EINVAL;
13670 			}
13671 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
13672 			if (ret < 0)
13673 				return ret;
13674 			break;
13675 		case KF_ARG_PTR_TO_MEM:
13676 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
13677 			if (IS_ERR(resolve_ret)) {
13678 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
13679 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
13680 				return -EINVAL;
13681 			}
13682 			ret = check_mem_reg(env, reg, regno, type_size);
13683 			if (ret < 0)
13684 				return ret;
13685 			break;
13686 		case KF_ARG_PTR_TO_MEM_SIZE:
13687 		{
13688 			struct bpf_reg_state *buff_reg = &regs[regno];
13689 			const struct btf_param *buff_arg = &args[i];
13690 			struct bpf_reg_state *size_reg = &regs[regno + 1];
13691 			const struct btf_param *size_arg = &args[i + 1];
13692 
13693 			if (!register_is_null(buff_reg) || !is_kfunc_arg_nullable(meta->btf, buff_arg)) {
13694 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
13695 				if (ret < 0) {
13696 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
13697 					return ret;
13698 				}
13699 			}
13700 
13701 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
13702 				if (meta->arg_constant.found) {
13703 					verifier_bug(env, "only one constant argument permitted");
13704 					return -EFAULT;
13705 				}
13706 				if (!tnum_is_const(size_reg->var_off)) {
13707 					verbose(env, "R%d must be a known constant\n", regno + 1);
13708 					return -EINVAL;
13709 				}
13710 				meta->arg_constant.found = true;
13711 				meta->arg_constant.value = size_reg->var_off.value;
13712 			}
13713 
13714 			/* Skip next '__sz' or '__szk' argument */
13715 			i++;
13716 			break;
13717 		}
13718 		case KF_ARG_PTR_TO_CALLBACK:
13719 			if (reg->type != PTR_TO_FUNC) {
13720 				verbose(env, "arg%d expected pointer to func\n", i);
13721 				return -EINVAL;
13722 			}
13723 			meta->subprogno = reg->subprogno;
13724 			break;
13725 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13726 			if (!type_is_ptr_alloc_obj(reg->type)) {
13727 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
13728 				return -EINVAL;
13729 			}
13730 			if (!type_is_non_owning_ref(reg->type))
13731 				meta->arg_owning_ref = true;
13732 
13733 			rec = reg_btf_record(reg);
13734 			if (!rec) {
13735 				verifier_bug(env, "Couldn't find btf_record");
13736 				return -EFAULT;
13737 			}
13738 
13739 			if (rec->refcount_off < 0) {
13740 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
13741 				return -EINVAL;
13742 			}
13743 
13744 			meta->arg_btf = reg->btf;
13745 			meta->arg_btf_id = reg->btf_id;
13746 			break;
13747 		case KF_ARG_PTR_TO_CONST_STR:
13748 			if (reg->type != PTR_TO_MAP_VALUE) {
13749 				verbose(env, "arg#%d doesn't point to a const string\n", i);
13750 				return -EINVAL;
13751 			}
13752 			ret = check_reg_const_str(env, reg, regno);
13753 			if (ret)
13754 				return ret;
13755 			break;
13756 		case KF_ARG_PTR_TO_WORKQUEUE:
13757 			if (reg->type != PTR_TO_MAP_VALUE) {
13758 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13759 				return -EINVAL;
13760 			}
13761 			ret = check_map_field_pointer(env, regno, BPF_WORKQUEUE, &meta->map);
13762 			if (ret < 0)
13763 				return ret;
13764 			break;
13765 		case KF_ARG_PTR_TO_TIMER:
13766 			if (reg->type != PTR_TO_MAP_VALUE) {
13767 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13768 				return -EINVAL;
13769 			}
13770 			ret = process_timer_kfunc(env, regno, meta);
13771 			if (ret < 0)
13772 				return ret;
13773 			break;
13774 		case KF_ARG_PTR_TO_TASK_WORK:
13775 			if (reg->type != PTR_TO_MAP_VALUE) {
13776 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13777 				return -EINVAL;
13778 			}
13779 			ret = check_map_field_pointer(env, regno, BPF_TASK_WORK, &meta->map);
13780 			if (ret < 0)
13781 				return ret;
13782 			break;
13783 		case KF_ARG_PTR_TO_IRQ_FLAG:
13784 			if (reg->type != PTR_TO_STACK) {
13785 				verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i);
13786 				return -EINVAL;
13787 			}
13788 			ret = process_irq_flag(env, regno, meta);
13789 			if (ret < 0)
13790 				return ret;
13791 			break;
13792 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13793 		{
13794 			int flags = PROCESS_RES_LOCK;
13795 
13796 			if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13797 				verbose(env, "arg#%d doesn't point to map value or allocated object\n", i);
13798 				return -EINVAL;
13799 			}
13800 
13801 			if (!is_bpf_res_spin_lock_kfunc(meta->func_id))
13802 				return -EFAULT;
13803 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13804 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
13805 				flags |= PROCESS_SPIN_LOCK;
13806 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
13807 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
13808 				flags |= PROCESS_LOCK_IRQ;
13809 			ret = process_spin_lock(env, regno, flags);
13810 			if (ret < 0)
13811 				return ret;
13812 			break;
13813 		}
13814 		}
13815 	}
13816 
13817 	if (is_kfunc_release(meta) && !meta->release_regno) {
13818 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
13819 			func_name);
13820 		return -EINVAL;
13821 	}
13822 
13823 	return 0;
13824 }
13825 
13826 static int fetch_kfunc_arg_meta(struct bpf_verifier_env *env,
13827 				s32 func_id,
13828 				s16 offset,
13829 				struct bpf_kfunc_call_arg_meta *meta)
13830 {
13831 	struct bpf_kfunc_meta kfunc;
13832 	int err;
13833 
13834 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
13835 	if (err)
13836 		return err;
13837 
13838 	memset(meta, 0, sizeof(*meta));
13839 	meta->btf = kfunc.btf;
13840 	meta->func_id = kfunc.id;
13841 	meta->func_proto = kfunc.proto;
13842 	meta->func_name = kfunc.name;
13843 
13844 	if (!kfunc.flags || !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env->prog))
13845 		return -EACCES;
13846 
13847 	meta->kfunc_flags = *kfunc.flags;
13848 
13849 	return 0;
13850 }
13851 
13852 /* check special kfuncs and return:
13853  *  1  - not fall-through to 'else' branch, continue verification
13854  *  0  - fall-through to 'else' branch
13855  * < 0 - not fall-through to 'else' branch, return error
13856  */
13857 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13858 			       struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
13859 			       const struct btf_type *ptr_type, struct btf *desc_btf)
13860 {
13861 	const struct btf_type *ret_t;
13862 	int err = 0;
13863 
13864 	if (meta->btf != btf_vmlinux)
13865 		return 0;
13866 
13867 	if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
13868 	    meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13869 		struct btf_struct_meta *struct_meta;
13870 		struct btf *ret_btf;
13871 		u32 ret_btf_id;
13872 
13873 		if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
13874 			return -ENOMEM;
13875 
13876 		if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) {
13877 			verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
13878 			return -EINVAL;
13879 		}
13880 
13881 		ret_btf = env->prog->aux->btf;
13882 		ret_btf_id = meta->arg_constant.value;
13883 
13884 		/* This may be NULL due to user not supplying a BTF */
13885 		if (!ret_btf) {
13886 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
13887 			return -EINVAL;
13888 		}
13889 
13890 		ret_t = btf_type_by_id(ret_btf, ret_btf_id);
13891 		if (!ret_t || !__btf_type_is_struct(ret_t)) {
13892 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
13893 			return -EINVAL;
13894 		}
13895 
13896 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13897 			if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
13898 				verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
13899 					ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
13900 				return -EINVAL;
13901 			}
13902 
13903 			if (!bpf_global_percpu_ma_set) {
13904 				mutex_lock(&bpf_percpu_ma_lock);
13905 				if (!bpf_global_percpu_ma_set) {
13906 					/* Charge memory allocated with bpf_global_percpu_ma to
13907 					 * root memcg. The obj_cgroup for root memcg is NULL.
13908 					 */
13909 					err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
13910 					if (!err)
13911 						bpf_global_percpu_ma_set = true;
13912 				}
13913 				mutex_unlock(&bpf_percpu_ma_lock);
13914 				if (err)
13915 					return err;
13916 			}
13917 
13918 			mutex_lock(&bpf_percpu_ma_lock);
13919 			err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
13920 			mutex_unlock(&bpf_percpu_ma_lock);
13921 			if (err)
13922 				return err;
13923 		}
13924 
13925 		struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
13926 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13927 			if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
13928 				verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
13929 				return -EINVAL;
13930 			}
13931 
13932 			if (struct_meta) {
13933 				verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
13934 				return -EINVAL;
13935 			}
13936 		}
13937 
13938 		mark_reg_known_zero(env, regs, BPF_REG_0);
13939 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13940 		regs[BPF_REG_0].btf = ret_btf;
13941 		regs[BPF_REG_0].btf_id = ret_btf_id;
13942 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
13943 			regs[BPF_REG_0].type |= MEM_PERCPU;
13944 
13945 		insn_aux->obj_new_size = ret_t->size;
13946 		insn_aux->kptr_struct_meta = struct_meta;
13947 	} else if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
13948 		mark_reg_known_zero(env, regs, BPF_REG_0);
13949 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13950 		regs[BPF_REG_0].btf = meta->arg_btf;
13951 		regs[BPF_REG_0].btf_id = meta->arg_btf_id;
13952 
13953 		insn_aux->kptr_struct_meta =
13954 			btf_find_struct_meta(meta->arg_btf,
13955 					     meta->arg_btf_id);
13956 	} else if (is_list_node_type(ptr_type)) {
13957 		struct btf_field *field = meta->arg_list_head.field;
13958 
13959 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13960 	} else if (is_rbtree_node_type(ptr_type)) {
13961 		struct btf_field *field = meta->arg_rbtree_root.field;
13962 
13963 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13964 	} else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13965 		mark_reg_known_zero(env, regs, BPF_REG_0);
13966 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
13967 		regs[BPF_REG_0].btf = desc_btf;
13968 		regs[BPF_REG_0].btf_id = meta->ret_btf_id;
13969 	} else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
13970 		ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value);
13971 		if (!ret_t) {
13972 			verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n",
13973 				meta->arg_constant.value);
13974 			return -EINVAL;
13975 		} else if (btf_type_is_struct(ret_t)) {
13976 			mark_reg_known_zero(env, regs, BPF_REG_0);
13977 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
13978 			regs[BPF_REG_0].btf = desc_btf;
13979 			regs[BPF_REG_0].btf_id = meta->arg_constant.value;
13980 		} else if (btf_type_is_void(ret_t)) {
13981 			mark_reg_known_zero(env, regs, BPF_REG_0);
13982 			regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
13983 			regs[BPF_REG_0].mem_size = 0;
13984 		} else {
13985 			verbose(env,
13986 				"kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n");
13987 			return -EINVAL;
13988 		}
13989 	} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
13990 		   meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
13991 		enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->initialized_dynptr.type);
13992 
13993 		mark_reg_known_zero(env, regs, BPF_REG_0);
13994 
13995 		if (!meta->arg_constant.found) {
13996 			verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size");
13997 			return -EFAULT;
13998 		}
13999 
14000 		regs[BPF_REG_0].mem_size = meta->arg_constant.value;
14001 
14002 		/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
14003 		regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
14004 
14005 		if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
14006 			regs[BPF_REG_0].type |= MEM_RDONLY;
14007 		} else {
14008 			/* this will set env->seen_direct_write to true */
14009 			if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
14010 				verbose(env, "the prog does not allow writes to packet data\n");
14011 				return -EINVAL;
14012 			}
14013 		}
14014 
14015 		if (!meta->initialized_dynptr.id) {
14016 			verifier_bug(env, "no dynptr id");
14017 			return -EFAULT;
14018 		}
14019 		regs[BPF_REG_0].dynptr_id = meta->initialized_dynptr.id;
14020 
14021 		/* we don't need to set BPF_REG_0's ref obj id
14022 		 * because packet slices are not refcounted (see
14023 		 * dynptr_type_refcounted)
14024 		 */
14025 	} else {
14026 		return 0;
14027 	}
14028 
14029 	return 1;
14030 }
14031 
14032 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
14033 
14034 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
14035 			    int *insn_idx_p)
14036 {
14037 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
14038 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
14039 	struct bpf_reg_state *regs = cur_regs(env);
14040 	const char *func_name, *ptr_type_name;
14041 	const struct btf_type *t, *ptr_type;
14042 	struct bpf_kfunc_call_arg_meta meta;
14043 	struct bpf_insn_aux_data *insn_aux;
14044 	int err, insn_idx = *insn_idx_p;
14045 	const struct btf_param *args;
14046 	struct btf *desc_btf;
14047 
14048 	/* skip for now, but return error when we find this in fixup_kfunc_call */
14049 	if (!insn->imm)
14050 		return 0;
14051 
14052 	err = fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta);
14053 	if (err == -EACCES && meta.func_name)
14054 		verbose(env, "calling kernel function %s is not allowed\n", meta.func_name);
14055 	if (err)
14056 		return err;
14057 	desc_btf = meta.btf;
14058 	func_name = meta.func_name;
14059 	insn_aux = &env->insn_aux_data[insn_idx];
14060 
14061 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
14062 
14063 	if (!insn->off &&
14064 	    (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
14065 	     insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
14066 		struct bpf_verifier_state *branch;
14067 		struct bpf_reg_state *regs;
14068 
14069 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
14070 		if (IS_ERR(branch)) {
14071 			verbose(env, "failed to push state for failed lock acquisition\n");
14072 			return PTR_ERR(branch);
14073 		}
14074 
14075 		regs = branch->frame[branch->curframe]->regs;
14076 
14077 		/* Clear r0-r5 registers in forked state */
14078 		for (i = 0; i < CALLER_SAVED_REGS; i++)
14079 			mark_reg_not_init(env, regs, caller_saved[i]);
14080 
14081 		mark_reg_unknown(env, regs, BPF_REG_0);
14082 		err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1);
14083 		if (err) {
14084 			verbose(env, "failed to mark s32 range for retval in forked state for lock\n");
14085 			return err;
14086 		}
14087 		__mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32));
14088 	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
14089 		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
14090 		return -EFAULT;
14091 	}
14092 
14093 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
14094 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
14095 		return -EACCES;
14096 	}
14097 
14098 	sleepable = is_kfunc_sleepable(&meta);
14099 	if (sleepable && !in_sleepable(env)) {
14100 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
14101 		return -EACCES;
14102 	}
14103 
14104 	/* Track non-sleepable context for kfuncs, same as for helpers. */
14105 	if (!in_sleepable_context(env))
14106 		insn_aux->non_sleepable = true;
14107 
14108 	/* Check the arguments */
14109 	err = check_kfunc_args(env, &meta, insn_idx);
14110 	if (err < 0)
14111 		return err;
14112 
14113 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
14114 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
14115 					 set_rbtree_add_callback_state);
14116 		if (err) {
14117 			verbose(env, "kfunc %s#%d failed callback verification\n",
14118 				func_name, meta.func_id);
14119 			return err;
14120 		}
14121 	}
14122 
14123 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
14124 		meta.r0_size = sizeof(u64);
14125 		meta.r0_rdonly = false;
14126 	}
14127 
14128 	if (is_bpf_wq_set_callback_kfunc(meta.func_id)) {
14129 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
14130 					 set_timer_callback_state);
14131 		if (err) {
14132 			verbose(env, "kfunc %s#%d failed callback verification\n",
14133 				func_name, meta.func_id);
14134 			return err;
14135 		}
14136 	}
14137 
14138 	if (is_task_work_add_kfunc(meta.func_id)) {
14139 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
14140 					 set_task_work_schedule_callback_state);
14141 		if (err) {
14142 			verbose(env, "kfunc %s#%d failed callback verification\n",
14143 				func_name, meta.func_id);
14144 			return err;
14145 		}
14146 	}
14147 
14148 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
14149 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
14150 
14151 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
14152 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
14153 
14154 	if (rcu_lock) {
14155 		env->cur_state->active_rcu_locks++;
14156 	} else if (rcu_unlock) {
14157 		struct bpf_func_state *state;
14158 		struct bpf_reg_state *reg;
14159 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
14160 
14161 		if (env->cur_state->active_rcu_locks == 0) {
14162 			verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
14163 			return -EINVAL;
14164 		}
14165 		if (--env->cur_state->active_rcu_locks == 0) {
14166 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
14167 				if (reg->type & MEM_RCU) {
14168 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
14169 					reg->type |= PTR_UNTRUSTED;
14170 				}
14171 			}));
14172 		}
14173 	} else if (sleepable && env->cur_state->active_rcu_locks) {
14174 		verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
14175 		return -EACCES;
14176 	}
14177 
14178 	if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
14179 		verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
14180 		return -EACCES;
14181 	}
14182 
14183 	if (env->cur_state->active_preempt_locks) {
14184 		if (preempt_disable) {
14185 			env->cur_state->active_preempt_locks++;
14186 		} else if (preempt_enable) {
14187 			env->cur_state->active_preempt_locks--;
14188 		} else if (sleepable) {
14189 			verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
14190 			return -EACCES;
14191 		}
14192 	} else if (preempt_disable) {
14193 		env->cur_state->active_preempt_locks++;
14194 	} else if (preempt_enable) {
14195 		verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
14196 		return -EINVAL;
14197 	}
14198 
14199 	if (env->cur_state->active_irq_id && sleepable) {
14200 		verbose(env, "kernel func %s is sleepable within IRQ-disabled region\n", func_name);
14201 		return -EACCES;
14202 	}
14203 
14204 	if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) {
14205 		verbose(env, "kernel func %s requires RCU critical section protection\n", func_name);
14206 		return -EACCES;
14207 	}
14208 
14209 	/* In case of release function, we get register number of refcounted
14210 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
14211 	 */
14212 	if (meta.release_regno) {
14213 		struct bpf_reg_state *reg = &regs[meta.release_regno];
14214 
14215 		if (meta.initialized_dynptr.ref_obj_id) {
14216 			err = unmark_stack_slots_dynptr(env, reg);
14217 		} else {
14218 			err = release_reference(env, reg->ref_obj_id);
14219 			if (err)
14220 				verbose(env, "kfunc %s#%d reference has not been acquired before\n",
14221 					func_name, meta.func_id);
14222 		}
14223 		if (err)
14224 			return err;
14225 	}
14226 
14227 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
14228 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
14229 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
14230 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
14231 		insn_aux->insert_off = regs[BPF_REG_2].off;
14232 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
14233 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
14234 		if (err) {
14235 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
14236 				func_name, meta.func_id);
14237 			return err;
14238 		}
14239 
14240 		err = release_reference(env, release_ref_obj_id);
14241 		if (err) {
14242 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
14243 				func_name, meta.func_id);
14244 			return err;
14245 		}
14246 	}
14247 
14248 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
14249 		if (!bpf_jit_supports_exceptions()) {
14250 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
14251 				func_name, meta.func_id);
14252 			return -ENOTSUPP;
14253 		}
14254 		env->seen_exception = true;
14255 
14256 		/* In the case of the default callback, the cookie value passed
14257 		 * to bpf_throw becomes the return value of the program.
14258 		 */
14259 		if (!env->exception_callback_subprog) {
14260 			err = check_return_code(env, BPF_REG_1, "R1");
14261 			if (err < 0)
14262 				return err;
14263 		}
14264 	}
14265 
14266 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14267 		u32 regno = caller_saved[i];
14268 
14269 		mark_reg_not_init(env, regs, regno);
14270 		regs[regno].subreg_def = DEF_NOT_SUBREG;
14271 	}
14272 
14273 	/* Check return type */
14274 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
14275 
14276 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
14277 		/* Only exception is bpf_obj_new_impl */
14278 		if (meta.btf != btf_vmlinux ||
14279 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
14280 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
14281 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
14282 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
14283 			return -EINVAL;
14284 		}
14285 	}
14286 
14287 	if (btf_type_is_scalar(t)) {
14288 		mark_reg_unknown(env, regs, BPF_REG_0);
14289 		if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
14290 		    meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
14291 			__mark_reg_const_zero(env, &regs[BPF_REG_0]);
14292 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
14293 	} else if (btf_type_is_ptr(t)) {
14294 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
14295 		err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
14296 		if (err) {
14297 			if (err < 0)
14298 				return err;
14299 		} else if (btf_type_is_void(ptr_type)) {
14300 			/* kfunc returning 'void *' is equivalent to returning scalar */
14301 			mark_reg_unknown(env, regs, BPF_REG_0);
14302 		} else if (!__btf_type_is_struct(ptr_type)) {
14303 			if (!meta.r0_size) {
14304 				__u32 sz;
14305 
14306 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
14307 					meta.r0_size = sz;
14308 					meta.r0_rdonly = true;
14309 				}
14310 			}
14311 			if (!meta.r0_size) {
14312 				ptr_type_name = btf_name_by_offset(desc_btf,
14313 								   ptr_type->name_off);
14314 				verbose(env,
14315 					"kernel function %s returns pointer type %s %s is not supported\n",
14316 					func_name,
14317 					btf_type_str(ptr_type),
14318 					ptr_type_name);
14319 				return -EINVAL;
14320 			}
14321 
14322 			mark_reg_known_zero(env, regs, BPF_REG_0);
14323 			regs[BPF_REG_0].type = PTR_TO_MEM;
14324 			regs[BPF_REG_0].mem_size = meta.r0_size;
14325 
14326 			if (meta.r0_rdonly)
14327 				regs[BPF_REG_0].type |= MEM_RDONLY;
14328 
14329 			/* Ensures we don't access the memory after a release_reference() */
14330 			if (meta.ref_obj_id)
14331 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
14332 
14333 			if (is_kfunc_rcu_protected(&meta))
14334 				regs[BPF_REG_0].type |= MEM_RCU;
14335 		} else {
14336 			enum bpf_reg_type type = PTR_TO_BTF_ID;
14337 
14338 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
14339 				type |= PTR_UNTRUSTED;
14340 			else if (is_kfunc_rcu_protected(&meta) ||
14341 				 (is_iter_next_kfunc(&meta) &&
14342 				  (get_iter_from_state(env->cur_state, &meta)
14343 					   ->type & MEM_RCU))) {
14344 				/*
14345 				 * If the iterator's constructor (the _new
14346 				 * function e.g., bpf_iter_task_new) has been
14347 				 * annotated with BPF kfunc flag
14348 				 * KF_RCU_PROTECTED and was called within a RCU
14349 				 * read-side critical section, also propagate
14350 				 * the MEM_RCU flag to the pointer returned from
14351 				 * the iterator's next function (e.g.,
14352 				 * bpf_iter_task_next).
14353 				 */
14354 				type |= MEM_RCU;
14355 			} else {
14356 				/*
14357 				 * Any PTR_TO_BTF_ID that is returned from a BPF
14358 				 * kfunc should by default be treated as
14359 				 * implicitly trusted.
14360 				 */
14361 				type |= PTR_TRUSTED;
14362 			}
14363 
14364 			mark_reg_known_zero(env, regs, BPF_REG_0);
14365 			regs[BPF_REG_0].btf = desc_btf;
14366 			regs[BPF_REG_0].type = type;
14367 			regs[BPF_REG_0].btf_id = ptr_type_id;
14368 		}
14369 
14370 		if (is_kfunc_ret_null(&meta)) {
14371 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
14372 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
14373 			regs[BPF_REG_0].id = ++env->id_gen;
14374 		}
14375 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
14376 		if (is_kfunc_acquire(&meta)) {
14377 			int id = acquire_reference(env, insn_idx);
14378 
14379 			if (id < 0)
14380 				return id;
14381 			if (is_kfunc_ret_null(&meta))
14382 				regs[BPF_REG_0].id = id;
14383 			regs[BPF_REG_0].ref_obj_id = id;
14384 		} else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
14385 			ref_set_non_owning(env, &regs[BPF_REG_0]);
14386 		}
14387 
14388 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
14389 			regs[BPF_REG_0].id = ++env->id_gen;
14390 	} else if (btf_type_is_void(t)) {
14391 		if (meta.btf == btf_vmlinux) {
14392 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
14393 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
14394 				insn_aux->kptr_struct_meta =
14395 					btf_find_struct_meta(meta.arg_btf,
14396 							     meta.arg_btf_id);
14397 			}
14398 		}
14399 	}
14400 
14401 	if (is_kfunc_pkt_changing(&meta))
14402 		clear_all_pkt_pointers(env);
14403 
14404 	nargs = btf_type_vlen(meta.func_proto);
14405 	args = (const struct btf_param *)(meta.func_proto + 1);
14406 	for (i = 0; i < nargs; i++) {
14407 		u32 regno = i + 1;
14408 
14409 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
14410 		if (btf_type_is_ptr(t))
14411 			mark_btf_func_reg_size(env, regno, sizeof(void *));
14412 		else
14413 			/* scalar. ensured by btf_check_kfunc_arg_match() */
14414 			mark_btf_func_reg_size(env, regno, t->size);
14415 	}
14416 
14417 	if (is_iter_next_kfunc(&meta)) {
14418 		err = process_iter_next_call(env, insn_idx, &meta);
14419 		if (err)
14420 			return err;
14421 	}
14422 
14423 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie])
14424 		env->prog->call_session_cookie = true;
14425 
14426 	return 0;
14427 }
14428 
14429 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
14430 				  const struct bpf_reg_state *reg,
14431 				  enum bpf_reg_type type)
14432 {
14433 	bool known = tnum_is_const(reg->var_off);
14434 	s64 val = reg->var_off.value;
14435 	s64 smin = reg->smin_value;
14436 
14437 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
14438 		verbose(env, "math between %s pointer and %lld is not allowed\n",
14439 			reg_type_str(env, type), val);
14440 		return false;
14441 	}
14442 
14443 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
14444 		verbose(env, "%s pointer offset %d is not allowed\n",
14445 			reg_type_str(env, type), reg->off);
14446 		return false;
14447 	}
14448 
14449 	if (smin == S64_MIN) {
14450 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
14451 			reg_type_str(env, type));
14452 		return false;
14453 	}
14454 
14455 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
14456 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
14457 			smin, reg_type_str(env, type));
14458 		return false;
14459 	}
14460 
14461 	return true;
14462 }
14463 
14464 enum {
14465 	REASON_BOUNDS	= -1,
14466 	REASON_TYPE	= -2,
14467 	REASON_PATHS	= -3,
14468 	REASON_LIMIT	= -4,
14469 	REASON_STACK	= -5,
14470 };
14471 
14472 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
14473 			      u32 *alu_limit, bool mask_to_left)
14474 {
14475 	u32 max = 0, ptr_limit = 0;
14476 
14477 	switch (ptr_reg->type) {
14478 	case PTR_TO_STACK:
14479 		/* Offset 0 is out-of-bounds, but acceptable start for the
14480 		 * left direction, see BPF_REG_FP. Also, unknown scalar
14481 		 * offset where we would need to deal with min/max bounds is
14482 		 * currently prohibited for unprivileged.
14483 		 */
14484 		max = MAX_BPF_STACK + mask_to_left;
14485 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
14486 		break;
14487 	case PTR_TO_MAP_VALUE:
14488 		max = ptr_reg->map_ptr->value_size;
14489 		ptr_limit = (mask_to_left ?
14490 			     ptr_reg->smin_value :
14491 			     ptr_reg->umax_value) + ptr_reg->off;
14492 		break;
14493 	default:
14494 		return REASON_TYPE;
14495 	}
14496 
14497 	if (ptr_limit >= max)
14498 		return REASON_LIMIT;
14499 	*alu_limit = ptr_limit;
14500 	return 0;
14501 }
14502 
14503 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
14504 				    const struct bpf_insn *insn)
14505 {
14506 	return env->bypass_spec_v1 ||
14507 		BPF_SRC(insn->code) == BPF_K ||
14508 		cur_aux(env)->nospec;
14509 }
14510 
14511 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
14512 				       u32 alu_state, u32 alu_limit)
14513 {
14514 	/* If we arrived here from different branches with different
14515 	 * state or limits to sanitize, then this won't work.
14516 	 */
14517 	if (aux->alu_state &&
14518 	    (aux->alu_state != alu_state ||
14519 	     aux->alu_limit != alu_limit))
14520 		return REASON_PATHS;
14521 
14522 	/* Corresponding fixup done in do_misc_fixups(). */
14523 	aux->alu_state = alu_state;
14524 	aux->alu_limit = alu_limit;
14525 	return 0;
14526 }
14527 
14528 static int sanitize_val_alu(struct bpf_verifier_env *env,
14529 			    struct bpf_insn *insn)
14530 {
14531 	struct bpf_insn_aux_data *aux = cur_aux(env);
14532 
14533 	if (can_skip_alu_sanitation(env, insn))
14534 		return 0;
14535 
14536 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
14537 }
14538 
14539 static bool sanitize_needed(u8 opcode)
14540 {
14541 	return opcode == BPF_ADD || opcode == BPF_SUB;
14542 }
14543 
14544 struct bpf_sanitize_info {
14545 	struct bpf_insn_aux_data aux;
14546 	bool mask_to_left;
14547 };
14548 
14549 static int sanitize_speculative_path(struct bpf_verifier_env *env,
14550 				     const struct bpf_insn *insn,
14551 				     u32 next_idx, u32 curr_idx)
14552 {
14553 	struct bpf_verifier_state *branch;
14554 	struct bpf_reg_state *regs;
14555 
14556 	branch = push_stack(env, next_idx, curr_idx, true);
14557 	if (!IS_ERR(branch) && insn) {
14558 		regs = branch->frame[branch->curframe]->regs;
14559 		if (BPF_SRC(insn->code) == BPF_K) {
14560 			mark_reg_unknown(env, regs, insn->dst_reg);
14561 		} else if (BPF_SRC(insn->code) == BPF_X) {
14562 			mark_reg_unknown(env, regs, insn->dst_reg);
14563 			mark_reg_unknown(env, regs, insn->src_reg);
14564 		}
14565 	}
14566 	return PTR_ERR_OR_ZERO(branch);
14567 }
14568 
14569 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
14570 			    struct bpf_insn *insn,
14571 			    const struct bpf_reg_state *ptr_reg,
14572 			    const struct bpf_reg_state *off_reg,
14573 			    struct bpf_reg_state *dst_reg,
14574 			    struct bpf_sanitize_info *info,
14575 			    const bool commit_window)
14576 {
14577 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
14578 	struct bpf_verifier_state *vstate = env->cur_state;
14579 	bool off_is_imm = tnum_is_const(off_reg->var_off);
14580 	bool off_is_neg = off_reg->smin_value < 0;
14581 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
14582 	u8 opcode = BPF_OP(insn->code);
14583 	u32 alu_state, alu_limit;
14584 	struct bpf_reg_state tmp;
14585 	int err;
14586 
14587 	if (can_skip_alu_sanitation(env, insn))
14588 		return 0;
14589 
14590 	/* We already marked aux for masking from non-speculative
14591 	 * paths, thus we got here in the first place. We only care
14592 	 * to explore bad access from here.
14593 	 */
14594 	if (vstate->speculative)
14595 		goto do_sim;
14596 
14597 	if (!commit_window) {
14598 		if (!tnum_is_const(off_reg->var_off) &&
14599 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
14600 			return REASON_BOUNDS;
14601 
14602 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
14603 				     (opcode == BPF_SUB && !off_is_neg);
14604 	}
14605 
14606 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
14607 	if (err < 0)
14608 		return err;
14609 
14610 	if (commit_window) {
14611 		/* In commit phase we narrow the masking window based on
14612 		 * the observed pointer move after the simulated operation.
14613 		 */
14614 		alu_state = info->aux.alu_state;
14615 		alu_limit = abs(info->aux.alu_limit - alu_limit);
14616 	} else {
14617 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
14618 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
14619 		alu_state |= ptr_is_dst_reg ?
14620 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
14621 
14622 		/* Limit pruning on unknown scalars to enable deep search for
14623 		 * potential masking differences from other program paths.
14624 		 */
14625 		if (!off_is_imm)
14626 			env->explore_alu_limits = true;
14627 	}
14628 
14629 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
14630 	if (err < 0)
14631 		return err;
14632 do_sim:
14633 	/* If we're in commit phase, we're done here given we already
14634 	 * pushed the truncated dst_reg into the speculative verification
14635 	 * stack.
14636 	 *
14637 	 * Also, when register is a known constant, we rewrite register-based
14638 	 * operation to immediate-based, and thus do not need masking (and as
14639 	 * a consequence, do not need to simulate the zero-truncation either).
14640 	 */
14641 	if (commit_window || off_is_imm)
14642 		return 0;
14643 
14644 	/* Simulate and find potential out-of-bounds access under
14645 	 * speculative execution from truncation as a result of
14646 	 * masking when off was not within expected range. If off
14647 	 * sits in dst, then we temporarily need to move ptr there
14648 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
14649 	 * for cases where we use K-based arithmetic in one direction
14650 	 * and truncated reg-based in the other in order to explore
14651 	 * bad access.
14652 	 */
14653 	if (!ptr_is_dst_reg) {
14654 		tmp = *dst_reg;
14655 		copy_register_state(dst_reg, ptr_reg);
14656 	}
14657 	err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx);
14658 	if (err < 0)
14659 		return REASON_STACK;
14660 	if (!ptr_is_dst_reg)
14661 		*dst_reg = tmp;
14662 	return 0;
14663 }
14664 
14665 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
14666 {
14667 	struct bpf_verifier_state *vstate = env->cur_state;
14668 
14669 	/* If we simulate paths under speculation, we don't update the
14670 	 * insn as 'seen' such that when we verify unreachable paths in
14671 	 * the non-speculative domain, sanitize_dead_code() can still
14672 	 * rewrite/sanitize them.
14673 	 */
14674 	if (!vstate->speculative)
14675 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
14676 }
14677 
14678 static int sanitize_err(struct bpf_verifier_env *env,
14679 			const struct bpf_insn *insn, int reason,
14680 			const struct bpf_reg_state *off_reg,
14681 			const struct bpf_reg_state *dst_reg)
14682 {
14683 	static const char *err = "pointer arithmetic with it prohibited for !root";
14684 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
14685 	u32 dst = insn->dst_reg, src = insn->src_reg;
14686 
14687 	switch (reason) {
14688 	case REASON_BOUNDS:
14689 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
14690 			off_reg == dst_reg ? dst : src, err);
14691 		break;
14692 	case REASON_TYPE:
14693 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
14694 			off_reg == dst_reg ? src : dst, err);
14695 		break;
14696 	case REASON_PATHS:
14697 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
14698 			dst, op, err);
14699 		break;
14700 	case REASON_LIMIT:
14701 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
14702 			dst, op, err);
14703 		break;
14704 	case REASON_STACK:
14705 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
14706 			dst, err);
14707 		return -ENOMEM;
14708 	default:
14709 		verifier_bug(env, "unknown reason (%d)", reason);
14710 		break;
14711 	}
14712 
14713 	return -EACCES;
14714 }
14715 
14716 /* check that stack access falls within stack limits and that 'reg' doesn't
14717  * have a variable offset.
14718  *
14719  * Variable offset is prohibited for unprivileged mode for simplicity since it
14720  * requires corresponding support in Spectre masking for stack ALU.  See also
14721  * retrieve_ptr_limit().
14722  *
14723  *
14724  * 'off' includes 'reg->off'.
14725  */
14726 static int check_stack_access_for_ptr_arithmetic(
14727 				struct bpf_verifier_env *env,
14728 				int regno,
14729 				const struct bpf_reg_state *reg,
14730 				int off)
14731 {
14732 	if (!tnum_is_const(reg->var_off)) {
14733 		char tn_buf[48];
14734 
14735 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
14736 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
14737 			regno, tn_buf, off);
14738 		return -EACCES;
14739 	}
14740 
14741 	if (off >= 0 || off < -MAX_BPF_STACK) {
14742 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
14743 			"prohibited for !root; off=%d\n", regno, off);
14744 		return -EACCES;
14745 	}
14746 
14747 	return 0;
14748 }
14749 
14750 static int sanitize_check_bounds(struct bpf_verifier_env *env,
14751 				 const struct bpf_insn *insn,
14752 				 const struct bpf_reg_state *dst_reg)
14753 {
14754 	u32 dst = insn->dst_reg;
14755 
14756 	/* For unprivileged we require that resulting offset must be in bounds
14757 	 * in order to be able to sanitize access later on.
14758 	 */
14759 	if (env->bypass_spec_v1)
14760 		return 0;
14761 
14762 	switch (dst_reg->type) {
14763 	case PTR_TO_STACK:
14764 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
14765 					dst_reg->off + dst_reg->var_off.value))
14766 			return -EACCES;
14767 		break;
14768 	case PTR_TO_MAP_VALUE:
14769 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
14770 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
14771 				"prohibited for !root\n", dst);
14772 			return -EACCES;
14773 		}
14774 		break;
14775 	default:
14776 		return -EOPNOTSUPP;
14777 	}
14778 
14779 	return 0;
14780 }
14781 
14782 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
14783  * Caller should also handle BPF_MOV case separately.
14784  * If we return -EACCES, caller may want to try again treating pointer as a
14785  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
14786  */
14787 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
14788 				   struct bpf_insn *insn,
14789 				   const struct bpf_reg_state *ptr_reg,
14790 				   const struct bpf_reg_state *off_reg)
14791 {
14792 	struct bpf_verifier_state *vstate = env->cur_state;
14793 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14794 	struct bpf_reg_state *regs = state->regs, *dst_reg;
14795 	bool known = tnum_is_const(off_reg->var_off);
14796 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
14797 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
14798 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
14799 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
14800 	struct bpf_sanitize_info info = {};
14801 	u8 opcode = BPF_OP(insn->code);
14802 	u32 dst = insn->dst_reg;
14803 	int ret, bounds_ret;
14804 
14805 	dst_reg = &regs[dst];
14806 
14807 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
14808 	    smin_val > smax_val || umin_val > umax_val) {
14809 		/* Taint dst register if offset had invalid bounds derived from
14810 		 * e.g. dead branches.
14811 		 */
14812 		__mark_reg_unknown(env, dst_reg);
14813 		return 0;
14814 	}
14815 
14816 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
14817 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
14818 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14819 			__mark_reg_unknown(env, dst_reg);
14820 			return 0;
14821 		}
14822 
14823 		verbose(env,
14824 			"R%d 32-bit pointer arithmetic prohibited\n",
14825 			dst);
14826 		return -EACCES;
14827 	}
14828 
14829 	if (ptr_reg->type & PTR_MAYBE_NULL) {
14830 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
14831 			dst, reg_type_str(env, ptr_reg->type));
14832 		return -EACCES;
14833 	}
14834 
14835 	/*
14836 	 * Accesses to untrusted PTR_TO_MEM are done through probe
14837 	 * instructions, hence no need to track offsets.
14838 	 */
14839 	if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED))
14840 		return 0;
14841 
14842 	switch (base_type(ptr_reg->type)) {
14843 	case PTR_TO_CTX:
14844 	case PTR_TO_MAP_VALUE:
14845 	case PTR_TO_MAP_KEY:
14846 	case PTR_TO_STACK:
14847 	case PTR_TO_PACKET_META:
14848 	case PTR_TO_PACKET:
14849 	case PTR_TO_TP_BUFFER:
14850 	case PTR_TO_BTF_ID:
14851 	case PTR_TO_MEM:
14852 	case PTR_TO_BUF:
14853 	case PTR_TO_FUNC:
14854 	case CONST_PTR_TO_DYNPTR:
14855 		break;
14856 	case PTR_TO_FLOW_KEYS:
14857 		if (known)
14858 			break;
14859 		fallthrough;
14860 	case CONST_PTR_TO_MAP:
14861 		/* smin_val represents the known value */
14862 		if (known && smin_val == 0 && opcode == BPF_ADD)
14863 			break;
14864 		fallthrough;
14865 	default:
14866 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
14867 			dst, reg_type_str(env, ptr_reg->type));
14868 		return -EACCES;
14869 	}
14870 
14871 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
14872 	 * The id may be overwritten later if we create a new variable offset.
14873 	 */
14874 	dst_reg->type = ptr_reg->type;
14875 	dst_reg->id = ptr_reg->id;
14876 
14877 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
14878 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
14879 		return -EINVAL;
14880 
14881 	/* pointer types do not carry 32-bit bounds at the moment. */
14882 	__mark_reg32_unbounded(dst_reg);
14883 
14884 	if (sanitize_needed(opcode)) {
14885 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
14886 				       &info, false);
14887 		if (ret < 0)
14888 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14889 	}
14890 
14891 	switch (opcode) {
14892 	case BPF_ADD:
14893 		/* We can take a fixed offset as long as it doesn't overflow
14894 		 * the s32 'off' field
14895 		 */
14896 		if (known && (ptr_reg->off + smin_val ==
14897 			      (s64)(s32)(ptr_reg->off + smin_val))) {
14898 			/* pointer += K.  Accumulate it into fixed offset */
14899 			dst_reg->smin_value = smin_ptr;
14900 			dst_reg->smax_value = smax_ptr;
14901 			dst_reg->umin_value = umin_ptr;
14902 			dst_reg->umax_value = umax_ptr;
14903 			dst_reg->var_off = ptr_reg->var_off;
14904 			dst_reg->off = ptr_reg->off + smin_val;
14905 			dst_reg->raw = ptr_reg->raw;
14906 			break;
14907 		}
14908 		/* A new variable offset is created.  Note that off_reg->off
14909 		 * == 0, since it's a scalar.
14910 		 * dst_reg gets the pointer type and since some positive
14911 		 * integer value was added to the pointer, give it a new 'id'
14912 		 * if it's a PTR_TO_PACKET.
14913 		 * this creates a new 'base' pointer, off_reg (variable) gets
14914 		 * added into the variable offset, and we copy the fixed offset
14915 		 * from ptr_reg.
14916 		 */
14917 		if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
14918 		    check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
14919 			dst_reg->smin_value = S64_MIN;
14920 			dst_reg->smax_value = S64_MAX;
14921 		}
14922 		if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
14923 		    check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
14924 			dst_reg->umin_value = 0;
14925 			dst_reg->umax_value = U64_MAX;
14926 		}
14927 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
14928 		dst_reg->off = ptr_reg->off;
14929 		dst_reg->raw = ptr_reg->raw;
14930 		if (reg_is_pkt_pointer(ptr_reg)) {
14931 			dst_reg->id = ++env->id_gen;
14932 			/* something was added to pkt_ptr, set range to zero */
14933 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14934 		}
14935 		break;
14936 	case BPF_SUB:
14937 		if (dst_reg == off_reg) {
14938 			/* scalar -= pointer.  Creates an unknown scalar */
14939 			verbose(env, "R%d tried to subtract pointer from scalar\n",
14940 				dst);
14941 			return -EACCES;
14942 		}
14943 		/* We don't allow subtraction from FP, because (according to
14944 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
14945 		 * be able to deal with it.
14946 		 */
14947 		if (ptr_reg->type == PTR_TO_STACK) {
14948 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
14949 				dst);
14950 			return -EACCES;
14951 		}
14952 		if (known && (ptr_reg->off - smin_val ==
14953 			      (s64)(s32)(ptr_reg->off - smin_val))) {
14954 			/* pointer -= K.  Subtract it from fixed offset */
14955 			dst_reg->smin_value = smin_ptr;
14956 			dst_reg->smax_value = smax_ptr;
14957 			dst_reg->umin_value = umin_ptr;
14958 			dst_reg->umax_value = umax_ptr;
14959 			dst_reg->var_off = ptr_reg->var_off;
14960 			dst_reg->id = ptr_reg->id;
14961 			dst_reg->off = ptr_reg->off - smin_val;
14962 			dst_reg->raw = ptr_reg->raw;
14963 			break;
14964 		}
14965 		/* A new variable offset is created.  If the subtrahend is known
14966 		 * nonnegative, then any reg->range we had before is still good.
14967 		 */
14968 		if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
14969 		    check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
14970 			/* Overflow possible, we know nothing */
14971 			dst_reg->smin_value = S64_MIN;
14972 			dst_reg->smax_value = S64_MAX;
14973 		}
14974 		if (umin_ptr < umax_val) {
14975 			/* Overflow possible, we know nothing */
14976 			dst_reg->umin_value = 0;
14977 			dst_reg->umax_value = U64_MAX;
14978 		} else {
14979 			/* Cannot overflow (as long as bounds are consistent) */
14980 			dst_reg->umin_value = umin_ptr - umax_val;
14981 			dst_reg->umax_value = umax_ptr - umin_val;
14982 		}
14983 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
14984 		dst_reg->off = ptr_reg->off;
14985 		dst_reg->raw = ptr_reg->raw;
14986 		if (reg_is_pkt_pointer(ptr_reg)) {
14987 			dst_reg->id = ++env->id_gen;
14988 			/* something was added to pkt_ptr, set range to zero */
14989 			if (smin_val < 0)
14990 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14991 		}
14992 		break;
14993 	case BPF_AND:
14994 	case BPF_OR:
14995 	case BPF_XOR:
14996 		/* bitwise ops on pointers are troublesome, prohibit. */
14997 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
14998 			dst, bpf_alu_string[opcode >> 4]);
14999 		return -EACCES;
15000 	default:
15001 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
15002 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
15003 			dst, bpf_alu_string[opcode >> 4]);
15004 		return -EACCES;
15005 	}
15006 
15007 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
15008 		return -EINVAL;
15009 	reg_bounds_sync(dst_reg);
15010 	bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
15011 	if (bounds_ret == -EACCES)
15012 		return bounds_ret;
15013 	if (sanitize_needed(opcode)) {
15014 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
15015 				       &info, true);
15016 		if (verifier_bug_if(!can_skip_alu_sanitation(env, insn)
15017 				    && !env->cur_state->speculative
15018 				    && bounds_ret
15019 				    && !ret,
15020 				    env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) {
15021 			return -EFAULT;
15022 		}
15023 		if (ret < 0)
15024 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
15025 	}
15026 
15027 	return 0;
15028 }
15029 
15030 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
15031 				 struct bpf_reg_state *src_reg)
15032 {
15033 	s32 *dst_smin = &dst_reg->s32_min_value;
15034 	s32 *dst_smax = &dst_reg->s32_max_value;
15035 	u32 *dst_umin = &dst_reg->u32_min_value;
15036 	u32 *dst_umax = &dst_reg->u32_max_value;
15037 	u32 umin_val = src_reg->u32_min_value;
15038 	u32 umax_val = src_reg->u32_max_value;
15039 	bool min_overflow, max_overflow;
15040 
15041 	if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
15042 	    check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
15043 		*dst_smin = S32_MIN;
15044 		*dst_smax = S32_MAX;
15045 	}
15046 
15047 	/* If either all additions overflow or no additions overflow, then
15048 	 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
15049 	 * dst_umax + src_umax. Otherwise (some additions overflow), set
15050 	 * the output bounds to unbounded.
15051 	 */
15052 	min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
15053 	max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
15054 
15055 	if (!min_overflow && max_overflow) {
15056 		*dst_umin = 0;
15057 		*dst_umax = U32_MAX;
15058 	}
15059 }
15060 
15061 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
15062 			       struct bpf_reg_state *src_reg)
15063 {
15064 	s64 *dst_smin = &dst_reg->smin_value;
15065 	s64 *dst_smax = &dst_reg->smax_value;
15066 	u64 *dst_umin = &dst_reg->umin_value;
15067 	u64 *dst_umax = &dst_reg->umax_value;
15068 	u64 umin_val = src_reg->umin_value;
15069 	u64 umax_val = src_reg->umax_value;
15070 	bool min_overflow, max_overflow;
15071 
15072 	if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
15073 	    check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
15074 		*dst_smin = S64_MIN;
15075 		*dst_smax = S64_MAX;
15076 	}
15077 
15078 	/* If either all additions overflow or no additions overflow, then
15079 	 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
15080 	 * dst_umax + src_umax. Otherwise (some additions overflow), set
15081 	 * the output bounds to unbounded.
15082 	 */
15083 	min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
15084 	max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
15085 
15086 	if (!min_overflow && max_overflow) {
15087 		*dst_umin = 0;
15088 		*dst_umax = U64_MAX;
15089 	}
15090 }
15091 
15092 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
15093 				 struct bpf_reg_state *src_reg)
15094 {
15095 	s32 *dst_smin = &dst_reg->s32_min_value;
15096 	s32 *dst_smax = &dst_reg->s32_max_value;
15097 	u32 *dst_umin = &dst_reg->u32_min_value;
15098 	u32 *dst_umax = &dst_reg->u32_max_value;
15099 	u32 umin_val = src_reg->u32_min_value;
15100 	u32 umax_val = src_reg->u32_max_value;
15101 	bool min_underflow, max_underflow;
15102 
15103 	if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
15104 	    check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
15105 		/* Overflow possible, we know nothing */
15106 		*dst_smin = S32_MIN;
15107 		*dst_smax = S32_MAX;
15108 	}
15109 
15110 	/* If either all subtractions underflow or no subtractions
15111 	 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
15112 	 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
15113 	 * underflow), set the output bounds to unbounded.
15114 	 */
15115 	min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
15116 	max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
15117 
15118 	if (min_underflow && !max_underflow) {
15119 		*dst_umin = 0;
15120 		*dst_umax = U32_MAX;
15121 	}
15122 }
15123 
15124 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
15125 			       struct bpf_reg_state *src_reg)
15126 {
15127 	s64 *dst_smin = &dst_reg->smin_value;
15128 	s64 *dst_smax = &dst_reg->smax_value;
15129 	u64 *dst_umin = &dst_reg->umin_value;
15130 	u64 *dst_umax = &dst_reg->umax_value;
15131 	u64 umin_val = src_reg->umin_value;
15132 	u64 umax_val = src_reg->umax_value;
15133 	bool min_underflow, max_underflow;
15134 
15135 	if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
15136 	    check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
15137 		/* Overflow possible, we know nothing */
15138 		*dst_smin = S64_MIN;
15139 		*dst_smax = S64_MAX;
15140 	}
15141 
15142 	/* If either all subtractions underflow or no subtractions
15143 	 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
15144 	 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
15145 	 * underflow), set the output bounds to unbounded.
15146 	 */
15147 	min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
15148 	max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
15149 
15150 	if (min_underflow && !max_underflow) {
15151 		*dst_umin = 0;
15152 		*dst_umax = U64_MAX;
15153 	}
15154 }
15155 
15156 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
15157 				 struct bpf_reg_state *src_reg)
15158 {
15159 	s32 *dst_smin = &dst_reg->s32_min_value;
15160 	s32 *dst_smax = &dst_reg->s32_max_value;
15161 	u32 *dst_umin = &dst_reg->u32_min_value;
15162 	u32 *dst_umax = &dst_reg->u32_max_value;
15163 	s32 tmp_prod[4];
15164 
15165 	if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) ||
15166 	    check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) {
15167 		/* Overflow possible, we know nothing */
15168 		*dst_umin = 0;
15169 		*dst_umax = U32_MAX;
15170 	}
15171 	if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) ||
15172 	    check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) ||
15173 	    check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) ||
15174 	    check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) {
15175 		/* Overflow possible, we know nothing */
15176 		*dst_smin = S32_MIN;
15177 		*dst_smax = S32_MAX;
15178 	} else {
15179 		*dst_smin = min_array(tmp_prod, 4);
15180 		*dst_smax = max_array(tmp_prod, 4);
15181 	}
15182 }
15183 
15184 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
15185 			       struct bpf_reg_state *src_reg)
15186 {
15187 	s64 *dst_smin = &dst_reg->smin_value;
15188 	s64 *dst_smax = &dst_reg->smax_value;
15189 	u64 *dst_umin = &dst_reg->umin_value;
15190 	u64 *dst_umax = &dst_reg->umax_value;
15191 	s64 tmp_prod[4];
15192 
15193 	if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) ||
15194 	    check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) {
15195 		/* Overflow possible, we know nothing */
15196 		*dst_umin = 0;
15197 		*dst_umax = U64_MAX;
15198 	}
15199 	if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) ||
15200 	    check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) ||
15201 	    check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) ||
15202 	    check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) {
15203 		/* Overflow possible, we know nothing */
15204 		*dst_smin = S64_MIN;
15205 		*dst_smax = S64_MAX;
15206 	} else {
15207 		*dst_smin = min_array(tmp_prod, 4);
15208 		*dst_smax = max_array(tmp_prod, 4);
15209 	}
15210 }
15211 
15212 static void scalar32_min_max_udiv(struct bpf_reg_state *dst_reg,
15213 				  struct bpf_reg_state *src_reg)
15214 {
15215 	u32 *dst_umin = &dst_reg->u32_min_value;
15216 	u32 *dst_umax = &dst_reg->u32_max_value;
15217 	u32 src_val = src_reg->u32_min_value; /* non-zero, const divisor */
15218 
15219 	*dst_umin = *dst_umin / src_val;
15220 	*dst_umax = *dst_umax / src_val;
15221 
15222 	/* Reset other ranges/tnum to unbounded/unknown. */
15223 	dst_reg->s32_min_value = S32_MIN;
15224 	dst_reg->s32_max_value = S32_MAX;
15225 	reset_reg64_and_tnum(dst_reg);
15226 }
15227 
15228 static void scalar_min_max_udiv(struct bpf_reg_state *dst_reg,
15229 				struct bpf_reg_state *src_reg)
15230 {
15231 	u64 *dst_umin = &dst_reg->umin_value;
15232 	u64 *dst_umax = &dst_reg->umax_value;
15233 	u64 src_val = src_reg->umin_value; /* non-zero, const divisor */
15234 
15235 	*dst_umin = div64_u64(*dst_umin, src_val);
15236 	*dst_umax = div64_u64(*dst_umax, src_val);
15237 
15238 	/* Reset other ranges/tnum to unbounded/unknown. */
15239 	dst_reg->smin_value = S64_MIN;
15240 	dst_reg->smax_value = S64_MAX;
15241 	reset_reg32_and_tnum(dst_reg);
15242 }
15243 
15244 static void scalar32_min_max_sdiv(struct bpf_reg_state *dst_reg,
15245 				  struct bpf_reg_state *src_reg)
15246 {
15247 	s32 *dst_smin = &dst_reg->s32_min_value;
15248 	s32 *dst_smax = &dst_reg->s32_max_value;
15249 	s32 src_val = src_reg->s32_min_value; /* non-zero, const divisor */
15250 	s32 res1, res2;
15251 
15252 	/* BPF div specification: S32_MIN / -1 = S32_MIN */
15253 	if (*dst_smin == S32_MIN && src_val == -1) {
15254 		/*
15255 		 * If the dividend range contains more than just S32_MIN,
15256 		 * we cannot precisely track the result, so it becomes unbounded.
15257 		 * e.g., [S32_MIN, S32_MIN+10]/(-1),
15258 		 *     = {S32_MIN} U [-(S32_MIN+10), -(S32_MIN+1)]
15259 		 *     = {S32_MIN} U [S32_MAX-9, S32_MAX] = [S32_MIN, S32_MAX]
15260 		 * Otherwise (if dividend is exactly S32_MIN), result remains S32_MIN.
15261 		 */
15262 		if (*dst_smax != S32_MIN) {
15263 			*dst_smin = S32_MIN;
15264 			*dst_smax = S32_MAX;
15265 		}
15266 		goto reset;
15267 	}
15268 
15269 	res1 = *dst_smin / src_val;
15270 	res2 = *dst_smax / src_val;
15271 	*dst_smin = min(res1, res2);
15272 	*dst_smax = max(res1, res2);
15273 
15274 reset:
15275 	/* Reset other ranges/tnum to unbounded/unknown. */
15276 	dst_reg->u32_min_value = 0;
15277 	dst_reg->u32_max_value = U32_MAX;
15278 	reset_reg64_and_tnum(dst_reg);
15279 }
15280 
15281 static void scalar_min_max_sdiv(struct bpf_reg_state *dst_reg,
15282 				struct bpf_reg_state *src_reg)
15283 {
15284 	s64 *dst_smin = &dst_reg->smin_value;
15285 	s64 *dst_smax = &dst_reg->smax_value;
15286 	s64 src_val = src_reg->smin_value; /* non-zero, const divisor */
15287 	s64 res1, res2;
15288 
15289 	/* BPF div specification: S64_MIN / -1 = S64_MIN */
15290 	if (*dst_smin == S64_MIN && src_val == -1) {
15291 		/*
15292 		 * If the dividend range contains more than just S64_MIN,
15293 		 * we cannot precisely track the result, so it becomes unbounded.
15294 		 * e.g., [S64_MIN, S64_MIN+10]/(-1),
15295 		 *     = {S64_MIN} U [-(S64_MIN+10), -(S64_MIN+1)]
15296 		 *     = {S64_MIN} U [S64_MAX-9, S64_MAX] = [S64_MIN, S64_MAX]
15297 		 * Otherwise (if dividend is exactly S64_MIN), result remains S64_MIN.
15298 		 */
15299 		if (*dst_smax != S64_MIN) {
15300 			*dst_smin = S64_MIN;
15301 			*dst_smax = S64_MAX;
15302 		}
15303 		goto reset;
15304 	}
15305 
15306 	res1 = div64_s64(*dst_smin, src_val);
15307 	res2 = div64_s64(*dst_smax, src_val);
15308 	*dst_smin = min(res1, res2);
15309 	*dst_smax = max(res1, res2);
15310 
15311 reset:
15312 	/* Reset other ranges/tnum to unbounded/unknown. */
15313 	dst_reg->umin_value = 0;
15314 	dst_reg->umax_value = U64_MAX;
15315 	reset_reg32_and_tnum(dst_reg);
15316 }
15317 
15318 static void scalar32_min_max_umod(struct bpf_reg_state *dst_reg,
15319 				  struct bpf_reg_state *src_reg)
15320 {
15321 	u32 *dst_umin = &dst_reg->u32_min_value;
15322 	u32 *dst_umax = &dst_reg->u32_max_value;
15323 	u32 src_val = src_reg->u32_min_value; /* non-zero, const divisor */
15324 	u32 res_max = src_val - 1;
15325 
15326 	/*
15327 	 * If dst_umax <= res_max, the result remains unchanged.
15328 	 * e.g., [2, 5] % 10 = [2, 5].
15329 	 */
15330 	if (*dst_umax <= res_max)
15331 		return;
15332 
15333 	*dst_umin = 0;
15334 	*dst_umax = min(*dst_umax, res_max);
15335 
15336 	/* Reset other ranges/tnum to unbounded/unknown. */
15337 	dst_reg->s32_min_value = S32_MIN;
15338 	dst_reg->s32_max_value = S32_MAX;
15339 	reset_reg64_and_tnum(dst_reg);
15340 }
15341 
15342 static void scalar_min_max_umod(struct bpf_reg_state *dst_reg,
15343 				struct bpf_reg_state *src_reg)
15344 {
15345 	u64 *dst_umin = &dst_reg->umin_value;
15346 	u64 *dst_umax = &dst_reg->umax_value;
15347 	u64 src_val = src_reg->umin_value; /* non-zero, const divisor */
15348 	u64 res_max = src_val - 1;
15349 
15350 	/*
15351 	 * If dst_umax <= res_max, the result remains unchanged.
15352 	 * e.g., [2, 5] % 10 = [2, 5].
15353 	 */
15354 	if (*dst_umax <= res_max)
15355 		return;
15356 
15357 	*dst_umin = 0;
15358 	*dst_umax = min(*dst_umax, res_max);
15359 
15360 	/* Reset other ranges/tnum to unbounded/unknown. */
15361 	dst_reg->smin_value = S64_MIN;
15362 	dst_reg->smax_value = S64_MAX;
15363 	reset_reg32_and_tnum(dst_reg);
15364 }
15365 
15366 static void scalar32_min_max_smod(struct bpf_reg_state *dst_reg,
15367 				  struct bpf_reg_state *src_reg)
15368 {
15369 	s32 *dst_smin = &dst_reg->s32_min_value;
15370 	s32 *dst_smax = &dst_reg->s32_max_value;
15371 	s32 src_val = src_reg->s32_min_value; /* non-zero, const divisor */
15372 
15373 	/*
15374 	 * Safe absolute value calculation:
15375 	 * If src_val == S32_MIN (-2147483648), src_abs becomes 2147483648.
15376 	 * Here use unsigned integer to avoid overflow.
15377 	 */
15378 	u32 src_abs = (src_val > 0) ? (u32)src_val : -(u32)src_val;
15379 
15380 	/*
15381 	 * Calculate the maximum possible absolute value of the result.
15382 	 * Even if src_abs is 2147483648 (S32_MIN), subtracting 1 gives
15383 	 * 2147483647 (S32_MAX), which fits perfectly in s32.
15384 	 */
15385 	s32 res_max_abs = src_abs - 1;
15386 
15387 	/*
15388 	 * If the dividend is already within the result range,
15389 	 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5].
15390 	 */
15391 	if (*dst_smin >= -res_max_abs && *dst_smax <= res_max_abs)
15392 		return;
15393 
15394 	/* General case: result has the same sign as the dividend. */
15395 	if (*dst_smin >= 0) {
15396 		*dst_smin = 0;
15397 		*dst_smax = min(*dst_smax, res_max_abs);
15398 	} else if (*dst_smax <= 0) {
15399 		*dst_smax = 0;
15400 		*dst_smin = max(*dst_smin, -res_max_abs);
15401 	} else {
15402 		*dst_smin = -res_max_abs;
15403 		*dst_smax = res_max_abs;
15404 	}
15405 
15406 	/* Reset other ranges/tnum to unbounded/unknown. */
15407 	dst_reg->u32_min_value = 0;
15408 	dst_reg->u32_max_value = U32_MAX;
15409 	reset_reg64_and_tnum(dst_reg);
15410 }
15411 
15412 static void scalar_min_max_smod(struct bpf_reg_state *dst_reg,
15413 				struct bpf_reg_state *src_reg)
15414 {
15415 	s64 *dst_smin = &dst_reg->smin_value;
15416 	s64 *dst_smax = &dst_reg->smax_value;
15417 	s64 src_val = src_reg->smin_value; /* non-zero, const divisor */
15418 
15419 	/*
15420 	 * Safe absolute value calculation:
15421 	 * If src_val == S64_MIN (-2^63), src_abs becomes 2^63.
15422 	 * Here use unsigned integer to avoid overflow.
15423 	 */
15424 	u64 src_abs = (src_val > 0) ? (u64)src_val : -(u64)src_val;
15425 
15426 	/*
15427 	 * Calculate the maximum possible absolute value of the result.
15428 	 * Even if src_abs is 2^63 (S64_MIN), subtracting 1 gives
15429 	 * 2^63 - 1 (S64_MAX), which fits perfectly in s64.
15430 	 */
15431 	s64 res_max_abs = src_abs - 1;
15432 
15433 	/*
15434 	 * If the dividend is already within the result range,
15435 	 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5].
15436 	 */
15437 	if (*dst_smin >= -res_max_abs && *dst_smax <= res_max_abs)
15438 		return;
15439 
15440 	/* General case: result has the same sign as the dividend. */
15441 	if (*dst_smin >= 0) {
15442 		*dst_smin = 0;
15443 		*dst_smax = min(*dst_smax, res_max_abs);
15444 	} else if (*dst_smax <= 0) {
15445 		*dst_smax = 0;
15446 		*dst_smin = max(*dst_smin, -res_max_abs);
15447 	} else {
15448 		*dst_smin = -res_max_abs;
15449 		*dst_smax = res_max_abs;
15450 	}
15451 
15452 	/* Reset other ranges/tnum to unbounded/unknown. */
15453 	dst_reg->umin_value = 0;
15454 	dst_reg->umax_value = U64_MAX;
15455 	reset_reg32_and_tnum(dst_reg);
15456 }
15457 
15458 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
15459 				 struct bpf_reg_state *src_reg)
15460 {
15461 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15462 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15463 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15464 	u32 umax_val = src_reg->u32_max_value;
15465 
15466 	if (src_known && dst_known) {
15467 		__mark_reg32_known(dst_reg, var32_off.value);
15468 		return;
15469 	}
15470 
15471 	/* We get our minimum from the var_off, since that's inherently
15472 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
15473 	 */
15474 	dst_reg->u32_min_value = var32_off.value;
15475 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
15476 
15477 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15478 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15479 	 */
15480 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15481 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15482 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15483 	} else {
15484 		dst_reg->s32_min_value = S32_MIN;
15485 		dst_reg->s32_max_value = S32_MAX;
15486 	}
15487 }
15488 
15489 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
15490 			       struct bpf_reg_state *src_reg)
15491 {
15492 	bool src_known = tnum_is_const(src_reg->var_off);
15493 	bool dst_known = tnum_is_const(dst_reg->var_off);
15494 	u64 umax_val = src_reg->umax_value;
15495 
15496 	if (src_known && dst_known) {
15497 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15498 		return;
15499 	}
15500 
15501 	/* We get our minimum from the var_off, since that's inherently
15502 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
15503 	 */
15504 	dst_reg->umin_value = dst_reg->var_off.value;
15505 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
15506 
15507 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15508 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15509 	 */
15510 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15511 		dst_reg->smin_value = dst_reg->umin_value;
15512 		dst_reg->smax_value = dst_reg->umax_value;
15513 	} else {
15514 		dst_reg->smin_value = S64_MIN;
15515 		dst_reg->smax_value = S64_MAX;
15516 	}
15517 	/* We may learn something more from the var_off */
15518 	__update_reg_bounds(dst_reg);
15519 }
15520 
15521 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
15522 				struct bpf_reg_state *src_reg)
15523 {
15524 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15525 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15526 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15527 	u32 umin_val = src_reg->u32_min_value;
15528 
15529 	if (src_known && dst_known) {
15530 		__mark_reg32_known(dst_reg, var32_off.value);
15531 		return;
15532 	}
15533 
15534 	/* We get our maximum from the var_off, and our minimum is the
15535 	 * maximum of the operands' minima
15536 	 */
15537 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
15538 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15539 
15540 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15541 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15542 	 */
15543 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15544 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15545 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15546 	} else {
15547 		dst_reg->s32_min_value = S32_MIN;
15548 		dst_reg->s32_max_value = S32_MAX;
15549 	}
15550 }
15551 
15552 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
15553 			      struct bpf_reg_state *src_reg)
15554 {
15555 	bool src_known = tnum_is_const(src_reg->var_off);
15556 	bool dst_known = tnum_is_const(dst_reg->var_off);
15557 	u64 umin_val = src_reg->umin_value;
15558 
15559 	if (src_known && dst_known) {
15560 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15561 		return;
15562 	}
15563 
15564 	/* We get our maximum from the var_off, and our minimum is the
15565 	 * maximum of the operands' minima
15566 	 */
15567 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
15568 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15569 
15570 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15571 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15572 	 */
15573 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15574 		dst_reg->smin_value = dst_reg->umin_value;
15575 		dst_reg->smax_value = dst_reg->umax_value;
15576 	} else {
15577 		dst_reg->smin_value = S64_MIN;
15578 		dst_reg->smax_value = S64_MAX;
15579 	}
15580 	/* We may learn something more from the var_off */
15581 	__update_reg_bounds(dst_reg);
15582 }
15583 
15584 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
15585 				 struct bpf_reg_state *src_reg)
15586 {
15587 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15588 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15589 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15590 
15591 	if (src_known && dst_known) {
15592 		__mark_reg32_known(dst_reg, var32_off.value);
15593 		return;
15594 	}
15595 
15596 	/* We get both minimum and maximum from the var32_off. */
15597 	dst_reg->u32_min_value = var32_off.value;
15598 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15599 
15600 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15601 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15602 	 */
15603 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15604 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15605 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15606 	} else {
15607 		dst_reg->s32_min_value = S32_MIN;
15608 		dst_reg->s32_max_value = S32_MAX;
15609 	}
15610 }
15611 
15612 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
15613 			       struct bpf_reg_state *src_reg)
15614 {
15615 	bool src_known = tnum_is_const(src_reg->var_off);
15616 	bool dst_known = tnum_is_const(dst_reg->var_off);
15617 
15618 	if (src_known && dst_known) {
15619 		/* dst_reg->var_off.value has been updated earlier */
15620 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15621 		return;
15622 	}
15623 
15624 	/* We get both minimum and maximum from the var_off. */
15625 	dst_reg->umin_value = dst_reg->var_off.value;
15626 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15627 
15628 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15629 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15630 	 */
15631 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15632 		dst_reg->smin_value = dst_reg->umin_value;
15633 		dst_reg->smax_value = dst_reg->umax_value;
15634 	} else {
15635 		dst_reg->smin_value = S64_MIN;
15636 		dst_reg->smax_value = S64_MAX;
15637 	}
15638 
15639 	__update_reg_bounds(dst_reg);
15640 }
15641 
15642 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15643 				   u64 umin_val, u64 umax_val)
15644 {
15645 	/* We lose all sign bit information (except what we can pick
15646 	 * up from var_off)
15647 	 */
15648 	dst_reg->s32_min_value = S32_MIN;
15649 	dst_reg->s32_max_value = S32_MAX;
15650 	/* If we might shift our top bit out, then we know nothing */
15651 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
15652 		dst_reg->u32_min_value = 0;
15653 		dst_reg->u32_max_value = U32_MAX;
15654 	} else {
15655 		dst_reg->u32_min_value <<= umin_val;
15656 		dst_reg->u32_max_value <<= umax_val;
15657 	}
15658 }
15659 
15660 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15661 				 struct bpf_reg_state *src_reg)
15662 {
15663 	u32 umax_val = src_reg->u32_max_value;
15664 	u32 umin_val = src_reg->u32_min_value;
15665 	/* u32 alu operation will zext upper bits */
15666 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15667 
15668 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15669 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
15670 	/* Not required but being careful mark reg64 bounds as unknown so
15671 	 * that we are forced to pick them up from tnum and zext later and
15672 	 * if some path skips this step we are still safe.
15673 	 */
15674 	__mark_reg64_unbounded(dst_reg);
15675 	__update_reg32_bounds(dst_reg);
15676 }
15677 
15678 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
15679 				   u64 umin_val, u64 umax_val)
15680 {
15681 	/* Special case <<32 because it is a common compiler pattern to sign
15682 	 * extend subreg by doing <<32 s>>32. smin/smax assignments are correct
15683 	 * because s32 bounds don't flip sign when shifting to the left by
15684 	 * 32bits.
15685 	 */
15686 	if (umin_val == 32 && umax_val == 32) {
15687 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
15688 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
15689 	} else {
15690 		dst_reg->smax_value = S64_MAX;
15691 		dst_reg->smin_value = S64_MIN;
15692 	}
15693 
15694 	/* If we might shift our top bit out, then we know nothing */
15695 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
15696 		dst_reg->umin_value = 0;
15697 		dst_reg->umax_value = U64_MAX;
15698 	} else {
15699 		dst_reg->umin_value <<= umin_val;
15700 		dst_reg->umax_value <<= umax_val;
15701 	}
15702 }
15703 
15704 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
15705 			       struct bpf_reg_state *src_reg)
15706 {
15707 	u64 umax_val = src_reg->umax_value;
15708 	u64 umin_val = src_reg->umin_value;
15709 
15710 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
15711 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
15712 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15713 
15714 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
15715 	/* We may learn something more from the var_off */
15716 	__update_reg_bounds(dst_reg);
15717 }
15718 
15719 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
15720 				 struct bpf_reg_state *src_reg)
15721 {
15722 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15723 	u32 umax_val = src_reg->u32_max_value;
15724 	u32 umin_val = src_reg->u32_min_value;
15725 
15726 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15727 	 * be negative, then either:
15728 	 * 1) src_reg might be zero, so the sign bit of the result is
15729 	 *    unknown, so we lose our signed bounds
15730 	 * 2) it's known negative, thus the unsigned bounds capture the
15731 	 *    signed bounds
15732 	 * 3) the signed bounds cross zero, so they tell us nothing
15733 	 *    about the result
15734 	 * If the value in dst_reg is known nonnegative, then again the
15735 	 * unsigned bounds capture the signed bounds.
15736 	 * Thus, in all cases it suffices to blow away our signed bounds
15737 	 * and rely on inferring new ones from the unsigned bounds and
15738 	 * var_off of the result.
15739 	 */
15740 	dst_reg->s32_min_value = S32_MIN;
15741 	dst_reg->s32_max_value = S32_MAX;
15742 
15743 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
15744 	dst_reg->u32_min_value >>= umax_val;
15745 	dst_reg->u32_max_value >>= umin_val;
15746 
15747 	__mark_reg64_unbounded(dst_reg);
15748 	__update_reg32_bounds(dst_reg);
15749 }
15750 
15751 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
15752 			       struct bpf_reg_state *src_reg)
15753 {
15754 	u64 umax_val = src_reg->umax_value;
15755 	u64 umin_val = src_reg->umin_value;
15756 
15757 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15758 	 * be negative, then either:
15759 	 * 1) src_reg might be zero, so the sign bit of the result is
15760 	 *    unknown, so we lose our signed bounds
15761 	 * 2) it's known negative, thus the unsigned bounds capture the
15762 	 *    signed bounds
15763 	 * 3) the signed bounds cross zero, so they tell us nothing
15764 	 *    about the result
15765 	 * If the value in dst_reg is known nonnegative, then again the
15766 	 * unsigned bounds capture the signed bounds.
15767 	 * Thus, in all cases it suffices to blow away our signed bounds
15768 	 * and rely on inferring new ones from the unsigned bounds and
15769 	 * var_off of the result.
15770 	 */
15771 	dst_reg->smin_value = S64_MIN;
15772 	dst_reg->smax_value = S64_MAX;
15773 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
15774 	dst_reg->umin_value >>= umax_val;
15775 	dst_reg->umax_value >>= umin_val;
15776 
15777 	/* Its not easy to operate on alu32 bounds here because it depends
15778 	 * on bits being shifted in. Take easy way out and mark unbounded
15779 	 * so we can recalculate later from tnum.
15780 	 */
15781 	__mark_reg32_unbounded(dst_reg);
15782 	__update_reg_bounds(dst_reg);
15783 }
15784 
15785 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
15786 				  struct bpf_reg_state *src_reg)
15787 {
15788 	u64 umin_val = src_reg->u32_min_value;
15789 
15790 	/* Upon reaching here, src_known is true and
15791 	 * umax_val is equal to umin_val.
15792 	 */
15793 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
15794 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
15795 
15796 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
15797 
15798 	/* blow away the dst_reg umin_value/umax_value and rely on
15799 	 * dst_reg var_off to refine the result.
15800 	 */
15801 	dst_reg->u32_min_value = 0;
15802 	dst_reg->u32_max_value = U32_MAX;
15803 
15804 	__mark_reg64_unbounded(dst_reg);
15805 	__update_reg32_bounds(dst_reg);
15806 }
15807 
15808 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
15809 				struct bpf_reg_state *src_reg)
15810 {
15811 	u64 umin_val = src_reg->umin_value;
15812 
15813 	/* Upon reaching here, src_known is true and umax_val is equal
15814 	 * to umin_val.
15815 	 */
15816 	dst_reg->smin_value >>= umin_val;
15817 	dst_reg->smax_value >>= umin_val;
15818 
15819 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
15820 
15821 	/* blow away the dst_reg umin_value/umax_value and rely on
15822 	 * dst_reg var_off to refine the result.
15823 	 */
15824 	dst_reg->umin_value = 0;
15825 	dst_reg->umax_value = U64_MAX;
15826 
15827 	/* Its not easy to operate on alu32 bounds here because it depends
15828 	 * on bits being shifted in from upper 32-bits. Take easy way out
15829 	 * and mark unbounded so we can recalculate later from tnum.
15830 	 */
15831 	__mark_reg32_unbounded(dst_reg);
15832 	__update_reg_bounds(dst_reg);
15833 }
15834 
15835 static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *insn)
15836 {
15837 	/*
15838 	 * Byte swap operation - update var_off using tnum_bswap.
15839 	 * Three cases:
15840 	 * 1. bswap(16|32|64): opcode=0xd7 (BPF_END | BPF_ALU64 | BPF_TO_LE)
15841 	 *    unconditional swap
15842 	 * 2. to_le(16|32|64): opcode=0xd4 (BPF_END | BPF_ALU | BPF_TO_LE)
15843 	 *    swap on big-endian, truncation or no-op on little-endian
15844 	 * 3. to_be(16|32|64): opcode=0xdc (BPF_END | BPF_ALU | BPF_TO_BE)
15845 	 *    swap on little-endian, truncation or no-op on big-endian
15846 	 */
15847 
15848 	bool alu64 = BPF_CLASS(insn->code) == BPF_ALU64;
15849 	bool to_le = BPF_SRC(insn->code) == BPF_TO_LE;
15850 	bool is_big_endian;
15851 #ifdef CONFIG_CPU_BIG_ENDIAN
15852 	is_big_endian = true;
15853 #else
15854 	is_big_endian = false;
15855 #endif
15856 	/* Apply bswap if alu64 or switch between big-endian and little-endian machines */
15857 	bool need_bswap = alu64 || (to_le == is_big_endian);
15858 
15859 	if (need_bswap) {
15860 		if (insn->imm == 16)
15861 			dst_reg->var_off = tnum_bswap16(dst_reg->var_off);
15862 		else if (insn->imm == 32)
15863 			dst_reg->var_off = tnum_bswap32(dst_reg->var_off);
15864 		else if (insn->imm == 64)
15865 			dst_reg->var_off = tnum_bswap64(dst_reg->var_off);
15866 		/*
15867 		 * Byteswap scrambles the range, so we must reset bounds.
15868 		 * Bounds will be re-derived from the new tnum later.
15869 		 */
15870 		__mark_reg_unbounded(dst_reg);
15871 	}
15872 	/* For bswap16/32, truncate dst register to match the swapped size */
15873 	if (insn->imm == 16 || insn->imm == 32)
15874 		coerce_reg_to_size(dst_reg, insn->imm / 8);
15875 }
15876 
15877 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
15878 					     const struct bpf_reg_state *src_reg)
15879 {
15880 	bool src_is_const = false;
15881 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
15882 
15883 	if (insn_bitness == 32) {
15884 		if (tnum_subreg_is_const(src_reg->var_off)
15885 		    && src_reg->s32_min_value == src_reg->s32_max_value
15886 		    && src_reg->u32_min_value == src_reg->u32_max_value)
15887 			src_is_const = true;
15888 	} else {
15889 		if (tnum_is_const(src_reg->var_off)
15890 		    && src_reg->smin_value == src_reg->smax_value
15891 		    && src_reg->umin_value == src_reg->umax_value)
15892 			src_is_const = true;
15893 	}
15894 
15895 	switch (BPF_OP(insn->code)) {
15896 	case BPF_ADD:
15897 	case BPF_SUB:
15898 	case BPF_NEG:
15899 	case BPF_AND:
15900 	case BPF_XOR:
15901 	case BPF_OR:
15902 	case BPF_MUL:
15903 	case BPF_END:
15904 		return true;
15905 
15906 	/*
15907 	 * Division and modulo operators range is only safe to compute when the
15908 	 * divisor is a constant.
15909 	 */
15910 	case BPF_DIV:
15911 	case BPF_MOD:
15912 		return src_is_const;
15913 
15914 	/* Shift operators range is only computable if shift dimension operand
15915 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
15916 	 * includes shifts by a negative number.
15917 	 */
15918 	case BPF_LSH:
15919 	case BPF_RSH:
15920 	case BPF_ARSH:
15921 		return (src_is_const && src_reg->umax_value < insn_bitness);
15922 	default:
15923 		return false;
15924 	}
15925 }
15926 
15927 static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn,
15928 			      struct bpf_reg_state *dst_reg)
15929 {
15930 	struct bpf_verifier_state *branch;
15931 	struct bpf_reg_state *regs;
15932 	bool alu32;
15933 
15934 	if (dst_reg->smin_value == -1 && dst_reg->smax_value == 0)
15935 		alu32 = false;
15936 	else if (dst_reg->s32_min_value == -1 && dst_reg->s32_max_value == 0)
15937 		alu32 = true;
15938 	else
15939 		return 0;
15940 
15941 	branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
15942 	if (IS_ERR(branch))
15943 		return PTR_ERR(branch);
15944 
15945 	regs = branch->frame[branch->curframe]->regs;
15946 	if (alu32) {
15947 		__mark_reg32_known(&regs[insn->dst_reg], 0);
15948 		__mark_reg32_known(dst_reg, -1ull);
15949 	} else {
15950 		__mark_reg_known(&regs[insn->dst_reg], 0);
15951 		__mark_reg_known(dst_reg, -1ull);
15952 	}
15953 	return 0;
15954 }
15955 
15956 /* WARNING: This function does calculations on 64-bit values, but the actual
15957  * execution may occur on 32-bit values. Therefore, things like bitshifts
15958  * need extra checks in the 32-bit case.
15959  */
15960 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
15961 				      struct bpf_insn *insn,
15962 				      struct bpf_reg_state *dst_reg,
15963 				      struct bpf_reg_state src_reg)
15964 {
15965 	u8 opcode = BPF_OP(insn->code);
15966 	s16 off = insn->off;
15967 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15968 	int ret;
15969 
15970 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
15971 		__mark_reg_unknown(env, dst_reg);
15972 		return 0;
15973 	}
15974 
15975 	if (sanitize_needed(opcode)) {
15976 		ret = sanitize_val_alu(env, insn);
15977 		if (ret < 0)
15978 			return sanitize_err(env, insn, ret, NULL, NULL);
15979 	}
15980 
15981 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
15982 	 * There are two classes of instructions: The first class we track both
15983 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
15984 	 * greatest amount of precision when alu operations are mixed with jmp32
15985 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
15986 	 * and BPF_OR. This is possible because these ops have fairly easy to
15987 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
15988 	 * See alu32 verifier tests for examples. The second class of
15989 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
15990 	 * with regards to tracking sign/unsigned bounds because the bits may
15991 	 * cross subreg boundaries in the alu64 case. When this happens we mark
15992 	 * the reg unbounded in the subreg bound space and use the resulting
15993 	 * tnum to calculate an approximation of the sign/unsigned bounds.
15994 	 */
15995 	switch (opcode) {
15996 	case BPF_ADD:
15997 		scalar32_min_max_add(dst_reg, &src_reg);
15998 		scalar_min_max_add(dst_reg, &src_reg);
15999 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
16000 		break;
16001 	case BPF_SUB:
16002 		scalar32_min_max_sub(dst_reg, &src_reg);
16003 		scalar_min_max_sub(dst_reg, &src_reg);
16004 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
16005 		break;
16006 	case BPF_NEG:
16007 		env->fake_reg[0] = *dst_reg;
16008 		__mark_reg_known(dst_reg, 0);
16009 		scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
16010 		scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
16011 		dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
16012 		break;
16013 	case BPF_MUL:
16014 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
16015 		scalar32_min_max_mul(dst_reg, &src_reg);
16016 		scalar_min_max_mul(dst_reg, &src_reg);
16017 		break;
16018 	case BPF_DIV:
16019 		/* BPF div specification: x / 0 = 0 */
16020 		if ((alu32 && src_reg.u32_min_value == 0) || (!alu32 && src_reg.umin_value == 0)) {
16021 			___mark_reg_known(dst_reg, 0);
16022 			break;
16023 		}
16024 		if (alu32)
16025 			if (off == 1)
16026 				scalar32_min_max_sdiv(dst_reg, &src_reg);
16027 			else
16028 				scalar32_min_max_udiv(dst_reg, &src_reg);
16029 		else
16030 			if (off == 1)
16031 				scalar_min_max_sdiv(dst_reg, &src_reg);
16032 			else
16033 				scalar_min_max_udiv(dst_reg, &src_reg);
16034 		break;
16035 	case BPF_MOD:
16036 		/* BPF mod specification: x % 0 = x */
16037 		if ((alu32 && src_reg.u32_min_value == 0) || (!alu32 && src_reg.umin_value == 0))
16038 			break;
16039 		if (alu32)
16040 			if (off == 1)
16041 				scalar32_min_max_smod(dst_reg, &src_reg);
16042 			else
16043 				scalar32_min_max_umod(dst_reg, &src_reg);
16044 		else
16045 			if (off == 1)
16046 				scalar_min_max_smod(dst_reg, &src_reg);
16047 			else
16048 				scalar_min_max_umod(dst_reg, &src_reg);
16049 		break;
16050 	case BPF_AND:
16051 		if (tnum_is_const(src_reg.var_off)) {
16052 			ret = maybe_fork_scalars(env, insn, dst_reg);
16053 			if (ret)
16054 				return ret;
16055 		}
16056 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
16057 		scalar32_min_max_and(dst_reg, &src_reg);
16058 		scalar_min_max_and(dst_reg, &src_reg);
16059 		break;
16060 	case BPF_OR:
16061 		if (tnum_is_const(src_reg.var_off)) {
16062 			ret = maybe_fork_scalars(env, insn, dst_reg);
16063 			if (ret)
16064 				return ret;
16065 		}
16066 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
16067 		scalar32_min_max_or(dst_reg, &src_reg);
16068 		scalar_min_max_or(dst_reg, &src_reg);
16069 		break;
16070 	case BPF_XOR:
16071 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
16072 		scalar32_min_max_xor(dst_reg, &src_reg);
16073 		scalar_min_max_xor(dst_reg, &src_reg);
16074 		break;
16075 	case BPF_LSH:
16076 		if (alu32)
16077 			scalar32_min_max_lsh(dst_reg, &src_reg);
16078 		else
16079 			scalar_min_max_lsh(dst_reg, &src_reg);
16080 		break;
16081 	case BPF_RSH:
16082 		if (alu32)
16083 			scalar32_min_max_rsh(dst_reg, &src_reg);
16084 		else
16085 			scalar_min_max_rsh(dst_reg, &src_reg);
16086 		break;
16087 	case BPF_ARSH:
16088 		if (alu32)
16089 			scalar32_min_max_arsh(dst_reg, &src_reg);
16090 		else
16091 			scalar_min_max_arsh(dst_reg, &src_reg);
16092 		break;
16093 	case BPF_END:
16094 		scalar_byte_swap(dst_reg, insn);
16095 		break;
16096 	default:
16097 		break;
16098 	}
16099 
16100 	/*
16101 	 * ALU32 ops are zero extended into 64bit register.
16102 	 *
16103 	 * BPF_END is already handled inside the helper (truncation),
16104 	 * so skip zext here to avoid unexpected zero extension.
16105 	 * e.g., le64: opcode=(BPF_END|BPF_ALU|BPF_TO_LE), imm=0x40
16106 	 * This is a 64bit byte swap operation with alu32==true,
16107 	 * but we should not zero extend the result.
16108 	 */
16109 	if (alu32 && opcode != BPF_END)
16110 		zext_32_to_64(dst_reg);
16111 	reg_bounds_sync(dst_reg);
16112 	return 0;
16113 }
16114 
16115 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
16116  * and var_off.
16117  */
16118 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
16119 				   struct bpf_insn *insn)
16120 {
16121 	struct bpf_verifier_state *vstate = env->cur_state;
16122 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
16123 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
16124 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
16125 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
16126 	u8 opcode = BPF_OP(insn->code);
16127 	int err;
16128 
16129 	dst_reg = &regs[insn->dst_reg];
16130 	src_reg = NULL;
16131 
16132 	if (dst_reg->type == PTR_TO_ARENA) {
16133 		struct bpf_insn_aux_data *aux = cur_aux(env);
16134 
16135 		if (BPF_CLASS(insn->code) == BPF_ALU64)
16136 			/*
16137 			 * 32-bit operations zero upper bits automatically.
16138 			 * 64-bit operations need to be converted to 32.
16139 			 */
16140 			aux->needs_zext = true;
16141 
16142 		/* Any arithmetic operations are allowed on arena pointers */
16143 		return 0;
16144 	}
16145 
16146 	if (dst_reg->type != SCALAR_VALUE)
16147 		ptr_reg = dst_reg;
16148 
16149 	if (BPF_SRC(insn->code) == BPF_X) {
16150 		src_reg = &regs[insn->src_reg];
16151 		if (src_reg->type != SCALAR_VALUE) {
16152 			if (dst_reg->type != SCALAR_VALUE) {
16153 				/* Combining two pointers by any ALU op yields
16154 				 * an arbitrary scalar. Disallow all math except
16155 				 * pointer subtraction
16156 				 */
16157 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
16158 					mark_reg_unknown(env, regs, insn->dst_reg);
16159 					return 0;
16160 				}
16161 				verbose(env, "R%d pointer %s pointer prohibited\n",
16162 					insn->dst_reg,
16163 					bpf_alu_string[opcode >> 4]);
16164 				return -EACCES;
16165 			} else {
16166 				/* scalar += pointer
16167 				 * This is legal, but we have to reverse our
16168 				 * src/dest handling in computing the range
16169 				 */
16170 				err = mark_chain_precision(env, insn->dst_reg);
16171 				if (err)
16172 					return err;
16173 				return adjust_ptr_min_max_vals(env, insn,
16174 							       src_reg, dst_reg);
16175 			}
16176 		} else if (ptr_reg) {
16177 			/* pointer += scalar */
16178 			err = mark_chain_precision(env, insn->src_reg);
16179 			if (err)
16180 				return err;
16181 			return adjust_ptr_min_max_vals(env, insn,
16182 						       dst_reg, src_reg);
16183 		} else if (dst_reg->precise) {
16184 			/* if dst_reg is precise, src_reg should be precise as well */
16185 			err = mark_chain_precision(env, insn->src_reg);
16186 			if (err)
16187 				return err;
16188 		}
16189 	} else {
16190 		/* Pretend the src is a reg with a known value, since we only
16191 		 * need to be able to read from this state.
16192 		 */
16193 		off_reg.type = SCALAR_VALUE;
16194 		__mark_reg_known(&off_reg, insn->imm);
16195 		src_reg = &off_reg;
16196 		if (ptr_reg) /* pointer += K */
16197 			return adjust_ptr_min_max_vals(env, insn,
16198 						       ptr_reg, src_reg);
16199 	}
16200 
16201 	/* Got here implies adding two SCALAR_VALUEs */
16202 	if (WARN_ON_ONCE(ptr_reg)) {
16203 		print_verifier_state(env, vstate, vstate->curframe, true);
16204 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
16205 		return -EFAULT;
16206 	}
16207 	if (WARN_ON(!src_reg)) {
16208 		print_verifier_state(env, vstate, vstate->curframe, true);
16209 		verbose(env, "verifier internal error: no src_reg\n");
16210 		return -EFAULT;
16211 	}
16212 	/*
16213 	 * For alu32 linked register tracking, we need to check dst_reg's
16214 	 * umax_value before the ALU operation. After adjust_scalar_min_max_vals(),
16215 	 * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX.
16216 	 */
16217 	u64 dst_umax = dst_reg->umax_value;
16218 
16219 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
16220 	if (err)
16221 		return err;
16222 	/*
16223 	 * Compilers can generate the code
16224 	 * r1 = r2
16225 	 * r1 += 0x1
16226 	 * if r2 < 1000 goto ...
16227 	 * use r1 in memory access
16228 	 * So remember constant delta between r2 and r1 and update r1 after
16229 	 * 'if' condition.
16230 	 */
16231 	if (env->bpf_capable &&
16232 	    (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) &&
16233 	    dst_reg->id && is_reg_const(src_reg, alu32)) {
16234 		u64 val = reg_const_value(src_reg, alu32);
16235 		s32 off;
16236 
16237 		if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX))
16238 			goto clear_id;
16239 
16240 		if (alu32 && (dst_umax > U32_MAX))
16241 			goto clear_id;
16242 
16243 		off = (s32)val;
16244 
16245 		if (BPF_OP(insn->code) == BPF_SUB) {
16246 			/* Negating S32_MIN would overflow */
16247 			if (off == S32_MIN)
16248 				goto clear_id;
16249 			off = -off;
16250 		}
16251 
16252 		if (dst_reg->id & BPF_ADD_CONST) {
16253 			/*
16254 			 * If the register already went through rX += val
16255 			 * we cannot accumulate another val into rx->off.
16256 			 */
16257 clear_id:
16258 			dst_reg->off = 0;
16259 			dst_reg->id = 0;
16260 		} else {
16261 			if (alu32)
16262 				dst_reg->id |= BPF_ADD_CONST32;
16263 			else
16264 				dst_reg->id |= BPF_ADD_CONST64;
16265 			dst_reg->off = off;
16266 		}
16267 	} else {
16268 		/*
16269 		 * Make sure ID is cleared otherwise dst_reg min/max could be
16270 		 * incorrectly propagated into other registers by sync_linked_regs()
16271 		 */
16272 		dst_reg->id = 0;
16273 	}
16274 	return 0;
16275 }
16276 
16277 /* check validity of 32-bit and 64-bit arithmetic operations */
16278 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
16279 {
16280 	struct bpf_reg_state *regs = cur_regs(env);
16281 	u8 opcode = BPF_OP(insn->code);
16282 	int err;
16283 
16284 	if (opcode == BPF_END || opcode == BPF_NEG) {
16285 		if (opcode == BPF_NEG) {
16286 			if (BPF_SRC(insn->code) != BPF_K ||
16287 			    insn->src_reg != BPF_REG_0 ||
16288 			    insn->off != 0 || insn->imm != 0) {
16289 				verbose(env, "BPF_NEG uses reserved fields\n");
16290 				return -EINVAL;
16291 			}
16292 		} else {
16293 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
16294 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
16295 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
16296 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
16297 				verbose(env, "BPF_END uses reserved fields\n");
16298 				return -EINVAL;
16299 			}
16300 		}
16301 
16302 		/* check src operand */
16303 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16304 		if (err)
16305 			return err;
16306 
16307 		if (is_pointer_value(env, insn->dst_reg)) {
16308 			verbose(env, "R%d pointer arithmetic prohibited\n",
16309 				insn->dst_reg);
16310 			return -EACCES;
16311 		}
16312 
16313 		/* check dest operand */
16314 		if ((opcode == BPF_NEG || opcode == BPF_END) &&
16315 		    regs[insn->dst_reg].type == SCALAR_VALUE) {
16316 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16317 			err = err ?: adjust_scalar_min_max_vals(env, insn,
16318 							 &regs[insn->dst_reg],
16319 							 regs[insn->dst_reg]);
16320 		} else {
16321 			err = check_reg_arg(env, insn->dst_reg, DST_OP);
16322 		}
16323 		if (err)
16324 			return err;
16325 
16326 	} else if (opcode == BPF_MOV) {
16327 
16328 		if (BPF_SRC(insn->code) == BPF_X) {
16329 			if (BPF_CLASS(insn->code) == BPF_ALU) {
16330 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
16331 				    insn->imm) {
16332 					verbose(env, "BPF_MOV uses reserved fields\n");
16333 					return -EINVAL;
16334 				}
16335 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
16336 				if (insn->imm != 1 && insn->imm != 1u << 16) {
16337 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
16338 					return -EINVAL;
16339 				}
16340 				if (!env->prog->aux->arena) {
16341 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
16342 					return -EINVAL;
16343 				}
16344 			} else {
16345 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
16346 				     insn->off != 32) || insn->imm) {
16347 					verbose(env, "BPF_MOV uses reserved fields\n");
16348 					return -EINVAL;
16349 				}
16350 			}
16351 
16352 			/* check src operand */
16353 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
16354 			if (err)
16355 				return err;
16356 		} else {
16357 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
16358 				verbose(env, "BPF_MOV uses reserved fields\n");
16359 				return -EINVAL;
16360 			}
16361 		}
16362 
16363 		/* check dest operand, mark as required later */
16364 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16365 		if (err)
16366 			return err;
16367 
16368 		if (BPF_SRC(insn->code) == BPF_X) {
16369 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
16370 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
16371 
16372 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
16373 				if (insn->imm) {
16374 					/* off == BPF_ADDR_SPACE_CAST */
16375 					mark_reg_unknown(env, regs, insn->dst_reg);
16376 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
16377 						dst_reg->type = PTR_TO_ARENA;
16378 						/* PTR_TO_ARENA is 32-bit */
16379 						dst_reg->subreg_def = env->insn_idx + 1;
16380 					}
16381 				} else if (insn->off == 0) {
16382 					/* case: R1 = R2
16383 					 * copy register state to dest reg
16384 					 */
16385 					assign_scalar_id_before_mov(env, src_reg);
16386 					copy_register_state(dst_reg, src_reg);
16387 					dst_reg->subreg_def = DEF_NOT_SUBREG;
16388 				} else {
16389 					/* case: R1 = (s8, s16 s32)R2 */
16390 					if (is_pointer_value(env, insn->src_reg)) {
16391 						verbose(env,
16392 							"R%d sign-extension part of pointer\n",
16393 							insn->src_reg);
16394 						return -EACCES;
16395 					} else if (src_reg->type == SCALAR_VALUE) {
16396 						bool no_sext;
16397 
16398 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
16399 						if (no_sext)
16400 							assign_scalar_id_before_mov(env, src_reg);
16401 						copy_register_state(dst_reg, src_reg);
16402 						if (!no_sext)
16403 							dst_reg->id = 0;
16404 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
16405 						dst_reg->subreg_def = DEF_NOT_SUBREG;
16406 					} else {
16407 						mark_reg_unknown(env, regs, insn->dst_reg);
16408 					}
16409 				}
16410 			} else {
16411 				/* R1 = (u32) R2 */
16412 				if (is_pointer_value(env, insn->src_reg)) {
16413 					verbose(env,
16414 						"R%d partial copy of pointer\n",
16415 						insn->src_reg);
16416 					return -EACCES;
16417 				} else if (src_reg->type == SCALAR_VALUE) {
16418 					if (insn->off == 0) {
16419 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
16420 
16421 						if (is_src_reg_u32)
16422 							assign_scalar_id_before_mov(env, src_reg);
16423 						copy_register_state(dst_reg, src_reg);
16424 						/* Make sure ID is cleared if src_reg is not in u32
16425 						 * range otherwise dst_reg min/max could be incorrectly
16426 						 * propagated into src_reg by sync_linked_regs()
16427 						 */
16428 						if (!is_src_reg_u32)
16429 							dst_reg->id = 0;
16430 						dst_reg->subreg_def = env->insn_idx + 1;
16431 					} else {
16432 						/* case: W1 = (s8, s16)W2 */
16433 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
16434 
16435 						if (no_sext)
16436 							assign_scalar_id_before_mov(env, src_reg);
16437 						copy_register_state(dst_reg, src_reg);
16438 						if (!no_sext)
16439 							dst_reg->id = 0;
16440 						dst_reg->subreg_def = env->insn_idx + 1;
16441 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
16442 					}
16443 				} else {
16444 					mark_reg_unknown(env, regs,
16445 							 insn->dst_reg);
16446 				}
16447 				zext_32_to_64(dst_reg);
16448 				reg_bounds_sync(dst_reg);
16449 			}
16450 		} else {
16451 			/* case: R = imm
16452 			 * remember the value we stored into this reg
16453 			 */
16454 			/* clear any state __mark_reg_known doesn't set */
16455 			mark_reg_unknown(env, regs, insn->dst_reg);
16456 			regs[insn->dst_reg].type = SCALAR_VALUE;
16457 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
16458 				__mark_reg_known(regs + insn->dst_reg,
16459 						 insn->imm);
16460 			} else {
16461 				__mark_reg_known(regs + insn->dst_reg,
16462 						 (u32)insn->imm);
16463 			}
16464 		}
16465 
16466 	} else if (opcode > BPF_END) {
16467 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
16468 		return -EINVAL;
16469 
16470 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
16471 
16472 		if (BPF_SRC(insn->code) == BPF_X) {
16473 			if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) ||
16474 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
16475 				verbose(env, "BPF_ALU uses reserved fields\n");
16476 				return -EINVAL;
16477 			}
16478 			/* check src1 operand */
16479 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
16480 			if (err)
16481 				return err;
16482 		} else {
16483 			if (insn->src_reg != BPF_REG_0 || (insn->off != 0 && insn->off != 1) ||
16484 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
16485 				verbose(env, "BPF_ALU uses reserved fields\n");
16486 				return -EINVAL;
16487 			}
16488 		}
16489 
16490 		/* check src2 operand */
16491 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16492 		if (err)
16493 			return err;
16494 
16495 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
16496 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
16497 			verbose(env, "div by zero\n");
16498 			return -EINVAL;
16499 		}
16500 
16501 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
16502 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
16503 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
16504 
16505 			if (insn->imm < 0 || insn->imm >= size) {
16506 				verbose(env, "invalid shift %d\n", insn->imm);
16507 				return -EINVAL;
16508 			}
16509 		}
16510 
16511 		/* check dest operand */
16512 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16513 		err = err ?: adjust_reg_min_max_vals(env, insn);
16514 		if (err)
16515 			return err;
16516 	}
16517 
16518 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
16519 }
16520 
16521 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
16522 				   struct bpf_reg_state *dst_reg,
16523 				   enum bpf_reg_type type,
16524 				   bool range_right_open)
16525 {
16526 	struct bpf_func_state *state;
16527 	struct bpf_reg_state *reg;
16528 	int new_range;
16529 
16530 	if (dst_reg->off < 0 ||
16531 	    (dst_reg->off == 0 && range_right_open))
16532 		/* This doesn't give us any range */
16533 		return;
16534 
16535 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
16536 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
16537 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
16538 		 * than pkt_end, but that's because it's also less than pkt.
16539 		 */
16540 		return;
16541 
16542 	new_range = dst_reg->off;
16543 	if (range_right_open)
16544 		new_range++;
16545 
16546 	/* Examples for register markings:
16547 	 *
16548 	 * pkt_data in dst register:
16549 	 *
16550 	 *   r2 = r3;
16551 	 *   r2 += 8;
16552 	 *   if (r2 > pkt_end) goto <handle exception>
16553 	 *   <access okay>
16554 	 *
16555 	 *   r2 = r3;
16556 	 *   r2 += 8;
16557 	 *   if (r2 < pkt_end) goto <access okay>
16558 	 *   <handle exception>
16559 	 *
16560 	 *   Where:
16561 	 *     r2 == dst_reg, pkt_end == src_reg
16562 	 *     r2=pkt(id=n,off=8,r=0)
16563 	 *     r3=pkt(id=n,off=0,r=0)
16564 	 *
16565 	 * pkt_data in src register:
16566 	 *
16567 	 *   r2 = r3;
16568 	 *   r2 += 8;
16569 	 *   if (pkt_end >= r2) goto <access okay>
16570 	 *   <handle exception>
16571 	 *
16572 	 *   r2 = r3;
16573 	 *   r2 += 8;
16574 	 *   if (pkt_end <= r2) goto <handle exception>
16575 	 *   <access okay>
16576 	 *
16577 	 *   Where:
16578 	 *     pkt_end == dst_reg, r2 == src_reg
16579 	 *     r2=pkt(id=n,off=8,r=0)
16580 	 *     r3=pkt(id=n,off=0,r=0)
16581 	 *
16582 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
16583 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
16584 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
16585 	 * the check.
16586 	 */
16587 
16588 	/* If our ids match, then we must have the same max_value.  And we
16589 	 * don't care about the other reg's fixed offset, since if it's too big
16590 	 * the range won't allow anything.
16591 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
16592 	 */
16593 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
16594 		if (reg->type == type && reg->id == dst_reg->id)
16595 			/* keep the maximum range already checked */
16596 			reg->range = max(reg->range, new_range);
16597 	}));
16598 }
16599 
16600 /*
16601  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
16602  */
16603 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16604 				  u8 opcode, bool is_jmp32)
16605 {
16606 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
16607 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
16608 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
16609 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
16610 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
16611 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
16612 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
16613 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
16614 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
16615 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
16616 
16617 	if (reg1 == reg2) {
16618 		switch (opcode) {
16619 		case BPF_JGE:
16620 		case BPF_JLE:
16621 		case BPF_JSGE:
16622 		case BPF_JSLE:
16623 		case BPF_JEQ:
16624 			return 1;
16625 		case BPF_JGT:
16626 		case BPF_JLT:
16627 		case BPF_JSGT:
16628 		case BPF_JSLT:
16629 		case BPF_JNE:
16630 			return 0;
16631 		case BPF_JSET:
16632 			if (tnum_is_const(t1))
16633 				return t1.value != 0;
16634 			else
16635 				return (smin1 <= 0 && smax1 >= 0) ? -1 : 1;
16636 		default:
16637 			return -1;
16638 		}
16639 	}
16640 
16641 	switch (opcode) {
16642 	case BPF_JEQ:
16643 		/* constants, umin/umax and smin/smax checks would be
16644 		 * redundant in this case because they all should match
16645 		 */
16646 		if (tnum_is_const(t1) && tnum_is_const(t2))
16647 			return t1.value == t2.value;
16648 		if (!tnum_overlap(t1, t2))
16649 			return 0;
16650 		/* non-overlapping ranges */
16651 		if (umin1 > umax2 || umax1 < umin2)
16652 			return 0;
16653 		if (smin1 > smax2 || smax1 < smin2)
16654 			return 0;
16655 		if (!is_jmp32) {
16656 			/* if 64-bit ranges are inconclusive, see if we can
16657 			 * utilize 32-bit subrange knowledge to eliminate
16658 			 * branches that can't be taken a priori
16659 			 */
16660 			if (reg1->u32_min_value > reg2->u32_max_value ||
16661 			    reg1->u32_max_value < reg2->u32_min_value)
16662 				return 0;
16663 			if (reg1->s32_min_value > reg2->s32_max_value ||
16664 			    reg1->s32_max_value < reg2->s32_min_value)
16665 				return 0;
16666 		}
16667 		break;
16668 	case BPF_JNE:
16669 		/* constants, umin/umax and smin/smax checks would be
16670 		 * redundant in this case because they all should match
16671 		 */
16672 		if (tnum_is_const(t1) && tnum_is_const(t2))
16673 			return t1.value != t2.value;
16674 		if (!tnum_overlap(t1, t2))
16675 			return 1;
16676 		/* non-overlapping ranges */
16677 		if (umin1 > umax2 || umax1 < umin2)
16678 			return 1;
16679 		if (smin1 > smax2 || smax1 < smin2)
16680 			return 1;
16681 		if (!is_jmp32) {
16682 			/* if 64-bit ranges are inconclusive, see if we can
16683 			 * utilize 32-bit subrange knowledge to eliminate
16684 			 * branches that can't be taken a priori
16685 			 */
16686 			if (reg1->u32_min_value > reg2->u32_max_value ||
16687 			    reg1->u32_max_value < reg2->u32_min_value)
16688 				return 1;
16689 			if (reg1->s32_min_value > reg2->s32_max_value ||
16690 			    reg1->s32_max_value < reg2->s32_min_value)
16691 				return 1;
16692 		}
16693 		break;
16694 	case BPF_JSET:
16695 		if (!is_reg_const(reg2, is_jmp32)) {
16696 			swap(reg1, reg2);
16697 			swap(t1, t2);
16698 		}
16699 		if (!is_reg_const(reg2, is_jmp32))
16700 			return -1;
16701 		if ((~t1.mask & t1.value) & t2.value)
16702 			return 1;
16703 		if (!((t1.mask | t1.value) & t2.value))
16704 			return 0;
16705 		break;
16706 	case BPF_JGT:
16707 		if (umin1 > umax2)
16708 			return 1;
16709 		else if (umax1 <= umin2)
16710 			return 0;
16711 		break;
16712 	case BPF_JSGT:
16713 		if (smin1 > smax2)
16714 			return 1;
16715 		else if (smax1 <= smin2)
16716 			return 0;
16717 		break;
16718 	case BPF_JLT:
16719 		if (umax1 < umin2)
16720 			return 1;
16721 		else if (umin1 >= umax2)
16722 			return 0;
16723 		break;
16724 	case BPF_JSLT:
16725 		if (smax1 < smin2)
16726 			return 1;
16727 		else if (smin1 >= smax2)
16728 			return 0;
16729 		break;
16730 	case BPF_JGE:
16731 		if (umin1 >= umax2)
16732 			return 1;
16733 		else if (umax1 < umin2)
16734 			return 0;
16735 		break;
16736 	case BPF_JSGE:
16737 		if (smin1 >= smax2)
16738 			return 1;
16739 		else if (smax1 < smin2)
16740 			return 0;
16741 		break;
16742 	case BPF_JLE:
16743 		if (umax1 <= umin2)
16744 			return 1;
16745 		else if (umin1 > umax2)
16746 			return 0;
16747 		break;
16748 	case BPF_JSLE:
16749 		if (smax1 <= smin2)
16750 			return 1;
16751 		else if (smin1 > smax2)
16752 			return 0;
16753 		break;
16754 	}
16755 
16756 	return -1;
16757 }
16758 
16759 static int flip_opcode(u32 opcode)
16760 {
16761 	/* How can we transform "a <op> b" into "b <op> a"? */
16762 	static const u8 opcode_flip[16] = {
16763 		/* these stay the same */
16764 		[BPF_JEQ  >> 4] = BPF_JEQ,
16765 		[BPF_JNE  >> 4] = BPF_JNE,
16766 		[BPF_JSET >> 4] = BPF_JSET,
16767 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
16768 		[BPF_JGE  >> 4] = BPF_JLE,
16769 		[BPF_JGT  >> 4] = BPF_JLT,
16770 		[BPF_JLE  >> 4] = BPF_JGE,
16771 		[BPF_JLT  >> 4] = BPF_JGT,
16772 		[BPF_JSGE >> 4] = BPF_JSLE,
16773 		[BPF_JSGT >> 4] = BPF_JSLT,
16774 		[BPF_JSLE >> 4] = BPF_JSGE,
16775 		[BPF_JSLT >> 4] = BPF_JSGT
16776 	};
16777 	return opcode_flip[opcode >> 4];
16778 }
16779 
16780 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
16781 				   struct bpf_reg_state *src_reg,
16782 				   u8 opcode)
16783 {
16784 	struct bpf_reg_state *pkt;
16785 
16786 	if (src_reg->type == PTR_TO_PACKET_END) {
16787 		pkt = dst_reg;
16788 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
16789 		pkt = src_reg;
16790 		opcode = flip_opcode(opcode);
16791 	} else {
16792 		return -1;
16793 	}
16794 
16795 	if (pkt->range >= 0)
16796 		return -1;
16797 
16798 	switch (opcode) {
16799 	case BPF_JLE:
16800 		/* pkt <= pkt_end */
16801 		fallthrough;
16802 	case BPF_JGT:
16803 		/* pkt > pkt_end */
16804 		if (pkt->range == BEYOND_PKT_END)
16805 			/* pkt has at last one extra byte beyond pkt_end */
16806 			return opcode == BPF_JGT;
16807 		break;
16808 	case BPF_JLT:
16809 		/* pkt < pkt_end */
16810 		fallthrough;
16811 	case BPF_JGE:
16812 		/* pkt >= pkt_end */
16813 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
16814 			return opcode == BPF_JGE;
16815 		break;
16816 	}
16817 	return -1;
16818 }
16819 
16820 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
16821  * and return:
16822  *  1 - branch will be taken and "goto target" will be executed
16823  *  0 - branch will not be taken and fall-through to next insn
16824  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
16825  *      range [0,10]
16826  */
16827 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16828 			   u8 opcode, bool is_jmp32)
16829 {
16830 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
16831 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
16832 
16833 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
16834 		u64 val;
16835 
16836 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
16837 		if (!is_reg_const(reg2, is_jmp32)) {
16838 			opcode = flip_opcode(opcode);
16839 			swap(reg1, reg2);
16840 		}
16841 		/* and ensure that reg2 is a constant */
16842 		if (!is_reg_const(reg2, is_jmp32))
16843 			return -1;
16844 
16845 		if (!reg_not_null(reg1))
16846 			return -1;
16847 
16848 		/* If pointer is valid tests against zero will fail so we can
16849 		 * use this to direct branch taken.
16850 		 */
16851 		val = reg_const_value(reg2, is_jmp32);
16852 		if (val != 0)
16853 			return -1;
16854 
16855 		switch (opcode) {
16856 		case BPF_JEQ:
16857 			return 0;
16858 		case BPF_JNE:
16859 			return 1;
16860 		default:
16861 			return -1;
16862 		}
16863 	}
16864 
16865 	/* now deal with two scalars, but not necessarily constants */
16866 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
16867 }
16868 
16869 /* Opcode that corresponds to a *false* branch condition.
16870  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
16871  */
16872 static u8 rev_opcode(u8 opcode)
16873 {
16874 	switch (opcode) {
16875 	case BPF_JEQ:		return BPF_JNE;
16876 	case BPF_JNE:		return BPF_JEQ;
16877 	/* JSET doesn't have it's reverse opcode in BPF, so add
16878 	 * BPF_X flag to denote the reverse of that operation
16879 	 */
16880 	case BPF_JSET:		return BPF_JSET | BPF_X;
16881 	case BPF_JSET | BPF_X:	return BPF_JSET;
16882 	case BPF_JGE:		return BPF_JLT;
16883 	case BPF_JGT:		return BPF_JLE;
16884 	case BPF_JLE:		return BPF_JGT;
16885 	case BPF_JLT:		return BPF_JGE;
16886 	case BPF_JSGE:		return BPF_JSLT;
16887 	case BPF_JSGT:		return BPF_JSLE;
16888 	case BPF_JSLE:		return BPF_JSGT;
16889 	case BPF_JSLT:		return BPF_JSGE;
16890 	default:		return 0;
16891 	}
16892 }
16893 
16894 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
16895 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16896 				u8 opcode, bool is_jmp32)
16897 {
16898 	struct tnum t;
16899 	u64 val;
16900 
16901 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
16902 	switch (opcode) {
16903 	case BPF_JGE:
16904 	case BPF_JGT:
16905 	case BPF_JSGE:
16906 	case BPF_JSGT:
16907 		opcode = flip_opcode(opcode);
16908 		swap(reg1, reg2);
16909 		break;
16910 	default:
16911 		break;
16912 	}
16913 
16914 	switch (opcode) {
16915 	case BPF_JEQ:
16916 		if (is_jmp32) {
16917 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16918 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16919 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16920 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16921 			reg2->u32_min_value = reg1->u32_min_value;
16922 			reg2->u32_max_value = reg1->u32_max_value;
16923 			reg2->s32_min_value = reg1->s32_min_value;
16924 			reg2->s32_max_value = reg1->s32_max_value;
16925 
16926 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
16927 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16928 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
16929 		} else {
16930 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
16931 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16932 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
16933 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16934 			reg2->umin_value = reg1->umin_value;
16935 			reg2->umax_value = reg1->umax_value;
16936 			reg2->smin_value = reg1->smin_value;
16937 			reg2->smax_value = reg1->smax_value;
16938 
16939 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
16940 			reg2->var_off = reg1->var_off;
16941 		}
16942 		break;
16943 	case BPF_JNE:
16944 		if (!is_reg_const(reg2, is_jmp32))
16945 			swap(reg1, reg2);
16946 		if (!is_reg_const(reg2, is_jmp32))
16947 			break;
16948 
16949 		/* try to recompute the bound of reg1 if reg2 is a const and
16950 		 * is exactly the edge of reg1.
16951 		 */
16952 		val = reg_const_value(reg2, is_jmp32);
16953 		if (is_jmp32) {
16954 			/* u32_min_value is not equal to 0xffffffff at this point,
16955 			 * because otherwise u32_max_value is 0xffffffff as well,
16956 			 * in such a case both reg1 and reg2 would be constants,
16957 			 * jump would be predicted and reg_set_min_max() won't
16958 			 * be called.
16959 			 *
16960 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
16961 			 * below.
16962 			 */
16963 			if (reg1->u32_min_value == (u32)val)
16964 				reg1->u32_min_value++;
16965 			if (reg1->u32_max_value == (u32)val)
16966 				reg1->u32_max_value--;
16967 			if (reg1->s32_min_value == (s32)val)
16968 				reg1->s32_min_value++;
16969 			if (reg1->s32_max_value == (s32)val)
16970 				reg1->s32_max_value--;
16971 		} else {
16972 			if (reg1->umin_value == (u64)val)
16973 				reg1->umin_value++;
16974 			if (reg1->umax_value == (u64)val)
16975 				reg1->umax_value--;
16976 			if (reg1->smin_value == (s64)val)
16977 				reg1->smin_value++;
16978 			if (reg1->smax_value == (s64)val)
16979 				reg1->smax_value--;
16980 		}
16981 		break;
16982 	case BPF_JSET:
16983 		if (!is_reg_const(reg2, is_jmp32))
16984 			swap(reg1, reg2);
16985 		if (!is_reg_const(reg2, is_jmp32))
16986 			break;
16987 		val = reg_const_value(reg2, is_jmp32);
16988 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
16989 		 * requires single bit to learn something useful. E.g., if we
16990 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
16991 		 * are actually set? We can learn something definite only if
16992 		 * it's a single-bit value to begin with.
16993 		 *
16994 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
16995 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
16996 		 * bit 1 is set, which we can readily use in adjustments.
16997 		 */
16998 		if (!is_power_of_2(val))
16999 			break;
17000 		if (is_jmp32) {
17001 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
17002 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
17003 		} else {
17004 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
17005 		}
17006 		break;
17007 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
17008 		if (!is_reg_const(reg2, is_jmp32))
17009 			swap(reg1, reg2);
17010 		if (!is_reg_const(reg2, is_jmp32))
17011 			break;
17012 		val = reg_const_value(reg2, is_jmp32);
17013 		/* Forget the ranges before narrowing tnums, to avoid invariant
17014 		 * violations if we're on a dead branch.
17015 		 */
17016 		__mark_reg_unbounded(reg1);
17017 		if (is_jmp32) {
17018 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
17019 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
17020 		} else {
17021 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
17022 		}
17023 		break;
17024 	case BPF_JLE:
17025 		if (is_jmp32) {
17026 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
17027 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
17028 		} else {
17029 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
17030 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
17031 		}
17032 		break;
17033 	case BPF_JLT:
17034 		if (is_jmp32) {
17035 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
17036 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
17037 		} else {
17038 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
17039 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
17040 		}
17041 		break;
17042 	case BPF_JSLE:
17043 		if (is_jmp32) {
17044 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
17045 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
17046 		} else {
17047 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
17048 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
17049 		}
17050 		break;
17051 	case BPF_JSLT:
17052 		if (is_jmp32) {
17053 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
17054 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
17055 		} else {
17056 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
17057 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
17058 		}
17059 		break;
17060 	default:
17061 		return;
17062 	}
17063 }
17064 
17065 /* Adjusts the register min/max values in the case that the dst_reg and
17066  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
17067  * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
17068  * Technically we can do similar adjustments for pointers to the same object,
17069  * but we don't support that right now.
17070  */
17071 static int reg_set_min_max(struct bpf_verifier_env *env,
17072 			   struct bpf_reg_state *true_reg1,
17073 			   struct bpf_reg_state *true_reg2,
17074 			   struct bpf_reg_state *false_reg1,
17075 			   struct bpf_reg_state *false_reg2,
17076 			   u8 opcode, bool is_jmp32)
17077 {
17078 	int err;
17079 
17080 	/* If either register is a pointer, we can't learn anything about its
17081 	 * variable offset from the compare (unless they were a pointer into
17082 	 * the same object, but we don't bother with that).
17083 	 */
17084 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
17085 		return 0;
17086 
17087 	/* We compute branch direction for same SCALAR_VALUE registers in
17088 	 * is_scalar_branch_taken(). For unknown branch directions (e.g., BPF_JSET)
17089 	 * on the same registers, we don't need to adjust the min/max values.
17090 	 */
17091 	if (false_reg1 == false_reg2)
17092 		return 0;
17093 
17094 	/* fallthrough (FALSE) branch */
17095 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
17096 	reg_bounds_sync(false_reg1);
17097 	reg_bounds_sync(false_reg2);
17098 
17099 	/* jump (TRUE) branch */
17100 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
17101 	reg_bounds_sync(true_reg1);
17102 	reg_bounds_sync(true_reg2);
17103 
17104 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
17105 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
17106 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
17107 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
17108 	return err;
17109 }
17110 
17111 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
17112 				 struct bpf_reg_state *reg, u32 id,
17113 				 bool is_null)
17114 {
17115 	if (type_may_be_null(reg->type) && reg->id == id &&
17116 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
17117 		/* Old offset (both fixed and variable parts) should have been
17118 		 * known-zero, because we don't allow pointer arithmetic on
17119 		 * pointers that might be NULL. If we see this happening, don't
17120 		 * convert the register.
17121 		 *
17122 		 * But in some cases, some helpers that return local kptrs
17123 		 * advance offset for the returned pointer. In those cases, it
17124 		 * is fine to expect to see reg->off.
17125 		 */
17126 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
17127 			return;
17128 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
17129 		    WARN_ON_ONCE(reg->off))
17130 			return;
17131 
17132 		if (is_null) {
17133 			reg->type = SCALAR_VALUE;
17134 			/* We don't need id and ref_obj_id from this point
17135 			 * onwards anymore, thus we should better reset it,
17136 			 * so that state pruning has chances to take effect.
17137 			 */
17138 			reg->id = 0;
17139 			reg->ref_obj_id = 0;
17140 
17141 			return;
17142 		}
17143 
17144 		mark_ptr_not_null_reg(reg);
17145 
17146 		if (!reg_may_point_to_spin_lock(reg)) {
17147 			/* For not-NULL ptr, reg->ref_obj_id will be reset
17148 			 * in release_reference().
17149 			 *
17150 			 * reg->id is still used by spin_lock ptr. Other
17151 			 * than spin_lock ptr type, reg->id can be reset.
17152 			 */
17153 			reg->id = 0;
17154 		}
17155 	}
17156 }
17157 
17158 /* The logic is similar to find_good_pkt_pointers(), both could eventually
17159  * be folded together at some point.
17160  */
17161 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
17162 				  bool is_null)
17163 {
17164 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
17165 	struct bpf_reg_state *regs = state->regs, *reg;
17166 	u32 ref_obj_id = regs[regno].ref_obj_id;
17167 	u32 id = regs[regno].id;
17168 
17169 	if (ref_obj_id && ref_obj_id == id && is_null)
17170 		/* regs[regno] is in the " == NULL" branch.
17171 		 * No one could have freed the reference state before
17172 		 * doing the NULL check.
17173 		 */
17174 		WARN_ON_ONCE(release_reference_nomark(vstate, id));
17175 
17176 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
17177 		mark_ptr_or_null_reg(state, reg, id, is_null);
17178 	}));
17179 }
17180 
17181 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
17182 				   struct bpf_reg_state *dst_reg,
17183 				   struct bpf_reg_state *src_reg,
17184 				   struct bpf_verifier_state *this_branch,
17185 				   struct bpf_verifier_state *other_branch)
17186 {
17187 	if (BPF_SRC(insn->code) != BPF_X)
17188 		return false;
17189 
17190 	/* Pointers are always 64-bit. */
17191 	if (BPF_CLASS(insn->code) == BPF_JMP32)
17192 		return false;
17193 
17194 	switch (BPF_OP(insn->code)) {
17195 	case BPF_JGT:
17196 		if ((dst_reg->type == PTR_TO_PACKET &&
17197 		     src_reg->type == PTR_TO_PACKET_END) ||
17198 		    (dst_reg->type == PTR_TO_PACKET_META &&
17199 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
17200 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
17201 			find_good_pkt_pointers(this_branch, dst_reg,
17202 					       dst_reg->type, false);
17203 			mark_pkt_end(other_branch, insn->dst_reg, true);
17204 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
17205 			    src_reg->type == PTR_TO_PACKET) ||
17206 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
17207 			    src_reg->type == PTR_TO_PACKET_META)) {
17208 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
17209 			find_good_pkt_pointers(other_branch, src_reg,
17210 					       src_reg->type, true);
17211 			mark_pkt_end(this_branch, insn->src_reg, false);
17212 		} else {
17213 			return false;
17214 		}
17215 		break;
17216 	case BPF_JLT:
17217 		if ((dst_reg->type == PTR_TO_PACKET &&
17218 		     src_reg->type == PTR_TO_PACKET_END) ||
17219 		    (dst_reg->type == PTR_TO_PACKET_META &&
17220 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
17221 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
17222 			find_good_pkt_pointers(other_branch, dst_reg,
17223 					       dst_reg->type, true);
17224 			mark_pkt_end(this_branch, insn->dst_reg, false);
17225 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
17226 			    src_reg->type == PTR_TO_PACKET) ||
17227 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
17228 			    src_reg->type == PTR_TO_PACKET_META)) {
17229 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
17230 			find_good_pkt_pointers(this_branch, src_reg,
17231 					       src_reg->type, false);
17232 			mark_pkt_end(other_branch, insn->src_reg, true);
17233 		} else {
17234 			return false;
17235 		}
17236 		break;
17237 	case BPF_JGE:
17238 		if ((dst_reg->type == PTR_TO_PACKET &&
17239 		     src_reg->type == PTR_TO_PACKET_END) ||
17240 		    (dst_reg->type == PTR_TO_PACKET_META &&
17241 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
17242 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
17243 			find_good_pkt_pointers(this_branch, dst_reg,
17244 					       dst_reg->type, true);
17245 			mark_pkt_end(other_branch, insn->dst_reg, false);
17246 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
17247 			    src_reg->type == PTR_TO_PACKET) ||
17248 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
17249 			    src_reg->type == PTR_TO_PACKET_META)) {
17250 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
17251 			find_good_pkt_pointers(other_branch, src_reg,
17252 					       src_reg->type, false);
17253 			mark_pkt_end(this_branch, insn->src_reg, true);
17254 		} else {
17255 			return false;
17256 		}
17257 		break;
17258 	case BPF_JLE:
17259 		if ((dst_reg->type == PTR_TO_PACKET &&
17260 		     src_reg->type == PTR_TO_PACKET_END) ||
17261 		    (dst_reg->type == PTR_TO_PACKET_META &&
17262 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
17263 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
17264 			find_good_pkt_pointers(other_branch, dst_reg,
17265 					       dst_reg->type, false);
17266 			mark_pkt_end(this_branch, insn->dst_reg, true);
17267 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
17268 			    src_reg->type == PTR_TO_PACKET) ||
17269 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
17270 			    src_reg->type == PTR_TO_PACKET_META)) {
17271 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
17272 			find_good_pkt_pointers(this_branch, src_reg,
17273 					       src_reg->type, true);
17274 			mark_pkt_end(other_branch, insn->src_reg, false);
17275 		} else {
17276 			return false;
17277 		}
17278 		break;
17279 	default:
17280 		return false;
17281 	}
17282 
17283 	return true;
17284 }
17285 
17286 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
17287 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
17288 {
17289 	struct linked_reg *e;
17290 
17291 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
17292 		return;
17293 
17294 	e = linked_regs_push(reg_set);
17295 	if (e) {
17296 		e->frameno = frameno;
17297 		e->is_reg = is_reg;
17298 		e->regno = spi_or_reg;
17299 	} else {
17300 		reg->id = 0;
17301 	}
17302 }
17303 
17304 /* For all R being scalar registers or spilled scalar registers
17305  * in verifier state, save R in linked_regs if R->id == id.
17306  * If there are too many Rs sharing same id, reset id for leftover Rs.
17307  */
17308 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id,
17309 				struct linked_regs *linked_regs)
17310 {
17311 	struct bpf_func_state *func;
17312 	struct bpf_reg_state *reg;
17313 	int i, j;
17314 
17315 	id = id & ~BPF_ADD_CONST;
17316 	for (i = vstate->curframe; i >= 0; i--) {
17317 		func = vstate->frame[i];
17318 		for (j = 0; j < BPF_REG_FP; j++) {
17319 			reg = &func->regs[j];
17320 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
17321 		}
17322 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
17323 			if (!is_spilled_reg(&func->stack[j]))
17324 				continue;
17325 			reg = &func->stack[j].spilled_ptr;
17326 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
17327 		}
17328 	}
17329 }
17330 
17331 /* For all R in linked_regs, copy known_reg range into R
17332  * if R->id == known_reg->id.
17333  */
17334 static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate,
17335 			     struct bpf_reg_state *known_reg, struct linked_regs *linked_regs)
17336 {
17337 	struct bpf_reg_state fake_reg;
17338 	struct bpf_reg_state *reg;
17339 	struct linked_reg *e;
17340 	int i;
17341 
17342 	for (i = 0; i < linked_regs->cnt; ++i) {
17343 		e = &linked_regs->entries[i];
17344 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
17345 				: &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
17346 		if (reg->type != SCALAR_VALUE || reg == known_reg)
17347 			continue;
17348 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
17349 			continue;
17350 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
17351 		    reg->off == known_reg->off) {
17352 			s32 saved_subreg_def = reg->subreg_def;
17353 
17354 			copy_register_state(reg, known_reg);
17355 			reg->subreg_def = saved_subreg_def;
17356 		} else {
17357 			s32 saved_subreg_def = reg->subreg_def;
17358 			s32 saved_off = reg->off;
17359 			u32 saved_id = reg->id;
17360 
17361 			fake_reg.type = SCALAR_VALUE;
17362 			__mark_reg_known(&fake_reg, (s64)reg->off - (s64)known_reg->off);
17363 
17364 			/* reg = known_reg; reg += delta */
17365 			copy_register_state(reg, known_reg);
17366 			/*
17367 			 * Must preserve off, id and subreg_def flag,
17368 			 * otherwise another sync_linked_regs() will be incorrect.
17369 			 */
17370 			reg->off = saved_off;
17371 			reg->id = saved_id;
17372 			reg->subreg_def = saved_subreg_def;
17373 
17374 			scalar32_min_max_add(reg, &fake_reg);
17375 			scalar_min_max_add(reg, &fake_reg);
17376 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
17377 			if (known_reg->id & BPF_ADD_CONST32)
17378 				zext_32_to_64(reg);
17379 			reg_bounds_sync(reg);
17380 		}
17381 		if (e->is_reg)
17382 			mark_reg_scratched(env, e->regno);
17383 		else
17384 			mark_stack_slot_scratched(env, e->spi);
17385 	}
17386 }
17387 
17388 static int check_cond_jmp_op(struct bpf_verifier_env *env,
17389 			     struct bpf_insn *insn, int *insn_idx)
17390 {
17391 	struct bpf_verifier_state *this_branch = env->cur_state;
17392 	struct bpf_verifier_state *other_branch;
17393 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
17394 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
17395 	struct bpf_reg_state *eq_branch_regs;
17396 	struct linked_regs linked_regs = {};
17397 	u8 opcode = BPF_OP(insn->code);
17398 	int insn_flags = 0;
17399 	bool is_jmp32;
17400 	int pred = -1;
17401 	int err;
17402 
17403 	/* Only conditional jumps are expected to reach here. */
17404 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
17405 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17406 		return -EINVAL;
17407 	}
17408 
17409 	if (opcode == BPF_JCOND) {
17410 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
17411 		int idx = *insn_idx;
17412 
17413 		if (insn->code != (BPF_JMP | BPF_JCOND) ||
17414 		    insn->src_reg != BPF_MAY_GOTO ||
17415 		    insn->dst_reg || insn->imm) {
17416 			verbose(env, "invalid may_goto imm %d\n", insn->imm);
17417 			return -EINVAL;
17418 		}
17419 		prev_st = find_prev_entry(env, cur_st->parent, idx);
17420 
17421 		/* branch out 'fallthrough' insn as a new state to explore */
17422 		queued_st = push_stack(env, idx + 1, idx, false);
17423 		if (IS_ERR(queued_st))
17424 			return PTR_ERR(queued_st);
17425 
17426 		queued_st->may_goto_depth++;
17427 		if (prev_st)
17428 			widen_imprecise_scalars(env, prev_st, queued_st);
17429 		*insn_idx += insn->off;
17430 		return 0;
17431 	}
17432 
17433 	/* check src2 operand */
17434 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17435 	if (err)
17436 		return err;
17437 
17438 	dst_reg = &regs[insn->dst_reg];
17439 	if (BPF_SRC(insn->code) == BPF_X) {
17440 		if (insn->imm != 0) {
17441 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17442 			return -EINVAL;
17443 		}
17444 
17445 		/* check src1 operand */
17446 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
17447 		if (err)
17448 			return err;
17449 
17450 		src_reg = &regs[insn->src_reg];
17451 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
17452 		    is_pointer_value(env, insn->src_reg)) {
17453 			verbose(env, "R%d pointer comparison prohibited\n",
17454 				insn->src_reg);
17455 			return -EACCES;
17456 		}
17457 
17458 		if (src_reg->type == PTR_TO_STACK)
17459 			insn_flags |= INSN_F_SRC_REG_STACK;
17460 		if (dst_reg->type == PTR_TO_STACK)
17461 			insn_flags |= INSN_F_DST_REG_STACK;
17462 	} else {
17463 		if (insn->src_reg != BPF_REG_0) {
17464 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17465 			return -EINVAL;
17466 		}
17467 		src_reg = &env->fake_reg[0];
17468 		memset(src_reg, 0, sizeof(*src_reg));
17469 		src_reg->type = SCALAR_VALUE;
17470 		__mark_reg_known(src_reg, insn->imm);
17471 
17472 		if (dst_reg->type == PTR_TO_STACK)
17473 			insn_flags |= INSN_F_DST_REG_STACK;
17474 	}
17475 
17476 	if (insn_flags) {
17477 		err = push_jmp_history(env, this_branch, insn_flags, 0);
17478 		if (err)
17479 			return err;
17480 	}
17481 
17482 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
17483 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
17484 	if (pred >= 0) {
17485 		/* If we get here with a dst_reg pointer type it is because
17486 		 * above is_branch_taken() special cased the 0 comparison.
17487 		 */
17488 		if (!__is_pointer_value(false, dst_reg))
17489 			err = mark_chain_precision(env, insn->dst_reg);
17490 		if (BPF_SRC(insn->code) == BPF_X && !err &&
17491 		    !__is_pointer_value(false, src_reg))
17492 			err = mark_chain_precision(env, insn->src_reg);
17493 		if (err)
17494 			return err;
17495 	}
17496 
17497 	if (pred == 1) {
17498 		/* Only follow the goto, ignore fall-through. If needed, push
17499 		 * the fall-through branch for simulation under speculative
17500 		 * execution.
17501 		 */
17502 		if (!env->bypass_spec_v1) {
17503 			err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx);
17504 			if (err < 0)
17505 				return err;
17506 		}
17507 		if (env->log.level & BPF_LOG_LEVEL)
17508 			print_insn_state(env, this_branch, this_branch->curframe);
17509 		*insn_idx += insn->off;
17510 		return 0;
17511 	} else if (pred == 0) {
17512 		/* Only follow the fall-through branch, since that's where the
17513 		 * program will go. If needed, push the goto branch for
17514 		 * simulation under speculative execution.
17515 		 */
17516 		if (!env->bypass_spec_v1) {
17517 			err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1,
17518 							*insn_idx);
17519 			if (err < 0)
17520 				return err;
17521 		}
17522 		if (env->log.level & BPF_LOG_LEVEL)
17523 			print_insn_state(env, this_branch, this_branch->curframe);
17524 		return 0;
17525 	}
17526 
17527 	/* Push scalar registers sharing same ID to jump history,
17528 	 * do this before creating 'other_branch', so that both
17529 	 * 'this_branch' and 'other_branch' share this history
17530 	 * if parent state is created.
17531 	 */
17532 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
17533 		collect_linked_regs(this_branch, src_reg->id, &linked_regs);
17534 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
17535 		collect_linked_regs(this_branch, dst_reg->id, &linked_regs);
17536 	if (linked_regs.cnt > 1) {
17537 		err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs));
17538 		if (err)
17539 			return err;
17540 	}
17541 
17542 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false);
17543 	if (IS_ERR(other_branch))
17544 		return PTR_ERR(other_branch);
17545 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17546 
17547 	if (BPF_SRC(insn->code) == BPF_X) {
17548 		err = reg_set_min_max(env,
17549 				      &other_branch_regs[insn->dst_reg],
17550 				      &other_branch_regs[insn->src_reg],
17551 				      dst_reg, src_reg, opcode, is_jmp32);
17552 	} else /* BPF_SRC(insn->code) == BPF_K */ {
17553 		/* reg_set_min_max() can mangle the fake_reg. Make a copy
17554 		 * so that these are two different memory locations. The
17555 		 * src_reg is not used beyond here in context of K.
17556 		 */
17557 		memcpy(&env->fake_reg[1], &env->fake_reg[0],
17558 		       sizeof(env->fake_reg[0]));
17559 		err = reg_set_min_max(env,
17560 				      &other_branch_regs[insn->dst_reg],
17561 				      &env->fake_reg[0],
17562 				      dst_reg, &env->fake_reg[1],
17563 				      opcode, is_jmp32);
17564 	}
17565 	if (err)
17566 		return err;
17567 
17568 	if (BPF_SRC(insn->code) == BPF_X &&
17569 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
17570 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
17571 		sync_linked_regs(env, this_branch, src_reg, &linked_regs);
17572 		sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg],
17573 				 &linked_regs);
17574 	}
17575 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
17576 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
17577 		sync_linked_regs(env, this_branch, dst_reg, &linked_regs);
17578 		sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg],
17579 				 &linked_regs);
17580 	}
17581 
17582 	/* if one pointer register is compared to another pointer
17583 	 * register check if PTR_MAYBE_NULL could be lifted.
17584 	 * E.g. register A - maybe null
17585 	 *      register B - not null
17586 	 * for JNE A, B, ... - A is not null in the false branch;
17587 	 * for JEQ A, B, ... - A is not null in the true branch.
17588 	 *
17589 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
17590 	 * not need to be null checked by the BPF program, i.e.,
17591 	 * could be null even without PTR_MAYBE_NULL marking, so
17592 	 * only propagate nullness when neither reg is that type.
17593 	 */
17594 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
17595 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
17596 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
17597 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
17598 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
17599 		eq_branch_regs = NULL;
17600 		switch (opcode) {
17601 		case BPF_JEQ:
17602 			eq_branch_regs = other_branch_regs;
17603 			break;
17604 		case BPF_JNE:
17605 			eq_branch_regs = regs;
17606 			break;
17607 		default:
17608 			/* do nothing */
17609 			break;
17610 		}
17611 		if (eq_branch_regs) {
17612 			if (type_may_be_null(src_reg->type))
17613 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
17614 			else
17615 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
17616 		}
17617 	}
17618 
17619 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
17620 	 * NOTE: these optimizations below are related with pointer comparison
17621 	 *       which will never be JMP32.
17622 	 */
17623 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
17624 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
17625 	    type_may_be_null(dst_reg->type)) {
17626 		/* Mark all identical registers in each branch as either
17627 		 * safe or unknown depending R == 0 or R != 0 conditional.
17628 		 */
17629 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
17630 				      opcode == BPF_JNE);
17631 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
17632 				      opcode == BPF_JEQ);
17633 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
17634 					   this_branch, other_branch) &&
17635 		   is_pointer_value(env, insn->dst_reg)) {
17636 		verbose(env, "R%d pointer comparison prohibited\n",
17637 			insn->dst_reg);
17638 		return -EACCES;
17639 	}
17640 	if (env->log.level & BPF_LOG_LEVEL)
17641 		print_insn_state(env, this_branch, this_branch->curframe);
17642 	return 0;
17643 }
17644 
17645 /* verify BPF_LD_IMM64 instruction */
17646 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17647 {
17648 	struct bpf_insn_aux_data *aux = cur_aux(env);
17649 	struct bpf_reg_state *regs = cur_regs(env);
17650 	struct bpf_reg_state *dst_reg;
17651 	struct bpf_map *map;
17652 	int err;
17653 
17654 	if (BPF_SIZE(insn->code) != BPF_DW) {
17655 		verbose(env, "invalid BPF_LD_IMM insn\n");
17656 		return -EINVAL;
17657 	}
17658 	if (insn->off != 0) {
17659 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17660 		return -EINVAL;
17661 	}
17662 
17663 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
17664 	if (err)
17665 		return err;
17666 
17667 	dst_reg = &regs[insn->dst_reg];
17668 	if (insn->src_reg == 0) {
17669 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
17670 
17671 		dst_reg->type = SCALAR_VALUE;
17672 		__mark_reg_known(&regs[insn->dst_reg], imm);
17673 		return 0;
17674 	}
17675 
17676 	/* All special src_reg cases are listed below. From this point onwards
17677 	 * we either succeed and assign a corresponding dst_reg->type after
17678 	 * zeroing the offset, or fail and reject the program.
17679 	 */
17680 	mark_reg_known_zero(env, regs, insn->dst_reg);
17681 
17682 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
17683 		dst_reg->type = aux->btf_var.reg_type;
17684 		switch (base_type(dst_reg->type)) {
17685 		case PTR_TO_MEM:
17686 			dst_reg->mem_size = aux->btf_var.mem_size;
17687 			break;
17688 		case PTR_TO_BTF_ID:
17689 			dst_reg->btf = aux->btf_var.btf;
17690 			dst_reg->btf_id = aux->btf_var.btf_id;
17691 			break;
17692 		default:
17693 			verifier_bug(env, "pseudo btf id: unexpected dst reg type");
17694 			return -EFAULT;
17695 		}
17696 		return 0;
17697 	}
17698 
17699 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
17700 		struct bpf_prog_aux *aux = env->prog->aux;
17701 		u32 subprogno = find_subprog(env,
17702 					     env->insn_idx + insn->imm + 1);
17703 
17704 		if (!aux->func_info) {
17705 			verbose(env, "missing btf func_info\n");
17706 			return -EINVAL;
17707 		}
17708 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
17709 			verbose(env, "callback function not static\n");
17710 			return -EINVAL;
17711 		}
17712 
17713 		dst_reg->type = PTR_TO_FUNC;
17714 		dst_reg->subprogno = subprogno;
17715 		return 0;
17716 	}
17717 
17718 	map = env->used_maps[aux->map_index];
17719 	dst_reg->map_ptr = map;
17720 
17721 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
17722 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
17723 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
17724 			__mark_reg_unknown(env, dst_reg);
17725 			return 0;
17726 		}
17727 		dst_reg->type = PTR_TO_MAP_VALUE;
17728 		dst_reg->off = aux->map_off;
17729 		WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY &&
17730 			     map->max_entries != 1);
17731 		/* We want reg->id to be same (0) as map_value is not distinct */
17732 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
17733 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
17734 		dst_reg->type = CONST_PTR_TO_MAP;
17735 	} else {
17736 		verifier_bug(env, "unexpected src reg value for ldimm64");
17737 		return -EFAULT;
17738 	}
17739 
17740 	return 0;
17741 }
17742 
17743 static bool may_access_skb(enum bpf_prog_type type)
17744 {
17745 	switch (type) {
17746 	case BPF_PROG_TYPE_SOCKET_FILTER:
17747 	case BPF_PROG_TYPE_SCHED_CLS:
17748 	case BPF_PROG_TYPE_SCHED_ACT:
17749 		return true;
17750 	default:
17751 		return false;
17752 	}
17753 }
17754 
17755 /* verify safety of LD_ABS|LD_IND instructions:
17756  * - they can only appear in the programs where ctx == skb
17757  * - since they are wrappers of function calls, they scratch R1-R5 registers,
17758  *   preserve R6-R9, and store return value into R0
17759  *
17760  * Implicit input:
17761  *   ctx == skb == R6 == CTX
17762  *
17763  * Explicit input:
17764  *   SRC == any register
17765  *   IMM == 32-bit immediate
17766  *
17767  * Output:
17768  *   R0 - 8/16/32-bit skb data converted to cpu endianness
17769  */
17770 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
17771 {
17772 	struct bpf_reg_state *regs = cur_regs(env);
17773 	static const int ctx_reg = BPF_REG_6;
17774 	u8 mode = BPF_MODE(insn->code);
17775 	int i, err;
17776 
17777 	if (!may_access_skb(resolve_prog_type(env->prog))) {
17778 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
17779 		return -EINVAL;
17780 	}
17781 
17782 	if (!env->ops->gen_ld_abs) {
17783 		verifier_bug(env, "gen_ld_abs is null");
17784 		return -EFAULT;
17785 	}
17786 
17787 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
17788 	    BPF_SIZE(insn->code) == BPF_DW ||
17789 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
17790 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
17791 		return -EINVAL;
17792 	}
17793 
17794 	/* check whether implicit source operand (register R6) is readable */
17795 	err = check_reg_arg(env, ctx_reg, SRC_OP);
17796 	if (err)
17797 		return err;
17798 
17799 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
17800 	 * gen_ld_abs() may terminate the program at runtime, leading to
17801 	 * reference leak.
17802 	 */
17803 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
17804 	if (err)
17805 		return err;
17806 
17807 	if (regs[ctx_reg].type != PTR_TO_CTX) {
17808 		verbose(env,
17809 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
17810 		return -EINVAL;
17811 	}
17812 
17813 	if (mode == BPF_IND) {
17814 		/* check explicit source operand */
17815 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
17816 		if (err)
17817 			return err;
17818 	}
17819 
17820 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
17821 	if (err < 0)
17822 		return err;
17823 
17824 	/* reset caller saved regs to unreadable */
17825 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
17826 		mark_reg_not_init(env, regs, caller_saved[i]);
17827 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
17828 	}
17829 
17830 	/* mark destination R0 register as readable, since it contains
17831 	 * the value fetched from the packet.
17832 	 * Already marked as written above.
17833 	 */
17834 	mark_reg_unknown(env, regs, BPF_REG_0);
17835 	/* ld_abs load up to 32-bit skb data. */
17836 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
17837 	return 0;
17838 }
17839 
17840 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
17841 {
17842 	const char *exit_ctx = "At program exit";
17843 	struct tnum enforce_attach_type_range = tnum_unknown;
17844 	const struct bpf_prog *prog = env->prog;
17845 	struct bpf_reg_state *reg = reg_state(env, regno);
17846 	struct bpf_retval_range range = retval_range(0, 1);
17847 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
17848 	int err;
17849 	struct bpf_func_state *frame = env->cur_state->frame[0];
17850 	const bool is_subprog = frame->subprogno;
17851 	bool return_32bit = false;
17852 	const struct btf_type *reg_type, *ret_type = NULL;
17853 
17854 	/* LSM and struct_ops func-ptr's return type could be "void" */
17855 	if (!is_subprog || frame->in_exception_callback_fn) {
17856 		switch (prog_type) {
17857 		case BPF_PROG_TYPE_LSM:
17858 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
17859 				/* See below, can be 0 or 0-1 depending on hook. */
17860 				break;
17861 			if (!prog->aux->attach_func_proto->type)
17862 				return 0;
17863 			break;
17864 		case BPF_PROG_TYPE_STRUCT_OPS:
17865 			if (!prog->aux->attach_func_proto->type)
17866 				return 0;
17867 
17868 			if (frame->in_exception_callback_fn)
17869 				break;
17870 
17871 			/* Allow a struct_ops program to return a referenced kptr if it
17872 			 * matches the operator's return type and is in its unmodified
17873 			 * form. A scalar zero (i.e., a null pointer) is also allowed.
17874 			 */
17875 			reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL;
17876 			ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
17877 							prog->aux->attach_func_proto->type,
17878 							NULL);
17879 			if (ret_type && ret_type == reg_type && reg->ref_obj_id)
17880 				return __check_ptr_off_reg(env, reg, regno, false);
17881 			break;
17882 		default:
17883 			break;
17884 		}
17885 	}
17886 
17887 	/* eBPF calling convention is such that R0 is used
17888 	 * to return the value from eBPF program.
17889 	 * Make sure that it's readable at this time
17890 	 * of bpf_exit, which means that program wrote
17891 	 * something into it earlier
17892 	 */
17893 	err = check_reg_arg(env, regno, SRC_OP);
17894 	if (err)
17895 		return err;
17896 
17897 	if (is_pointer_value(env, regno)) {
17898 		verbose(env, "R%d leaks addr as return value\n", regno);
17899 		return -EACCES;
17900 	}
17901 
17902 	if (frame->in_async_callback_fn) {
17903 		exit_ctx = "At async callback return";
17904 		range = frame->callback_ret_range;
17905 		goto enforce_retval;
17906 	}
17907 
17908 	if (is_subprog && !frame->in_exception_callback_fn) {
17909 		if (reg->type != SCALAR_VALUE) {
17910 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
17911 				regno, reg_type_str(env, reg->type));
17912 			return -EINVAL;
17913 		}
17914 		return 0;
17915 	}
17916 
17917 	switch (prog_type) {
17918 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
17919 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
17920 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
17921 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
17922 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
17923 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
17924 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
17925 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
17926 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
17927 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
17928 			range = retval_range(1, 1);
17929 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
17930 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
17931 			range = retval_range(0, 3);
17932 		break;
17933 	case BPF_PROG_TYPE_CGROUP_SKB:
17934 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
17935 			range = retval_range(0, 3);
17936 			enforce_attach_type_range = tnum_range(2, 3);
17937 		}
17938 		break;
17939 	case BPF_PROG_TYPE_CGROUP_SOCK:
17940 	case BPF_PROG_TYPE_SOCK_OPS:
17941 	case BPF_PROG_TYPE_CGROUP_DEVICE:
17942 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
17943 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
17944 		break;
17945 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17946 		if (!env->prog->aux->attach_btf_id)
17947 			return 0;
17948 		range = retval_range(0, 0);
17949 		break;
17950 	case BPF_PROG_TYPE_TRACING:
17951 		switch (env->prog->expected_attach_type) {
17952 		case BPF_TRACE_FENTRY:
17953 		case BPF_TRACE_FEXIT:
17954 		case BPF_TRACE_FSESSION:
17955 			range = retval_range(0, 0);
17956 			break;
17957 		case BPF_TRACE_RAW_TP:
17958 		case BPF_MODIFY_RETURN:
17959 			return 0;
17960 		case BPF_TRACE_ITER:
17961 			break;
17962 		default:
17963 			return -ENOTSUPP;
17964 		}
17965 		break;
17966 	case BPF_PROG_TYPE_KPROBE:
17967 		switch (env->prog->expected_attach_type) {
17968 		case BPF_TRACE_KPROBE_SESSION:
17969 		case BPF_TRACE_UPROBE_SESSION:
17970 			range = retval_range(0, 1);
17971 			break;
17972 		default:
17973 			return 0;
17974 		}
17975 		break;
17976 	case BPF_PROG_TYPE_SK_LOOKUP:
17977 		range = retval_range(SK_DROP, SK_PASS);
17978 		break;
17979 
17980 	case BPF_PROG_TYPE_LSM:
17981 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
17982 			/* no range found, any return value is allowed */
17983 			if (!get_func_retval_range(env->prog, &range))
17984 				return 0;
17985 			/* no restricted range, any return value is allowed */
17986 			if (range.minval == S32_MIN && range.maxval == S32_MAX)
17987 				return 0;
17988 			return_32bit = true;
17989 		} else if (!env->prog->aux->attach_func_proto->type) {
17990 			/* Make sure programs that attach to void
17991 			 * hooks don't try to modify return value.
17992 			 */
17993 			range = retval_range(1, 1);
17994 		}
17995 		break;
17996 
17997 	case BPF_PROG_TYPE_NETFILTER:
17998 		range = retval_range(NF_DROP, NF_ACCEPT);
17999 		break;
18000 	case BPF_PROG_TYPE_STRUCT_OPS:
18001 		if (!ret_type)
18002 			return 0;
18003 		range = retval_range(0, 0);
18004 		break;
18005 	case BPF_PROG_TYPE_EXT:
18006 		/* freplace program can return anything as its return value
18007 		 * depends on the to-be-replaced kernel func or bpf program.
18008 		 */
18009 	default:
18010 		return 0;
18011 	}
18012 
18013 enforce_retval:
18014 	if (reg->type != SCALAR_VALUE) {
18015 		verbose(env, "%s the register R%d is not a known value (%s)\n",
18016 			exit_ctx, regno, reg_type_str(env, reg->type));
18017 		return -EINVAL;
18018 	}
18019 
18020 	err = mark_chain_precision(env, regno);
18021 	if (err)
18022 		return err;
18023 
18024 	if (!retval_range_within(range, reg, return_32bit)) {
18025 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
18026 		if (!is_subprog &&
18027 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
18028 		    prog_type == BPF_PROG_TYPE_LSM &&
18029 		    !prog->aux->attach_func_proto->type)
18030 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
18031 		return -EINVAL;
18032 	}
18033 
18034 	if (!tnum_is_unknown(enforce_attach_type_range) &&
18035 	    tnum_in(enforce_attach_type_range, reg->var_off))
18036 		env->prog->enforce_expected_attach_type = 1;
18037 	return 0;
18038 }
18039 
18040 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off)
18041 {
18042 	struct bpf_subprog_info *subprog;
18043 
18044 	subprog = bpf_find_containing_subprog(env, off);
18045 	subprog->changes_pkt_data = true;
18046 }
18047 
18048 static void mark_subprog_might_sleep(struct bpf_verifier_env *env, int off)
18049 {
18050 	struct bpf_subprog_info *subprog;
18051 
18052 	subprog = bpf_find_containing_subprog(env, off);
18053 	subprog->might_sleep = true;
18054 }
18055 
18056 /* 't' is an index of a call-site.
18057  * 'w' is a callee entry point.
18058  * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED.
18059  * Rely on DFS traversal order and absence of recursive calls to guarantee that
18060  * callee's change_pkt_data marks would be correct at that moment.
18061  */
18062 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)
18063 {
18064 	struct bpf_subprog_info *caller, *callee;
18065 
18066 	caller = bpf_find_containing_subprog(env, t);
18067 	callee = bpf_find_containing_subprog(env, w);
18068 	caller->changes_pkt_data |= callee->changes_pkt_data;
18069 	caller->might_sleep |= callee->might_sleep;
18070 }
18071 
18072 /* non-recursive DFS pseudo code
18073  * 1  procedure DFS-iterative(G,v):
18074  * 2      label v as discovered
18075  * 3      let S be a stack
18076  * 4      S.push(v)
18077  * 5      while S is not empty
18078  * 6            t <- S.peek()
18079  * 7            if t is what we're looking for:
18080  * 8                return t
18081  * 9            for all edges e in G.adjacentEdges(t) do
18082  * 10               if edge e is already labelled
18083  * 11                   continue with the next edge
18084  * 12               w <- G.adjacentVertex(t,e)
18085  * 13               if vertex w is not discovered and not explored
18086  * 14                   label e as tree-edge
18087  * 15                   label w as discovered
18088  * 16                   S.push(w)
18089  * 17                   continue at 5
18090  * 18               else if vertex w is discovered
18091  * 19                   label e as back-edge
18092  * 20               else
18093  * 21                   // vertex w is explored
18094  * 22                   label e as forward- or cross-edge
18095  * 23           label t as explored
18096  * 24           S.pop()
18097  *
18098  * convention:
18099  * 0x10 - discovered
18100  * 0x11 - discovered and fall-through edge labelled
18101  * 0x12 - discovered and fall-through and branch edges labelled
18102  * 0x20 - explored
18103  */
18104 
18105 enum {
18106 	DISCOVERED = 0x10,
18107 	EXPLORED = 0x20,
18108 	FALLTHROUGH = 1,
18109 	BRANCH = 2,
18110 };
18111 
18112 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
18113 {
18114 	env->insn_aux_data[idx].prune_point = true;
18115 }
18116 
18117 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
18118 {
18119 	return env->insn_aux_data[insn_idx].prune_point;
18120 }
18121 
18122 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
18123 {
18124 	env->insn_aux_data[idx].force_checkpoint = true;
18125 }
18126 
18127 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
18128 {
18129 	return env->insn_aux_data[insn_idx].force_checkpoint;
18130 }
18131 
18132 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
18133 {
18134 	env->insn_aux_data[idx].calls_callback = true;
18135 }
18136 
18137 bool bpf_calls_callback(struct bpf_verifier_env *env, int insn_idx)
18138 {
18139 	return env->insn_aux_data[insn_idx].calls_callback;
18140 }
18141 
18142 enum {
18143 	DONE_EXPLORING = 0,
18144 	KEEP_EXPLORING = 1,
18145 };
18146 
18147 /* t, w, e - match pseudo-code above:
18148  * t - index of current instruction
18149  * w - next instruction
18150  * e - edge
18151  */
18152 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
18153 {
18154 	int *insn_stack = env->cfg.insn_stack;
18155 	int *insn_state = env->cfg.insn_state;
18156 
18157 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
18158 		return DONE_EXPLORING;
18159 
18160 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
18161 		return DONE_EXPLORING;
18162 
18163 	if (w < 0 || w >= env->prog->len) {
18164 		verbose_linfo(env, t, "%d: ", t);
18165 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
18166 		return -EINVAL;
18167 	}
18168 
18169 	if (e == BRANCH) {
18170 		/* mark branch target for state pruning */
18171 		mark_prune_point(env, w);
18172 		mark_jmp_point(env, w);
18173 	}
18174 
18175 	if (insn_state[w] == 0) {
18176 		/* tree-edge */
18177 		insn_state[t] = DISCOVERED | e;
18178 		insn_state[w] = DISCOVERED;
18179 		if (env->cfg.cur_stack >= env->prog->len)
18180 			return -E2BIG;
18181 		insn_stack[env->cfg.cur_stack++] = w;
18182 		return KEEP_EXPLORING;
18183 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
18184 		if (env->bpf_capable)
18185 			return DONE_EXPLORING;
18186 		verbose_linfo(env, t, "%d: ", t);
18187 		verbose_linfo(env, w, "%d: ", w);
18188 		verbose(env, "back-edge from insn %d to %d\n", t, w);
18189 		return -EINVAL;
18190 	} else if (insn_state[w] == EXPLORED) {
18191 		/* forward- or cross-edge */
18192 		insn_state[t] = DISCOVERED | e;
18193 	} else {
18194 		verifier_bug(env, "insn state internal bug");
18195 		return -EFAULT;
18196 	}
18197 	return DONE_EXPLORING;
18198 }
18199 
18200 static int visit_func_call_insn(int t, struct bpf_insn *insns,
18201 				struct bpf_verifier_env *env,
18202 				bool visit_callee)
18203 {
18204 	int ret, insn_sz;
18205 	int w;
18206 
18207 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
18208 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
18209 	if (ret)
18210 		return ret;
18211 
18212 	mark_prune_point(env, t + insn_sz);
18213 	/* when we exit from subprog, we need to record non-linear history */
18214 	mark_jmp_point(env, t + insn_sz);
18215 
18216 	if (visit_callee) {
18217 		w = t + insns[t].imm + 1;
18218 		mark_prune_point(env, t);
18219 		merge_callee_effects(env, t, w);
18220 		ret = push_insn(t, w, BRANCH, env);
18221 	}
18222 	return ret;
18223 }
18224 
18225 /* Bitmask with 1s for all caller saved registers */
18226 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
18227 
18228 /* True if do_misc_fixups() replaces calls to helper number 'imm',
18229  * replacement patch is presumed to follow bpf_fastcall contract
18230  * (see mark_fastcall_pattern_for_call() below).
18231  */
18232 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
18233 {
18234 	switch (imm) {
18235 #ifdef CONFIG_X86_64
18236 	case BPF_FUNC_get_smp_processor_id:
18237 #ifdef CONFIG_SMP
18238 	case BPF_FUNC_get_current_task_btf:
18239 	case BPF_FUNC_get_current_task:
18240 #endif
18241 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
18242 #endif
18243 	default:
18244 		return false;
18245 	}
18246 }
18247 
18248 struct call_summary {
18249 	u8 num_params;
18250 	bool is_void;
18251 	bool fastcall;
18252 };
18253 
18254 /* If @call is a kfunc or helper call, fills @cs and returns true,
18255  * otherwise returns false.
18256  */
18257 static bool get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
18258 			     struct call_summary *cs)
18259 {
18260 	struct bpf_kfunc_call_arg_meta meta;
18261 	const struct bpf_func_proto *fn;
18262 	int i;
18263 
18264 	if (bpf_helper_call(call)) {
18265 
18266 		if (get_helper_proto(env, call->imm, &fn) < 0)
18267 			/* error would be reported later */
18268 			return false;
18269 		cs->fastcall = fn->allow_fastcall &&
18270 			       (verifier_inlines_helper_call(env, call->imm) ||
18271 				bpf_jit_inlines_helper_call(call->imm));
18272 		cs->is_void = fn->ret_type == RET_VOID;
18273 		cs->num_params = 0;
18274 		for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
18275 			if (fn->arg_type[i] == ARG_DONTCARE)
18276 				break;
18277 			cs->num_params++;
18278 		}
18279 		return true;
18280 	}
18281 
18282 	if (bpf_pseudo_kfunc_call(call)) {
18283 		int err;
18284 
18285 		err = fetch_kfunc_arg_meta(env, call->imm, call->off, &meta);
18286 		if (err < 0)
18287 			/* error would be reported later */
18288 			return false;
18289 		cs->num_params = btf_type_vlen(meta.func_proto);
18290 		cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
18291 		cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
18292 		return true;
18293 	}
18294 
18295 	return false;
18296 }
18297 
18298 /* LLVM define a bpf_fastcall function attribute.
18299  * This attribute means that function scratches only some of
18300  * the caller saved registers defined by ABI.
18301  * For BPF the set of such registers could be defined as follows:
18302  * - R0 is scratched only if function is non-void;
18303  * - R1-R5 are scratched only if corresponding parameter type is defined
18304  *   in the function prototype.
18305  *
18306  * The contract between kernel and clang allows to simultaneously use
18307  * such functions and maintain backwards compatibility with old
18308  * kernels that don't understand bpf_fastcall calls:
18309  *
18310  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
18311  *   registers are not scratched by the call;
18312  *
18313  * - as a post-processing step, clang visits each bpf_fastcall call and adds
18314  *   spill/fill for every live r0-r5;
18315  *
18316  * - stack offsets used for the spill/fill are allocated as lowest
18317  *   stack offsets in whole function and are not used for any other
18318  *   purposes;
18319  *
18320  * - when kernel loads a program, it looks for such patterns
18321  *   (bpf_fastcall function surrounded by spills/fills) and checks if
18322  *   spill/fill stack offsets are used exclusively in fastcall patterns;
18323  *
18324  * - if so, and if verifier or current JIT inlines the call to the
18325  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
18326  *   spill/fill pairs;
18327  *
18328  * - when old kernel loads a program, presence of spill/fill pairs
18329  *   keeps BPF program valid, albeit slightly less efficient.
18330  *
18331  * For example:
18332  *
18333  *   r1 = 1;
18334  *   r2 = 2;
18335  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
18336  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
18337  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
18338  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
18339  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
18340  *   r0 = r1;                            exit;
18341  *   r0 += r2;
18342  *   exit;
18343  *
18344  * The purpose of mark_fastcall_pattern_for_call is to:
18345  * - look for such patterns;
18346  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
18347  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
18348  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
18349  *   at which bpf_fastcall spill/fill stack slots start;
18350  * - update env->subprog_info[*]->keep_fastcall_stack.
18351  *
18352  * The .fastcall_pattern and .fastcall_stack_off are used by
18353  * check_fastcall_stack_contract() to check if every stack access to
18354  * fastcall spill/fill stack slot originates from spill/fill
18355  * instructions, members of fastcall patterns.
18356  *
18357  * If such condition holds true for a subprogram, fastcall patterns could
18358  * be rewritten by remove_fastcall_spills_fills().
18359  * Otherwise bpf_fastcall patterns are not changed in the subprogram
18360  * (code, presumably, generated by an older clang version).
18361  *
18362  * For example, it is *not* safe to remove spill/fill below:
18363  *
18364  *   r1 = 1;
18365  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
18366  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
18367  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
18368  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
18369  *   r0 += r1;                           exit;
18370  *   exit;
18371  */
18372 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
18373 					   struct bpf_subprog_info *subprog,
18374 					   int insn_idx, s16 lowest_off)
18375 {
18376 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
18377 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
18378 	u32 clobbered_regs_mask;
18379 	struct call_summary cs;
18380 	u32 expected_regs_mask;
18381 	s16 off;
18382 	int i;
18383 
18384 	if (!get_call_summary(env, call, &cs))
18385 		return;
18386 
18387 	/* A bitmask specifying which caller saved registers are clobbered
18388 	 * by a call to a helper/kfunc *as if* this helper/kfunc follows
18389 	 * bpf_fastcall contract:
18390 	 * - includes R0 if function is non-void;
18391 	 * - includes R1-R5 if corresponding parameter has is described
18392 	 *   in the function prototype.
18393 	 */
18394 	clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0);
18395 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
18396 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
18397 
18398 	/* match pairs of form:
18399 	 *
18400 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
18401 	 * ...
18402 	 * call %[to_be_inlined]
18403 	 * ...
18404 	 * rX = *(u64 *)(r10 - Y)
18405 	 */
18406 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
18407 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
18408 			break;
18409 		stx = &insns[insn_idx - i];
18410 		ldx = &insns[insn_idx + i];
18411 		/* must be a stack spill/fill pair */
18412 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
18413 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
18414 		    stx->dst_reg != BPF_REG_10 ||
18415 		    ldx->src_reg != BPF_REG_10)
18416 			break;
18417 		/* must be a spill/fill for the same reg */
18418 		if (stx->src_reg != ldx->dst_reg)
18419 			break;
18420 		/* must be one of the previously unseen registers */
18421 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
18422 			break;
18423 		/* must be a spill/fill for the same expected offset,
18424 		 * no need to check offset alignment, BPF_DW stack access
18425 		 * is always 8-byte aligned.
18426 		 */
18427 		if (stx->off != off || ldx->off != off)
18428 			break;
18429 		expected_regs_mask &= ~BIT(stx->src_reg);
18430 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
18431 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
18432 	}
18433 	if (i == 1)
18434 		return;
18435 
18436 	/* Conditionally set 'fastcall_spills_num' to allow forward
18437 	 * compatibility when more helper functions are marked as
18438 	 * bpf_fastcall at compile time than current kernel supports, e.g:
18439 	 *
18440 	 *   1: *(u64 *)(r10 - 8) = r1
18441 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
18442 	 *   3: r1 = *(u64 *)(r10 - 8)
18443 	 *   4: *(u64 *)(r10 - 8) = r1
18444 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
18445 	 *   6: r1 = *(u64 *)(r10 - 8)
18446 	 *
18447 	 * There is no need to block bpf_fastcall rewrite for such program.
18448 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
18449 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
18450 	 * does not remove spill/fill pair {4,6}.
18451 	 */
18452 	if (cs.fastcall)
18453 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
18454 	else
18455 		subprog->keep_fastcall_stack = 1;
18456 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
18457 }
18458 
18459 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
18460 {
18461 	struct bpf_subprog_info *subprog = env->subprog_info;
18462 	struct bpf_insn *insn;
18463 	s16 lowest_off;
18464 	int s, i;
18465 
18466 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
18467 		/* find lowest stack spill offset used in this subprog */
18468 		lowest_off = 0;
18469 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
18470 			insn = env->prog->insnsi + i;
18471 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
18472 			    insn->dst_reg != BPF_REG_10)
18473 				continue;
18474 			lowest_off = min(lowest_off, insn->off);
18475 		}
18476 		/* use this offset to find fastcall patterns */
18477 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
18478 			insn = env->prog->insnsi + i;
18479 			if (insn->code != (BPF_JMP | BPF_CALL))
18480 				continue;
18481 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
18482 		}
18483 	}
18484 	return 0;
18485 }
18486 
18487 static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem)
18488 {
18489 	size_t new_size = sizeof(struct bpf_iarray) + n_elem * sizeof(old->items[0]);
18490 	struct bpf_iarray *new;
18491 
18492 	new = kvrealloc(old, new_size, GFP_KERNEL_ACCOUNT);
18493 	if (!new) {
18494 		/* this is what callers always want, so simplify the call site */
18495 		kvfree(old);
18496 		return NULL;
18497 	}
18498 
18499 	new->cnt = n_elem;
18500 	return new;
18501 }
18502 
18503 static int copy_insn_array(struct bpf_map *map, u32 start, u32 end, u32 *items)
18504 {
18505 	struct bpf_insn_array_value *value;
18506 	u32 i;
18507 
18508 	for (i = start; i <= end; i++) {
18509 		value = map->ops->map_lookup_elem(map, &i);
18510 		/*
18511 		 * map_lookup_elem of an array map will never return an error,
18512 		 * but not checking it makes some static analysers to worry
18513 		 */
18514 		if (IS_ERR(value))
18515 			return PTR_ERR(value);
18516 		else if (!value)
18517 			return -EINVAL;
18518 		items[i - start] = value->xlated_off;
18519 	}
18520 	return 0;
18521 }
18522 
18523 static int cmp_ptr_to_u32(const void *a, const void *b)
18524 {
18525 	return *(u32 *)a - *(u32 *)b;
18526 }
18527 
18528 static int sort_insn_array_uniq(u32 *items, int cnt)
18529 {
18530 	int unique = 1;
18531 	int i;
18532 
18533 	sort(items, cnt, sizeof(items[0]), cmp_ptr_to_u32, NULL);
18534 
18535 	for (i = 1; i < cnt; i++)
18536 		if (items[i] != items[unique - 1])
18537 			items[unique++] = items[i];
18538 
18539 	return unique;
18540 }
18541 
18542 /*
18543  * sort_unique({map[start], ..., map[end]}) into off
18544  */
18545 static int copy_insn_array_uniq(struct bpf_map *map, u32 start, u32 end, u32 *off)
18546 {
18547 	u32 n = end - start + 1;
18548 	int err;
18549 
18550 	err = copy_insn_array(map, start, end, off);
18551 	if (err)
18552 		return err;
18553 
18554 	return sort_insn_array_uniq(off, n);
18555 }
18556 
18557 /*
18558  * Copy all unique offsets from the map
18559  */
18560 static struct bpf_iarray *jt_from_map(struct bpf_map *map)
18561 {
18562 	struct bpf_iarray *jt;
18563 	int err;
18564 	int n;
18565 
18566 	jt = iarray_realloc(NULL, map->max_entries);
18567 	if (!jt)
18568 		return ERR_PTR(-ENOMEM);
18569 
18570 	n = copy_insn_array_uniq(map, 0, map->max_entries - 1, jt->items);
18571 	if (n < 0) {
18572 		err = n;
18573 		goto err_free;
18574 	}
18575 	if (n == 0) {
18576 		err = -EINVAL;
18577 		goto err_free;
18578 	}
18579 	jt->cnt = n;
18580 	return jt;
18581 
18582 err_free:
18583 	kvfree(jt);
18584 	return ERR_PTR(err);
18585 }
18586 
18587 /*
18588  * Find and collect all maps which fit in the subprog. Return the result as one
18589  * combined jump table in jt->items (allocated with kvcalloc)
18590  */
18591 static struct bpf_iarray *jt_from_subprog(struct bpf_verifier_env *env,
18592 					  int subprog_start, int subprog_end)
18593 {
18594 	struct bpf_iarray *jt = NULL;
18595 	struct bpf_map *map;
18596 	struct bpf_iarray *jt_cur;
18597 	int i;
18598 
18599 	for (i = 0; i < env->insn_array_map_cnt; i++) {
18600 		/*
18601 		 * TODO (when needed): collect only jump tables, not static keys
18602 		 * or maps for indirect calls
18603 		 */
18604 		map = env->insn_array_maps[i];
18605 
18606 		jt_cur = jt_from_map(map);
18607 		if (IS_ERR(jt_cur)) {
18608 			kvfree(jt);
18609 			return jt_cur;
18610 		}
18611 
18612 		/*
18613 		 * This is enough to check one element. The full table is
18614 		 * checked to fit inside the subprog later in create_jt()
18615 		 */
18616 		if (jt_cur->items[0] >= subprog_start && jt_cur->items[0] < subprog_end) {
18617 			u32 old_cnt = jt ? jt->cnt : 0;
18618 			jt = iarray_realloc(jt, old_cnt + jt_cur->cnt);
18619 			if (!jt) {
18620 				kvfree(jt_cur);
18621 				return ERR_PTR(-ENOMEM);
18622 			}
18623 			memcpy(jt->items + old_cnt, jt_cur->items, jt_cur->cnt << 2);
18624 		}
18625 
18626 		kvfree(jt_cur);
18627 	}
18628 
18629 	if (!jt) {
18630 		verbose(env, "no jump tables found for subprog starting at %u\n", subprog_start);
18631 		return ERR_PTR(-EINVAL);
18632 	}
18633 
18634 	jt->cnt = sort_insn_array_uniq(jt->items, jt->cnt);
18635 	return jt;
18636 }
18637 
18638 static struct bpf_iarray *
18639 create_jt(int t, struct bpf_verifier_env *env)
18640 {
18641 	static struct bpf_subprog_info *subprog;
18642 	int subprog_start, subprog_end;
18643 	struct bpf_iarray *jt;
18644 	int i;
18645 
18646 	subprog = bpf_find_containing_subprog(env, t);
18647 	subprog_start = subprog->start;
18648 	subprog_end = (subprog + 1)->start;
18649 	jt = jt_from_subprog(env, subprog_start, subprog_end);
18650 	if (IS_ERR(jt))
18651 		return jt;
18652 
18653 	/* Check that the every element of the jump table fits within the given subprogram */
18654 	for (i = 0; i < jt->cnt; i++) {
18655 		if (jt->items[i] < subprog_start || jt->items[i] >= subprog_end) {
18656 			verbose(env, "jump table for insn %d points outside of the subprog [%u,%u]\n",
18657 					t, subprog_start, subprog_end);
18658 			kvfree(jt);
18659 			return ERR_PTR(-EINVAL);
18660 		}
18661 	}
18662 
18663 	return jt;
18664 }
18665 
18666 /* "conditional jump with N edges" */
18667 static int visit_gotox_insn(int t, struct bpf_verifier_env *env)
18668 {
18669 	int *insn_stack = env->cfg.insn_stack;
18670 	int *insn_state = env->cfg.insn_state;
18671 	bool keep_exploring = false;
18672 	struct bpf_iarray *jt;
18673 	int i, w;
18674 
18675 	jt = env->insn_aux_data[t].jt;
18676 	if (!jt) {
18677 		jt = create_jt(t, env);
18678 		if (IS_ERR(jt))
18679 			return PTR_ERR(jt);
18680 
18681 		env->insn_aux_data[t].jt = jt;
18682 	}
18683 
18684 	mark_prune_point(env, t);
18685 	for (i = 0; i < jt->cnt; i++) {
18686 		w = jt->items[i];
18687 		if (w < 0 || w >= env->prog->len) {
18688 			verbose(env, "indirect jump out of range from insn %d to %d\n", t, w);
18689 			return -EINVAL;
18690 		}
18691 
18692 		mark_jmp_point(env, w);
18693 
18694 		/* EXPLORED || DISCOVERED */
18695 		if (insn_state[w])
18696 			continue;
18697 
18698 		if (env->cfg.cur_stack >= env->prog->len)
18699 			return -E2BIG;
18700 
18701 		insn_stack[env->cfg.cur_stack++] = w;
18702 		insn_state[w] |= DISCOVERED;
18703 		keep_exploring = true;
18704 	}
18705 
18706 	return keep_exploring ? KEEP_EXPLORING : DONE_EXPLORING;
18707 }
18708 
18709 static int visit_tailcall_insn(struct bpf_verifier_env *env, int t)
18710 {
18711 	static struct bpf_subprog_info *subprog;
18712 	struct bpf_iarray *jt;
18713 
18714 	if (env->insn_aux_data[t].jt)
18715 		return 0;
18716 
18717 	jt = iarray_realloc(NULL, 2);
18718 	if (!jt)
18719 		return -ENOMEM;
18720 
18721 	subprog = bpf_find_containing_subprog(env, t);
18722 	jt->items[0] = t + 1;
18723 	jt->items[1] = subprog->exit_idx;
18724 	env->insn_aux_data[t].jt = jt;
18725 	return 0;
18726 }
18727 
18728 /* Visits the instruction at index t and returns one of the following:
18729  *  < 0 - an error occurred
18730  *  DONE_EXPLORING - the instruction was fully explored
18731  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
18732  */
18733 static int visit_insn(int t, struct bpf_verifier_env *env)
18734 {
18735 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
18736 	int ret, off, insn_sz;
18737 
18738 	if (bpf_pseudo_func(insn))
18739 		return visit_func_call_insn(t, insns, env, true);
18740 
18741 	/* All non-branch instructions have a single fall-through edge. */
18742 	if (BPF_CLASS(insn->code) != BPF_JMP &&
18743 	    BPF_CLASS(insn->code) != BPF_JMP32) {
18744 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
18745 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
18746 	}
18747 
18748 	switch (BPF_OP(insn->code)) {
18749 	case BPF_EXIT:
18750 		return DONE_EXPLORING;
18751 
18752 	case BPF_CALL:
18753 		if (is_async_callback_calling_insn(insn))
18754 			/* Mark this call insn as a prune point to trigger
18755 			 * is_state_visited() check before call itself is
18756 			 * processed by __check_func_call(). Otherwise new
18757 			 * async state will be pushed for further exploration.
18758 			 */
18759 			mark_prune_point(env, t);
18760 		/* For functions that invoke callbacks it is not known how many times
18761 		 * callback would be called. Verifier models callback calling functions
18762 		 * by repeatedly visiting callback bodies and returning to origin call
18763 		 * instruction.
18764 		 * In order to stop such iteration verifier needs to identify when a
18765 		 * state identical some state from a previous iteration is reached.
18766 		 * Check below forces creation of checkpoint before callback calling
18767 		 * instruction to allow search for such identical states.
18768 		 */
18769 		if (is_sync_callback_calling_insn(insn)) {
18770 			mark_calls_callback(env, t);
18771 			mark_force_checkpoint(env, t);
18772 			mark_prune_point(env, t);
18773 			mark_jmp_point(env, t);
18774 		}
18775 		if (bpf_helper_call(insn)) {
18776 			const struct bpf_func_proto *fp;
18777 
18778 			ret = get_helper_proto(env, insn->imm, &fp);
18779 			/* If called in a non-sleepable context program will be
18780 			 * rejected anyway, so we should end up with precise
18781 			 * sleepable marks on subprogs, except for dead code
18782 			 * elimination.
18783 			 */
18784 			if (ret == 0 && fp->might_sleep)
18785 				mark_subprog_might_sleep(env, t);
18786 			if (bpf_helper_changes_pkt_data(insn->imm))
18787 				mark_subprog_changes_pkt_data(env, t);
18788 			if (insn->imm == BPF_FUNC_tail_call)
18789 				visit_tailcall_insn(env, t);
18790 		} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18791 			struct bpf_kfunc_call_arg_meta meta;
18792 
18793 			ret = fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta);
18794 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
18795 				mark_prune_point(env, t);
18796 				/* Checking and saving state checkpoints at iter_next() call
18797 				 * is crucial for fast convergence of open-coded iterator loop
18798 				 * logic, so we need to force it. If we don't do that,
18799 				 * is_state_visited() might skip saving a checkpoint, causing
18800 				 * unnecessarily long sequence of not checkpointed
18801 				 * instructions and jumps, leading to exhaustion of jump
18802 				 * history buffer, and potentially other undesired outcomes.
18803 				 * It is expected that with correct open-coded iterators
18804 				 * convergence will happen quickly, so we don't run a risk of
18805 				 * exhausting memory.
18806 				 */
18807 				mark_force_checkpoint(env, t);
18808 			}
18809 			/* Same as helpers, if called in a non-sleepable context
18810 			 * program will be rejected anyway, so we should end up
18811 			 * with precise sleepable marks on subprogs, except for
18812 			 * dead code elimination.
18813 			 */
18814 			if (ret == 0 && is_kfunc_sleepable(&meta))
18815 				mark_subprog_might_sleep(env, t);
18816 			if (ret == 0 && is_kfunc_pkt_changing(&meta))
18817 				mark_subprog_changes_pkt_data(env, t);
18818 		}
18819 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
18820 
18821 	case BPF_JA:
18822 		if (BPF_SRC(insn->code) == BPF_X)
18823 			return visit_gotox_insn(t, env);
18824 
18825 		if (BPF_CLASS(insn->code) == BPF_JMP)
18826 			off = insn->off;
18827 		else
18828 			off = insn->imm;
18829 
18830 		/* unconditional jump with single edge */
18831 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
18832 		if (ret)
18833 			return ret;
18834 
18835 		mark_prune_point(env, t + off + 1);
18836 		mark_jmp_point(env, t + off + 1);
18837 
18838 		return ret;
18839 
18840 	default:
18841 		/* conditional jump with two edges */
18842 		mark_prune_point(env, t);
18843 		if (is_may_goto_insn(insn))
18844 			mark_force_checkpoint(env, t);
18845 
18846 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
18847 		if (ret)
18848 			return ret;
18849 
18850 		return push_insn(t, t + insn->off + 1, BRANCH, env);
18851 	}
18852 }
18853 
18854 /* non-recursive depth-first-search to detect loops in BPF program
18855  * loop == back-edge in directed graph
18856  */
18857 static int check_cfg(struct bpf_verifier_env *env)
18858 {
18859 	int insn_cnt = env->prog->len;
18860 	int *insn_stack, *insn_state;
18861 	int ex_insn_beg, i, ret = 0;
18862 
18863 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
18864 	if (!insn_state)
18865 		return -ENOMEM;
18866 
18867 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
18868 	if (!insn_stack) {
18869 		kvfree(insn_state);
18870 		return -ENOMEM;
18871 	}
18872 
18873 	ex_insn_beg = env->exception_callback_subprog
18874 		      ? env->subprog_info[env->exception_callback_subprog].start
18875 		      : 0;
18876 
18877 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
18878 	insn_stack[0] = 0; /* 0 is the first instruction */
18879 	env->cfg.cur_stack = 1;
18880 
18881 walk_cfg:
18882 	while (env->cfg.cur_stack > 0) {
18883 		int t = insn_stack[env->cfg.cur_stack - 1];
18884 
18885 		ret = visit_insn(t, env);
18886 		switch (ret) {
18887 		case DONE_EXPLORING:
18888 			insn_state[t] = EXPLORED;
18889 			env->cfg.cur_stack--;
18890 			break;
18891 		case KEEP_EXPLORING:
18892 			break;
18893 		default:
18894 			if (ret > 0) {
18895 				verifier_bug(env, "visit_insn internal bug");
18896 				ret = -EFAULT;
18897 			}
18898 			goto err_free;
18899 		}
18900 	}
18901 
18902 	if (env->cfg.cur_stack < 0) {
18903 		verifier_bug(env, "pop stack internal bug");
18904 		ret = -EFAULT;
18905 		goto err_free;
18906 	}
18907 
18908 	if (ex_insn_beg && insn_state[ex_insn_beg] != EXPLORED) {
18909 		insn_state[ex_insn_beg] = DISCOVERED;
18910 		insn_stack[0] = ex_insn_beg;
18911 		env->cfg.cur_stack = 1;
18912 		goto walk_cfg;
18913 	}
18914 
18915 	for (i = 0; i < insn_cnt; i++) {
18916 		struct bpf_insn *insn = &env->prog->insnsi[i];
18917 
18918 		if (insn_state[i] != EXPLORED) {
18919 			verbose(env, "unreachable insn %d\n", i);
18920 			ret = -EINVAL;
18921 			goto err_free;
18922 		}
18923 		if (bpf_is_ldimm64(insn)) {
18924 			if (insn_state[i + 1] != 0) {
18925 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
18926 				ret = -EINVAL;
18927 				goto err_free;
18928 			}
18929 			i++; /* skip second half of ldimm64 */
18930 		}
18931 	}
18932 	ret = 0; /* cfg looks good */
18933 	env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data;
18934 	env->prog->aux->might_sleep = env->subprog_info[0].might_sleep;
18935 
18936 err_free:
18937 	kvfree(insn_state);
18938 	kvfree(insn_stack);
18939 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
18940 	return ret;
18941 }
18942 
18943 /*
18944  * For each subprogram 'i' fill array env->cfg.insn_subprogram sub-range
18945  * [env->subprog_info[i].postorder_start, env->subprog_info[i+1].postorder_start)
18946  * with indices of 'i' instructions in postorder.
18947  */
18948 static int compute_postorder(struct bpf_verifier_env *env)
18949 {
18950 	u32 cur_postorder, i, top, stack_sz, s;
18951 	int *stack = NULL, *postorder = NULL, *state = NULL;
18952 	struct bpf_iarray *succ;
18953 
18954 	postorder = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
18955 	state = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
18956 	stack = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
18957 	if (!postorder || !state || !stack) {
18958 		kvfree(postorder);
18959 		kvfree(state);
18960 		kvfree(stack);
18961 		return -ENOMEM;
18962 	}
18963 	cur_postorder = 0;
18964 	for (i = 0; i < env->subprog_cnt; i++) {
18965 		env->subprog_info[i].postorder_start = cur_postorder;
18966 		stack[0] = env->subprog_info[i].start;
18967 		stack_sz = 1;
18968 		do {
18969 			top = stack[stack_sz - 1];
18970 			state[top] |= DISCOVERED;
18971 			if (state[top] & EXPLORED) {
18972 				postorder[cur_postorder++] = top;
18973 				stack_sz--;
18974 				continue;
18975 			}
18976 			succ = bpf_insn_successors(env, top);
18977 			for (s = 0; s < succ->cnt; ++s) {
18978 				if (!state[succ->items[s]]) {
18979 					stack[stack_sz++] = succ->items[s];
18980 					state[succ->items[s]] |= DISCOVERED;
18981 				}
18982 			}
18983 			state[top] |= EXPLORED;
18984 		} while (stack_sz);
18985 	}
18986 	env->subprog_info[i].postorder_start = cur_postorder;
18987 	env->cfg.insn_postorder = postorder;
18988 	env->cfg.cur_postorder = cur_postorder;
18989 	kvfree(stack);
18990 	kvfree(state);
18991 	return 0;
18992 }
18993 
18994 static int check_abnormal_return(struct bpf_verifier_env *env)
18995 {
18996 	int i;
18997 
18998 	for (i = 1; i < env->subprog_cnt; i++) {
18999 		if (env->subprog_info[i].has_ld_abs) {
19000 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
19001 			return -EINVAL;
19002 		}
19003 		if (env->subprog_info[i].has_tail_call) {
19004 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
19005 			return -EINVAL;
19006 		}
19007 	}
19008 	return 0;
19009 }
19010 
19011 /* The minimum supported BTF func info size */
19012 #define MIN_BPF_FUNCINFO_SIZE	8
19013 #define MAX_FUNCINFO_REC_SIZE	252
19014 
19015 static int check_btf_func_early(struct bpf_verifier_env *env,
19016 				const union bpf_attr *attr,
19017 				bpfptr_t uattr)
19018 {
19019 	u32 krec_size = sizeof(struct bpf_func_info);
19020 	const struct btf_type *type, *func_proto;
19021 	u32 i, nfuncs, urec_size, min_size;
19022 	struct bpf_func_info *krecord;
19023 	struct bpf_prog *prog;
19024 	const struct btf *btf;
19025 	u32 prev_offset = 0;
19026 	bpfptr_t urecord;
19027 	int ret = -ENOMEM;
19028 
19029 	nfuncs = attr->func_info_cnt;
19030 	if (!nfuncs) {
19031 		if (check_abnormal_return(env))
19032 			return -EINVAL;
19033 		return 0;
19034 	}
19035 
19036 	urec_size = attr->func_info_rec_size;
19037 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
19038 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
19039 	    urec_size % sizeof(u32)) {
19040 		verbose(env, "invalid func info rec size %u\n", urec_size);
19041 		return -EINVAL;
19042 	}
19043 
19044 	prog = env->prog;
19045 	btf = prog->aux->btf;
19046 
19047 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
19048 	min_size = min_t(u32, krec_size, urec_size);
19049 
19050 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
19051 	if (!krecord)
19052 		return -ENOMEM;
19053 
19054 	for (i = 0; i < nfuncs; i++) {
19055 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
19056 		if (ret) {
19057 			if (ret == -E2BIG) {
19058 				verbose(env, "nonzero tailing record in func info");
19059 				/* set the size kernel expects so loader can zero
19060 				 * out the rest of the record.
19061 				 */
19062 				if (copy_to_bpfptr_offset(uattr,
19063 							  offsetof(union bpf_attr, func_info_rec_size),
19064 							  &min_size, sizeof(min_size)))
19065 					ret = -EFAULT;
19066 			}
19067 			goto err_free;
19068 		}
19069 
19070 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
19071 			ret = -EFAULT;
19072 			goto err_free;
19073 		}
19074 
19075 		/* check insn_off */
19076 		ret = -EINVAL;
19077 		if (i == 0) {
19078 			if (krecord[i].insn_off) {
19079 				verbose(env,
19080 					"nonzero insn_off %u for the first func info record",
19081 					krecord[i].insn_off);
19082 				goto err_free;
19083 			}
19084 		} else if (krecord[i].insn_off <= prev_offset) {
19085 			verbose(env,
19086 				"same or smaller insn offset (%u) than previous func info record (%u)",
19087 				krecord[i].insn_off, prev_offset);
19088 			goto err_free;
19089 		}
19090 
19091 		/* check type_id */
19092 		type = btf_type_by_id(btf, krecord[i].type_id);
19093 		if (!type || !btf_type_is_func(type)) {
19094 			verbose(env, "invalid type id %d in func info",
19095 				krecord[i].type_id);
19096 			goto err_free;
19097 		}
19098 
19099 		func_proto = btf_type_by_id(btf, type->type);
19100 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
19101 			/* btf_func_check() already verified it during BTF load */
19102 			goto err_free;
19103 
19104 		prev_offset = krecord[i].insn_off;
19105 		bpfptr_add(&urecord, urec_size);
19106 	}
19107 
19108 	prog->aux->func_info = krecord;
19109 	prog->aux->func_info_cnt = nfuncs;
19110 	return 0;
19111 
19112 err_free:
19113 	kvfree(krecord);
19114 	return ret;
19115 }
19116 
19117 static int check_btf_func(struct bpf_verifier_env *env,
19118 			  const union bpf_attr *attr,
19119 			  bpfptr_t uattr)
19120 {
19121 	const struct btf_type *type, *func_proto, *ret_type;
19122 	u32 i, nfuncs, urec_size;
19123 	struct bpf_func_info *krecord;
19124 	struct bpf_func_info_aux *info_aux = NULL;
19125 	struct bpf_prog *prog;
19126 	const struct btf *btf;
19127 	bpfptr_t urecord;
19128 	bool scalar_return;
19129 	int ret = -ENOMEM;
19130 
19131 	nfuncs = attr->func_info_cnt;
19132 	if (!nfuncs) {
19133 		if (check_abnormal_return(env))
19134 			return -EINVAL;
19135 		return 0;
19136 	}
19137 	if (nfuncs != env->subprog_cnt) {
19138 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
19139 		return -EINVAL;
19140 	}
19141 
19142 	urec_size = attr->func_info_rec_size;
19143 
19144 	prog = env->prog;
19145 	btf = prog->aux->btf;
19146 
19147 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
19148 
19149 	krecord = prog->aux->func_info;
19150 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
19151 	if (!info_aux)
19152 		return -ENOMEM;
19153 
19154 	for (i = 0; i < nfuncs; i++) {
19155 		/* check insn_off */
19156 		ret = -EINVAL;
19157 
19158 		if (env->subprog_info[i].start != krecord[i].insn_off) {
19159 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
19160 			goto err_free;
19161 		}
19162 
19163 		/* Already checked type_id */
19164 		type = btf_type_by_id(btf, krecord[i].type_id);
19165 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
19166 		/* Already checked func_proto */
19167 		func_proto = btf_type_by_id(btf, type->type);
19168 
19169 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
19170 		scalar_return =
19171 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
19172 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
19173 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
19174 			goto err_free;
19175 		}
19176 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
19177 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
19178 			goto err_free;
19179 		}
19180 
19181 		bpfptr_add(&urecord, urec_size);
19182 	}
19183 
19184 	prog->aux->func_info_aux = info_aux;
19185 	return 0;
19186 
19187 err_free:
19188 	kfree(info_aux);
19189 	return ret;
19190 }
19191 
19192 static void adjust_btf_func(struct bpf_verifier_env *env)
19193 {
19194 	struct bpf_prog_aux *aux = env->prog->aux;
19195 	int i;
19196 
19197 	if (!aux->func_info)
19198 		return;
19199 
19200 	/* func_info is not available for hidden subprogs */
19201 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
19202 		aux->func_info[i].insn_off = env->subprog_info[i].start;
19203 }
19204 
19205 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
19206 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
19207 
19208 static int check_btf_line(struct bpf_verifier_env *env,
19209 			  const union bpf_attr *attr,
19210 			  bpfptr_t uattr)
19211 {
19212 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
19213 	struct bpf_subprog_info *sub;
19214 	struct bpf_line_info *linfo;
19215 	struct bpf_prog *prog;
19216 	const struct btf *btf;
19217 	bpfptr_t ulinfo;
19218 	int err;
19219 
19220 	nr_linfo = attr->line_info_cnt;
19221 	if (!nr_linfo)
19222 		return 0;
19223 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
19224 		return -EINVAL;
19225 
19226 	rec_size = attr->line_info_rec_size;
19227 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
19228 	    rec_size > MAX_LINEINFO_REC_SIZE ||
19229 	    rec_size & (sizeof(u32) - 1))
19230 		return -EINVAL;
19231 
19232 	/* Need to zero it in case the userspace may
19233 	 * pass in a smaller bpf_line_info object.
19234 	 */
19235 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
19236 			 GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
19237 	if (!linfo)
19238 		return -ENOMEM;
19239 
19240 	prog = env->prog;
19241 	btf = prog->aux->btf;
19242 
19243 	s = 0;
19244 	sub = env->subprog_info;
19245 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
19246 	expected_size = sizeof(struct bpf_line_info);
19247 	ncopy = min_t(u32, expected_size, rec_size);
19248 	for (i = 0; i < nr_linfo; i++) {
19249 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
19250 		if (err) {
19251 			if (err == -E2BIG) {
19252 				verbose(env, "nonzero tailing record in line_info");
19253 				if (copy_to_bpfptr_offset(uattr,
19254 							  offsetof(union bpf_attr, line_info_rec_size),
19255 							  &expected_size, sizeof(expected_size)))
19256 					err = -EFAULT;
19257 			}
19258 			goto err_free;
19259 		}
19260 
19261 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
19262 			err = -EFAULT;
19263 			goto err_free;
19264 		}
19265 
19266 		/*
19267 		 * Check insn_off to ensure
19268 		 * 1) strictly increasing AND
19269 		 * 2) bounded by prog->len
19270 		 *
19271 		 * The linfo[0].insn_off == 0 check logically falls into
19272 		 * the later "missing bpf_line_info for func..." case
19273 		 * because the first linfo[0].insn_off must be the
19274 		 * first sub also and the first sub must have
19275 		 * subprog_info[0].start == 0.
19276 		 */
19277 		if ((i && linfo[i].insn_off <= prev_offset) ||
19278 		    linfo[i].insn_off >= prog->len) {
19279 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
19280 				i, linfo[i].insn_off, prev_offset,
19281 				prog->len);
19282 			err = -EINVAL;
19283 			goto err_free;
19284 		}
19285 
19286 		if (!prog->insnsi[linfo[i].insn_off].code) {
19287 			verbose(env,
19288 				"Invalid insn code at line_info[%u].insn_off\n",
19289 				i);
19290 			err = -EINVAL;
19291 			goto err_free;
19292 		}
19293 
19294 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
19295 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
19296 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
19297 			err = -EINVAL;
19298 			goto err_free;
19299 		}
19300 
19301 		if (s != env->subprog_cnt) {
19302 			if (linfo[i].insn_off == sub[s].start) {
19303 				sub[s].linfo_idx = i;
19304 				s++;
19305 			} else if (sub[s].start < linfo[i].insn_off) {
19306 				verbose(env, "missing bpf_line_info for func#%u\n", s);
19307 				err = -EINVAL;
19308 				goto err_free;
19309 			}
19310 		}
19311 
19312 		prev_offset = linfo[i].insn_off;
19313 		bpfptr_add(&ulinfo, rec_size);
19314 	}
19315 
19316 	if (s != env->subprog_cnt) {
19317 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
19318 			env->subprog_cnt - s, s);
19319 		err = -EINVAL;
19320 		goto err_free;
19321 	}
19322 
19323 	prog->aux->linfo = linfo;
19324 	prog->aux->nr_linfo = nr_linfo;
19325 
19326 	return 0;
19327 
19328 err_free:
19329 	kvfree(linfo);
19330 	return err;
19331 }
19332 
19333 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
19334 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
19335 
19336 static int check_core_relo(struct bpf_verifier_env *env,
19337 			   const union bpf_attr *attr,
19338 			   bpfptr_t uattr)
19339 {
19340 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
19341 	struct bpf_core_relo core_relo = {};
19342 	struct bpf_prog *prog = env->prog;
19343 	const struct btf *btf = prog->aux->btf;
19344 	struct bpf_core_ctx ctx = {
19345 		.log = &env->log,
19346 		.btf = btf,
19347 	};
19348 	bpfptr_t u_core_relo;
19349 	int err;
19350 
19351 	nr_core_relo = attr->core_relo_cnt;
19352 	if (!nr_core_relo)
19353 		return 0;
19354 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
19355 		return -EINVAL;
19356 
19357 	rec_size = attr->core_relo_rec_size;
19358 	if (rec_size < MIN_CORE_RELO_SIZE ||
19359 	    rec_size > MAX_CORE_RELO_SIZE ||
19360 	    rec_size % sizeof(u32))
19361 		return -EINVAL;
19362 
19363 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
19364 	expected_size = sizeof(struct bpf_core_relo);
19365 	ncopy = min_t(u32, expected_size, rec_size);
19366 
19367 	/* Unlike func_info and line_info, copy and apply each CO-RE
19368 	 * relocation record one at a time.
19369 	 */
19370 	for (i = 0; i < nr_core_relo; i++) {
19371 		/* future proofing when sizeof(bpf_core_relo) changes */
19372 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
19373 		if (err) {
19374 			if (err == -E2BIG) {
19375 				verbose(env, "nonzero tailing record in core_relo");
19376 				if (copy_to_bpfptr_offset(uattr,
19377 							  offsetof(union bpf_attr, core_relo_rec_size),
19378 							  &expected_size, sizeof(expected_size)))
19379 					err = -EFAULT;
19380 			}
19381 			break;
19382 		}
19383 
19384 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
19385 			err = -EFAULT;
19386 			break;
19387 		}
19388 
19389 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
19390 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
19391 				i, core_relo.insn_off, prog->len);
19392 			err = -EINVAL;
19393 			break;
19394 		}
19395 
19396 		err = bpf_core_apply(&ctx, &core_relo, i,
19397 				     &prog->insnsi[core_relo.insn_off / 8]);
19398 		if (err)
19399 			break;
19400 		bpfptr_add(&u_core_relo, rec_size);
19401 	}
19402 	return err;
19403 }
19404 
19405 static int check_btf_info_early(struct bpf_verifier_env *env,
19406 				const union bpf_attr *attr,
19407 				bpfptr_t uattr)
19408 {
19409 	struct btf *btf;
19410 	int err;
19411 
19412 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
19413 		if (check_abnormal_return(env))
19414 			return -EINVAL;
19415 		return 0;
19416 	}
19417 
19418 	btf = btf_get_by_fd(attr->prog_btf_fd);
19419 	if (IS_ERR(btf))
19420 		return PTR_ERR(btf);
19421 	if (btf_is_kernel(btf)) {
19422 		btf_put(btf);
19423 		return -EACCES;
19424 	}
19425 	env->prog->aux->btf = btf;
19426 
19427 	err = check_btf_func_early(env, attr, uattr);
19428 	if (err)
19429 		return err;
19430 	return 0;
19431 }
19432 
19433 static int check_btf_info(struct bpf_verifier_env *env,
19434 			  const union bpf_attr *attr,
19435 			  bpfptr_t uattr)
19436 {
19437 	int err;
19438 
19439 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
19440 		if (check_abnormal_return(env))
19441 			return -EINVAL;
19442 		return 0;
19443 	}
19444 
19445 	err = check_btf_func(env, attr, uattr);
19446 	if (err)
19447 		return err;
19448 
19449 	err = check_btf_line(env, attr, uattr);
19450 	if (err)
19451 		return err;
19452 
19453 	err = check_core_relo(env, attr, uattr);
19454 	if (err)
19455 		return err;
19456 
19457 	return 0;
19458 }
19459 
19460 /* check %cur's range satisfies %old's */
19461 static bool range_within(const struct bpf_reg_state *old,
19462 			 const struct bpf_reg_state *cur)
19463 {
19464 	return old->umin_value <= cur->umin_value &&
19465 	       old->umax_value >= cur->umax_value &&
19466 	       old->smin_value <= cur->smin_value &&
19467 	       old->smax_value >= cur->smax_value &&
19468 	       old->u32_min_value <= cur->u32_min_value &&
19469 	       old->u32_max_value >= cur->u32_max_value &&
19470 	       old->s32_min_value <= cur->s32_min_value &&
19471 	       old->s32_max_value >= cur->s32_max_value;
19472 }
19473 
19474 /* If in the old state two registers had the same id, then they need to have
19475  * the same id in the new state as well.  But that id could be different from
19476  * the old state, so we need to track the mapping from old to new ids.
19477  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
19478  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
19479  * regs with a different old id could still have new id 9, we don't care about
19480  * that.
19481  * So we look through our idmap to see if this old id has been seen before.  If
19482  * so, we require the new id to match; otherwise, we add the id pair to the map.
19483  */
19484 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
19485 {
19486 	struct bpf_id_pair *map = idmap->map;
19487 	unsigned int i;
19488 
19489 	/* either both IDs should be set or both should be zero */
19490 	if (!!old_id != !!cur_id)
19491 		return false;
19492 
19493 	if (old_id == 0) /* cur_id == 0 as well */
19494 		return true;
19495 
19496 	for (i = 0; i < idmap->cnt; i++) {
19497 		if (map[i].old == old_id)
19498 			return map[i].cur == cur_id;
19499 		if (map[i].cur == cur_id)
19500 			return false;
19501 	}
19502 
19503 	/* Reached the end of known mappings; haven't seen this id before */
19504 	if (idmap->cnt < BPF_ID_MAP_SIZE) {
19505 		map[idmap->cnt].old = old_id;
19506 		map[idmap->cnt].cur = cur_id;
19507 		idmap->cnt++;
19508 		return true;
19509 	}
19510 
19511 	/* We ran out of idmap slots, which should be impossible */
19512 	WARN_ON_ONCE(1);
19513 	return false;
19514 }
19515 
19516 /*
19517  * Compare scalar register IDs for state equivalence.
19518  *
19519  * When old_id == 0, the old register is independent - not linked to any
19520  * other register. Any linking in the current state only adds constraints,
19521  * making it more restrictive. Since the old state didn't rely on any ID
19522  * relationships for this register, it's always safe to accept cur regardless
19523  * of its ID. Hence, return true immediately.
19524  *
19525  * When old_id != 0 but cur_id == 0, we need to ensure that different
19526  * independent registers in cur don't incorrectly satisfy the ID matching
19527  * requirements of linked registers in old.
19528  *
19529  * Example: if old has r6.id=X and r7.id=X (linked), but cur has r6.id=0
19530  * and r7.id=0 (both independent), without temp IDs both would map old_id=X
19531  * to cur_id=0 and pass. With temp IDs: r6 maps X->temp1, r7 tries to map
19532  * X->temp2, but X is already mapped to temp1, so the check fails correctly.
19533  */
19534 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
19535 {
19536 	if (!old_id)
19537 		return true;
19538 
19539 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
19540 
19541 	return check_ids(old_id, cur_id, idmap);
19542 }
19543 
19544 static void clean_func_state(struct bpf_verifier_env *env,
19545 			     struct bpf_func_state *st,
19546 			     u32 ip)
19547 {
19548 	u16 live_regs = env->insn_aux_data[ip].live_regs_before;
19549 	int i, j;
19550 
19551 	for (i = 0; i < BPF_REG_FP; i++) {
19552 		/* liveness must not touch this register anymore */
19553 		if (!(live_regs & BIT(i)))
19554 			/* since the register is unused, clear its state
19555 			 * to make further comparison simpler
19556 			 */
19557 			__mark_reg_not_init(env, &st->regs[i]);
19558 	}
19559 
19560 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
19561 		if (!bpf_stack_slot_alive(env, st->frameno, i)) {
19562 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
19563 			for (j = 0; j < BPF_REG_SIZE; j++)
19564 				st->stack[i].slot_type[j] = STACK_INVALID;
19565 		}
19566 	}
19567 }
19568 
19569 static void clean_verifier_state(struct bpf_verifier_env *env,
19570 				 struct bpf_verifier_state *st)
19571 {
19572 	int i, ip;
19573 
19574 	bpf_live_stack_query_init(env, st);
19575 	st->cleaned = true;
19576 	for (i = 0; i <= st->curframe; i++) {
19577 		ip = frame_insn_idx(st, i);
19578 		clean_func_state(env, st->frame[i], ip);
19579 	}
19580 }
19581 
19582 /* the parentage chains form a tree.
19583  * the verifier states are added to state lists at given insn and
19584  * pushed into state stack for future exploration.
19585  * when the verifier reaches bpf_exit insn some of the verifier states
19586  * stored in the state lists have their final liveness state already,
19587  * but a lot of states will get revised from liveness point of view when
19588  * the verifier explores other branches.
19589  * Example:
19590  * 1: *(u64)(r10 - 8) = 1
19591  * 2: if r1 == 100 goto pc+1
19592  * 3: *(u64)(r10 - 8) = 2
19593  * 4: r0 = *(u64)(r10 - 8)
19594  * 5: exit
19595  * when the verifier reaches exit insn the stack slot -8 in the state list of
19596  * insn 2 is not yet marked alive. Then the verifier pops the other_branch
19597  * of insn 2 and goes exploring further. After the insn 4 read, liveness
19598  * analysis would propagate read mark for -8 at insn 2.
19599  *
19600  * Since the verifier pushes the branch states as it sees them while exploring
19601  * the program the condition of walking the branch instruction for the second
19602  * time means that all states below this branch were already explored and
19603  * their final liveness marks are already propagated.
19604  * Hence when the verifier completes the search of state list in is_state_visited()
19605  * we can call this clean_live_states() function to clear dead the registers and stack
19606  * slots to simplify state merging.
19607  *
19608  * Important note here that walking the same branch instruction in the callee
19609  * doesn't meant that the states are DONE. The verifier has to compare
19610  * the callsites
19611  */
19612 
19613 /* Find id in idset and increment its count, or add new entry */
19614 static void idset_cnt_inc(struct bpf_idset *idset, u32 id)
19615 {
19616 	u32 i;
19617 
19618 	for (i = 0; i < idset->num_ids; i++) {
19619 		if (idset->entries[i].id == id) {
19620 			idset->entries[i].cnt++;
19621 			return;
19622 		}
19623 	}
19624 	/* New id */
19625 	if (idset->num_ids < BPF_ID_MAP_SIZE) {
19626 		idset->entries[idset->num_ids].id = id;
19627 		idset->entries[idset->num_ids].cnt = 1;
19628 		idset->num_ids++;
19629 	}
19630 }
19631 
19632 /* Find id in idset and return its count, or 0 if not found */
19633 static u32 idset_cnt_get(struct bpf_idset *idset, u32 id)
19634 {
19635 	u32 i;
19636 
19637 	for (i = 0; i < idset->num_ids; i++) {
19638 		if (idset->entries[i].id == id)
19639 			return idset->entries[i].cnt;
19640 	}
19641 	return 0;
19642 }
19643 
19644 /*
19645  * Clear singular scalar ids in a state.
19646  * A register with a non-zero id is called singular if no other register shares
19647  * the same base id. Such registers can be treated as independent (id=0).
19648  */
19649 static void clear_singular_ids(struct bpf_verifier_env *env,
19650 			       struct bpf_verifier_state *st)
19651 {
19652 	struct bpf_idset *idset = &env->idset_scratch;
19653 	struct bpf_func_state *func;
19654 	struct bpf_reg_state *reg;
19655 
19656 	idset->num_ids = 0;
19657 
19658 	bpf_for_each_reg_in_vstate(st, func, reg, ({
19659 		if (reg->type != SCALAR_VALUE)
19660 			continue;
19661 		if (!reg->id)
19662 			continue;
19663 		idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST);
19664 	}));
19665 
19666 	bpf_for_each_reg_in_vstate(st, func, reg, ({
19667 		if (reg->type != SCALAR_VALUE)
19668 			continue;
19669 		if (!reg->id)
19670 			continue;
19671 		if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1) {
19672 			reg->id = 0;
19673 			reg->off = 0;
19674 		}
19675 	}));
19676 }
19677 
19678 static void clean_live_states(struct bpf_verifier_env *env, int insn,
19679 			      struct bpf_verifier_state *cur)
19680 {
19681 	struct bpf_verifier_state_list *sl;
19682 	struct list_head *pos, *head;
19683 
19684 	head = explored_state(env, insn);
19685 	list_for_each(pos, head) {
19686 		sl = container_of(pos, struct bpf_verifier_state_list, node);
19687 		if (sl->state.branches)
19688 			continue;
19689 		if (sl->state.insn_idx != insn ||
19690 		    !same_callsites(&sl->state, cur))
19691 			continue;
19692 		if (sl->state.cleaned)
19693 			/* all regs in this state in all frames were already marked */
19694 			continue;
19695 		if (incomplete_read_marks(env, &sl->state))
19696 			continue;
19697 		clean_verifier_state(env, &sl->state);
19698 	}
19699 }
19700 
19701 static bool regs_exact(const struct bpf_reg_state *rold,
19702 		       const struct bpf_reg_state *rcur,
19703 		       struct bpf_idmap *idmap)
19704 {
19705 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
19706 	       check_ids(rold->id, rcur->id, idmap) &&
19707 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
19708 }
19709 
19710 enum exact_level {
19711 	NOT_EXACT,
19712 	EXACT,
19713 	RANGE_WITHIN
19714 };
19715 
19716 /* Returns true if (rold safe implies rcur safe) */
19717 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
19718 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
19719 		    enum exact_level exact)
19720 {
19721 	if (exact == EXACT)
19722 		return regs_exact(rold, rcur, idmap);
19723 
19724 	if (rold->type == NOT_INIT)
19725 		/* explored state can't have used this */
19726 		return true;
19727 
19728 	/* Enforce that register types have to match exactly, including their
19729 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
19730 	 * rule.
19731 	 *
19732 	 * One can make a point that using a pointer register as unbounded
19733 	 * SCALAR would be technically acceptable, but this could lead to
19734 	 * pointer leaks because scalars are allowed to leak while pointers
19735 	 * are not. We could make this safe in special cases if root is
19736 	 * calling us, but it's probably not worth the hassle.
19737 	 *
19738 	 * Also, register types that are *not* MAYBE_NULL could technically be
19739 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
19740 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
19741 	 * to the same map).
19742 	 * However, if the old MAYBE_NULL register then got NULL checked,
19743 	 * doing so could have affected others with the same id, and we can't
19744 	 * check for that because we lost the id when we converted to
19745 	 * a non-MAYBE_NULL variant.
19746 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
19747 	 * non-MAYBE_NULL registers as well.
19748 	 */
19749 	if (rold->type != rcur->type)
19750 		return false;
19751 
19752 	switch (base_type(rold->type)) {
19753 	case SCALAR_VALUE:
19754 		if (env->explore_alu_limits) {
19755 			/* explore_alu_limits disables tnum_in() and range_within()
19756 			 * logic and requires everything to be strict
19757 			 */
19758 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
19759 			       check_scalar_ids(rold->id, rcur->id, idmap);
19760 		}
19761 		if (!rold->precise && exact == NOT_EXACT)
19762 			return true;
19763 		/*
19764 		 * Linked register tracking uses rold->id to detect relationships.
19765 		 * When rold->id == 0, the register is independent and any linking
19766 		 * in rcur only adds constraints. When rold->id != 0, we must verify
19767 		 * id mapping and (for BPF_ADD_CONST) offset consistency.
19768 		 *
19769 		 * +------------------+-----------+------------------+---------------+
19770 		 * |                  | rold->id  | rold + ADD_CONST | rold->id == 0 |
19771 		 * |------------------+-----------+------------------+---------------|
19772 		 * | rcur->id         | range,ids | false            | range         |
19773 		 * | rcur + ADD_CONST | false     | range,ids,off    | range         |
19774 		 * | rcur->id == 0    | range,ids | false            | range         |
19775 		 * +------------------+-----------+------------------+---------------+
19776 		 *
19777 		 * Why check_ids() for scalar registers?
19778 		 *
19779 		 * Consider the following BPF code:
19780 		 *   1: r6 = ... unbound scalar, ID=a ...
19781 		 *   2: r7 = ... unbound scalar, ID=b ...
19782 		 *   3: if (r6 > r7) goto +1
19783 		 *   4: r6 = r7
19784 		 *   5: if (r6 > X) goto ...
19785 		 *   6: ... memory operation using r7 ...
19786 		 *
19787 		 * First verification path is [1-6]:
19788 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
19789 		 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
19790 		 *   r7 <= X, because r6 and r7 share same id.
19791 		 * Next verification path is [1-4, 6].
19792 		 *
19793 		 * Instruction (6) would be reached in two states:
19794 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
19795 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
19796 		 *
19797 		 * Use check_ids() to distinguish these states.
19798 		 * ---
19799 		 * Also verify that new value satisfies old value range knowledge.
19800 		 */
19801 
19802 		/* ADD_CONST mismatch: different linking semantics */
19803 		if ((rold->id & BPF_ADD_CONST) && !(rcur->id & BPF_ADD_CONST))
19804 			return false;
19805 
19806 		if (rold->id && !(rold->id & BPF_ADD_CONST) && (rcur->id & BPF_ADD_CONST))
19807 			return false;
19808 
19809 		/* Both have offset linkage: offsets must match */
19810 		if ((rold->id & BPF_ADD_CONST) && rold->off != rcur->off)
19811 			return false;
19812 
19813 		if (!check_scalar_ids(rold->id, rcur->id, idmap))
19814 			return false;
19815 
19816 		return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off);
19817 	case PTR_TO_MAP_KEY:
19818 	case PTR_TO_MAP_VALUE:
19819 	case PTR_TO_MEM:
19820 	case PTR_TO_BUF:
19821 	case PTR_TO_TP_BUFFER:
19822 		/* If the new min/max/var_off satisfy the old ones and
19823 		 * everything else matches, we are OK.
19824 		 */
19825 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
19826 		       range_within(rold, rcur) &&
19827 		       tnum_in(rold->var_off, rcur->var_off) &&
19828 		       check_ids(rold->id, rcur->id, idmap) &&
19829 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
19830 	case PTR_TO_PACKET_META:
19831 	case PTR_TO_PACKET:
19832 		/* We must have at least as much range as the old ptr
19833 		 * did, so that any accesses which were safe before are
19834 		 * still safe.  This is true even if old range < old off,
19835 		 * since someone could have accessed through (ptr - k), or
19836 		 * even done ptr -= k in a register, to get a safe access.
19837 		 */
19838 		if (rold->range > rcur->range)
19839 			return false;
19840 		/* If the offsets don't match, we can't trust our alignment;
19841 		 * nor can we be sure that we won't fall out of range.
19842 		 */
19843 		if (rold->off != rcur->off)
19844 			return false;
19845 		/* id relations must be preserved */
19846 		if (!check_ids(rold->id, rcur->id, idmap))
19847 			return false;
19848 		/* new val must satisfy old val knowledge */
19849 		return range_within(rold, rcur) &&
19850 		       tnum_in(rold->var_off, rcur->var_off);
19851 	case PTR_TO_STACK:
19852 		/* two stack pointers are equal only if they're pointing to
19853 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
19854 		 */
19855 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
19856 	case PTR_TO_ARENA:
19857 		return true;
19858 	case PTR_TO_INSN:
19859 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
19860 			rold->off == rcur->off && range_within(rold, rcur) &&
19861 			tnum_in(rold->var_off, rcur->var_off);
19862 	default:
19863 		return regs_exact(rold, rcur, idmap);
19864 	}
19865 }
19866 
19867 static struct bpf_reg_state unbound_reg;
19868 
19869 static __init int unbound_reg_init(void)
19870 {
19871 	__mark_reg_unknown_imprecise(&unbound_reg);
19872 	return 0;
19873 }
19874 late_initcall(unbound_reg_init);
19875 
19876 static bool is_stack_all_misc(struct bpf_verifier_env *env,
19877 			      struct bpf_stack_state *stack)
19878 {
19879 	u32 i;
19880 
19881 	for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
19882 		if ((stack->slot_type[i] == STACK_MISC) ||
19883 		    (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
19884 			continue;
19885 		return false;
19886 	}
19887 
19888 	return true;
19889 }
19890 
19891 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
19892 						  struct bpf_stack_state *stack)
19893 {
19894 	if (is_spilled_scalar_reg64(stack))
19895 		return &stack->spilled_ptr;
19896 
19897 	if (is_stack_all_misc(env, stack))
19898 		return &unbound_reg;
19899 
19900 	return NULL;
19901 }
19902 
19903 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
19904 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
19905 		      enum exact_level exact)
19906 {
19907 	int i, spi;
19908 
19909 	/* walk slots of the explored stack and ignore any additional
19910 	 * slots in the current stack, since explored(safe) state
19911 	 * didn't use them
19912 	 */
19913 	for (i = 0; i < old->allocated_stack; i++) {
19914 		struct bpf_reg_state *old_reg, *cur_reg;
19915 
19916 		spi = i / BPF_REG_SIZE;
19917 
19918 		if (exact == EXACT &&
19919 		    (i >= cur->allocated_stack ||
19920 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
19921 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
19922 			return false;
19923 
19924 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
19925 			continue;
19926 
19927 		if (env->allow_uninit_stack &&
19928 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
19929 			continue;
19930 
19931 		/* explored stack has more populated slots than current stack
19932 		 * and these slots were used
19933 		 */
19934 		if (i >= cur->allocated_stack)
19935 			return false;
19936 
19937 		/* 64-bit scalar spill vs all slots MISC and vice versa.
19938 		 * Load from all slots MISC produces unbound scalar.
19939 		 * Construct a fake register for such stack and call
19940 		 * regsafe() to ensure scalar ids are compared.
19941 		 */
19942 		old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
19943 		cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
19944 		if (old_reg && cur_reg) {
19945 			if (!regsafe(env, old_reg, cur_reg, idmap, exact))
19946 				return false;
19947 			i += BPF_REG_SIZE - 1;
19948 			continue;
19949 		}
19950 
19951 		/* if old state was safe with misc data in the stack
19952 		 * it will be safe with zero-initialized stack.
19953 		 * The opposite is not true
19954 		 */
19955 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
19956 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
19957 			continue;
19958 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
19959 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
19960 			/* Ex: old explored (safe) state has STACK_SPILL in
19961 			 * this stack slot, but current has STACK_MISC ->
19962 			 * this verifier states are not equivalent,
19963 			 * return false to continue verification of this path
19964 			 */
19965 			return false;
19966 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
19967 			continue;
19968 		/* Both old and cur are having same slot_type */
19969 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
19970 		case STACK_SPILL:
19971 			/* when explored and current stack slot are both storing
19972 			 * spilled registers, check that stored pointers types
19973 			 * are the same as well.
19974 			 * Ex: explored safe path could have stored
19975 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
19976 			 * but current path has stored:
19977 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
19978 			 * such verifier states are not equivalent.
19979 			 * return false to continue verification of this path
19980 			 */
19981 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
19982 				     &cur->stack[spi].spilled_ptr, idmap, exact))
19983 				return false;
19984 			break;
19985 		case STACK_DYNPTR:
19986 			old_reg = &old->stack[spi].spilled_ptr;
19987 			cur_reg = &cur->stack[spi].spilled_ptr;
19988 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
19989 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
19990 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
19991 				return false;
19992 			break;
19993 		case STACK_ITER:
19994 			old_reg = &old->stack[spi].spilled_ptr;
19995 			cur_reg = &cur->stack[spi].spilled_ptr;
19996 			/* iter.depth is not compared between states as it
19997 			 * doesn't matter for correctness and would otherwise
19998 			 * prevent convergence; we maintain it only to prevent
19999 			 * infinite loop check triggering, see
20000 			 * iter_active_depths_differ()
20001 			 */
20002 			if (old_reg->iter.btf != cur_reg->iter.btf ||
20003 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
20004 			    old_reg->iter.state != cur_reg->iter.state ||
20005 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
20006 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
20007 				return false;
20008 			break;
20009 		case STACK_IRQ_FLAG:
20010 			old_reg = &old->stack[spi].spilled_ptr;
20011 			cur_reg = &cur->stack[spi].spilled_ptr;
20012 			if (!check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) ||
20013 			    old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class)
20014 				return false;
20015 			break;
20016 		case STACK_MISC:
20017 		case STACK_ZERO:
20018 		case STACK_INVALID:
20019 			continue;
20020 		/* Ensure that new unhandled slot types return false by default */
20021 		default:
20022 			return false;
20023 		}
20024 	}
20025 	return true;
20026 }
20027 
20028 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur,
20029 		    struct bpf_idmap *idmap)
20030 {
20031 	int i;
20032 
20033 	if (old->acquired_refs != cur->acquired_refs)
20034 		return false;
20035 
20036 	if (old->active_locks != cur->active_locks)
20037 		return false;
20038 
20039 	if (old->active_preempt_locks != cur->active_preempt_locks)
20040 		return false;
20041 
20042 	if (old->active_rcu_locks != cur->active_rcu_locks)
20043 		return false;
20044 
20045 	if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap))
20046 		return false;
20047 
20048 	if (!check_ids(old->active_lock_id, cur->active_lock_id, idmap) ||
20049 	    old->active_lock_ptr != cur->active_lock_ptr)
20050 		return false;
20051 
20052 	for (i = 0; i < old->acquired_refs; i++) {
20053 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) ||
20054 		    old->refs[i].type != cur->refs[i].type)
20055 			return false;
20056 		switch (old->refs[i].type) {
20057 		case REF_TYPE_PTR:
20058 		case REF_TYPE_IRQ:
20059 			break;
20060 		case REF_TYPE_LOCK:
20061 		case REF_TYPE_RES_LOCK:
20062 		case REF_TYPE_RES_LOCK_IRQ:
20063 			if (old->refs[i].ptr != cur->refs[i].ptr)
20064 				return false;
20065 			break;
20066 		default:
20067 			WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type);
20068 			return false;
20069 		}
20070 	}
20071 
20072 	return true;
20073 }
20074 
20075 /* compare two verifier states
20076  *
20077  * all states stored in state_list are known to be valid, since
20078  * verifier reached 'bpf_exit' instruction through them
20079  *
20080  * this function is called when verifier exploring different branches of
20081  * execution popped from the state stack. If it sees an old state that has
20082  * more strict register state and more strict stack state then this execution
20083  * branch doesn't need to be explored further, since verifier already
20084  * concluded that more strict state leads to valid finish.
20085  *
20086  * Therefore two states are equivalent if register state is more conservative
20087  * and explored stack state is more conservative than the current one.
20088  * Example:
20089  *       explored                   current
20090  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
20091  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
20092  *
20093  * In other words if current stack state (one being explored) has more
20094  * valid slots than old one that already passed validation, it means
20095  * the verifier can stop exploring and conclude that current state is valid too
20096  *
20097  * Similarly with registers. If explored state has register type as invalid
20098  * whereas register type in current state is meaningful, it means that
20099  * the current state will reach 'bpf_exit' instruction safely
20100  */
20101 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
20102 			      struct bpf_func_state *cur, u32 insn_idx, enum exact_level exact)
20103 {
20104 	u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
20105 	u16 i;
20106 
20107 	if (old->callback_depth > cur->callback_depth)
20108 		return false;
20109 
20110 	for (i = 0; i < MAX_BPF_REG; i++)
20111 		if (((1 << i) & live_regs) &&
20112 		    !regsafe(env, &old->regs[i], &cur->regs[i],
20113 			     &env->idmap_scratch, exact))
20114 			return false;
20115 
20116 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
20117 		return false;
20118 
20119 	return true;
20120 }
20121 
20122 static void reset_idmap_scratch(struct bpf_verifier_env *env)
20123 {
20124 	struct bpf_idmap *idmap = &env->idmap_scratch;
20125 
20126 	idmap->tmp_id_gen = env->id_gen;
20127 	idmap->cnt = 0;
20128 }
20129 
20130 static bool states_equal(struct bpf_verifier_env *env,
20131 			 struct bpf_verifier_state *old,
20132 			 struct bpf_verifier_state *cur,
20133 			 enum exact_level exact)
20134 {
20135 	u32 insn_idx;
20136 	int i;
20137 
20138 	if (old->curframe != cur->curframe)
20139 		return false;
20140 
20141 	reset_idmap_scratch(env);
20142 
20143 	/* Verification state from speculative execution simulation
20144 	 * must never prune a non-speculative execution one.
20145 	 */
20146 	if (old->speculative && !cur->speculative)
20147 		return false;
20148 
20149 	if (old->in_sleepable != cur->in_sleepable)
20150 		return false;
20151 
20152 	if (!refsafe(old, cur, &env->idmap_scratch))
20153 		return false;
20154 
20155 	/* for states to be equal callsites have to be the same
20156 	 * and all frame states need to be equivalent
20157 	 */
20158 	for (i = 0; i <= old->curframe; i++) {
20159 		insn_idx = frame_insn_idx(old, i);
20160 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
20161 			return false;
20162 		if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact))
20163 			return false;
20164 	}
20165 	return true;
20166 }
20167 
20168 /* find precise scalars in the previous equivalent state and
20169  * propagate them into the current state
20170  */
20171 static int propagate_precision(struct bpf_verifier_env *env,
20172 			       const struct bpf_verifier_state *old,
20173 			       struct bpf_verifier_state *cur,
20174 			       bool *changed)
20175 {
20176 	struct bpf_reg_state *state_reg;
20177 	struct bpf_func_state *state;
20178 	int i, err = 0, fr;
20179 	bool first;
20180 
20181 	for (fr = old->curframe; fr >= 0; fr--) {
20182 		state = old->frame[fr];
20183 		state_reg = state->regs;
20184 		first = true;
20185 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
20186 			if (state_reg->type != SCALAR_VALUE ||
20187 			    !state_reg->precise)
20188 				continue;
20189 			if (env->log.level & BPF_LOG_LEVEL2) {
20190 				if (first)
20191 					verbose(env, "frame %d: propagating r%d", fr, i);
20192 				else
20193 					verbose(env, ",r%d", i);
20194 			}
20195 			bt_set_frame_reg(&env->bt, fr, i);
20196 			first = false;
20197 		}
20198 
20199 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
20200 			if (!is_spilled_reg(&state->stack[i]))
20201 				continue;
20202 			state_reg = &state->stack[i].spilled_ptr;
20203 			if (state_reg->type != SCALAR_VALUE ||
20204 			    !state_reg->precise)
20205 				continue;
20206 			if (env->log.level & BPF_LOG_LEVEL2) {
20207 				if (first)
20208 					verbose(env, "frame %d: propagating fp%d",
20209 						fr, (-i - 1) * BPF_REG_SIZE);
20210 				else
20211 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
20212 			}
20213 			bt_set_frame_slot(&env->bt, fr, i);
20214 			first = false;
20215 		}
20216 		if (!first && (env->log.level & BPF_LOG_LEVEL2))
20217 			verbose(env, "\n");
20218 	}
20219 
20220 	err = __mark_chain_precision(env, cur, -1, changed);
20221 	if (err < 0)
20222 		return err;
20223 
20224 	return 0;
20225 }
20226 
20227 #define MAX_BACKEDGE_ITERS 64
20228 
20229 /* Propagate read and precision marks from visit->backedges[*].state->equal_state
20230  * to corresponding parent states of visit->backedges[*].state until fixed point is reached,
20231  * then free visit->backedges.
20232  * After execution of this function incomplete_read_marks() will return false
20233  * for all states corresponding to @visit->callchain.
20234  */
20235 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit)
20236 {
20237 	struct bpf_scc_backedge *backedge;
20238 	struct bpf_verifier_state *st;
20239 	bool changed;
20240 	int i, err;
20241 
20242 	i = 0;
20243 	do {
20244 		if (i++ > MAX_BACKEDGE_ITERS) {
20245 			if (env->log.level & BPF_LOG_LEVEL2)
20246 				verbose(env, "%s: too many iterations\n", __func__);
20247 			for (backedge = visit->backedges; backedge; backedge = backedge->next)
20248 				mark_all_scalars_precise(env, &backedge->state);
20249 			break;
20250 		}
20251 		changed = false;
20252 		for (backedge = visit->backedges; backedge; backedge = backedge->next) {
20253 			st = &backedge->state;
20254 			err = propagate_precision(env, st->equal_state, st, &changed);
20255 			if (err)
20256 				return err;
20257 		}
20258 	} while (changed);
20259 
20260 	free_backedges(visit);
20261 	return 0;
20262 }
20263 
20264 static bool states_maybe_looping(struct bpf_verifier_state *old,
20265 				 struct bpf_verifier_state *cur)
20266 {
20267 	struct bpf_func_state *fold, *fcur;
20268 	int i, fr = cur->curframe;
20269 
20270 	if (old->curframe != fr)
20271 		return false;
20272 
20273 	fold = old->frame[fr];
20274 	fcur = cur->frame[fr];
20275 	for (i = 0; i < MAX_BPF_REG; i++)
20276 		if (memcmp(&fold->regs[i], &fcur->regs[i],
20277 			   offsetof(struct bpf_reg_state, frameno)))
20278 			return false;
20279 	return true;
20280 }
20281 
20282 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
20283 {
20284 	return env->insn_aux_data[insn_idx].is_iter_next;
20285 }
20286 
20287 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
20288  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
20289  * states to match, which otherwise would look like an infinite loop. So while
20290  * iter_next() calls are taken care of, we still need to be careful and
20291  * prevent erroneous and too eager declaration of "infinite loop", when
20292  * iterators are involved.
20293  *
20294  * Here's a situation in pseudo-BPF assembly form:
20295  *
20296  *   0: again:                          ; set up iter_next() call args
20297  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
20298  *   2:   call bpf_iter_num_next        ; this is iter_next() call
20299  *   3:   if r0 == 0 goto done
20300  *   4:   ... something useful here ...
20301  *   5:   goto again                    ; another iteration
20302  *   6: done:
20303  *   7:   r1 = &it
20304  *   8:   call bpf_iter_num_destroy     ; clean up iter state
20305  *   9:   exit
20306  *
20307  * This is a typical loop. Let's assume that we have a prune point at 1:,
20308  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
20309  * again`, assuming other heuristics don't get in a way).
20310  *
20311  * When we first time come to 1:, let's say we have some state X. We proceed
20312  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
20313  * Now we come back to validate that forked ACTIVE state. We proceed through
20314  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
20315  * are converging. But the problem is that we don't know that yet, as this
20316  * convergence has to happen at iter_next() call site only. So if nothing is
20317  * done, at 1: verifier will use bounded loop logic and declare infinite
20318  * looping (and would be *technically* correct, if not for iterator's
20319  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
20320  * don't want that. So what we do in process_iter_next_call() when we go on
20321  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
20322  * a different iteration. So when we suspect an infinite loop, we additionally
20323  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
20324  * pretend we are not looping and wait for next iter_next() call.
20325  *
20326  * This only applies to ACTIVE state. In DRAINED state we don't expect to
20327  * loop, because that would actually mean infinite loop, as DRAINED state is
20328  * "sticky", and so we'll keep returning into the same instruction with the
20329  * same state (at least in one of possible code paths).
20330  *
20331  * This approach allows to keep infinite loop heuristic even in the face of
20332  * active iterator. E.g., C snippet below is and will be detected as
20333  * infinitely looping:
20334  *
20335  *   struct bpf_iter_num it;
20336  *   int *p, x;
20337  *
20338  *   bpf_iter_num_new(&it, 0, 10);
20339  *   while ((p = bpf_iter_num_next(&t))) {
20340  *       x = p;
20341  *       while (x--) {} // <<-- infinite loop here
20342  *   }
20343  *
20344  */
20345 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
20346 {
20347 	struct bpf_reg_state *slot, *cur_slot;
20348 	struct bpf_func_state *state;
20349 	int i, fr;
20350 
20351 	for (fr = old->curframe; fr >= 0; fr--) {
20352 		state = old->frame[fr];
20353 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
20354 			if (state->stack[i].slot_type[0] != STACK_ITER)
20355 				continue;
20356 
20357 			slot = &state->stack[i].spilled_ptr;
20358 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
20359 				continue;
20360 
20361 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
20362 			if (cur_slot->iter.depth != slot->iter.depth)
20363 				return true;
20364 		}
20365 	}
20366 	return false;
20367 }
20368 
20369 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
20370 {
20371 	struct bpf_verifier_state_list *new_sl;
20372 	struct bpf_verifier_state_list *sl;
20373 	struct bpf_verifier_state *cur = env->cur_state, *new;
20374 	bool force_new_state, add_new_state, loop;
20375 	int n, err, states_cnt = 0;
20376 	struct list_head *pos, *tmp, *head;
20377 
20378 	force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
20379 			  /* Avoid accumulating infinitely long jmp history */
20380 			  cur->jmp_history_cnt > 40;
20381 
20382 	/* bpf progs typically have pruning point every 4 instructions
20383 	 * http://vger.kernel.org/bpfconf2019.html#session-1
20384 	 * Do not add new state for future pruning if the verifier hasn't seen
20385 	 * at least 2 jumps and at least 8 instructions.
20386 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
20387 	 * In tests that amounts to up to 50% reduction into total verifier
20388 	 * memory consumption and 20% verifier time speedup.
20389 	 */
20390 	add_new_state = force_new_state;
20391 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
20392 	    env->insn_processed - env->prev_insn_processed >= 8)
20393 		add_new_state = true;
20394 
20395 	clean_live_states(env, insn_idx, cur);
20396 
20397 	loop = false;
20398 	head = explored_state(env, insn_idx);
20399 	list_for_each_safe(pos, tmp, head) {
20400 		sl = container_of(pos, struct bpf_verifier_state_list, node);
20401 		states_cnt++;
20402 		if (sl->state.insn_idx != insn_idx)
20403 			continue;
20404 
20405 		if (sl->state.branches) {
20406 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
20407 
20408 			if (frame->in_async_callback_fn &&
20409 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
20410 				/* Different async_entry_cnt means that the verifier is
20411 				 * processing another entry into async callback.
20412 				 * Seeing the same state is not an indication of infinite
20413 				 * loop or infinite recursion.
20414 				 * But finding the same state doesn't mean that it's safe
20415 				 * to stop processing the current state. The previous state
20416 				 * hasn't yet reached bpf_exit, since state.branches > 0.
20417 				 * Checking in_async_callback_fn alone is not enough either.
20418 				 * Since the verifier still needs to catch infinite loops
20419 				 * inside async callbacks.
20420 				 */
20421 				goto skip_inf_loop_check;
20422 			}
20423 			/* BPF open-coded iterators loop detection is special.
20424 			 * states_maybe_looping() logic is too simplistic in detecting
20425 			 * states that *might* be equivalent, because it doesn't know
20426 			 * about ID remapping, so don't even perform it.
20427 			 * See process_iter_next_call() and iter_active_depths_differ()
20428 			 * for overview of the logic. When current and one of parent
20429 			 * states are detected as equivalent, it's a good thing: we prove
20430 			 * convergence and can stop simulating further iterations.
20431 			 * It's safe to assume that iterator loop will finish, taking into
20432 			 * account iter_next() contract of eventually returning
20433 			 * sticky NULL result.
20434 			 *
20435 			 * Note, that states have to be compared exactly in this case because
20436 			 * read and precision marks might not be finalized inside the loop.
20437 			 * E.g. as in the program below:
20438 			 *
20439 			 *     1. r7 = -16
20440 			 *     2. r6 = bpf_get_prandom_u32()
20441 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
20442 			 *     4.   if (r6 != 42) {
20443 			 *     5.     r7 = -32
20444 			 *     6.     r6 = bpf_get_prandom_u32()
20445 			 *     7.     continue
20446 			 *     8.   }
20447 			 *     9.   r0 = r10
20448 			 *    10.   r0 += r7
20449 			 *    11.   r8 = *(u64 *)(r0 + 0)
20450 			 *    12.   r6 = bpf_get_prandom_u32()
20451 			 *    13. }
20452 			 *
20453 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
20454 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
20455 			 * not have read or precision mark for r7 yet, thus inexact states
20456 			 * comparison would discard current state with r7=-32
20457 			 * => unsafe memory access at 11 would not be caught.
20458 			 */
20459 			if (is_iter_next_insn(env, insn_idx)) {
20460 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
20461 					struct bpf_func_state *cur_frame;
20462 					struct bpf_reg_state *iter_state, *iter_reg;
20463 					int spi;
20464 
20465 					cur_frame = cur->frame[cur->curframe];
20466 					/* btf_check_iter_kfuncs() enforces that
20467 					 * iter state pointer is always the first arg
20468 					 */
20469 					iter_reg = &cur_frame->regs[BPF_REG_1];
20470 					/* current state is valid due to states_equal(),
20471 					 * so we can assume valid iter and reg state,
20472 					 * no need for extra (re-)validations
20473 					 */
20474 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
20475 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
20476 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
20477 						loop = true;
20478 						goto hit;
20479 					}
20480 				}
20481 				goto skip_inf_loop_check;
20482 			}
20483 			if (is_may_goto_insn_at(env, insn_idx)) {
20484 				if (sl->state.may_goto_depth != cur->may_goto_depth &&
20485 				    states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
20486 					loop = true;
20487 					goto hit;
20488 				}
20489 			}
20490 			if (bpf_calls_callback(env, insn_idx)) {
20491 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
20492 					loop = true;
20493 					goto hit;
20494 				}
20495 				goto skip_inf_loop_check;
20496 			}
20497 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
20498 			if (states_maybe_looping(&sl->state, cur) &&
20499 			    states_equal(env, &sl->state, cur, EXACT) &&
20500 			    !iter_active_depths_differ(&sl->state, cur) &&
20501 			    sl->state.may_goto_depth == cur->may_goto_depth &&
20502 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
20503 				verbose_linfo(env, insn_idx, "; ");
20504 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
20505 				verbose(env, "cur state:");
20506 				print_verifier_state(env, cur, cur->curframe, true);
20507 				verbose(env, "old state:");
20508 				print_verifier_state(env, &sl->state, cur->curframe, true);
20509 				return -EINVAL;
20510 			}
20511 			/* if the verifier is processing a loop, avoid adding new state
20512 			 * too often, since different loop iterations have distinct
20513 			 * states and may not help future pruning.
20514 			 * This threshold shouldn't be too low to make sure that
20515 			 * a loop with large bound will be rejected quickly.
20516 			 * The most abusive loop will be:
20517 			 * r1 += 1
20518 			 * if r1 < 1000000 goto pc-2
20519 			 * 1M insn_procssed limit / 100 == 10k peak states.
20520 			 * This threshold shouldn't be too high either, since states
20521 			 * at the end of the loop are likely to be useful in pruning.
20522 			 */
20523 skip_inf_loop_check:
20524 			if (!force_new_state &&
20525 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
20526 			    env->insn_processed - env->prev_insn_processed < 100)
20527 				add_new_state = false;
20528 			goto miss;
20529 		}
20530 		/* See comments for mark_all_regs_read_and_precise() */
20531 		loop = incomplete_read_marks(env, &sl->state);
20532 		if (states_equal(env, &sl->state, cur, loop ? RANGE_WITHIN : NOT_EXACT)) {
20533 hit:
20534 			sl->hit_cnt++;
20535 
20536 			/* if previous state reached the exit with precision and
20537 			 * current state is equivalent to it (except precision marks)
20538 			 * the precision needs to be propagated back in
20539 			 * the current state.
20540 			 */
20541 			err = 0;
20542 			if (is_jmp_point(env, env->insn_idx))
20543 				err = push_jmp_history(env, cur, 0, 0);
20544 			err = err ? : propagate_precision(env, &sl->state, cur, NULL);
20545 			if (err)
20546 				return err;
20547 			/* When processing iterator based loops above propagate_liveness and
20548 			 * propagate_precision calls are not sufficient to transfer all relevant
20549 			 * read and precision marks. E.g. consider the following case:
20550 			 *
20551 			 *  .-> A --.  Assume the states are visited in the order A, B, C.
20552 			 *  |   |   |  Assume that state B reaches a state equivalent to state A.
20553 			 *  |   v   v  At this point, state C is not processed yet, so state A
20554 			 *  '-- B   C  has not received any read or precision marks from C.
20555 			 *             Thus, marks propagated from A to B are incomplete.
20556 			 *
20557 			 * The verifier mitigates this by performing the following steps:
20558 			 *
20559 			 * - Prior to the main verification pass, strongly connected components
20560 			 *   (SCCs) are computed over the program's control flow graph,
20561 			 *   intraprocedurally.
20562 			 *
20563 			 * - During the main verification pass, `maybe_enter_scc()` checks
20564 			 *   whether the current verifier state is entering an SCC. If so, an
20565 			 *   instance of a `bpf_scc_visit` object is created, and the state
20566 			 *   entering the SCC is recorded as the entry state.
20567 			 *
20568 			 * - This instance is associated not with the SCC itself, but with a
20569 			 *   `bpf_scc_callchain`: a tuple consisting of the call sites leading to
20570 			 *   the SCC and the SCC id. See `compute_scc_callchain()`.
20571 			 *
20572 			 * - When a verification path encounters a `states_equal(...,
20573 			 *   RANGE_WITHIN)` condition, there exists a call chain describing the
20574 			 *   current state and a corresponding `bpf_scc_visit` instance. A copy
20575 			 *   of the current state is created and added to
20576 			 *   `bpf_scc_visit->backedges`.
20577 			 *
20578 			 * - When a verification path terminates, `maybe_exit_scc()` is called
20579 			 *   from `update_branch_counts()`. For states with `branches == 0`, it
20580 			 *   checks whether the state is the entry state of any `bpf_scc_visit`
20581 			 *   instance. If it is, this indicates that all paths originating from
20582 			 *   this SCC visit have been explored. `propagate_backedges()` is then
20583 			 *   called, which propagates read and precision marks through the
20584 			 *   backedges until a fixed point is reached.
20585 			 *   (In the earlier example, this would propagate marks from A to B,
20586 			 *    from C to A, and then again from A to B.)
20587 			 *
20588 			 * A note on callchains
20589 			 * --------------------
20590 			 *
20591 			 * Consider the following example:
20592 			 *
20593 			 *     void foo() { loop { ... SCC#1 ... } }
20594 			 *     void main() {
20595 			 *       A: foo();
20596 			 *       B: ...
20597 			 *       C: foo();
20598 			 *     }
20599 			 *
20600 			 * Here, there are two distinct callchains leading to SCC#1:
20601 			 * - (A, SCC#1)
20602 			 * - (C, SCC#1)
20603 			 *
20604 			 * Each callchain identifies a separate `bpf_scc_visit` instance that
20605 			 * accumulates backedge states. The `propagate_{liveness,precision}()`
20606 			 * functions traverse the parent state of each backedge state, which
20607 			 * means these parent states must remain valid (i.e., not freed) while
20608 			 * the corresponding `bpf_scc_visit` instance exists.
20609 			 *
20610 			 * Associating `bpf_scc_visit` instances directly with SCCs instead of
20611 			 * callchains would break this invariant:
20612 			 * - States explored during `C: foo()` would contribute backedges to
20613 			 *   SCC#1, but SCC#1 would only be exited once the exploration of
20614 			 *   `A: foo()` completes.
20615 			 * - By that time, the states explored between `A: foo()` and `C: foo()`
20616 			 *   (i.e., `B: ...`) may have already been freed, causing the parent
20617 			 *   links for states from `C: foo()` to become invalid.
20618 			 */
20619 			if (loop) {
20620 				struct bpf_scc_backedge *backedge;
20621 
20622 				backedge = kzalloc(sizeof(*backedge), GFP_KERNEL_ACCOUNT);
20623 				if (!backedge)
20624 					return -ENOMEM;
20625 				err = copy_verifier_state(&backedge->state, cur);
20626 				backedge->state.equal_state = &sl->state;
20627 				backedge->state.insn_idx = insn_idx;
20628 				err = err ?: add_scc_backedge(env, &sl->state, backedge);
20629 				if (err) {
20630 					free_verifier_state(&backedge->state, false);
20631 					kfree(backedge);
20632 					return err;
20633 				}
20634 			}
20635 			return 1;
20636 		}
20637 miss:
20638 		/* when new state is not going to be added do not increase miss count.
20639 		 * Otherwise several loop iterations will remove the state
20640 		 * recorded earlier. The goal of these heuristics is to have
20641 		 * states from some iterations of the loop (some in the beginning
20642 		 * and some at the end) to help pruning.
20643 		 */
20644 		if (add_new_state)
20645 			sl->miss_cnt++;
20646 		/* heuristic to determine whether this state is beneficial
20647 		 * to keep checking from state equivalence point of view.
20648 		 * Higher numbers increase max_states_per_insn and verification time,
20649 		 * but do not meaningfully decrease insn_processed.
20650 		 * 'n' controls how many times state could miss before eviction.
20651 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
20652 		 * too early would hinder iterator convergence.
20653 		 */
20654 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
20655 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
20656 			/* the state is unlikely to be useful. Remove it to
20657 			 * speed up verification
20658 			 */
20659 			sl->in_free_list = true;
20660 			list_del(&sl->node);
20661 			list_add(&sl->node, &env->free_list);
20662 			env->free_list_size++;
20663 			env->explored_states_size--;
20664 			maybe_free_verifier_state(env, sl);
20665 		}
20666 	}
20667 
20668 	if (env->max_states_per_insn < states_cnt)
20669 		env->max_states_per_insn = states_cnt;
20670 
20671 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
20672 		return 0;
20673 
20674 	if (!add_new_state)
20675 		return 0;
20676 
20677 	/* There were no equivalent states, remember the current one.
20678 	 * Technically the current state is not proven to be safe yet,
20679 	 * but it will either reach outer most bpf_exit (which means it's safe)
20680 	 * or it will be rejected. When there are no loops the verifier won't be
20681 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
20682 	 * again on the way to bpf_exit.
20683 	 * When looping the sl->state.branches will be > 0 and this state
20684 	 * will not be considered for equivalence until branches == 0.
20685 	 */
20686 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL_ACCOUNT);
20687 	if (!new_sl)
20688 		return -ENOMEM;
20689 	env->total_states++;
20690 	env->explored_states_size++;
20691 	update_peak_states(env);
20692 	env->prev_jmps_processed = env->jmps_processed;
20693 	env->prev_insn_processed = env->insn_processed;
20694 
20695 	/* forget precise markings we inherited, see __mark_chain_precision */
20696 	if (env->bpf_capable)
20697 		mark_all_scalars_imprecise(env, cur);
20698 
20699 	clear_singular_ids(env, cur);
20700 
20701 	/* add new state to the head of linked list */
20702 	new = &new_sl->state;
20703 	err = copy_verifier_state(new, cur);
20704 	if (err) {
20705 		free_verifier_state(new, false);
20706 		kfree(new_sl);
20707 		return err;
20708 	}
20709 	new->insn_idx = insn_idx;
20710 	verifier_bug_if(new->branches != 1, env,
20711 			"%s:branches_to_explore=%d insn %d",
20712 			__func__, new->branches, insn_idx);
20713 	err = maybe_enter_scc(env, new);
20714 	if (err) {
20715 		free_verifier_state(new, false);
20716 		kfree(new_sl);
20717 		return err;
20718 	}
20719 
20720 	cur->parent = new;
20721 	cur->first_insn_idx = insn_idx;
20722 	cur->dfs_depth = new->dfs_depth + 1;
20723 	clear_jmp_history(cur);
20724 	list_add(&new_sl->node, head);
20725 	return 0;
20726 }
20727 
20728 /* Return true if it's OK to have the same insn return a different type. */
20729 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
20730 {
20731 	switch (base_type(type)) {
20732 	case PTR_TO_CTX:
20733 	case PTR_TO_SOCKET:
20734 	case PTR_TO_SOCK_COMMON:
20735 	case PTR_TO_TCP_SOCK:
20736 	case PTR_TO_XDP_SOCK:
20737 	case PTR_TO_BTF_ID:
20738 	case PTR_TO_ARENA:
20739 		return false;
20740 	default:
20741 		return true;
20742 	}
20743 }
20744 
20745 /* If an instruction was previously used with particular pointer types, then we
20746  * need to be careful to avoid cases such as the below, where it may be ok
20747  * for one branch accessing the pointer, but not ok for the other branch:
20748  *
20749  * R1 = sock_ptr
20750  * goto X;
20751  * ...
20752  * R1 = some_other_valid_ptr;
20753  * goto X;
20754  * ...
20755  * R2 = *(u32 *)(R1 + 0);
20756  */
20757 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
20758 {
20759 	return src != prev && (!reg_type_mismatch_ok(src) ||
20760 			       !reg_type_mismatch_ok(prev));
20761 }
20762 
20763 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)
20764 {
20765 	switch (base_type(type)) {
20766 	case PTR_TO_MEM:
20767 	case PTR_TO_BTF_ID:
20768 		return true;
20769 	default:
20770 		return false;
20771 	}
20772 }
20773 
20774 static bool is_ptr_to_mem(enum bpf_reg_type type)
20775 {
20776 	return base_type(type) == PTR_TO_MEM;
20777 }
20778 
20779 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
20780 			     bool allow_trust_mismatch)
20781 {
20782 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
20783 	enum bpf_reg_type merged_type;
20784 
20785 	if (*prev_type == NOT_INIT) {
20786 		/* Saw a valid insn
20787 		 * dst_reg = *(u32 *)(src_reg + off)
20788 		 * save type to validate intersecting paths
20789 		 */
20790 		*prev_type = type;
20791 	} else if (reg_type_mismatch(type, *prev_type)) {
20792 		/* Abuser program is trying to use the same insn
20793 		 * dst_reg = *(u32*) (src_reg + off)
20794 		 * with different pointer types:
20795 		 * src_reg == ctx in one branch and
20796 		 * src_reg == stack|map in some other branch.
20797 		 * Reject it.
20798 		 */
20799 		if (allow_trust_mismatch &&
20800 		    is_ptr_to_mem_or_btf_id(type) &&
20801 		    is_ptr_to_mem_or_btf_id(*prev_type)) {
20802 			/*
20803 			 * Have to support a use case when one path through
20804 			 * the program yields TRUSTED pointer while another
20805 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
20806 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
20807 			 * Same behavior of MEM_RDONLY flag.
20808 			 */
20809 			if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type))
20810 				merged_type = PTR_TO_MEM;
20811 			else
20812 				merged_type = PTR_TO_BTF_ID;
20813 			if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED))
20814 				merged_type |= PTR_UNTRUSTED;
20815 			if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY))
20816 				merged_type |= MEM_RDONLY;
20817 			*prev_type = merged_type;
20818 		} else {
20819 			verbose(env, "same insn cannot be used with different pointers\n");
20820 			return -EINVAL;
20821 		}
20822 	}
20823 
20824 	return 0;
20825 }
20826 
20827 enum {
20828 	PROCESS_BPF_EXIT = 1
20829 };
20830 
20831 static int process_bpf_exit_full(struct bpf_verifier_env *env,
20832 				 bool *do_print_state,
20833 				 bool exception_exit)
20834 {
20835 	/* We must do check_reference_leak here before
20836 	 * prepare_func_exit to handle the case when
20837 	 * state->curframe > 0, it may be a callback function,
20838 	 * for which reference_state must match caller reference
20839 	 * state when it exits.
20840 	 */
20841 	int err = check_resource_leak(env, exception_exit,
20842 				      !env->cur_state->curframe,
20843 				      "BPF_EXIT instruction in main prog");
20844 	if (err)
20845 		return err;
20846 
20847 	/* The side effect of the prepare_func_exit which is
20848 	 * being skipped is that it frees bpf_func_state.
20849 	 * Typically, process_bpf_exit will only be hit with
20850 	 * outermost exit. copy_verifier_state in pop_stack will
20851 	 * handle freeing of any extra bpf_func_state left over
20852 	 * from not processing all nested function exits. We
20853 	 * also skip return code checks as they are not needed
20854 	 * for exceptional exits.
20855 	 */
20856 	if (exception_exit)
20857 		return PROCESS_BPF_EXIT;
20858 
20859 	if (env->cur_state->curframe) {
20860 		/* exit from nested function */
20861 		err = prepare_func_exit(env, &env->insn_idx);
20862 		if (err)
20863 			return err;
20864 		*do_print_state = true;
20865 		return 0;
20866 	}
20867 
20868 	err = check_return_code(env, BPF_REG_0, "R0");
20869 	if (err)
20870 		return err;
20871 	return PROCESS_BPF_EXIT;
20872 }
20873 
20874 static int indirect_jump_min_max_index(struct bpf_verifier_env *env,
20875 				       int regno,
20876 				       struct bpf_map *map,
20877 				       u32 *pmin_index, u32 *pmax_index)
20878 {
20879 	struct bpf_reg_state *reg = reg_state(env, regno);
20880 	u64 min_index, max_index;
20881 	const u32 size = 8;
20882 
20883 	if (check_add_overflow(reg->umin_value, reg->off, &min_index) ||
20884 		(min_index > (u64) U32_MAX * size)) {
20885 		verbose(env, "the sum of R%u umin_value %llu and off %u is too big\n",
20886 			     regno, reg->umin_value, reg->off);
20887 		return -ERANGE;
20888 	}
20889 	if (check_add_overflow(reg->umax_value, reg->off, &max_index) ||
20890 		(max_index > (u64) U32_MAX * size)) {
20891 		verbose(env, "the sum of R%u umax_value %llu and off %u is too big\n",
20892 			     regno, reg->umax_value, reg->off);
20893 		return -ERANGE;
20894 	}
20895 
20896 	min_index /= size;
20897 	max_index /= size;
20898 
20899 	if (max_index >= map->max_entries) {
20900 		verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n",
20901 			     regno, min_index, max_index, map->max_entries);
20902 		return -EINVAL;
20903 	}
20904 
20905 	*pmin_index = min_index;
20906 	*pmax_index = max_index;
20907 	return 0;
20908 }
20909 
20910 /* gotox *dst_reg */
20911 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn)
20912 {
20913 	struct bpf_verifier_state *other_branch;
20914 	struct bpf_reg_state *dst_reg;
20915 	struct bpf_map *map;
20916 	u32 min_index, max_index;
20917 	int err = 0;
20918 	int n;
20919 	int i;
20920 
20921 	dst_reg = reg_state(env, insn->dst_reg);
20922 	if (dst_reg->type != PTR_TO_INSN) {
20923 		verbose(env, "R%d has type %s, expected PTR_TO_INSN\n",
20924 			     insn->dst_reg, reg_type_str(env, dst_reg->type));
20925 		return -EINVAL;
20926 	}
20927 
20928 	map = dst_reg->map_ptr;
20929 	if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg))
20930 		return -EFAULT;
20931 
20932 	if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env,
20933 			    "R%d has incorrect map type %d", insn->dst_reg, map->map_type))
20934 		return -EFAULT;
20935 
20936 	err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index);
20937 	if (err)
20938 		return err;
20939 
20940 	/* Ensure that the buffer is large enough */
20941 	if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) {
20942 		env->gotox_tmp_buf = iarray_realloc(env->gotox_tmp_buf,
20943 						    max_index - min_index + 1);
20944 		if (!env->gotox_tmp_buf)
20945 			return -ENOMEM;
20946 	}
20947 
20948 	n = copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items);
20949 	if (n < 0)
20950 		return n;
20951 	if (n == 0) {
20952 		verbose(env, "register R%d doesn't point to any offset in map id=%d\n",
20953 			     insn->dst_reg, map->id);
20954 		return -EINVAL;
20955 	}
20956 
20957 	for (i = 0; i < n - 1; i++) {
20958 		other_branch = push_stack(env, env->gotox_tmp_buf->items[i],
20959 					  env->insn_idx, env->cur_state->speculative);
20960 		if (IS_ERR(other_branch))
20961 			return PTR_ERR(other_branch);
20962 	}
20963 	env->insn_idx = env->gotox_tmp_buf->items[n-1];
20964 	return 0;
20965 }
20966 
20967 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
20968 {
20969 	int err;
20970 	struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
20971 	u8 class = BPF_CLASS(insn->code);
20972 
20973 	if (class == BPF_ALU || class == BPF_ALU64) {
20974 		err = check_alu_op(env, insn);
20975 		if (err)
20976 			return err;
20977 
20978 	} else if (class == BPF_LDX) {
20979 		bool is_ldsx = BPF_MODE(insn->code) == BPF_MEMSX;
20980 
20981 		/* Check for reserved fields is already done in
20982 		 * resolve_pseudo_ldimm64().
20983 		 */
20984 		err = check_load_mem(env, insn, false, is_ldsx, true, "ldx");
20985 		if (err)
20986 			return err;
20987 	} else if (class == BPF_STX) {
20988 		if (BPF_MODE(insn->code) == BPF_ATOMIC) {
20989 			err = check_atomic(env, insn);
20990 			if (err)
20991 				return err;
20992 			env->insn_idx++;
20993 			return 0;
20994 		}
20995 
20996 		if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
20997 			verbose(env, "BPF_STX uses reserved fields\n");
20998 			return -EINVAL;
20999 		}
21000 
21001 		err = check_store_reg(env, insn, false);
21002 		if (err)
21003 			return err;
21004 	} else if (class == BPF_ST) {
21005 		enum bpf_reg_type dst_reg_type;
21006 
21007 		if (BPF_MODE(insn->code) != BPF_MEM ||
21008 		    insn->src_reg != BPF_REG_0) {
21009 			verbose(env, "BPF_ST uses reserved fields\n");
21010 			return -EINVAL;
21011 		}
21012 		/* check src operand */
21013 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
21014 		if (err)
21015 			return err;
21016 
21017 		dst_reg_type = cur_regs(env)[insn->dst_reg].type;
21018 
21019 		/* check that memory (dst_reg + off) is writeable */
21020 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
21021 				       insn->off, BPF_SIZE(insn->code),
21022 				       BPF_WRITE, -1, false, false);
21023 		if (err)
21024 			return err;
21025 
21026 		err = save_aux_ptr_type(env, dst_reg_type, false);
21027 		if (err)
21028 			return err;
21029 	} else if (class == BPF_JMP || class == BPF_JMP32) {
21030 		u8 opcode = BPF_OP(insn->code);
21031 
21032 		env->jmps_processed++;
21033 		if (opcode == BPF_CALL) {
21034 			if (BPF_SRC(insn->code) != BPF_K ||
21035 			    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL &&
21036 			     insn->off != 0) ||
21037 			    (insn->src_reg != BPF_REG_0 &&
21038 			     insn->src_reg != BPF_PSEUDO_CALL &&
21039 			     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
21040 			    insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) {
21041 				verbose(env, "BPF_CALL uses reserved fields\n");
21042 				return -EINVAL;
21043 			}
21044 
21045 			if (env->cur_state->active_locks) {
21046 				if ((insn->src_reg == BPF_REG_0 &&
21047 				     insn->imm != BPF_FUNC_spin_unlock) ||
21048 				    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
21049 				     (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) {
21050 					verbose(env,
21051 						"function calls are not allowed while holding a lock\n");
21052 					return -EINVAL;
21053 				}
21054 			}
21055 			if (insn->src_reg == BPF_PSEUDO_CALL) {
21056 				err = check_func_call(env, insn, &env->insn_idx);
21057 			} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
21058 				err = check_kfunc_call(env, insn, &env->insn_idx);
21059 				if (!err && is_bpf_throw_kfunc(insn))
21060 					return process_bpf_exit_full(env, do_print_state, true);
21061 			} else {
21062 				err = check_helper_call(env, insn, &env->insn_idx);
21063 			}
21064 			if (err)
21065 				return err;
21066 
21067 			mark_reg_scratched(env, BPF_REG_0);
21068 		} else if (opcode == BPF_JA) {
21069 			if (BPF_SRC(insn->code) == BPF_X) {
21070 				if (insn->src_reg != BPF_REG_0 ||
21071 				    insn->imm != 0 || insn->off != 0) {
21072 					verbose(env, "BPF_JA|BPF_X uses reserved fields\n");
21073 					return -EINVAL;
21074 				}
21075 				return check_indirect_jump(env, insn);
21076 			}
21077 
21078 			if (BPF_SRC(insn->code) != BPF_K ||
21079 			    insn->src_reg != BPF_REG_0 ||
21080 			    insn->dst_reg != BPF_REG_0 ||
21081 			    (class == BPF_JMP && insn->imm != 0) ||
21082 			    (class == BPF_JMP32 && insn->off != 0)) {
21083 				verbose(env, "BPF_JA uses reserved fields\n");
21084 				return -EINVAL;
21085 			}
21086 
21087 			if (class == BPF_JMP)
21088 				env->insn_idx += insn->off + 1;
21089 			else
21090 				env->insn_idx += insn->imm + 1;
21091 			return 0;
21092 		} else if (opcode == BPF_EXIT) {
21093 			if (BPF_SRC(insn->code) != BPF_K ||
21094 			    insn->imm != 0 ||
21095 			    insn->src_reg != BPF_REG_0 ||
21096 			    insn->dst_reg != BPF_REG_0 ||
21097 			    class == BPF_JMP32) {
21098 				verbose(env, "BPF_EXIT uses reserved fields\n");
21099 				return -EINVAL;
21100 			}
21101 			return process_bpf_exit_full(env, do_print_state, false);
21102 		} else {
21103 			err = check_cond_jmp_op(env, insn, &env->insn_idx);
21104 			if (err)
21105 				return err;
21106 		}
21107 	} else if (class == BPF_LD) {
21108 		u8 mode = BPF_MODE(insn->code);
21109 
21110 		if (mode == BPF_ABS || mode == BPF_IND) {
21111 			err = check_ld_abs(env, insn);
21112 			if (err)
21113 				return err;
21114 
21115 		} else if (mode == BPF_IMM) {
21116 			err = check_ld_imm(env, insn);
21117 			if (err)
21118 				return err;
21119 
21120 			env->insn_idx++;
21121 			sanitize_mark_insn_seen(env);
21122 		} else {
21123 			verbose(env, "invalid BPF_LD mode\n");
21124 			return -EINVAL;
21125 		}
21126 	} else {
21127 		verbose(env, "unknown insn class %d\n", class);
21128 		return -EINVAL;
21129 	}
21130 
21131 	env->insn_idx++;
21132 	return 0;
21133 }
21134 
21135 static int do_check(struct bpf_verifier_env *env)
21136 {
21137 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
21138 	struct bpf_verifier_state *state = env->cur_state;
21139 	struct bpf_insn *insns = env->prog->insnsi;
21140 	int insn_cnt = env->prog->len;
21141 	bool do_print_state = false;
21142 	int prev_insn_idx = -1;
21143 
21144 	for (;;) {
21145 		struct bpf_insn *insn;
21146 		struct bpf_insn_aux_data *insn_aux;
21147 		int err, marks_err;
21148 
21149 		/* reset current history entry on each new instruction */
21150 		env->cur_hist_ent = NULL;
21151 
21152 		env->prev_insn_idx = prev_insn_idx;
21153 		if (env->insn_idx >= insn_cnt) {
21154 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
21155 				env->insn_idx, insn_cnt);
21156 			return -EFAULT;
21157 		}
21158 
21159 		insn = &insns[env->insn_idx];
21160 		insn_aux = &env->insn_aux_data[env->insn_idx];
21161 
21162 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
21163 			verbose(env,
21164 				"BPF program is too large. Processed %d insn\n",
21165 				env->insn_processed);
21166 			return -E2BIG;
21167 		}
21168 
21169 		state->last_insn_idx = env->prev_insn_idx;
21170 		state->insn_idx = env->insn_idx;
21171 
21172 		if (is_prune_point(env, env->insn_idx)) {
21173 			err = is_state_visited(env, env->insn_idx);
21174 			if (err < 0)
21175 				return err;
21176 			if (err == 1) {
21177 				/* found equivalent state, can prune the search */
21178 				if (env->log.level & BPF_LOG_LEVEL) {
21179 					if (do_print_state)
21180 						verbose(env, "\nfrom %d to %d%s: safe\n",
21181 							env->prev_insn_idx, env->insn_idx,
21182 							env->cur_state->speculative ?
21183 							" (speculative execution)" : "");
21184 					else
21185 						verbose(env, "%d: safe\n", env->insn_idx);
21186 				}
21187 				goto process_bpf_exit;
21188 			}
21189 		}
21190 
21191 		if (is_jmp_point(env, env->insn_idx)) {
21192 			err = push_jmp_history(env, state, 0, 0);
21193 			if (err)
21194 				return err;
21195 		}
21196 
21197 		if (signal_pending(current))
21198 			return -EAGAIN;
21199 
21200 		if (need_resched())
21201 			cond_resched();
21202 
21203 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
21204 			verbose(env, "\nfrom %d to %d%s:",
21205 				env->prev_insn_idx, env->insn_idx,
21206 				env->cur_state->speculative ?
21207 				" (speculative execution)" : "");
21208 			print_verifier_state(env, state, state->curframe, true);
21209 			do_print_state = false;
21210 		}
21211 
21212 		if (env->log.level & BPF_LOG_LEVEL) {
21213 			if (verifier_state_scratched(env))
21214 				print_insn_state(env, state, state->curframe);
21215 
21216 			verbose_linfo(env, env->insn_idx, "; ");
21217 			env->prev_log_pos = env->log.end_pos;
21218 			verbose(env, "%d: ", env->insn_idx);
21219 			verbose_insn(env, insn);
21220 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
21221 			env->prev_log_pos = env->log.end_pos;
21222 		}
21223 
21224 		if (bpf_prog_is_offloaded(env->prog->aux)) {
21225 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
21226 							   env->prev_insn_idx);
21227 			if (err)
21228 				return err;
21229 		}
21230 
21231 		sanitize_mark_insn_seen(env);
21232 		prev_insn_idx = env->insn_idx;
21233 
21234 		/* Reduce verification complexity by stopping speculative path
21235 		 * verification when a nospec is encountered.
21236 		 */
21237 		if (state->speculative && insn_aux->nospec)
21238 			goto process_bpf_exit;
21239 
21240 		err = bpf_reset_stack_write_marks(env, env->insn_idx);
21241 		if (err)
21242 			return err;
21243 		err = do_check_insn(env, &do_print_state);
21244 		if (err >= 0 || error_recoverable_with_nospec(err)) {
21245 			marks_err = bpf_commit_stack_write_marks(env);
21246 			if (marks_err)
21247 				return marks_err;
21248 		}
21249 		if (error_recoverable_with_nospec(err) && state->speculative) {
21250 			/* Prevent this speculative path from ever reaching the
21251 			 * insn that would have been unsafe to execute.
21252 			 */
21253 			insn_aux->nospec = true;
21254 			/* If it was an ADD/SUB insn, potentially remove any
21255 			 * markings for alu sanitization.
21256 			 */
21257 			insn_aux->alu_state = 0;
21258 			goto process_bpf_exit;
21259 		} else if (err < 0) {
21260 			return err;
21261 		} else if (err == PROCESS_BPF_EXIT) {
21262 			goto process_bpf_exit;
21263 		}
21264 		WARN_ON_ONCE(err);
21265 
21266 		if (state->speculative && insn_aux->nospec_result) {
21267 			/* If we are on a path that performed a jump-op, this
21268 			 * may skip a nospec patched-in after the jump. This can
21269 			 * currently never happen because nospec_result is only
21270 			 * used for the write-ops
21271 			 * `*(size*)(dst_reg+off)=src_reg|imm32` and helper
21272 			 * calls. These must never skip the following insn
21273 			 * (i.e., bpf_insn_successors()'s opcode_info.can_jump
21274 			 * is false). Still, add a warning to document this in
21275 			 * case nospec_result is used elsewhere in the future.
21276 			 *
21277 			 * All non-branch instructions have a single
21278 			 * fall-through edge. For these, nospec_result should
21279 			 * already work.
21280 			 */
21281 			if (verifier_bug_if((BPF_CLASS(insn->code) == BPF_JMP ||
21282 					     BPF_CLASS(insn->code) == BPF_JMP32) &&
21283 					    BPF_OP(insn->code) != BPF_CALL, env,
21284 					    "speculation barrier after jump instruction may not have the desired effect"))
21285 				return -EFAULT;
21286 process_bpf_exit:
21287 			mark_verifier_state_scratched(env);
21288 			err = update_branch_counts(env, env->cur_state);
21289 			if (err)
21290 				return err;
21291 			err = bpf_update_live_stack(env);
21292 			if (err)
21293 				return err;
21294 			err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
21295 					pop_log);
21296 			if (err < 0) {
21297 				if (err != -ENOENT)
21298 					return err;
21299 				break;
21300 			} else {
21301 				do_print_state = true;
21302 				continue;
21303 			}
21304 		}
21305 	}
21306 
21307 	return 0;
21308 }
21309 
21310 static int find_btf_percpu_datasec(struct btf *btf)
21311 {
21312 	const struct btf_type *t;
21313 	const char *tname;
21314 	int i, n;
21315 
21316 	/*
21317 	 * Both vmlinux and module each have their own ".data..percpu"
21318 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
21319 	 * types to look at only module's own BTF types.
21320 	 */
21321 	n = btf_nr_types(btf);
21322 	for (i = btf_named_start_id(btf, true); i < n; i++) {
21323 		t = btf_type_by_id(btf, i);
21324 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
21325 			continue;
21326 
21327 		tname = btf_name_by_offset(btf, t->name_off);
21328 		if (!strcmp(tname, ".data..percpu"))
21329 			return i;
21330 	}
21331 
21332 	return -ENOENT;
21333 }
21334 
21335 /*
21336  * Add btf to the used_btfs array and return the index. (If the btf was
21337  * already added, then just return the index.) Upon successful insertion
21338  * increase btf refcnt, and, if present, also refcount the corresponding
21339  * kernel module.
21340  */
21341 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
21342 {
21343 	struct btf_mod_pair *btf_mod;
21344 	int i;
21345 
21346 	/* check whether we recorded this BTF (and maybe module) already */
21347 	for (i = 0; i < env->used_btf_cnt; i++)
21348 		if (env->used_btfs[i].btf == btf)
21349 			return i;
21350 
21351 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
21352 		verbose(env, "The total number of btfs per program has reached the limit of %u\n",
21353 			MAX_USED_BTFS);
21354 		return -E2BIG;
21355 	}
21356 
21357 	btf_get(btf);
21358 
21359 	btf_mod = &env->used_btfs[env->used_btf_cnt];
21360 	btf_mod->btf = btf;
21361 	btf_mod->module = NULL;
21362 
21363 	/* if we reference variables from kernel module, bump its refcount */
21364 	if (btf_is_module(btf)) {
21365 		btf_mod->module = btf_try_get_module(btf);
21366 		if (!btf_mod->module) {
21367 			btf_put(btf);
21368 			return -ENXIO;
21369 		}
21370 	}
21371 
21372 	return env->used_btf_cnt++;
21373 }
21374 
21375 /* replace pseudo btf_id with kernel symbol address */
21376 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
21377 				 struct bpf_insn *insn,
21378 				 struct bpf_insn_aux_data *aux,
21379 				 struct btf *btf)
21380 {
21381 	const struct btf_var_secinfo *vsi;
21382 	const struct btf_type *datasec;
21383 	const struct btf_type *t;
21384 	const char *sym_name;
21385 	bool percpu = false;
21386 	u32 type, id = insn->imm;
21387 	s32 datasec_id;
21388 	u64 addr;
21389 	int i;
21390 
21391 	t = btf_type_by_id(btf, id);
21392 	if (!t) {
21393 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
21394 		return -ENOENT;
21395 	}
21396 
21397 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
21398 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
21399 		return -EINVAL;
21400 	}
21401 
21402 	sym_name = btf_name_by_offset(btf, t->name_off);
21403 	addr = kallsyms_lookup_name(sym_name);
21404 	if (!addr) {
21405 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
21406 			sym_name);
21407 		return -ENOENT;
21408 	}
21409 	insn[0].imm = (u32)addr;
21410 	insn[1].imm = addr >> 32;
21411 
21412 	if (btf_type_is_func(t)) {
21413 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
21414 		aux->btf_var.mem_size = 0;
21415 		return 0;
21416 	}
21417 
21418 	datasec_id = find_btf_percpu_datasec(btf);
21419 	if (datasec_id > 0) {
21420 		datasec = btf_type_by_id(btf, datasec_id);
21421 		for_each_vsi(i, datasec, vsi) {
21422 			if (vsi->type == id) {
21423 				percpu = true;
21424 				break;
21425 			}
21426 		}
21427 	}
21428 
21429 	type = t->type;
21430 	t = btf_type_skip_modifiers(btf, type, NULL);
21431 	if (percpu) {
21432 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
21433 		aux->btf_var.btf = btf;
21434 		aux->btf_var.btf_id = type;
21435 	} else if (!btf_type_is_struct(t)) {
21436 		const struct btf_type *ret;
21437 		const char *tname;
21438 		u32 tsize;
21439 
21440 		/* resolve the type size of ksym. */
21441 		ret = btf_resolve_size(btf, t, &tsize);
21442 		if (IS_ERR(ret)) {
21443 			tname = btf_name_by_offset(btf, t->name_off);
21444 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
21445 				tname, PTR_ERR(ret));
21446 			return -EINVAL;
21447 		}
21448 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
21449 		aux->btf_var.mem_size = tsize;
21450 	} else {
21451 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
21452 		aux->btf_var.btf = btf;
21453 		aux->btf_var.btf_id = type;
21454 	}
21455 
21456 	return 0;
21457 }
21458 
21459 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
21460 			       struct bpf_insn *insn,
21461 			       struct bpf_insn_aux_data *aux)
21462 {
21463 	struct btf *btf;
21464 	int btf_fd;
21465 	int err;
21466 
21467 	btf_fd = insn[1].imm;
21468 	if (btf_fd) {
21469 		CLASS(fd, f)(btf_fd);
21470 
21471 		btf = __btf_get_by_fd(f);
21472 		if (IS_ERR(btf)) {
21473 			verbose(env, "invalid module BTF object FD specified.\n");
21474 			return -EINVAL;
21475 		}
21476 	} else {
21477 		if (!btf_vmlinux) {
21478 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
21479 			return -EINVAL;
21480 		}
21481 		btf = btf_vmlinux;
21482 	}
21483 
21484 	err = __check_pseudo_btf_id(env, insn, aux, btf);
21485 	if (err)
21486 		return err;
21487 
21488 	err = __add_used_btf(env, btf);
21489 	if (err < 0)
21490 		return err;
21491 	return 0;
21492 }
21493 
21494 static bool is_tracing_prog_type(enum bpf_prog_type type)
21495 {
21496 	switch (type) {
21497 	case BPF_PROG_TYPE_KPROBE:
21498 	case BPF_PROG_TYPE_TRACEPOINT:
21499 	case BPF_PROG_TYPE_PERF_EVENT:
21500 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
21501 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
21502 		return true;
21503 	default:
21504 		return false;
21505 	}
21506 }
21507 
21508 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
21509 {
21510 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
21511 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
21512 }
21513 
21514 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
21515 					struct bpf_map *map,
21516 					struct bpf_prog *prog)
21517 
21518 {
21519 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
21520 
21521 	if (map->excl_prog_sha &&
21522 	    memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) {
21523 		verbose(env, "program's hash doesn't match map's excl_prog_hash\n");
21524 		return -EACCES;
21525 	}
21526 
21527 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
21528 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
21529 		if (is_tracing_prog_type(prog_type)) {
21530 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
21531 			return -EINVAL;
21532 		}
21533 	}
21534 
21535 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
21536 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
21537 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
21538 			return -EINVAL;
21539 		}
21540 
21541 		if (is_tracing_prog_type(prog_type)) {
21542 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
21543 			return -EINVAL;
21544 		}
21545 	}
21546 
21547 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
21548 	    !bpf_offload_prog_map_match(prog, map)) {
21549 		verbose(env, "offload device mismatch between prog and map\n");
21550 		return -EINVAL;
21551 	}
21552 
21553 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
21554 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
21555 		return -EINVAL;
21556 	}
21557 
21558 	if (prog->sleepable)
21559 		switch (map->map_type) {
21560 		case BPF_MAP_TYPE_HASH:
21561 		case BPF_MAP_TYPE_LRU_HASH:
21562 		case BPF_MAP_TYPE_ARRAY:
21563 		case BPF_MAP_TYPE_PERCPU_HASH:
21564 		case BPF_MAP_TYPE_PERCPU_ARRAY:
21565 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
21566 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
21567 		case BPF_MAP_TYPE_HASH_OF_MAPS:
21568 		case BPF_MAP_TYPE_RINGBUF:
21569 		case BPF_MAP_TYPE_USER_RINGBUF:
21570 		case BPF_MAP_TYPE_INODE_STORAGE:
21571 		case BPF_MAP_TYPE_SK_STORAGE:
21572 		case BPF_MAP_TYPE_TASK_STORAGE:
21573 		case BPF_MAP_TYPE_CGRP_STORAGE:
21574 		case BPF_MAP_TYPE_QUEUE:
21575 		case BPF_MAP_TYPE_STACK:
21576 		case BPF_MAP_TYPE_ARENA:
21577 		case BPF_MAP_TYPE_INSN_ARRAY:
21578 		case BPF_MAP_TYPE_PROG_ARRAY:
21579 			break;
21580 		default:
21581 			verbose(env,
21582 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
21583 			return -EINVAL;
21584 		}
21585 
21586 	if (bpf_map_is_cgroup_storage(map) &&
21587 	    bpf_cgroup_storage_assign(env->prog->aux, map)) {
21588 		verbose(env, "only one cgroup storage of each type is allowed\n");
21589 		return -EBUSY;
21590 	}
21591 
21592 	if (map->map_type == BPF_MAP_TYPE_ARENA) {
21593 		if (env->prog->aux->arena) {
21594 			verbose(env, "Only one arena per program\n");
21595 			return -EBUSY;
21596 		}
21597 		if (!env->allow_ptr_leaks || !env->bpf_capable) {
21598 			verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
21599 			return -EPERM;
21600 		}
21601 		if (!env->prog->jit_requested) {
21602 			verbose(env, "JIT is required to use arena\n");
21603 			return -EOPNOTSUPP;
21604 		}
21605 		if (!bpf_jit_supports_arena()) {
21606 			verbose(env, "JIT doesn't support arena\n");
21607 			return -EOPNOTSUPP;
21608 		}
21609 		env->prog->aux->arena = (void *)map;
21610 		if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
21611 			verbose(env, "arena's user address must be set via map_extra or mmap()\n");
21612 			return -EINVAL;
21613 		}
21614 	}
21615 
21616 	return 0;
21617 }
21618 
21619 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
21620 {
21621 	int i, err;
21622 
21623 	/* check whether we recorded this map already */
21624 	for (i = 0; i < env->used_map_cnt; i++)
21625 		if (env->used_maps[i] == map)
21626 			return i;
21627 
21628 	if (env->used_map_cnt >= MAX_USED_MAPS) {
21629 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
21630 			MAX_USED_MAPS);
21631 		return -E2BIG;
21632 	}
21633 
21634 	err = check_map_prog_compatibility(env, map, env->prog);
21635 	if (err)
21636 		return err;
21637 
21638 	if (env->prog->sleepable)
21639 		atomic64_inc(&map->sleepable_refcnt);
21640 
21641 	/* hold the map. If the program is rejected by verifier,
21642 	 * the map will be released by release_maps() or it
21643 	 * will be used by the valid program until it's unloaded
21644 	 * and all maps are released in bpf_free_used_maps()
21645 	 */
21646 	bpf_map_inc(map);
21647 
21648 	env->used_maps[env->used_map_cnt++] = map;
21649 
21650 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
21651 		err = bpf_insn_array_init(map, env->prog);
21652 		if (err) {
21653 			verbose(env, "Failed to properly initialize insn array\n");
21654 			return err;
21655 		}
21656 		env->insn_array_maps[env->insn_array_map_cnt++] = map;
21657 	}
21658 
21659 	return env->used_map_cnt - 1;
21660 }
21661 
21662 /* Add map behind fd to used maps list, if it's not already there, and return
21663  * its index.
21664  * Returns <0 on error, or >= 0 index, on success.
21665  */
21666 static int add_used_map(struct bpf_verifier_env *env, int fd)
21667 {
21668 	struct bpf_map *map;
21669 	CLASS(fd, f)(fd);
21670 
21671 	map = __bpf_map_get(f);
21672 	if (IS_ERR(map)) {
21673 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
21674 		return PTR_ERR(map);
21675 	}
21676 
21677 	return __add_used_map(env, map);
21678 }
21679 
21680 /* find and rewrite pseudo imm in ld_imm64 instructions:
21681  *
21682  * 1. if it accesses map FD, replace it with actual map pointer.
21683  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
21684  *
21685  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
21686  */
21687 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
21688 {
21689 	struct bpf_insn *insn = env->prog->insnsi;
21690 	int insn_cnt = env->prog->len;
21691 	int i, err;
21692 
21693 	err = bpf_prog_calc_tag(env->prog);
21694 	if (err)
21695 		return err;
21696 
21697 	for (i = 0; i < insn_cnt; i++, insn++) {
21698 		if (BPF_CLASS(insn->code) == BPF_LDX &&
21699 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
21700 		    insn->imm != 0)) {
21701 			verbose(env, "BPF_LDX uses reserved fields\n");
21702 			return -EINVAL;
21703 		}
21704 
21705 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
21706 			struct bpf_insn_aux_data *aux;
21707 			struct bpf_map *map;
21708 			int map_idx;
21709 			u64 addr;
21710 			u32 fd;
21711 
21712 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
21713 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
21714 			    insn[1].off != 0) {
21715 				verbose(env, "invalid bpf_ld_imm64 insn\n");
21716 				return -EINVAL;
21717 			}
21718 
21719 			if (insn[0].src_reg == 0)
21720 				/* valid generic load 64-bit imm */
21721 				goto next_insn;
21722 
21723 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
21724 				aux = &env->insn_aux_data[i];
21725 				err = check_pseudo_btf_id(env, insn, aux);
21726 				if (err)
21727 					return err;
21728 				goto next_insn;
21729 			}
21730 
21731 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
21732 				aux = &env->insn_aux_data[i];
21733 				aux->ptr_type = PTR_TO_FUNC;
21734 				goto next_insn;
21735 			}
21736 
21737 			/* In final convert_pseudo_ld_imm64() step, this is
21738 			 * converted into regular 64-bit imm load insn.
21739 			 */
21740 			switch (insn[0].src_reg) {
21741 			case BPF_PSEUDO_MAP_VALUE:
21742 			case BPF_PSEUDO_MAP_IDX_VALUE:
21743 				break;
21744 			case BPF_PSEUDO_MAP_FD:
21745 			case BPF_PSEUDO_MAP_IDX:
21746 				if (insn[1].imm == 0)
21747 					break;
21748 				fallthrough;
21749 			default:
21750 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
21751 				return -EINVAL;
21752 			}
21753 
21754 			switch (insn[0].src_reg) {
21755 			case BPF_PSEUDO_MAP_IDX_VALUE:
21756 			case BPF_PSEUDO_MAP_IDX:
21757 				if (bpfptr_is_null(env->fd_array)) {
21758 					verbose(env, "fd_idx without fd_array is invalid\n");
21759 					return -EPROTO;
21760 				}
21761 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
21762 							    insn[0].imm * sizeof(fd),
21763 							    sizeof(fd)))
21764 					return -EFAULT;
21765 				break;
21766 			default:
21767 				fd = insn[0].imm;
21768 				break;
21769 			}
21770 
21771 			map_idx = add_used_map(env, fd);
21772 			if (map_idx < 0)
21773 				return map_idx;
21774 			map = env->used_maps[map_idx];
21775 
21776 			aux = &env->insn_aux_data[i];
21777 			aux->map_index = map_idx;
21778 
21779 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
21780 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
21781 				addr = (unsigned long)map;
21782 			} else {
21783 				u32 off = insn[1].imm;
21784 
21785 				if (!map->ops->map_direct_value_addr) {
21786 					verbose(env, "no direct value access support for this map type\n");
21787 					return -EINVAL;
21788 				}
21789 
21790 				err = map->ops->map_direct_value_addr(map, &addr, off);
21791 				if (err) {
21792 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
21793 						map->value_size, off);
21794 					return err;
21795 				}
21796 
21797 				aux->map_off = off;
21798 				addr += off;
21799 			}
21800 
21801 			insn[0].imm = (u32)addr;
21802 			insn[1].imm = addr >> 32;
21803 
21804 next_insn:
21805 			insn++;
21806 			i++;
21807 			continue;
21808 		}
21809 
21810 		/* Basic sanity check before we invest more work here. */
21811 		if (!bpf_opcode_in_insntable(insn->code)) {
21812 			verbose(env, "unknown opcode %02x\n", insn->code);
21813 			return -EINVAL;
21814 		}
21815 	}
21816 
21817 	/* now all pseudo BPF_LD_IMM64 instructions load valid
21818 	 * 'struct bpf_map *' into a register instead of user map_fd.
21819 	 * These pointers will be used later by verifier to validate map access.
21820 	 */
21821 	return 0;
21822 }
21823 
21824 /* drop refcnt of maps used by the rejected program */
21825 static void release_maps(struct bpf_verifier_env *env)
21826 {
21827 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
21828 			     env->used_map_cnt);
21829 }
21830 
21831 /* drop refcnt of maps used by the rejected program */
21832 static void release_btfs(struct bpf_verifier_env *env)
21833 {
21834 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
21835 }
21836 
21837 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
21838 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
21839 {
21840 	struct bpf_insn *insn = env->prog->insnsi;
21841 	int insn_cnt = env->prog->len;
21842 	int i;
21843 
21844 	for (i = 0; i < insn_cnt; i++, insn++) {
21845 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
21846 			continue;
21847 		if (insn->src_reg == BPF_PSEUDO_FUNC)
21848 			continue;
21849 		insn->src_reg = 0;
21850 	}
21851 }
21852 
21853 /* single env->prog->insni[off] instruction was replaced with the range
21854  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
21855  * [0, off) and [off, end) to new locations, so the patched range stays zero
21856  */
21857 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
21858 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
21859 {
21860 	struct bpf_insn_aux_data *data = env->insn_aux_data;
21861 	struct bpf_insn *insn = new_prog->insnsi;
21862 	u32 old_seen = data[off].seen;
21863 	u32 prog_len;
21864 	int i;
21865 
21866 	/* aux info at OFF always needs adjustment, no matter fast path
21867 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
21868 	 * original insn at old prog.
21869 	 */
21870 	data[off].zext_dst = insn_has_def32(insn + off + cnt - 1);
21871 
21872 	if (cnt == 1)
21873 		return;
21874 	prog_len = new_prog->len;
21875 
21876 	memmove(data + off + cnt - 1, data + off,
21877 		sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
21878 	memset(data + off, 0, sizeof(struct bpf_insn_aux_data) * (cnt - 1));
21879 	for (i = off; i < off + cnt - 1; i++) {
21880 		/* Expand insni[off]'s seen count to the patched range. */
21881 		data[i].seen = old_seen;
21882 		data[i].zext_dst = insn_has_def32(insn + i);
21883 	}
21884 }
21885 
21886 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
21887 {
21888 	int i;
21889 
21890 	if (len == 1)
21891 		return;
21892 	/* NOTE: fake 'exit' subprog should be updated as well. */
21893 	for (i = 0; i <= env->subprog_cnt; i++) {
21894 		if (env->subprog_info[i].start <= off)
21895 			continue;
21896 		env->subprog_info[i].start += len - 1;
21897 	}
21898 }
21899 
21900 static void release_insn_arrays(struct bpf_verifier_env *env)
21901 {
21902 	int i;
21903 
21904 	for (i = 0; i < env->insn_array_map_cnt; i++)
21905 		bpf_insn_array_release(env->insn_array_maps[i]);
21906 }
21907 
21908 static void adjust_insn_arrays(struct bpf_verifier_env *env, u32 off, u32 len)
21909 {
21910 	int i;
21911 
21912 	if (len == 1)
21913 		return;
21914 
21915 	for (i = 0; i < env->insn_array_map_cnt; i++)
21916 		bpf_insn_array_adjust(env->insn_array_maps[i], off, len);
21917 }
21918 
21919 static void adjust_insn_arrays_after_remove(struct bpf_verifier_env *env, u32 off, u32 len)
21920 {
21921 	int i;
21922 
21923 	for (i = 0; i < env->insn_array_map_cnt; i++)
21924 		bpf_insn_array_adjust_after_remove(env->insn_array_maps[i], off, len);
21925 }
21926 
21927 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
21928 {
21929 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
21930 	int i, sz = prog->aux->size_poke_tab;
21931 	struct bpf_jit_poke_descriptor *desc;
21932 
21933 	for (i = 0; i < sz; i++) {
21934 		desc = &tab[i];
21935 		if (desc->insn_idx <= off)
21936 			continue;
21937 		desc->insn_idx += len - 1;
21938 	}
21939 }
21940 
21941 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
21942 					    const struct bpf_insn *patch, u32 len)
21943 {
21944 	struct bpf_prog *new_prog;
21945 	struct bpf_insn_aux_data *new_data = NULL;
21946 
21947 	if (len > 1) {
21948 		new_data = vrealloc(env->insn_aux_data,
21949 				    array_size(env->prog->len + len - 1,
21950 					       sizeof(struct bpf_insn_aux_data)),
21951 				    GFP_KERNEL_ACCOUNT | __GFP_ZERO);
21952 		if (!new_data)
21953 			return NULL;
21954 
21955 		env->insn_aux_data = new_data;
21956 	}
21957 
21958 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
21959 	if (IS_ERR(new_prog)) {
21960 		if (PTR_ERR(new_prog) == -ERANGE)
21961 			verbose(env,
21962 				"insn %d cannot be patched due to 16-bit range\n",
21963 				env->insn_aux_data[off].orig_idx);
21964 		return NULL;
21965 	}
21966 	adjust_insn_aux_data(env, new_prog, off, len);
21967 	adjust_subprog_starts(env, off, len);
21968 	adjust_insn_arrays(env, off, len);
21969 	adjust_poke_descs(new_prog, off, len);
21970 	return new_prog;
21971 }
21972 
21973 /*
21974  * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
21975  * jump offset by 'delta'.
21976  */
21977 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
21978 {
21979 	struct bpf_insn *insn = prog->insnsi;
21980 	u32 insn_cnt = prog->len, i;
21981 	s32 imm;
21982 	s16 off;
21983 
21984 	for (i = 0; i < insn_cnt; i++, insn++) {
21985 		u8 code = insn->code;
21986 
21987 		if (tgt_idx <= i && i < tgt_idx + delta)
21988 			continue;
21989 
21990 		if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
21991 		    BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
21992 			continue;
21993 
21994 		if (insn->code == (BPF_JMP32 | BPF_JA)) {
21995 			if (i + 1 + insn->imm != tgt_idx)
21996 				continue;
21997 			if (check_add_overflow(insn->imm, delta, &imm))
21998 				return -ERANGE;
21999 			insn->imm = imm;
22000 		} else {
22001 			if (i + 1 + insn->off != tgt_idx)
22002 				continue;
22003 			if (check_add_overflow(insn->off, delta, &off))
22004 				return -ERANGE;
22005 			insn->off = off;
22006 		}
22007 	}
22008 	return 0;
22009 }
22010 
22011 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
22012 					      u32 off, u32 cnt)
22013 {
22014 	int i, j;
22015 
22016 	/* find first prog starting at or after off (first to remove) */
22017 	for (i = 0; i < env->subprog_cnt; i++)
22018 		if (env->subprog_info[i].start >= off)
22019 			break;
22020 	/* find first prog starting at or after off + cnt (first to stay) */
22021 	for (j = i; j < env->subprog_cnt; j++)
22022 		if (env->subprog_info[j].start >= off + cnt)
22023 			break;
22024 	/* if j doesn't start exactly at off + cnt, we are just removing
22025 	 * the front of previous prog
22026 	 */
22027 	if (env->subprog_info[j].start != off + cnt)
22028 		j--;
22029 
22030 	if (j > i) {
22031 		struct bpf_prog_aux *aux = env->prog->aux;
22032 		int move;
22033 
22034 		/* move fake 'exit' subprog as well */
22035 		move = env->subprog_cnt + 1 - j;
22036 
22037 		memmove(env->subprog_info + i,
22038 			env->subprog_info + j,
22039 			sizeof(*env->subprog_info) * move);
22040 		env->subprog_cnt -= j - i;
22041 
22042 		/* remove func_info */
22043 		if (aux->func_info) {
22044 			move = aux->func_info_cnt - j;
22045 
22046 			memmove(aux->func_info + i,
22047 				aux->func_info + j,
22048 				sizeof(*aux->func_info) * move);
22049 			aux->func_info_cnt -= j - i;
22050 			/* func_info->insn_off is set after all code rewrites,
22051 			 * in adjust_btf_func() - no need to adjust
22052 			 */
22053 		}
22054 	} else {
22055 		/* convert i from "first prog to remove" to "first to adjust" */
22056 		if (env->subprog_info[i].start == off)
22057 			i++;
22058 	}
22059 
22060 	/* update fake 'exit' subprog as well */
22061 	for (; i <= env->subprog_cnt; i++)
22062 		env->subprog_info[i].start -= cnt;
22063 
22064 	return 0;
22065 }
22066 
22067 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
22068 				      u32 cnt)
22069 {
22070 	struct bpf_prog *prog = env->prog;
22071 	u32 i, l_off, l_cnt, nr_linfo;
22072 	struct bpf_line_info *linfo;
22073 
22074 	nr_linfo = prog->aux->nr_linfo;
22075 	if (!nr_linfo)
22076 		return 0;
22077 
22078 	linfo = prog->aux->linfo;
22079 
22080 	/* find first line info to remove, count lines to be removed */
22081 	for (i = 0; i < nr_linfo; i++)
22082 		if (linfo[i].insn_off >= off)
22083 			break;
22084 
22085 	l_off = i;
22086 	l_cnt = 0;
22087 	for (; i < nr_linfo; i++)
22088 		if (linfo[i].insn_off < off + cnt)
22089 			l_cnt++;
22090 		else
22091 			break;
22092 
22093 	/* First live insn doesn't match first live linfo, it needs to "inherit"
22094 	 * last removed linfo.  prog is already modified, so prog->len == off
22095 	 * means no live instructions after (tail of the program was removed).
22096 	 */
22097 	if (prog->len != off && l_cnt &&
22098 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
22099 		l_cnt--;
22100 		linfo[--i].insn_off = off + cnt;
22101 	}
22102 
22103 	/* remove the line info which refer to the removed instructions */
22104 	if (l_cnt) {
22105 		memmove(linfo + l_off, linfo + i,
22106 			sizeof(*linfo) * (nr_linfo - i));
22107 
22108 		prog->aux->nr_linfo -= l_cnt;
22109 		nr_linfo = prog->aux->nr_linfo;
22110 	}
22111 
22112 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
22113 	for (i = l_off; i < nr_linfo; i++)
22114 		linfo[i].insn_off -= cnt;
22115 
22116 	/* fix up all subprogs (incl. 'exit') which start >= off */
22117 	for (i = 0; i <= env->subprog_cnt; i++)
22118 		if (env->subprog_info[i].linfo_idx > l_off) {
22119 			/* program may have started in the removed region but
22120 			 * may not be fully removed
22121 			 */
22122 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
22123 				env->subprog_info[i].linfo_idx -= l_cnt;
22124 			else
22125 				env->subprog_info[i].linfo_idx = l_off;
22126 		}
22127 
22128 	return 0;
22129 }
22130 
22131 /*
22132  * Clean up dynamically allocated fields of aux data for instructions [start, ...]
22133  */
22134 static void clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len)
22135 {
22136 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
22137 	struct bpf_insn *insns = env->prog->insnsi;
22138 	int end = start + len;
22139 	int i;
22140 
22141 	for (i = start; i < end; i++) {
22142 		if (aux_data[i].jt) {
22143 			kvfree(aux_data[i].jt);
22144 			aux_data[i].jt = NULL;
22145 		}
22146 
22147 		if (bpf_is_ldimm64(&insns[i]))
22148 			i++;
22149 	}
22150 }
22151 
22152 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
22153 {
22154 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
22155 	unsigned int orig_prog_len = env->prog->len;
22156 	int err;
22157 
22158 	if (bpf_prog_is_offloaded(env->prog->aux))
22159 		bpf_prog_offload_remove_insns(env, off, cnt);
22160 
22161 	/* Should be called before bpf_remove_insns, as it uses prog->insnsi */
22162 	clear_insn_aux_data(env, off, cnt);
22163 
22164 	err = bpf_remove_insns(env->prog, off, cnt);
22165 	if (err)
22166 		return err;
22167 
22168 	err = adjust_subprog_starts_after_remove(env, off, cnt);
22169 	if (err)
22170 		return err;
22171 
22172 	err = bpf_adj_linfo_after_remove(env, off, cnt);
22173 	if (err)
22174 		return err;
22175 
22176 	adjust_insn_arrays_after_remove(env, off, cnt);
22177 
22178 	memmove(aux_data + off,	aux_data + off + cnt,
22179 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
22180 
22181 	return 0;
22182 }
22183 
22184 /* The verifier does more data flow analysis than llvm and will not
22185  * explore branches that are dead at run time. Malicious programs can
22186  * have dead code too. Therefore replace all dead at-run-time code
22187  * with 'ja -1'.
22188  *
22189  * Just nops are not optimal, e.g. if they would sit at the end of the
22190  * program and through another bug we would manage to jump there, then
22191  * we'd execute beyond program memory otherwise. Returning exception
22192  * code also wouldn't work since we can have subprogs where the dead
22193  * code could be located.
22194  */
22195 static void sanitize_dead_code(struct bpf_verifier_env *env)
22196 {
22197 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
22198 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
22199 	struct bpf_insn *insn = env->prog->insnsi;
22200 	const int insn_cnt = env->prog->len;
22201 	int i;
22202 
22203 	for (i = 0; i < insn_cnt; i++) {
22204 		if (aux_data[i].seen)
22205 			continue;
22206 		memcpy(insn + i, &trap, sizeof(trap));
22207 		aux_data[i].zext_dst = false;
22208 	}
22209 }
22210 
22211 static bool insn_is_cond_jump(u8 code)
22212 {
22213 	u8 op;
22214 
22215 	op = BPF_OP(code);
22216 	if (BPF_CLASS(code) == BPF_JMP32)
22217 		return op != BPF_JA;
22218 
22219 	if (BPF_CLASS(code) != BPF_JMP)
22220 		return false;
22221 
22222 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
22223 }
22224 
22225 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
22226 {
22227 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
22228 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
22229 	struct bpf_insn *insn = env->prog->insnsi;
22230 	const int insn_cnt = env->prog->len;
22231 	int i;
22232 
22233 	for (i = 0; i < insn_cnt; i++, insn++) {
22234 		if (!insn_is_cond_jump(insn->code))
22235 			continue;
22236 
22237 		if (!aux_data[i + 1].seen)
22238 			ja.off = insn->off;
22239 		else if (!aux_data[i + 1 + insn->off].seen)
22240 			ja.off = 0;
22241 		else
22242 			continue;
22243 
22244 		if (bpf_prog_is_offloaded(env->prog->aux))
22245 			bpf_prog_offload_replace_insn(env, i, &ja);
22246 
22247 		memcpy(insn, &ja, sizeof(ja));
22248 	}
22249 }
22250 
22251 static int opt_remove_dead_code(struct bpf_verifier_env *env)
22252 {
22253 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
22254 	int insn_cnt = env->prog->len;
22255 	int i, err;
22256 
22257 	for (i = 0; i < insn_cnt; i++) {
22258 		int j;
22259 
22260 		j = 0;
22261 		while (i + j < insn_cnt && !aux_data[i + j].seen)
22262 			j++;
22263 		if (!j)
22264 			continue;
22265 
22266 		err = verifier_remove_insns(env, i, j);
22267 		if (err)
22268 			return err;
22269 		insn_cnt = env->prog->len;
22270 	}
22271 
22272 	return 0;
22273 }
22274 
22275 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
22276 static const struct bpf_insn MAY_GOTO_0 = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0);
22277 
22278 static int opt_remove_nops(struct bpf_verifier_env *env)
22279 {
22280 	struct bpf_insn *insn = env->prog->insnsi;
22281 	int insn_cnt = env->prog->len;
22282 	bool is_may_goto_0, is_ja;
22283 	int i, err;
22284 
22285 	for (i = 0; i < insn_cnt; i++) {
22286 		is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0));
22287 		is_ja = !memcmp(&insn[i], &NOP, sizeof(NOP));
22288 
22289 		if (!is_may_goto_0 && !is_ja)
22290 			continue;
22291 
22292 		err = verifier_remove_insns(env, i, 1);
22293 		if (err)
22294 			return err;
22295 		insn_cnt--;
22296 		/* Go back one insn to catch may_goto +1; may_goto +0 sequence */
22297 		i -= (is_may_goto_0 && i > 0) ? 2 : 1;
22298 	}
22299 
22300 	return 0;
22301 }
22302 
22303 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
22304 					 const union bpf_attr *attr)
22305 {
22306 	struct bpf_insn *patch;
22307 	/* use env->insn_buf as two independent buffers */
22308 	struct bpf_insn *zext_patch = env->insn_buf;
22309 	struct bpf_insn *rnd_hi32_patch = &env->insn_buf[2];
22310 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
22311 	int i, patch_len, delta = 0, len = env->prog->len;
22312 	struct bpf_insn *insns = env->prog->insnsi;
22313 	struct bpf_prog *new_prog;
22314 	bool rnd_hi32;
22315 
22316 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
22317 	zext_patch[1] = BPF_ZEXT_REG(0);
22318 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
22319 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
22320 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
22321 	for (i = 0; i < len; i++) {
22322 		int adj_idx = i + delta;
22323 		struct bpf_insn insn;
22324 		int load_reg;
22325 
22326 		insn = insns[adj_idx];
22327 		load_reg = insn_def_regno(&insn);
22328 		if (!aux[adj_idx].zext_dst) {
22329 			u8 code, class;
22330 			u32 imm_rnd;
22331 
22332 			if (!rnd_hi32)
22333 				continue;
22334 
22335 			code = insn.code;
22336 			class = BPF_CLASS(code);
22337 			if (load_reg == -1)
22338 				continue;
22339 
22340 			/* NOTE: arg "reg" (the fourth one) is only used for
22341 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
22342 			 *       here.
22343 			 */
22344 			if (is_reg64(&insn, load_reg, NULL, DST_OP)) {
22345 				if (class == BPF_LD &&
22346 				    BPF_MODE(code) == BPF_IMM)
22347 					i++;
22348 				continue;
22349 			}
22350 
22351 			/* ctx load could be transformed into wider load. */
22352 			if (class == BPF_LDX &&
22353 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
22354 				continue;
22355 
22356 			imm_rnd = get_random_u32();
22357 			rnd_hi32_patch[0] = insn;
22358 			rnd_hi32_patch[1].imm = imm_rnd;
22359 			rnd_hi32_patch[3].dst_reg = load_reg;
22360 			patch = rnd_hi32_patch;
22361 			patch_len = 4;
22362 			goto apply_patch_buffer;
22363 		}
22364 
22365 		/* Add in an zero-extend instruction if a) the JIT has requested
22366 		 * it or b) it's a CMPXCHG.
22367 		 *
22368 		 * The latter is because: BPF_CMPXCHG always loads a value into
22369 		 * R0, therefore always zero-extends. However some archs'
22370 		 * equivalent instruction only does this load when the
22371 		 * comparison is successful. This detail of CMPXCHG is
22372 		 * orthogonal to the general zero-extension behaviour of the
22373 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
22374 		 */
22375 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
22376 			continue;
22377 
22378 		/* Zero-extension is done by the caller. */
22379 		if (bpf_pseudo_kfunc_call(&insn))
22380 			continue;
22381 
22382 		if (verifier_bug_if(load_reg == -1, env,
22383 				    "zext_dst is set, but no reg is defined"))
22384 			return -EFAULT;
22385 
22386 		zext_patch[0] = insn;
22387 		zext_patch[1].dst_reg = load_reg;
22388 		zext_patch[1].src_reg = load_reg;
22389 		patch = zext_patch;
22390 		patch_len = 2;
22391 apply_patch_buffer:
22392 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
22393 		if (!new_prog)
22394 			return -ENOMEM;
22395 		env->prog = new_prog;
22396 		insns = new_prog->insnsi;
22397 		aux = env->insn_aux_data;
22398 		delta += patch_len - 1;
22399 	}
22400 
22401 	return 0;
22402 }
22403 
22404 /* convert load instructions that access fields of a context type into a
22405  * sequence of instructions that access fields of the underlying structure:
22406  *     struct __sk_buff    -> struct sk_buff
22407  *     struct bpf_sock_ops -> struct sock
22408  */
22409 static int convert_ctx_accesses(struct bpf_verifier_env *env)
22410 {
22411 	struct bpf_subprog_info *subprogs = env->subprog_info;
22412 	const struct bpf_verifier_ops *ops = env->ops;
22413 	int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0;
22414 	const int insn_cnt = env->prog->len;
22415 	struct bpf_insn *epilogue_buf = env->epilogue_buf;
22416 	struct bpf_insn *insn_buf = env->insn_buf;
22417 	struct bpf_insn *insn;
22418 	u32 target_size, size_default, off;
22419 	struct bpf_prog *new_prog;
22420 	enum bpf_access_type type;
22421 	bool is_narrower_load;
22422 	int epilogue_idx = 0;
22423 
22424 	if (ops->gen_epilogue) {
22425 		epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
22426 						 -(subprogs[0].stack_depth + 8));
22427 		if (epilogue_cnt >= INSN_BUF_SIZE) {
22428 			verifier_bug(env, "epilogue is too long");
22429 			return -EFAULT;
22430 		} else if (epilogue_cnt) {
22431 			/* Save the ARG_PTR_TO_CTX for the epilogue to use */
22432 			cnt = 0;
22433 			subprogs[0].stack_depth += 8;
22434 			insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
22435 						      -subprogs[0].stack_depth);
22436 			insn_buf[cnt++] = env->prog->insnsi[0];
22437 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
22438 			if (!new_prog)
22439 				return -ENOMEM;
22440 			env->prog = new_prog;
22441 			delta += cnt - 1;
22442 
22443 			ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1);
22444 			if (ret < 0)
22445 				return ret;
22446 		}
22447 	}
22448 
22449 	if (ops->gen_prologue || env->seen_direct_write) {
22450 		if (!ops->gen_prologue) {
22451 			verifier_bug(env, "gen_prologue is null");
22452 			return -EFAULT;
22453 		}
22454 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
22455 					env->prog);
22456 		if (cnt >= INSN_BUF_SIZE) {
22457 			verifier_bug(env, "prologue is too long");
22458 			return -EFAULT;
22459 		} else if (cnt) {
22460 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
22461 			if (!new_prog)
22462 				return -ENOMEM;
22463 
22464 			env->prog = new_prog;
22465 			delta += cnt - 1;
22466 
22467 			ret = add_kfunc_in_insns(env, insn_buf, cnt - 1);
22468 			if (ret < 0)
22469 				return ret;
22470 		}
22471 	}
22472 
22473 	if (delta)
22474 		WARN_ON(adjust_jmp_off(env->prog, 0, delta));
22475 
22476 	if (bpf_prog_is_offloaded(env->prog->aux))
22477 		return 0;
22478 
22479 	insn = env->prog->insnsi + delta;
22480 
22481 	for (i = 0; i < insn_cnt; i++, insn++) {
22482 		bpf_convert_ctx_access_t convert_ctx_access;
22483 		u8 mode;
22484 
22485 		if (env->insn_aux_data[i + delta].nospec) {
22486 			WARN_ON_ONCE(env->insn_aux_data[i + delta].alu_state);
22487 			struct bpf_insn *patch = insn_buf;
22488 
22489 			*patch++ = BPF_ST_NOSPEC();
22490 			*patch++ = *insn;
22491 			cnt = patch - insn_buf;
22492 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22493 			if (!new_prog)
22494 				return -ENOMEM;
22495 
22496 			delta    += cnt - 1;
22497 			env->prog = new_prog;
22498 			insn      = new_prog->insnsi + i + delta;
22499 			/* This can not be easily merged with the
22500 			 * nospec_result-case, because an insn may require a
22501 			 * nospec before and after itself. Therefore also do not
22502 			 * 'continue' here but potentially apply further
22503 			 * patching to insn. *insn should equal patch[1] now.
22504 			 */
22505 		}
22506 
22507 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
22508 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
22509 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
22510 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
22511 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
22512 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
22513 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
22514 			type = BPF_READ;
22515 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
22516 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
22517 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
22518 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
22519 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
22520 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
22521 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
22522 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
22523 			type = BPF_WRITE;
22524 		} else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_B) ||
22525 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_H) ||
22526 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
22527 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
22528 			   env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
22529 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
22530 			env->prog->aux->num_exentries++;
22531 			continue;
22532 		} else if (insn->code == (BPF_JMP | BPF_EXIT) &&
22533 			   epilogue_cnt &&
22534 			   i + delta < subprogs[1].start) {
22535 			/* Generate epilogue for the main prog */
22536 			if (epilogue_idx) {
22537 				/* jump back to the earlier generated epilogue */
22538 				insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
22539 				cnt = 1;
22540 			} else {
22541 				memcpy(insn_buf, epilogue_buf,
22542 				       epilogue_cnt * sizeof(*epilogue_buf));
22543 				cnt = epilogue_cnt;
22544 				/* epilogue_idx cannot be 0. It must have at
22545 				 * least one ctx ptr saving insn before the
22546 				 * epilogue.
22547 				 */
22548 				epilogue_idx = i + delta;
22549 			}
22550 			goto patch_insn_buf;
22551 		} else {
22552 			continue;
22553 		}
22554 
22555 		if (type == BPF_WRITE &&
22556 		    env->insn_aux_data[i + delta].nospec_result) {
22557 			/* nospec_result is only used to mitigate Spectre v4 and
22558 			 * to limit verification-time for Spectre v1.
22559 			 */
22560 			struct bpf_insn *patch = insn_buf;
22561 
22562 			*patch++ = *insn;
22563 			*patch++ = BPF_ST_NOSPEC();
22564 			cnt = patch - insn_buf;
22565 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22566 			if (!new_prog)
22567 				return -ENOMEM;
22568 
22569 			delta    += cnt - 1;
22570 			env->prog = new_prog;
22571 			insn      = new_prog->insnsi + i + delta;
22572 			continue;
22573 		}
22574 
22575 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
22576 		case PTR_TO_CTX:
22577 			if (!ops->convert_ctx_access)
22578 				continue;
22579 			convert_ctx_access = ops->convert_ctx_access;
22580 			break;
22581 		case PTR_TO_SOCKET:
22582 		case PTR_TO_SOCK_COMMON:
22583 			convert_ctx_access = bpf_sock_convert_ctx_access;
22584 			break;
22585 		case PTR_TO_TCP_SOCK:
22586 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
22587 			break;
22588 		case PTR_TO_XDP_SOCK:
22589 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
22590 			break;
22591 		case PTR_TO_BTF_ID:
22592 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
22593 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
22594 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
22595 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
22596 		 * any faults for loads into such types. BPF_WRITE is disallowed
22597 		 * for this case.
22598 		 */
22599 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
22600 		case PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED:
22601 			if (type == BPF_READ) {
22602 				if (BPF_MODE(insn->code) == BPF_MEM)
22603 					insn->code = BPF_LDX | BPF_PROBE_MEM |
22604 						     BPF_SIZE((insn)->code);
22605 				else
22606 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
22607 						     BPF_SIZE((insn)->code);
22608 				env->prog->aux->num_exentries++;
22609 			}
22610 			continue;
22611 		case PTR_TO_ARENA:
22612 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
22613 				if (!bpf_jit_supports_insn(insn, true)) {
22614 					verbose(env, "sign extending loads from arena are not supported yet\n");
22615 					return -EOPNOTSUPP;
22616 				}
22617 				insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32SX | BPF_SIZE(insn->code);
22618 			} else {
22619 				insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
22620 			}
22621 			env->prog->aux->num_exentries++;
22622 			continue;
22623 		default:
22624 			continue;
22625 		}
22626 
22627 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
22628 		size = BPF_LDST_BYTES(insn);
22629 		mode = BPF_MODE(insn->code);
22630 
22631 		/* If the read access is a narrower load of the field,
22632 		 * convert to a 4/8-byte load, to minimum program type specific
22633 		 * convert_ctx_access changes. If conversion is successful,
22634 		 * we will apply proper mask to the result.
22635 		 */
22636 		is_narrower_load = size < ctx_field_size;
22637 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
22638 		off = insn->off;
22639 		if (is_narrower_load) {
22640 			u8 size_code;
22641 
22642 			if (type == BPF_WRITE) {
22643 				verifier_bug(env, "narrow ctx access misconfigured");
22644 				return -EFAULT;
22645 			}
22646 
22647 			size_code = BPF_H;
22648 			if (ctx_field_size == 4)
22649 				size_code = BPF_W;
22650 			else if (ctx_field_size == 8)
22651 				size_code = BPF_DW;
22652 
22653 			insn->off = off & ~(size_default - 1);
22654 			insn->code = BPF_LDX | BPF_MEM | size_code;
22655 		}
22656 
22657 		target_size = 0;
22658 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
22659 					 &target_size);
22660 		if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
22661 		    (ctx_field_size && !target_size)) {
22662 			verifier_bug(env, "error during ctx access conversion (%d)", cnt);
22663 			return -EFAULT;
22664 		}
22665 
22666 		if (is_narrower_load && size < target_size) {
22667 			u8 shift = bpf_ctx_narrow_access_offset(
22668 				off, size, size_default) * 8;
22669 			if (shift && cnt + 1 >= INSN_BUF_SIZE) {
22670 				verifier_bug(env, "narrow ctx load misconfigured");
22671 				return -EFAULT;
22672 			}
22673 			if (ctx_field_size <= 4) {
22674 				if (shift)
22675 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
22676 									insn->dst_reg,
22677 									shift);
22678 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
22679 								(1 << size * 8) - 1);
22680 			} else {
22681 				if (shift)
22682 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
22683 									insn->dst_reg,
22684 									shift);
22685 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
22686 								(1ULL << size * 8) - 1);
22687 			}
22688 		}
22689 		if (mode == BPF_MEMSX)
22690 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
22691 						       insn->dst_reg, insn->dst_reg,
22692 						       size * 8, 0);
22693 
22694 patch_insn_buf:
22695 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22696 		if (!new_prog)
22697 			return -ENOMEM;
22698 
22699 		delta += cnt - 1;
22700 
22701 		/* keep walking new program and skip insns we just inserted */
22702 		env->prog = new_prog;
22703 		insn      = new_prog->insnsi + i + delta;
22704 	}
22705 
22706 	return 0;
22707 }
22708 
22709 static int jit_subprogs(struct bpf_verifier_env *env)
22710 {
22711 	struct bpf_prog *prog = env->prog, **func, *tmp;
22712 	int i, j, subprog_start, subprog_end = 0, len, subprog;
22713 	struct bpf_map *map_ptr;
22714 	struct bpf_insn *insn;
22715 	void *old_bpf_func;
22716 	int err, num_exentries;
22717 	int old_len, subprog_start_adjustment = 0;
22718 
22719 	if (env->subprog_cnt <= 1)
22720 		return 0;
22721 
22722 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
22723 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
22724 			continue;
22725 
22726 		/* Upon error here we cannot fall back to interpreter but
22727 		 * need a hard reject of the program. Thus -EFAULT is
22728 		 * propagated in any case.
22729 		 */
22730 		subprog = find_subprog(env, i + insn->imm + 1);
22731 		if (verifier_bug_if(subprog < 0, env, "No program to jit at insn %d",
22732 				    i + insn->imm + 1))
22733 			return -EFAULT;
22734 		/* temporarily remember subprog id inside insn instead of
22735 		 * aux_data, since next loop will split up all insns into funcs
22736 		 */
22737 		insn->off = subprog;
22738 		/* remember original imm in case JIT fails and fallback
22739 		 * to interpreter will be needed
22740 		 */
22741 		env->insn_aux_data[i].call_imm = insn->imm;
22742 		/* point imm to __bpf_call_base+1 from JITs point of view */
22743 		insn->imm = 1;
22744 		if (bpf_pseudo_func(insn)) {
22745 #if defined(MODULES_VADDR)
22746 			u64 addr = MODULES_VADDR;
22747 #else
22748 			u64 addr = VMALLOC_START;
22749 #endif
22750 			/* jit (e.g. x86_64) may emit fewer instructions
22751 			 * if it learns a u32 imm is the same as a u64 imm.
22752 			 * Set close enough to possible prog address.
22753 			 */
22754 			insn[0].imm = (u32)addr;
22755 			insn[1].imm = addr >> 32;
22756 		}
22757 	}
22758 
22759 	err = bpf_prog_alloc_jited_linfo(prog);
22760 	if (err)
22761 		goto out_undo_insn;
22762 
22763 	err = -ENOMEM;
22764 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
22765 	if (!func)
22766 		goto out_undo_insn;
22767 
22768 	for (i = 0; i < env->subprog_cnt; i++) {
22769 		subprog_start = subprog_end;
22770 		subprog_end = env->subprog_info[i + 1].start;
22771 
22772 		len = subprog_end - subprog_start;
22773 		/* bpf_prog_run() doesn't call subprogs directly,
22774 		 * hence main prog stats include the runtime of subprogs.
22775 		 * subprogs don't have IDs and not reachable via prog_get_next_id
22776 		 * func[i]->stats will never be accessed and stays NULL
22777 		 */
22778 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
22779 		if (!func[i])
22780 			goto out_free;
22781 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
22782 		       len * sizeof(struct bpf_insn));
22783 		func[i]->type = prog->type;
22784 		func[i]->len = len;
22785 		if (bpf_prog_calc_tag(func[i]))
22786 			goto out_free;
22787 		func[i]->is_func = 1;
22788 		func[i]->sleepable = prog->sleepable;
22789 		func[i]->aux->func_idx = i;
22790 		/* Below members will be freed only at prog->aux */
22791 		func[i]->aux->btf = prog->aux->btf;
22792 		func[i]->aux->subprog_start = subprog_start + subprog_start_adjustment;
22793 		func[i]->aux->func_info = prog->aux->func_info;
22794 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
22795 		func[i]->aux->poke_tab = prog->aux->poke_tab;
22796 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
22797 		func[i]->aux->main_prog_aux = prog->aux;
22798 
22799 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
22800 			struct bpf_jit_poke_descriptor *poke;
22801 
22802 			poke = &prog->aux->poke_tab[j];
22803 			if (poke->insn_idx < subprog_end &&
22804 			    poke->insn_idx >= subprog_start)
22805 				poke->aux = func[i]->aux;
22806 		}
22807 
22808 		func[i]->aux->name[0] = 'F';
22809 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
22810 		if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE)
22811 			func[i]->aux->jits_use_priv_stack = true;
22812 
22813 		func[i]->jit_requested = 1;
22814 		func[i]->blinding_requested = prog->blinding_requested;
22815 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
22816 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
22817 		func[i]->aux->linfo = prog->aux->linfo;
22818 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
22819 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
22820 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
22821 		func[i]->aux->arena = prog->aux->arena;
22822 		func[i]->aux->used_maps = env->used_maps;
22823 		func[i]->aux->used_map_cnt = env->used_map_cnt;
22824 		num_exentries = 0;
22825 		insn = func[i]->insnsi;
22826 		for (j = 0; j < func[i]->len; j++, insn++) {
22827 			if (BPF_CLASS(insn->code) == BPF_LDX &&
22828 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
22829 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
22830 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32SX ||
22831 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
22832 				num_exentries++;
22833 			if ((BPF_CLASS(insn->code) == BPF_STX ||
22834 			     BPF_CLASS(insn->code) == BPF_ST) &&
22835 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
22836 				num_exentries++;
22837 			if (BPF_CLASS(insn->code) == BPF_STX &&
22838 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
22839 				num_exentries++;
22840 		}
22841 		func[i]->aux->num_exentries = num_exentries;
22842 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
22843 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
22844 		func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
22845 		func[i]->aux->might_sleep = env->subprog_info[i].might_sleep;
22846 		if (!i)
22847 			func[i]->aux->exception_boundary = env->seen_exception;
22848 
22849 		/*
22850 		 * To properly pass the absolute subprog start to jit
22851 		 * all instruction adjustments should be accumulated
22852 		 */
22853 		old_len = func[i]->len;
22854 		func[i] = bpf_int_jit_compile(func[i]);
22855 		subprog_start_adjustment += func[i]->len - old_len;
22856 
22857 		if (!func[i]->jited) {
22858 			err = -ENOTSUPP;
22859 			goto out_free;
22860 		}
22861 		cond_resched();
22862 	}
22863 
22864 	/* at this point all bpf functions were successfully JITed
22865 	 * now populate all bpf_calls with correct addresses and
22866 	 * run last pass of JIT
22867 	 */
22868 	for (i = 0; i < env->subprog_cnt; i++) {
22869 		insn = func[i]->insnsi;
22870 		for (j = 0; j < func[i]->len; j++, insn++) {
22871 			if (bpf_pseudo_func(insn)) {
22872 				subprog = insn->off;
22873 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
22874 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
22875 				continue;
22876 			}
22877 			if (!bpf_pseudo_call(insn))
22878 				continue;
22879 			subprog = insn->off;
22880 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
22881 		}
22882 
22883 		/* we use the aux data to keep a list of the start addresses
22884 		 * of the JITed images for each function in the program
22885 		 *
22886 		 * for some architectures, such as powerpc64, the imm field
22887 		 * might not be large enough to hold the offset of the start
22888 		 * address of the callee's JITed image from __bpf_call_base
22889 		 *
22890 		 * in such cases, we can lookup the start address of a callee
22891 		 * by using its subprog id, available from the off field of
22892 		 * the call instruction, as an index for this list
22893 		 */
22894 		func[i]->aux->func = func;
22895 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
22896 		func[i]->aux->real_func_cnt = env->subprog_cnt;
22897 	}
22898 	for (i = 0; i < env->subprog_cnt; i++) {
22899 		old_bpf_func = func[i]->bpf_func;
22900 		tmp = bpf_int_jit_compile(func[i]);
22901 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
22902 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
22903 			err = -ENOTSUPP;
22904 			goto out_free;
22905 		}
22906 		cond_resched();
22907 	}
22908 
22909 	/*
22910 	 * Cleanup func[i]->aux fields which aren't required
22911 	 * or can become invalid in future
22912 	 */
22913 	for (i = 0; i < env->subprog_cnt; i++) {
22914 		func[i]->aux->used_maps = NULL;
22915 		func[i]->aux->used_map_cnt = 0;
22916 	}
22917 
22918 	/* finally lock prog and jit images for all functions and
22919 	 * populate kallsysm. Begin at the first subprogram, since
22920 	 * bpf_prog_load will add the kallsyms for the main program.
22921 	 */
22922 	for (i = 1; i < env->subprog_cnt; i++) {
22923 		err = bpf_prog_lock_ro(func[i]);
22924 		if (err)
22925 			goto out_free;
22926 	}
22927 
22928 	for (i = 1; i < env->subprog_cnt; i++)
22929 		bpf_prog_kallsyms_add(func[i]);
22930 
22931 	/* Last step: make now unused interpreter insns from main
22932 	 * prog consistent for later dump requests, so they can
22933 	 * later look the same as if they were interpreted only.
22934 	 */
22935 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
22936 		if (bpf_pseudo_func(insn)) {
22937 			insn[0].imm = env->insn_aux_data[i].call_imm;
22938 			insn[1].imm = insn->off;
22939 			insn->off = 0;
22940 			continue;
22941 		}
22942 		if (!bpf_pseudo_call(insn))
22943 			continue;
22944 		insn->off = env->insn_aux_data[i].call_imm;
22945 		subprog = find_subprog(env, i + insn->off + 1);
22946 		insn->imm = subprog;
22947 	}
22948 
22949 	prog->jited = 1;
22950 	prog->bpf_func = func[0]->bpf_func;
22951 	prog->jited_len = func[0]->jited_len;
22952 	prog->aux->extable = func[0]->aux->extable;
22953 	prog->aux->num_exentries = func[0]->aux->num_exentries;
22954 	prog->aux->func = func;
22955 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
22956 	prog->aux->real_func_cnt = env->subprog_cnt;
22957 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
22958 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
22959 	bpf_prog_jit_attempt_done(prog);
22960 	return 0;
22961 out_free:
22962 	/* We failed JIT'ing, so at this point we need to unregister poke
22963 	 * descriptors from subprogs, so that kernel is not attempting to
22964 	 * patch it anymore as we're freeing the subprog JIT memory.
22965 	 */
22966 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
22967 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
22968 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
22969 	}
22970 	/* At this point we're guaranteed that poke descriptors are not
22971 	 * live anymore. We can just unlink its descriptor table as it's
22972 	 * released with the main prog.
22973 	 */
22974 	for (i = 0; i < env->subprog_cnt; i++) {
22975 		if (!func[i])
22976 			continue;
22977 		func[i]->aux->poke_tab = NULL;
22978 		bpf_jit_free(func[i]);
22979 	}
22980 	kfree(func);
22981 out_undo_insn:
22982 	/* cleanup main prog to be interpreted */
22983 	prog->jit_requested = 0;
22984 	prog->blinding_requested = 0;
22985 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
22986 		if (!bpf_pseudo_call(insn))
22987 			continue;
22988 		insn->off = 0;
22989 		insn->imm = env->insn_aux_data[i].call_imm;
22990 	}
22991 	bpf_prog_jit_attempt_done(prog);
22992 	return err;
22993 }
22994 
22995 static int fixup_call_args(struct bpf_verifier_env *env)
22996 {
22997 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
22998 	struct bpf_prog *prog = env->prog;
22999 	struct bpf_insn *insn = prog->insnsi;
23000 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
23001 	int i, depth;
23002 #endif
23003 	int err = 0;
23004 
23005 	if (env->prog->jit_requested &&
23006 	    !bpf_prog_is_offloaded(env->prog->aux)) {
23007 		err = jit_subprogs(env);
23008 		if (err == 0)
23009 			return 0;
23010 		if (err == -EFAULT)
23011 			return err;
23012 	}
23013 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
23014 	if (has_kfunc_call) {
23015 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
23016 		return -EINVAL;
23017 	}
23018 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
23019 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
23020 		 * have to be rejected, since interpreter doesn't support them yet.
23021 		 */
23022 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
23023 		return -EINVAL;
23024 	}
23025 	for (i = 0; i < prog->len; i++, insn++) {
23026 		if (bpf_pseudo_func(insn)) {
23027 			/* When JIT fails the progs with callback calls
23028 			 * have to be rejected, since interpreter doesn't support them yet.
23029 			 */
23030 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
23031 			return -EINVAL;
23032 		}
23033 
23034 		if (!bpf_pseudo_call(insn))
23035 			continue;
23036 		depth = get_callee_stack_depth(env, insn, i);
23037 		if (depth < 0)
23038 			return depth;
23039 		bpf_patch_call_args(insn, depth);
23040 	}
23041 	err = 0;
23042 #endif
23043 	return err;
23044 }
23045 
23046 /* replace a generic kfunc with a specialized version if necessary */
23047 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx)
23048 {
23049 	struct bpf_prog *prog = env->prog;
23050 	bool seen_direct_write;
23051 	void *xdp_kfunc;
23052 	bool is_rdonly;
23053 	u32 func_id = desc->func_id;
23054 	u16 offset = desc->offset;
23055 	unsigned long addr = desc->addr;
23056 
23057 	if (offset) /* return if module BTF is used */
23058 		return 0;
23059 
23060 	if (bpf_dev_bound_kfunc_id(func_id)) {
23061 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
23062 		if (xdp_kfunc)
23063 			addr = (unsigned long)xdp_kfunc;
23064 		/* fallback to default kfunc when not supported by netdev */
23065 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
23066 		seen_direct_write = env->seen_direct_write;
23067 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
23068 
23069 		if (is_rdonly)
23070 			addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
23071 
23072 		/* restore env->seen_direct_write to its original value, since
23073 		 * may_access_direct_pkt_data mutates it
23074 		 */
23075 		env->seen_direct_write = seen_direct_write;
23076 	} else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) {
23077 		if (bpf_lsm_has_d_inode_locked(prog))
23078 			addr = (unsigned long)bpf_set_dentry_xattr_locked;
23079 	} else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) {
23080 		if (bpf_lsm_has_d_inode_locked(prog))
23081 			addr = (unsigned long)bpf_remove_dentry_xattr_locked;
23082 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
23083 		if (!env->insn_aux_data[insn_idx].non_sleepable)
23084 			addr = (unsigned long)bpf_dynptr_from_file_sleepable;
23085 	} else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) {
23086 		if (env->insn_aux_data[insn_idx].non_sleepable)
23087 			addr = (unsigned long)bpf_arena_alloc_pages_non_sleepable;
23088 	} else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) {
23089 		if (env->insn_aux_data[insn_idx].non_sleepable)
23090 			addr = (unsigned long)bpf_arena_free_pages_non_sleepable;
23091 	}
23092 	desc->addr = addr;
23093 	return 0;
23094 }
23095 
23096 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
23097 					    u16 struct_meta_reg,
23098 					    u16 node_offset_reg,
23099 					    struct bpf_insn *insn,
23100 					    struct bpf_insn *insn_buf,
23101 					    int *cnt)
23102 {
23103 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
23104 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
23105 
23106 	insn_buf[0] = addr[0];
23107 	insn_buf[1] = addr[1];
23108 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
23109 	insn_buf[3] = *insn;
23110 	*cnt = 4;
23111 }
23112 
23113 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
23114 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
23115 {
23116 	struct bpf_kfunc_desc *desc;
23117 	int err;
23118 
23119 	if (!insn->imm) {
23120 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
23121 		return -EINVAL;
23122 	}
23123 
23124 	*cnt = 0;
23125 
23126 	/* insn->imm has the btf func_id. Replace it with an offset relative to
23127 	 * __bpf_call_base, unless the JIT needs to call functions that are
23128 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
23129 	 */
23130 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
23131 	if (!desc) {
23132 		verifier_bug(env, "kernel function descriptor not found for func_id %u",
23133 			     insn->imm);
23134 		return -EFAULT;
23135 	}
23136 
23137 	err = specialize_kfunc(env, desc, insn_idx);
23138 	if (err)
23139 		return err;
23140 
23141 	if (!bpf_jit_supports_far_kfunc_call())
23142 		insn->imm = BPF_CALL_IMM(desc->addr);
23143 
23144 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
23145 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
23146 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
23147 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
23148 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
23149 
23150 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
23151 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
23152 				     insn_idx);
23153 			return -EFAULT;
23154 		}
23155 
23156 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
23157 		insn_buf[1] = addr[0];
23158 		insn_buf[2] = addr[1];
23159 		insn_buf[3] = *insn;
23160 		*cnt = 4;
23161 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
23162 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
23163 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
23164 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
23165 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
23166 
23167 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
23168 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
23169 				     insn_idx);
23170 			return -EFAULT;
23171 		}
23172 
23173 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
23174 		    !kptr_struct_meta) {
23175 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
23176 				     insn_idx);
23177 			return -EFAULT;
23178 		}
23179 
23180 		insn_buf[0] = addr[0];
23181 		insn_buf[1] = addr[1];
23182 		insn_buf[2] = *insn;
23183 		*cnt = 3;
23184 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
23185 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
23186 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
23187 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
23188 		int struct_meta_reg = BPF_REG_3;
23189 		int node_offset_reg = BPF_REG_4;
23190 
23191 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
23192 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
23193 			struct_meta_reg = BPF_REG_4;
23194 			node_offset_reg = BPF_REG_5;
23195 		}
23196 
23197 		if (!kptr_struct_meta) {
23198 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
23199 				     insn_idx);
23200 			return -EFAULT;
23201 		}
23202 
23203 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
23204 						node_offset_reg, insn, insn_buf, cnt);
23205 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
23206 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
23207 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
23208 		*cnt = 1;
23209 	} else if (desc->func_id == special_kfunc_list[KF_bpf_session_is_return] &&
23210 		   env->prog->expected_attach_type == BPF_TRACE_FSESSION) {
23211 		/*
23212 		 * inline the bpf_session_is_return() for fsession:
23213 		 *   bool bpf_session_is_return(void *ctx)
23214 		 *   {
23215 		 *       return (((u64 *)ctx)[-1] >> BPF_TRAMP_IS_RETURN_SHIFT) & 1;
23216 		 *   }
23217 		 */
23218 		insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23219 		insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_IS_RETURN_SHIFT);
23220 		insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 1);
23221 		*cnt = 3;
23222 	} else if (desc->func_id == special_kfunc_list[KF_bpf_session_cookie] &&
23223 		   env->prog->expected_attach_type == BPF_TRACE_FSESSION) {
23224 		/*
23225 		 * inline bpf_session_cookie() for fsession:
23226 		 *   __u64 *bpf_session_cookie(void *ctx)
23227 		 *   {
23228 		 *       u64 off = (((u64 *)ctx)[-1] >> BPF_TRAMP_COOKIE_INDEX_SHIFT) & 0xFF;
23229 		 *       return &((u64 *)ctx)[-off];
23230 		 *   }
23231 		 */
23232 		insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23233 		insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_COOKIE_INDEX_SHIFT);
23234 		insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF);
23235 		insn_buf[3] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
23236 		insn_buf[4] = BPF_ALU64_REG(BPF_SUB, BPF_REG_0, BPF_REG_1);
23237 		insn_buf[5] = BPF_ALU64_IMM(BPF_NEG, BPF_REG_0, 0);
23238 		*cnt = 6;
23239 	}
23240 
23241 	if (env->insn_aux_data[insn_idx].arg_prog) {
23242 		u32 regno = env->insn_aux_data[insn_idx].arg_prog;
23243 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) };
23244 		int idx = *cnt;
23245 
23246 		insn_buf[idx++] = ld_addrs[0];
23247 		insn_buf[idx++] = ld_addrs[1];
23248 		insn_buf[idx++] = *insn;
23249 		*cnt = idx;
23250 	}
23251 	return 0;
23252 }
23253 
23254 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
23255 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
23256 {
23257 	struct bpf_subprog_info *info = env->subprog_info;
23258 	int cnt = env->subprog_cnt;
23259 	struct bpf_prog *prog;
23260 
23261 	/* We only reserve one slot for hidden subprogs in subprog_info. */
23262 	if (env->hidden_subprog_cnt) {
23263 		verifier_bug(env, "only one hidden subprog supported");
23264 		return -EFAULT;
23265 	}
23266 	/* We're not patching any existing instruction, just appending the new
23267 	 * ones for the hidden subprog. Hence all of the adjustment operations
23268 	 * in bpf_patch_insn_data are no-ops.
23269 	 */
23270 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
23271 	if (!prog)
23272 		return -ENOMEM;
23273 	env->prog = prog;
23274 	info[cnt + 1].start = info[cnt].start;
23275 	info[cnt].start = prog->len - len + 1;
23276 	env->subprog_cnt++;
23277 	env->hidden_subprog_cnt++;
23278 	return 0;
23279 }
23280 
23281 /* Do various post-verification rewrites in a single program pass.
23282  * These rewrites simplify JIT and interpreter implementations.
23283  */
23284 static int do_misc_fixups(struct bpf_verifier_env *env)
23285 {
23286 	struct bpf_prog *prog = env->prog;
23287 	enum bpf_attach_type eatype = prog->expected_attach_type;
23288 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
23289 	struct bpf_insn *insn = prog->insnsi;
23290 	const struct bpf_func_proto *fn;
23291 	const int insn_cnt = prog->len;
23292 	const struct bpf_map_ops *ops;
23293 	struct bpf_insn_aux_data *aux;
23294 	struct bpf_insn *insn_buf = env->insn_buf;
23295 	struct bpf_prog *new_prog;
23296 	struct bpf_map *map_ptr;
23297 	int i, ret, cnt, delta = 0, cur_subprog = 0;
23298 	struct bpf_subprog_info *subprogs = env->subprog_info;
23299 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
23300 	u16 stack_depth_extra = 0;
23301 
23302 	if (env->seen_exception && !env->exception_callback_subprog) {
23303 		struct bpf_insn *patch = insn_buf;
23304 
23305 		*patch++ = env->prog->insnsi[insn_cnt - 1];
23306 		*patch++ = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
23307 		*patch++ = BPF_EXIT_INSN();
23308 		ret = add_hidden_subprog(env, insn_buf, patch - insn_buf);
23309 		if (ret < 0)
23310 			return ret;
23311 		prog = env->prog;
23312 		insn = prog->insnsi;
23313 
23314 		env->exception_callback_subprog = env->subprog_cnt - 1;
23315 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
23316 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
23317 	}
23318 
23319 	for (i = 0; i < insn_cnt;) {
23320 		if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
23321 			if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
23322 			    (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
23323 				/* convert to 32-bit mov that clears upper 32-bit */
23324 				insn->code = BPF_ALU | BPF_MOV | BPF_X;
23325 				/* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
23326 				insn->off = 0;
23327 				insn->imm = 0;
23328 			} /* cast from as(0) to as(1) should be handled by JIT */
23329 			goto next_insn;
23330 		}
23331 
23332 		if (env->insn_aux_data[i + delta].needs_zext)
23333 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
23334 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
23335 
23336 		/* Make sdiv/smod divide-by-minus-one exceptions impossible. */
23337 		if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
23338 		     insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
23339 		     insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
23340 		     insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
23341 		    insn->off == 1 && insn->imm == -1) {
23342 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
23343 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
23344 			struct bpf_insn *patch = insn_buf;
23345 
23346 			if (isdiv)
23347 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
23348 							BPF_NEG | BPF_K, insn->dst_reg,
23349 							0, 0, 0);
23350 			else
23351 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
23352 
23353 			cnt = patch - insn_buf;
23354 
23355 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23356 			if (!new_prog)
23357 				return -ENOMEM;
23358 
23359 			delta    += cnt - 1;
23360 			env->prog = prog = new_prog;
23361 			insn      = new_prog->insnsi + i + delta;
23362 			goto next_insn;
23363 		}
23364 
23365 		/* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
23366 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
23367 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
23368 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
23369 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
23370 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
23371 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
23372 			bool is_sdiv = isdiv && insn->off == 1;
23373 			bool is_smod = !isdiv && insn->off == 1;
23374 			struct bpf_insn *patch = insn_buf;
23375 
23376 			if (is_sdiv) {
23377 				/* [R,W]x sdiv 0 -> 0
23378 				 * LLONG_MIN sdiv -1 -> LLONG_MIN
23379 				 * INT_MIN sdiv -1 -> INT_MIN
23380 				 */
23381 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
23382 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
23383 							BPF_ADD | BPF_K, BPF_REG_AX,
23384 							0, 0, 1);
23385 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
23386 							BPF_JGT | BPF_K, BPF_REG_AX,
23387 							0, 4, 1);
23388 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
23389 							BPF_JEQ | BPF_K, BPF_REG_AX,
23390 							0, 1, 0);
23391 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
23392 							BPF_MOV | BPF_K, insn->dst_reg,
23393 							0, 0, 0);
23394 				/* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
23395 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
23396 							BPF_NEG | BPF_K, insn->dst_reg,
23397 							0, 0, 0);
23398 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
23399 				*patch++ = *insn;
23400 				cnt = patch - insn_buf;
23401 			} else if (is_smod) {
23402 				/* [R,W]x mod 0 -> [R,W]x */
23403 				/* [R,W]x mod -1 -> 0 */
23404 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
23405 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
23406 							BPF_ADD | BPF_K, BPF_REG_AX,
23407 							0, 0, 1);
23408 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
23409 							BPF_JGT | BPF_K, BPF_REG_AX,
23410 							0, 3, 1);
23411 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
23412 							BPF_JEQ | BPF_K, BPF_REG_AX,
23413 							0, 3 + (is64 ? 0 : 1), 1);
23414 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
23415 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
23416 				*patch++ = *insn;
23417 
23418 				if (!is64) {
23419 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
23420 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
23421 				}
23422 				cnt = patch - insn_buf;
23423 			} else if (isdiv) {
23424 				/* [R,W]x div 0 -> 0 */
23425 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
23426 							BPF_JNE | BPF_K, insn->src_reg,
23427 							0, 2, 0);
23428 				*patch++ = BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg);
23429 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
23430 				*patch++ = *insn;
23431 				cnt = patch - insn_buf;
23432 			} else {
23433 				/* [R,W]x mod 0 -> [R,W]x */
23434 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
23435 							BPF_JEQ | BPF_K, insn->src_reg,
23436 							0, 1 + (is64 ? 0 : 1), 0);
23437 				*patch++ = *insn;
23438 
23439 				if (!is64) {
23440 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
23441 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
23442 				}
23443 				cnt = patch - insn_buf;
23444 			}
23445 
23446 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23447 			if (!new_prog)
23448 				return -ENOMEM;
23449 
23450 			delta    += cnt - 1;
23451 			env->prog = prog = new_prog;
23452 			insn      = new_prog->insnsi + i + delta;
23453 			goto next_insn;
23454 		}
23455 
23456 		/* Make it impossible to de-reference a userspace address */
23457 		if (BPF_CLASS(insn->code) == BPF_LDX &&
23458 		    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
23459 		     BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
23460 			struct bpf_insn *patch = insn_buf;
23461 			u64 uaddress_limit = bpf_arch_uaddress_limit();
23462 
23463 			if (!uaddress_limit)
23464 				goto next_insn;
23465 
23466 			*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
23467 			if (insn->off)
23468 				*patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
23469 			*patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
23470 			*patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
23471 			*patch++ = *insn;
23472 			*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
23473 			*patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
23474 
23475 			cnt = patch - insn_buf;
23476 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23477 			if (!new_prog)
23478 				return -ENOMEM;
23479 
23480 			delta    += cnt - 1;
23481 			env->prog = prog = new_prog;
23482 			insn      = new_prog->insnsi + i + delta;
23483 			goto next_insn;
23484 		}
23485 
23486 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
23487 		if (BPF_CLASS(insn->code) == BPF_LD &&
23488 		    (BPF_MODE(insn->code) == BPF_ABS ||
23489 		     BPF_MODE(insn->code) == BPF_IND)) {
23490 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
23491 			if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
23492 				verifier_bug(env, "%d insns generated for ld_abs", cnt);
23493 				return -EFAULT;
23494 			}
23495 
23496 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23497 			if (!new_prog)
23498 				return -ENOMEM;
23499 
23500 			delta    += cnt - 1;
23501 			env->prog = prog = new_prog;
23502 			insn      = new_prog->insnsi + i + delta;
23503 			goto next_insn;
23504 		}
23505 
23506 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
23507 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
23508 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
23509 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
23510 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
23511 			struct bpf_insn *patch = insn_buf;
23512 			bool issrc, isneg, isimm;
23513 			u32 off_reg;
23514 
23515 			aux = &env->insn_aux_data[i + delta];
23516 			if (!aux->alu_state ||
23517 			    aux->alu_state == BPF_ALU_NON_POINTER)
23518 				goto next_insn;
23519 
23520 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
23521 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
23522 				BPF_ALU_SANITIZE_SRC;
23523 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
23524 
23525 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
23526 			if (isimm) {
23527 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
23528 			} else {
23529 				if (isneg)
23530 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
23531 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
23532 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
23533 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
23534 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
23535 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
23536 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
23537 			}
23538 			if (!issrc)
23539 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
23540 			insn->src_reg = BPF_REG_AX;
23541 			if (isneg)
23542 				insn->code = insn->code == code_add ?
23543 					     code_sub : code_add;
23544 			*patch++ = *insn;
23545 			if (issrc && isneg && !isimm)
23546 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
23547 			cnt = patch - insn_buf;
23548 
23549 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23550 			if (!new_prog)
23551 				return -ENOMEM;
23552 
23553 			delta    += cnt - 1;
23554 			env->prog = prog = new_prog;
23555 			insn      = new_prog->insnsi + i + delta;
23556 			goto next_insn;
23557 		}
23558 
23559 		if (is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) {
23560 			int stack_off_cnt = -stack_depth - 16;
23561 
23562 			/*
23563 			 * Two 8 byte slots, depth-16 stores the count, and
23564 			 * depth-8 stores the start timestamp of the loop.
23565 			 *
23566 			 * The starting value of count is BPF_MAX_TIMED_LOOPS
23567 			 * (0xffff).  Every iteration loads it and subs it by 1,
23568 			 * until the value becomes 0 in AX (thus, 1 in stack),
23569 			 * after which we call arch_bpf_timed_may_goto, which
23570 			 * either sets AX to 0xffff to keep looping, or to 0
23571 			 * upon timeout. AX is then stored into the stack. In
23572 			 * the next iteration, we either see 0 and break out, or
23573 			 * continue iterating until the next time value is 0
23574 			 * after subtraction, rinse and repeat.
23575 			 */
23576 			stack_depth_extra = 16;
23577 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off_cnt);
23578 			if (insn->off >= 0)
23579 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 5);
23580 			else
23581 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
23582 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
23583 			insn_buf[3] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
23584 			/*
23585 			 * AX is used as an argument to pass in stack_off_cnt
23586 			 * (to add to r10/fp), and also as the return value of
23587 			 * the call to arch_bpf_timed_may_goto.
23588 			 */
23589 			insn_buf[4] = BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt);
23590 			insn_buf[5] = BPF_EMIT_CALL(arch_bpf_timed_may_goto);
23591 			insn_buf[6] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt);
23592 			cnt = 7;
23593 
23594 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23595 			if (!new_prog)
23596 				return -ENOMEM;
23597 
23598 			delta += cnt - 1;
23599 			env->prog = prog = new_prog;
23600 			insn = new_prog->insnsi + i + delta;
23601 			goto next_insn;
23602 		} else if (is_may_goto_insn(insn)) {
23603 			int stack_off = -stack_depth - 8;
23604 
23605 			stack_depth_extra = 8;
23606 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
23607 			if (insn->off >= 0)
23608 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
23609 			else
23610 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
23611 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
23612 			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
23613 			cnt = 4;
23614 
23615 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23616 			if (!new_prog)
23617 				return -ENOMEM;
23618 
23619 			delta += cnt - 1;
23620 			env->prog = prog = new_prog;
23621 			insn = new_prog->insnsi + i + delta;
23622 			goto next_insn;
23623 		}
23624 
23625 		if (insn->code != (BPF_JMP | BPF_CALL))
23626 			goto next_insn;
23627 		if (insn->src_reg == BPF_PSEUDO_CALL)
23628 			goto next_insn;
23629 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
23630 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
23631 			if (ret)
23632 				return ret;
23633 			if (cnt == 0)
23634 				goto next_insn;
23635 
23636 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23637 			if (!new_prog)
23638 				return -ENOMEM;
23639 
23640 			delta	 += cnt - 1;
23641 			env->prog = prog = new_prog;
23642 			insn	  = new_prog->insnsi + i + delta;
23643 			goto next_insn;
23644 		}
23645 
23646 		/* Skip inlining the helper call if the JIT does it. */
23647 		if (bpf_jit_inlines_helper_call(insn->imm))
23648 			goto next_insn;
23649 
23650 		if (insn->imm == BPF_FUNC_get_route_realm)
23651 			prog->dst_needed = 1;
23652 		if (insn->imm == BPF_FUNC_get_prandom_u32)
23653 			bpf_user_rnd_init_once();
23654 		if (insn->imm == BPF_FUNC_override_return)
23655 			prog->kprobe_override = 1;
23656 		if (insn->imm == BPF_FUNC_tail_call) {
23657 			/* If we tail call into other programs, we
23658 			 * cannot make any assumptions since they can
23659 			 * be replaced dynamically during runtime in
23660 			 * the program array.
23661 			 */
23662 			prog->cb_access = 1;
23663 			if (!allow_tail_call_in_subprogs(env))
23664 				prog->aux->stack_depth = MAX_BPF_STACK;
23665 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
23666 
23667 			/* mark bpf_tail_call as different opcode to avoid
23668 			 * conditional branch in the interpreter for every normal
23669 			 * call and to prevent accidental JITing by JIT compiler
23670 			 * that doesn't support bpf_tail_call yet
23671 			 */
23672 			insn->imm = 0;
23673 			insn->code = BPF_JMP | BPF_TAIL_CALL;
23674 
23675 			aux = &env->insn_aux_data[i + delta];
23676 			if (env->bpf_capable && !prog->blinding_requested &&
23677 			    prog->jit_requested &&
23678 			    !bpf_map_key_poisoned(aux) &&
23679 			    !bpf_map_ptr_poisoned(aux) &&
23680 			    !bpf_map_ptr_unpriv(aux)) {
23681 				struct bpf_jit_poke_descriptor desc = {
23682 					.reason = BPF_POKE_REASON_TAIL_CALL,
23683 					.tail_call.map = aux->map_ptr_state.map_ptr,
23684 					.tail_call.key = bpf_map_key_immediate(aux),
23685 					.insn_idx = i + delta,
23686 				};
23687 
23688 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
23689 				if (ret < 0) {
23690 					verbose(env, "adding tail call poke descriptor failed\n");
23691 					return ret;
23692 				}
23693 
23694 				insn->imm = ret + 1;
23695 				goto next_insn;
23696 			}
23697 
23698 			if (!bpf_map_ptr_unpriv(aux))
23699 				goto next_insn;
23700 
23701 			/* instead of changing every JIT dealing with tail_call
23702 			 * emit two extra insns:
23703 			 * if (index >= max_entries) goto out;
23704 			 * index &= array->index_mask;
23705 			 * to avoid out-of-bounds cpu speculation
23706 			 */
23707 			if (bpf_map_ptr_poisoned(aux)) {
23708 				verbose(env, "tail_call abusing map_ptr\n");
23709 				return -EINVAL;
23710 			}
23711 
23712 			map_ptr = aux->map_ptr_state.map_ptr;
23713 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
23714 						  map_ptr->max_entries, 2);
23715 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
23716 						    container_of(map_ptr,
23717 								 struct bpf_array,
23718 								 map)->index_mask);
23719 			insn_buf[2] = *insn;
23720 			cnt = 3;
23721 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23722 			if (!new_prog)
23723 				return -ENOMEM;
23724 
23725 			delta    += cnt - 1;
23726 			env->prog = prog = new_prog;
23727 			insn      = new_prog->insnsi + i + delta;
23728 			goto next_insn;
23729 		}
23730 
23731 		if (insn->imm == BPF_FUNC_timer_set_callback) {
23732 			/* The verifier will process callback_fn as many times as necessary
23733 			 * with different maps and the register states prepared by
23734 			 * set_timer_callback_state will be accurate.
23735 			 *
23736 			 * The following use case is valid:
23737 			 *   map1 is shared by prog1, prog2, prog3.
23738 			 *   prog1 calls bpf_timer_init for some map1 elements
23739 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
23740 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
23741 			 *   prog3 calls bpf_timer_start for some map1 elements.
23742 			 *     Those that were not both bpf_timer_init-ed and
23743 			 *     bpf_timer_set_callback-ed will return -EINVAL.
23744 			 */
23745 			struct bpf_insn ld_addrs[2] = {
23746 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
23747 			};
23748 
23749 			insn_buf[0] = ld_addrs[0];
23750 			insn_buf[1] = ld_addrs[1];
23751 			insn_buf[2] = *insn;
23752 			cnt = 3;
23753 
23754 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23755 			if (!new_prog)
23756 				return -ENOMEM;
23757 
23758 			delta    += cnt - 1;
23759 			env->prog = prog = new_prog;
23760 			insn      = new_prog->insnsi + i + delta;
23761 			goto patch_call_imm;
23762 		}
23763 
23764 		if (is_storage_get_function(insn->imm)) {
23765 			if (env->insn_aux_data[i + delta].non_sleepable)
23766 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
23767 			else
23768 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
23769 			insn_buf[1] = *insn;
23770 			cnt = 2;
23771 
23772 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23773 			if (!new_prog)
23774 				return -ENOMEM;
23775 
23776 			delta += cnt - 1;
23777 			env->prog = prog = new_prog;
23778 			insn = new_prog->insnsi + i + delta;
23779 			goto patch_call_imm;
23780 		}
23781 
23782 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
23783 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
23784 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
23785 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
23786 			 */
23787 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
23788 			insn_buf[1] = *insn;
23789 			cnt = 2;
23790 
23791 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23792 			if (!new_prog)
23793 				return -ENOMEM;
23794 
23795 			delta += cnt - 1;
23796 			env->prog = prog = new_prog;
23797 			insn = new_prog->insnsi + i + delta;
23798 			goto patch_call_imm;
23799 		}
23800 
23801 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
23802 		 * and other inlining handlers are currently limited to 64 bit
23803 		 * only.
23804 		 */
23805 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
23806 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
23807 		     insn->imm == BPF_FUNC_map_update_elem ||
23808 		     insn->imm == BPF_FUNC_map_delete_elem ||
23809 		     insn->imm == BPF_FUNC_map_push_elem   ||
23810 		     insn->imm == BPF_FUNC_map_pop_elem    ||
23811 		     insn->imm == BPF_FUNC_map_peek_elem   ||
23812 		     insn->imm == BPF_FUNC_redirect_map    ||
23813 		     insn->imm == BPF_FUNC_for_each_map_elem ||
23814 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
23815 			aux = &env->insn_aux_data[i + delta];
23816 			if (bpf_map_ptr_poisoned(aux))
23817 				goto patch_call_imm;
23818 
23819 			map_ptr = aux->map_ptr_state.map_ptr;
23820 			ops = map_ptr->ops;
23821 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
23822 			    ops->map_gen_lookup) {
23823 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
23824 				if (cnt == -EOPNOTSUPP)
23825 					goto patch_map_ops_generic;
23826 				if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
23827 					verifier_bug(env, "%d insns generated for map lookup", cnt);
23828 					return -EFAULT;
23829 				}
23830 
23831 				new_prog = bpf_patch_insn_data(env, i + delta,
23832 							       insn_buf, cnt);
23833 				if (!new_prog)
23834 					return -ENOMEM;
23835 
23836 				delta    += cnt - 1;
23837 				env->prog = prog = new_prog;
23838 				insn      = new_prog->insnsi + i + delta;
23839 				goto next_insn;
23840 			}
23841 
23842 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
23843 				     (void *(*)(struct bpf_map *map, void *key))NULL));
23844 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
23845 				     (long (*)(struct bpf_map *map, void *key))NULL));
23846 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
23847 				     (long (*)(struct bpf_map *map, void *key, void *value,
23848 					      u64 flags))NULL));
23849 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
23850 				     (long (*)(struct bpf_map *map, void *value,
23851 					      u64 flags))NULL));
23852 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
23853 				     (long (*)(struct bpf_map *map, void *value))NULL));
23854 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
23855 				     (long (*)(struct bpf_map *map, void *value))NULL));
23856 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
23857 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
23858 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
23859 				     (long (*)(struct bpf_map *map,
23860 					      bpf_callback_t callback_fn,
23861 					      void *callback_ctx,
23862 					      u64 flags))NULL));
23863 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
23864 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
23865 
23866 patch_map_ops_generic:
23867 			switch (insn->imm) {
23868 			case BPF_FUNC_map_lookup_elem:
23869 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
23870 				goto next_insn;
23871 			case BPF_FUNC_map_update_elem:
23872 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
23873 				goto next_insn;
23874 			case BPF_FUNC_map_delete_elem:
23875 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
23876 				goto next_insn;
23877 			case BPF_FUNC_map_push_elem:
23878 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
23879 				goto next_insn;
23880 			case BPF_FUNC_map_pop_elem:
23881 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
23882 				goto next_insn;
23883 			case BPF_FUNC_map_peek_elem:
23884 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
23885 				goto next_insn;
23886 			case BPF_FUNC_redirect_map:
23887 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
23888 				goto next_insn;
23889 			case BPF_FUNC_for_each_map_elem:
23890 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
23891 				goto next_insn;
23892 			case BPF_FUNC_map_lookup_percpu_elem:
23893 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
23894 				goto next_insn;
23895 			}
23896 
23897 			goto patch_call_imm;
23898 		}
23899 
23900 		/* Implement bpf_jiffies64 inline. */
23901 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
23902 		    insn->imm == BPF_FUNC_jiffies64) {
23903 			struct bpf_insn ld_jiffies_addr[2] = {
23904 				BPF_LD_IMM64(BPF_REG_0,
23905 					     (unsigned long)&jiffies),
23906 			};
23907 
23908 			insn_buf[0] = ld_jiffies_addr[0];
23909 			insn_buf[1] = ld_jiffies_addr[1];
23910 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
23911 						  BPF_REG_0, 0);
23912 			cnt = 3;
23913 
23914 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
23915 						       cnt);
23916 			if (!new_prog)
23917 				return -ENOMEM;
23918 
23919 			delta    += cnt - 1;
23920 			env->prog = prog = new_prog;
23921 			insn      = new_prog->insnsi + i + delta;
23922 			goto next_insn;
23923 		}
23924 
23925 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
23926 		/* Implement bpf_get_smp_processor_id() inline. */
23927 		if (insn->imm == BPF_FUNC_get_smp_processor_id &&
23928 		    verifier_inlines_helper_call(env, insn->imm)) {
23929 			/* BPF_FUNC_get_smp_processor_id inlining is an
23930 			 * optimization, so if cpu_number is ever
23931 			 * changed in some incompatible and hard to support
23932 			 * way, it's fine to back out this inlining logic
23933 			 */
23934 #ifdef CONFIG_SMP
23935 			insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&cpu_number);
23936 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
23937 			insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
23938 			cnt = 3;
23939 #else
23940 			insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
23941 			cnt = 1;
23942 #endif
23943 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23944 			if (!new_prog)
23945 				return -ENOMEM;
23946 
23947 			delta    += cnt - 1;
23948 			env->prog = prog = new_prog;
23949 			insn      = new_prog->insnsi + i + delta;
23950 			goto next_insn;
23951 		}
23952 
23953 		/* Implement bpf_get_current_task() and bpf_get_current_task_btf() inline. */
23954 		if ((insn->imm == BPF_FUNC_get_current_task || insn->imm == BPF_FUNC_get_current_task_btf) &&
23955 		    verifier_inlines_helper_call(env, insn->imm)) {
23956 			insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&current_task);
23957 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
23958 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_0, 0);
23959 			cnt = 3;
23960 
23961 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23962 			if (!new_prog)
23963 				return -ENOMEM;
23964 
23965 			delta    += cnt - 1;
23966 			env->prog = prog = new_prog;
23967 			insn      = new_prog->insnsi + i + delta;
23968 			goto next_insn;
23969 		}
23970 #endif
23971 		/* Implement bpf_get_func_arg inline. */
23972 		if (prog_type == BPF_PROG_TYPE_TRACING &&
23973 		    insn->imm == BPF_FUNC_get_func_arg) {
23974 			if (eatype == BPF_TRACE_RAW_TP) {
23975 				int nr_args = btf_type_vlen(prog->aux->attach_func_proto);
23976 
23977 				/* skip 'void *__data' in btf_trace_##name() and save to reg0 */
23978 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, nr_args - 1);
23979 				cnt = 1;
23980 			} else {
23981 				/* Load nr_args from ctx - 8 */
23982 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23983 				insn_buf[1] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF);
23984 				cnt = 2;
23985 			}
23986 			insn_buf[cnt++] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
23987 			insn_buf[cnt++] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
23988 			insn_buf[cnt++] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
23989 			insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
23990 			insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
23991 			insn_buf[cnt++] = BPF_MOV64_IMM(BPF_REG_0, 0);
23992 			insn_buf[cnt++] = BPF_JMP_A(1);
23993 			insn_buf[cnt++] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
23994 
23995 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23996 			if (!new_prog)
23997 				return -ENOMEM;
23998 
23999 			delta    += cnt - 1;
24000 			env->prog = prog = new_prog;
24001 			insn      = new_prog->insnsi + i + delta;
24002 			goto next_insn;
24003 		}
24004 
24005 		/* Implement bpf_get_func_ret inline. */
24006 		if (prog_type == BPF_PROG_TYPE_TRACING &&
24007 		    insn->imm == BPF_FUNC_get_func_ret) {
24008 			if (eatype == BPF_TRACE_FEXIT ||
24009 			    eatype == BPF_TRACE_FSESSION ||
24010 			    eatype == BPF_MODIFY_RETURN) {
24011 				/* Load nr_args from ctx - 8 */
24012 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
24013 				insn_buf[1] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF);
24014 				insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
24015 				insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
24016 				insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
24017 				insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
24018 				insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
24019 				cnt = 7;
24020 			} else {
24021 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
24022 				cnt = 1;
24023 			}
24024 
24025 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
24026 			if (!new_prog)
24027 				return -ENOMEM;
24028 
24029 			delta    += cnt - 1;
24030 			env->prog = prog = new_prog;
24031 			insn      = new_prog->insnsi + i + delta;
24032 			goto next_insn;
24033 		}
24034 
24035 		/* Implement get_func_arg_cnt inline. */
24036 		if (prog_type == BPF_PROG_TYPE_TRACING &&
24037 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
24038 			if (eatype == BPF_TRACE_RAW_TP) {
24039 				int nr_args = btf_type_vlen(prog->aux->attach_func_proto);
24040 
24041 				/* skip 'void *__data' in btf_trace_##name() and save to reg0 */
24042 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, nr_args - 1);
24043 				cnt = 1;
24044 			} else {
24045 				/* Load nr_args from ctx - 8 */
24046 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
24047 				insn_buf[1] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF);
24048 				cnt = 2;
24049 			}
24050 
24051 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
24052 			if (!new_prog)
24053 				return -ENOMEM;
24054 
24055 			delta    += cnt - 1;
24056 			env->prog = prog = new_prog;
24057 			insn      = new_prog->insnsi + i + delta;
24058 			goto next_insn;
24059 		}
24060 
24061 		/* Implement bpf_get_func_ip inline. */
24062 		if (prog_type == BPF_PROG_TYPE_TRACING &&
24063 		    insn->imm == BPF_FUNC_get_func_ip) {
24064 			/* Load IP address from ctx - 16 */
24065 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
24066 
24067 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
24068 			if (!new_prog)
24069 				return -ENOMEM;
24070 
24071 			env->prog = prog = new_prog;
24072 			insn      = new_prog->insnsi + i + delta;
24073 			goto next_insn;
24074 		}
24075 
24076 		/* Implement bpf_get_branch_snapshot inline. */
24077 		if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
24078 		    prog->jit_requested && BITS_PER_LONG == 64 &&
24079 		    insn->imm == BPF_FUNC_get_branch_snapshot) {
24080 			/* We are dealing with the following func protos:
24081 			 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
24082 			 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
24083 			 */
24084 			const u32 br_entry_size = sizeof(struct perf_branch_entry);
24085 
24086 			/* struct perf_branch_entry is part of UAPI and is
24087 			 * used as an array element, so extremely unlikely to
24088 			 * ever grow or shrink
24089 			 */
24090 			BUILD_BUG_ON(br_entry_size != 24);
24091 
24092 			/* if (unlikely(flags)) return -EINVAL */
24093 			insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
24094 
24095 			/* Transform size (bytes) into number of entries (cnt = size / 24).
24096 			 * But to avoid expensive division instruction, we implement
24097 			 * divide-by-3 through multiplication, followed by further
24098 			 * division by 8 through 3-bit right shift.
24099 			 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
24100 			 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
24101 			 *
24102 			 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
24103 			 */
24104 			insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
24105 			insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
24106 			insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
24107 
24108 			/* call perf_snapshot_branch_stack implementation */
24109 			insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
24110 			/* if (entry_cnt == 0) return -ENOENT */
24111 			insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
24112 			/* return entry_cnt * sizeof(struct perf_branch_entry) */
24113 			insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
24114 			insn_buf[7] = BPF_JMP_A(3);
24115 			/* return -EINVAL; */
24116 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
24117 			insn_buf[9] = BPF_JMP_A(1);
24118 			/* return -ENOENT; */
24119 			insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
24120 			cnt = 11;
24121 
24122 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
24123 			if (!new_prog)
24124 				return -ENOMEM;
24125 
24126 			delta    += cnt - 1;
24127 			env->prog = prog = new_prog;
24128 			insn      = new_prog->insnsi + i + delta;
24129 			goto next_insn;
24130 		}
24131 
24132 		/* Implement bpf_kptr_xchg inline */
24133 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
24134 		    insn->imm == BPF_FUNC_kptr_xchg &&
24135 		    bpf_jit_supports_ptr_xchg()) {
24136 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
24137 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
24138 			cnt = 2;
24139 
24140 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
24141 			if (!new_prog)
24142 				return -ENOMEM;
24143 
24144 			delta    += cnt - 1;
24145 			env->prog = prog = new_prog;
24146 			insn      = new_prog->insnsi + i + delta;
24147 			goto next_insn;
24148 		}
24149 patch_call_imm:
24150 		fn = env->ops->get_func_proto(insn->imm, env->prog);
24151 		/* all functions that have prototype and verifier allowed
24152 		 * programs to call them, must be real in-kernel functions
24153 		 */
24154 		if (!fn->func) {
24155 			verifier_bug(env,
24156 				     "not inlined functions %s#%d is missing func",
24157 				     func_id_name(insn->imm), insn->imm);
24158 			return -EFAULT;
24159 		}
24160 		insn->imm = fn->func - __bpf_call_base;
24161 next_insn:
24162 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
24163 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
24164 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
24165 
24166 			stack_depth = subprogs[cur_subprog].stack_depth;
24167 			if (stack_depth > MAX_BPF_STACK && !prog->jit_requested) {
24168 				verbose(env, "stack size %d(extra %d) is too large\n",
24169 					stack_depth, stack_depth_extra);
24170 				return -EINVAL;
24171 			}
24172 			cur_subprog++;
24173 			stack_depth = subprogs[cur_subprog].stack_depth;
24174 			stack_depth_extra = 0;
24175 		}
24176 		i++;
24177 		insn++;
24178 	}
24179 
24180 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
24181 	for (i = 0; i < env->subprog_cnt; i++) {
24182 		int delta = bpf_jit_supports_timed_may_goto() ? 2 : 1;
24183 		int subprog_start = subprogs[i].start;
24184 		int stack_slots = subprogs[i].stack_extra / 8;
24185 		int slots = delta, cnt = 0;
24186 
24187 		if (!stack_slots)
24188 			continue;
24189 		/* We need two slots in case timed may_goto is supported. */
24190 		if (stack_slots > slots) {
24191 			verifier_bug(env, "stack_slots supports may_goto only");
24192 			return -EFAULT;
24193 		}
24194 
24195 		stack_depth = subprogs[i].stack_depth;
24196 		if (bpf_jit_supports_timed_may_goto()) {
24197 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
24198 						     BPF_MAX_TIMED_LOOPS);
24199 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth + 8, 0);
24200 		} else {
24201 			/* Add ST insn to subprog prologue to init extra stack */
24202 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
24203 						     BPF_MAX_LOOPS);
24204 		}
24205 		/* Copy first actual insn to preserve it */
24206 		insn_buf[cnt++] = env->prog->insnsi[subprog_start];
24207 
24208 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, cnt);
24209 		if (!new_prog)
24210 			return -ENOMEM;
24211 		env->prog = prog = new_prog;
24212 		/*
24213 		 * If may_goto is a first insn of a prog there could be a jmp
24214 		 * insn that points to it, hence adjust all such jmps to point
24215 		 * to insn after BPF_ST that inits may_goto count.
24216 		 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
24217 		 */
24218 		WARN_ON(adjust_jmp_off(env->prog, subprog_start, delta));
24219 	}
24220 
24221 	/* Since poke tab is now finalized, publish aux to tracker. */
24222 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
24223 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
24224 		if (!map_ptr->ops->map_poke_track ||
24225 		    !map_ptr->ops->map_poke_untrack ||
24226 		    !map_ptr->ops->map_poke_run) {
24227 			verifier_bug(env, "poke tab is misconfigured");
24228 			return -EFAULT;
24229 		}
24230 
24231 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
24232 		if (ret < 0) {
24233 			verbose(env, "tracking tail call prog failed\n");
24234 			return ret;
24235 		}
24236 	}
24237 
24238 	ret = sort_kfunc_descs_by_imm_off(env);
24239 	if (ret)
24240 		return ret;
24241 
24242 	return 0;
24243 }
24244 
24245 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
24246 					int position,
24247 					s32 stack_base,
24248 					u32 callback_subprogno,
24249 					u32 *total_cnt)
24250 {
24251 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
24252 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
24253 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
24254 	int reg_loop_max = BPF_REG_6;
24255 	int reg_loop_cnt = BPF_REG_7;
24256 	int reg_loop_ctx = BPF_REG_8;
24257 
24258 	struct bpf_insn *insn_buf = env->insn_buf;
24259 	struct bpf_prog *new_prog;
24260 	u32 callback_start;
24261 	u32 call_insn_offset;
24262 	s32 callback_offset;
24263 	u32 cnt = 0;
24264 
24265 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
24266 	 * be careful to modify this code in sync.
24267 	 */
24268 
24269 	/* Return error and jump to the end of the patch if
24270 	 * expected number of iterations is too big.
24271 	 */
24272 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
24273 	insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
24274 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
24275 	/* spill R6, R7, R8 to use these as loop vars */
24276 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
24277 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
24278 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
24279 	/* initialize loop vars */
24280 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
24281 	insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
24282 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
24283 	/* loop header,
24284 	 * if reg_loop_cnt >= reg_loop_max skip the loop body
24285 	 */
24286 	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
24287 	/* callback call,
24288 	 * correct callback offset would be set after patching
24289 	 */
24290 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
24291 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
24292 	insn_buf[cnt++] = BPF_CALL_REL(0);
24293 	/* increment loop counter */
24294 	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
24295 	/* jump to loop header if callback returned 0 */
24296 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
24297 	/* return value of bpf_loop,
24298 	 * set R0 to the number of iterations
24299 	 */
24300 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
24301 	/* restore original values of R6, R7, R8 */
24302 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
24303 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
24304 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
24305 
24306 	*total_cnt = cnt;
24307 	new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
24308 	if (!new_prog)
24309 		return new_prog;
24310 
24311 	/* callback start is known only after patching */
24312 	callback_start = env->subprog_info[callback_subprogno].start;
24313 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
24314 	call_insn_offset = position + 12;
24315 	callback_offset = callback_start - call_insn_offset - 1;
24316 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
24317 
24318 	return new_prog;
24319 }
24320 
24321 static bool is_bpf_loop_call(struct bpf_insn *insn)
24322 {
24323 	return insn->code == (BPF_JMP | BPF_CALL) &&
24324 		insn->src_reg == 0 &&
24325 		insn->imm == BPF_FUNC_loop;
24326 }
24327 
24328 /* For all sub-programs in the program (including main) check
24329  * insn_aux_data to see if there are bpf_loop calls that require
24330  * inlining. If such calls are found the calls are replaced with a
24331  * sequence of instructions produced by `inline_bpf_loop` function and
24332  * subprog stack_depth is increased by the size of 3 registers.
24333  * This stack space is used to spill values of the R6, R7, R8.  These
24334  * registers are used to store the loop bound, counter and context
24335  * variables.
24336  */
24337 static int optimize_bpf_loop(struct bpf_verifier_env *env)
24338 {
24339 	struct bpf_subprog_info *subprogs = env->subprog_info;
24340 	int i, cur_subprog = 0, cnt, delta = 0;
24341 	struct bpf_insn *insn = env->prog->insnsi;
24342 	int insn_cnt = env->prog->len;
24343 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
24344 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
24345 	u16 stack_depth_extra = 0;
24346 
24347 	for (i = 0; i < insn_cnt; i++, insn++) {
24348 		struct bpf_loop_inline_state *inline_state =
24349 			&env->insn_aux_data[i + delta].loop_inline_state;
24350 
24351 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
24352 			struct bpf_prog *new_prog;
24353 
24354 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
24355 			new_prog = inline_bpf_loop(env,
24356 						   i + delta,
24357 						   -(stack_depth + stack_depth_extra),
24358 						   inline_state->callback_subprogno,
24359 						   &cnt);
24360 			if (!new_prog)
24361 				return -ENOMEM;
24362 
24363 			delta     += cnt - 1;
24364 			env->prog  = new_prog;
24365 			insn       = new_prog->insnsi + i + delta;
24366 		}
24367 
24368 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
24369 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
24370 			cur_subprog++;
24371 			stack_depth = subprogs[cur_subprog].stack_depth;
24372 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
24373 			stack_depth_extra = 0;
24374 		}
24375 	}
24376 
24377 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
24378 
24379 	return 0;
24380 }
24381 
24382 /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
24383  * adjust subprograms stack depth when possible.
24384  */
24385 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env)
24386 {
24387 	struct bpf_subprog_info *subprog = env->subprog_info;
24388 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
24389 	struct bpf_insn *insn = env->prog->insnsi;
24390 	int insn_cnt = env->prog->len;
24391 	u32 spills_num;
24392 	bool modified = false;
24393 	int i, j;
24394 
24395 	for (i = 0; i < insn_cnt; i++, insn++) {
24396 		if (aux[i].fastcall_spills_num > 0) {
24397 			spills_num = aux[i].fastcall_spills_num;
24398 			/* NOPs would be removed by opt_remove_nops() */
24399 			for (j = 1; j <= spills_num; ++j) {
24400 				*(insn - j) = NOP;
24401 				*(insn + j) = NOP;
24402 			}
24403 			modified = true;
24404 		}
24405 		if ((subprog + 1)->start == i + 1) {
24406 			if (modified && !subprog->keep_fastcall_stack)
24407 				subprog->stack_depth = -subprog->fastcall_stack_off;
24408 			subprog++;
24409 			modified = false;
24410 		}
24411 	}
24412 
24413 	return 0;
24414 }
24415 
24416 static void free_states(struct bpf_verifier_env *env)
24417 {
24418 	struct bpf_verifier_state_list *sl;
24419 	struct list_head *head, *pos, *tmp;
24420 	struct bpf_scc_info *info;
24421 	int i, j;
24422 
24423 	free_verifier_state(env->cur_state, true);
24424 	env->cur_state = NULL;
24425 	while (!pop_stack(env, NULL, NULL, false));
24426 
24427 	list_for_each_safe(pos, tmp, &env->free_list) {
24428 		sl = container_of(pos, struct bpf_verifier_state_list, node);
24429 		free_verifier_state(&sl->state, false);
24430 		kfree(sl);
24431 	}
24432 	INIT_LIST_HEAD(&env->free_list);
24433 
24434 	for (i = 0; i < env->scc_cnt; ++i) {
24435 		info = env->scc_info[i];
24436 		if (!info)
24437 			continue;
24438 		for (j = 0; j < info->num_visits; j++)
24439 			free_backedges(&info->visits[j]);
24440 		kvfree(info);
24441 		env->scc_info[i] = NULL;
24442 	}
24443 
24444 	if (!env->explored_states)
24445 		return;
24446 
24447 	for (i = 0; i < state_htab_size(env); i++) {
24448 		head = &env->explored_states[i];
24449 
24450 		list_for_each_safe(pos, tmp, head) {
24451 			sl = container_of(pos, struct bpf_verifier_state_list, node);
24452 			free_verifier_state(&sl->state, false);
24453 			kfree(sl);
24454 		}
24455 		INIT_LIST_HEAD(&env->explored_states[i]);
24456 	}
24457 }
24458 
24459 static int do_check_common(struct bpf_verifier_env *env, int subprog)
24460 {
24461 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
24462 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
24463 	struct bpf_prog_aux *aux = env->prog->aux;
24464 	struct bpf_verifier_state *state;
24465 	struct bpf_reg_state *regs;
24466 	int ret, i;
24467 
24468 	env->prev_linfo = NULL;
24469 	env->pass_cnt++;
24470 
24471 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL_ACCOUNT);
24472 	if (!state)
24473 		return -ENOMEM;
24474 	state->curframe = 0;
24475 	state->speculative = false;
24476 	state->branches = 1;
24477 	state->in_sleepable = env->prog->sleepable;
24478 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL_ACCOUNT);
24479 	if (!state->frame[0]) {
24480 		kfree(state);
24481 		return -ENOMEM;
24482 	}
24483 	env->cur_state = state;
24484 	init_func_state(env, state->frame[0],
24485 			BPF_MAIN_FUNC /* callsite */,
24486 			0 /* frameno */,
24487 			subprog);
24488 	state->first_insn_idx = env->subprog_info[subprog].start;
24489 	state->last_insn_idx = -1;
24490 
24491 	regs = state->frame[state->curframe]->regs;
24492 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
24493 		const char *sub_name = subprog_name(env, subprog);
24494 		struct bpf_subprog_arg_info *arg;
24495 		struct bpf_reg_state *reg;
24496 
24497 		if (env->log.level & BPF_LOG_LEVEL)
24498 			verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
24499 		ret = btf_prepare_func_args(env, subprog);
24500 		if (ret)
24501 			goto out;
24502 
24503 		if (subprog_is_exc_cb(env, subprog)) {
24504 			state->frame[0]->in_exception_callback_fn = true;
24505 			/* We have already ensured that the callback returns an integer, just
24506 			 * like all global subprogs. We need to determine it only has a single
24507 			 * scalar argument.
24508 			 */
24509 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
24510 				verbose(env, "exception cb only supports single integer argument\n");
24511 				ret = -EINVAL;
24512 				goto out;
24513 			}
24514 		}
24515 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
24516 			arg = &sub->args[i - BPF_REG_1];
24517 			reg = &regs[i];
24518 
24519 			if (arg->arg_type == ARG_PTR_TO_CTX) {
24520 				reg->type = PTR_TO_CTX;
24521 				mark_reg_known_zero(env, regs, i);
24522 			} else if (arg->arg_type == ARG_ANYTHING) {
24523 				reg->type = SCALAR_VALUE;
24524 				mark_reg_unknown(env, regs, i);
24525 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
24526 				/* assume unspecial LOCAL dynptr type */
24527 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
24528 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
24529 				reg->type = PTR_TO_MEM;
24530 				reg->type |= arg->arg_type &
24531 					     (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY);
24532 				mark_reg_known_zero(env, regs, i);
24533 				reg->mem_size = arg->mem_size;
24534 				if (arg->arg_type & PTR_MAYBE_NULL)
24535 					reg->id = ++env->id_gen;
24536 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
24537 				reg->type = PTR_TO_BTF_ID;
24538 				if (arg->arg_type & PTR_MAYBE_NULL)
24539 					reg->type |= PTR_MAYBE_NULL;
24540 				if (arg->arg_type & PTR_UNTRUSTED)
24541 					reg->type |= PTR_UNTRUSTED;
24542 				if (arg->arg_type & PTR_TRUSTED)
24543 					reg->type |= PTR_TRUSTED;
24544 				mark_reg_known_zero(env, regs, i);
24545 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
24546 				reg->btf_id = arg->btf_id;
24547 				reg->id = ++env->id_gen;
24548 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
24549 				/* caller can pass either PTR_TO_ARENA or SCALAR */
24550 				mark_reg_unknown(env, regs, i);
24551 			} else {
24552 				verifier_bug(env, "unhandled arg#%d type %d",
24553 					     i - BPF_REG_1, arg->arg_type);
24554 				ret = -EFAULT;
24555 				goto out;
24556 			}
24557 		}
24558 	} else {
24559 		/* if main BPF program has associated BTF info, validate that
24560 		 * it's matching expected signature, and otherwise mark BTF
24561 		 * info for main program as unreliable
24562 		 */
24563 		if (env->prog->aux->func_info_aux) {
24564 			ret = btf_prepare_func_args(env, 0);
24565 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
24566 				env->prog->aux->func_info_aux[0].unreliable = true;
24567 		}
24568 
24569 		/* 1st arg to a function */
24570 		regs[BPF_REG_1].type = PTR_TO_CTX;
24571 		mark_reg_known_zero(env, regs, BPF_REG_1);
24572 	}
24573 
24574 	/* Acquire references for struct_ops program arguments tagged with "__ref" */
24575 	if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
24576 		for (i = 0; i < aux->ctx_arg_info_size; i++)
24577 			aux->ctx_arg_info[i].ref_obj_id = aux->ctx_arg_info[i].refcounted ?
24578 							  acquire_reference(env, 0) : 0;
24579 	}
24580 
24581 	ret = do_check(env);
24582 out:
24583 	if (!ret && pop_log)
24584 		bpf_vlog_reset(&env->log, 0);
24585 	free_states(env);
24586 	return ret;
24587 }
24588 
24589 /* Lazily verify all global functions based on their BTF, if they are called
24590  * from main BPF program or any of subprograms transitively.
24591  * BPF global subprogs called from dead code are not validated.
24592  * All callable global functions must pass verification.
24593  * Otherwise the whole program is rejected.
24594  * Consider:
24595  * int bar(int);
24596  * int foo(int f)
24597  * {
24598  *    return bar(f);
24599  * }
24600  * int bar(int b)
24601  * {
24602  *    ...
24603  * }
24604  * foo() will be verified first for R1=any_scalar_value. During verification it
24605  * will be assumed that bar() already verified successfully and call to bar()
24606  * from foo() will be checked for type match only. Later bar() will be verified
24607  * independently to check that it's safe for R1=any_scalar_value.
24608  */
24609 static int do_check_subprogs(struct bpf_verifier_env *env)
24610 {
24611 	struct bpf_prog_aux *aux = env->prog->aux;
24612 	struct bpf_func_info_aux *sub_aux;
24613 	int i, ret, new_cnt;
24614 
24615 	if (!aux->func_info)
24616 		return 0;
24617 
24618 	/* exception callback is presumed to be always called */
24619 	if (env->exception_callback_subprog)
24620 		subprog_aux(env, env->exception_callback_subprog)->called = true;
24621 
24622 again:
24623 	new_cnt = 0;
24624 	for (i = 1; i < env->subprog_cnt; i++) {
24625 		if (!subprog_is_global(env, i))
24626 			continue;
24627 
24628 		sub_aux = subprog_aux(env, i);
24629 		if (!sub_aux->called || sub_aux->verified)
24630 			continue;
24631 
24632 		env->insn_idx = env->subprog_info[i].start;
24633 		WARN_ON_ONCE(env->insn_idx == 0);
24634 		ret = do_check_common(env, i);
24635 		if (ret) {
24636 			return ret;
24637 		} else if (env->log.level & BPF_LOG_LEVEL) {
24638 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
24639 				i, subprog_name(env, i));
24640 		}
24641 
24642 		/* We verified new global subprog, it might have called some
24643 		 * more global subprogs that we haven't verified yet, so we
24644 		 * need to do another pass over subprogs to verify those.
24645 		 */
24646 		sub_aux->verified = true;
24647 		new_cnt++;
24648 	}
24649 
24650 	/* We can't loop forever as we verify at least one global subprog on
24651 	 * each pass.
24652 	 */
24653 	if (new_cnt)
24654 		goto again;
24655 
24656 	return 0;
24657 }
24658 
24659 static int do_check_main(struct bpf_verifier_env *env)
24660 {
24661 	int ret;
24662 
24663 	env->insn_idx = 0;
24664 	ret = do_check_common(env, 0);
24665 	if (!ret)
24666 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
24667 	return ret;
24668 }
24669 
24670 
24671 static void print_verification_stats(struct bpf_verifier_env *env)
24672 {
24673 	int i;
24674 
24675 	if (env->log.level & BPF_LOG_STATS) {
24676 		verbose(env, "verification time %lld usec\n",
24677 			div_u64(env->verification_time, 1000));
24678 		verbose(env, "stack depth ");
24679 		for (i = 0; i < env->subprog_cnt; i++) {
24680 			u32 depth = env->subprog_info[i].stack_depth;
24681 
24682 			verbose(env, "%d", depth);
24683 			if (i + 1 < env->subprog_cnt)
24684 				verbose(env, "+");
24685 		}
24686 		verbose(env, "\n");
24687 	}
24688 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
24689 		"total_states %d peak_states %d mark_read %d\n",
24690 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
24691 		env->max_states_per_insn, env->total_states,
24692 		env->peak_states, env->longest_mark_read_walk);
24693 }
24694 
24695 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
24696 			       const struct bpf_ctx_arg_aux *info, u32 cnt)
24697 {
24698 	prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT);
24699 	prog->aux->ctx_arg_info_size = cnt;
24700 
24701 	return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
24702 }
24703 
24704 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
24705 {
24706 	const struct btf_type *t, *func_proto;
24707 	const struct bpf_struct_ops_desc *st_ops_desc;
24708 	const struct bpf_struct_ops *st_ops;
24709 	const struct btf_member *member;
24710 	struct bpf_prog *prog = env->prog;
24711 	bool has_refcounted_arg = false;
24712 	u32 btf_id, member_idx, member_off;
24713 	struct btf *btf;
24714 	const char *mname;
24715 	int i, err;
24716 
24717 	if (!prog->gpl_compatible) {
24718 		verbose(env, "struct ops programs must have a GPL compatible license\n");
24719 		return -EINVAL;
24720 	}
24721 
24722 	if (!prog->aux->attach_btf_id)
24723 		return -ENOTSUPP;
24724 
24725 	btf = prog->aux->attach_btf;
24726 	if (btf_is_module(btf)) {
24727 		/* Make sure st_ops is valid through the lifetime of env */
24728 		env->attach_btf_mod = btf_try_get_module(btf);
24729 		if (!env->attach_btf_mod) {
24730 			verbose(env, "struct_ops module %s is not found\n",
24731 				btf_get_name(btf));
24732 			return -ENOTSUPP;
24733 		}
24734 	}
24735 
24736 	btf_id = prog->aux->attach_btf_id;
24737 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
24738 	if (!st_ops_desc) {
24739 		verbose(env, "attach_btf_id %u is not a supported struct\n",
24740 			btf_id);
24741 		return -ENOTSUPP;
24742 	}
24743 	st_ops = st_ops_desc->st_ops;
24744 
24745 	t = st_ops_desc->type;
24746 	member_idx = prog->expected_attach_type;
24747 	if (member_idx >= btf_type_vlen(t)) {
24748 		verbose(env, "attach to invalid member idx %u of struct %s\n",
24749 			member_idx, st_ops->name);
24750 		return -EINVAL;
24751 	}
24752 
24753 	member = &btf_type_member(t)[member_idx];
24754 	mname = btf_name_by_offset(btf, member->name_off);
24755 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
24756 					       NULL);
24757 	if (!func_proto) {
24758 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
24759 			mname, member_idx, st_ops->name);
24760 		return -EINVAL;
24761 	}
24762 
24763 	member_off = __btf_member_bit_offset(t, member) / 8;
24764 	err = bpf_struct_ops_supported(st_ops, member_off);
24765 	if (err) {
24766 		verbose(env, "attach to unsupported member %s of struct %s\n",
24767 			mname, st_ops->name);
24768 		return err;
24769 	}
24770 
24771 	if (st_ops->check_member) {
24772 		err = st_ops->check_member(t, member, prog);
24773 
24774 		if (err) {
24775 			verbose(env, "attach to unsupported member %s of struct %s\n",
24776 				mname, st_ops->name);
24777 			return err;
24778 		}
24779 	}
24780 
24781 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
24782 		verbose(env, "Private stack not supported by jit\n");
24783 		return -EACCES;
24784 	}
24785 
24786 	for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) {
24787 		if (st_ops_desc->arg_info[member_idx].info->refcounted) {
24788 			has_refcounted_arg = true;
24789 			break;
24790 		}
24791 	}
24792 
24793 	/* Tail call is not allowed for programs with refcounted arguments since we
24794 	 * cannot guarantee that valid refcounted kptrs will be passed to the callee.
24795 	 */
24796 	for (i = 0; i < env->subprog_cnt; i++) {
24797 		if (has_refcounted_arg && env->subprog_info[i].has_tail_call) {
24798 			verbose(env, "program with __ref argument cannot tail call\n");
24799 			return -EINVAL;
24800 		}
24801 	}
24802 
24803 	prog->aux->st_ops = st_ops;
24804 	prog->aux->attach_st_ops_member_off = member_off;
24805 
24806 	prog->aux->attach_func_proto = func_proto;
24807 	prog->aux->attach_func_name = mname;
24808 	env->ops = st_ops->verifier_ops;
24809 
24810 	return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info,
24811 					  st_ops_desc->arg_info[member_idx].cnt);
24812 }
24813 #define SECURITY_PREFIX "security_"
24814 
24815 static int check_attach_modify_return(unsigned long addr, const char *func_name)
24816 {
24817 	if (within_error_injection_list(addr) ||
24818 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
24819 		return 0;
24820 
24821 	return -EINVAL;
24822 }
24823 
24824 /* list of non-sleepable functions that are otherwise on
24825  * ALLOW_ERROR_INJECTION list
24826  */
24827 BTF_SET_START(btf_non_sleepable_error_inject)
24828 /* Three functions below can be called from sleepable and non-sleepable context.
24829  * Assume non-sleepable from bpf safety point of view.
24830  */
24831 BTF_ID(func, __filemap_add_folio)
24832 #ifdef CONFIG_FAIL_PAGE_ALLOC
24833 BTF_ID(func, should_fail_alloc_page)
24834 #endif
24835 #ifdef CONFIG_FAILSLAB
24836 BTF_ID(func, should_failslab)
24837 #endif
24838 BTF_SET_END(btf_non_sleepable_error_inject)
24839 
24840 static int check_non_sleepable_error_inject(u32 btf_id)
24841 {
24842 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
24843 }
24844 
24845 int bpf_check_attach_target(struct bpf_verifier_log *log,
24846 			    const struct bpf_prog *prog,
24847 			    const struct bpf_prog *tgt_prog,
24848 			    u32 btf_id,
24849 			    struct bpf_attach_target_info *tgt_info)
24850 {
24851 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
24852 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
24853 	char trace_symbol[KSYM_SYMBOL_LEN];
24854 	const char prefix[] = "btf_trace_";
24855 	struct bpf_raw_event_map *btp;
24856 	int ret = 0, subprog = -1, i;
24857 	const struct btf_type *t;
24858 	bool conservative = true;
24859 	const char *tname, *fname;
24860 	struct btf *btf;
24861 	long addr = 0;
24862 	struct module *mod = NULL;
24863 
24864 	if (!btf_id) {
24865 		bpf_log(log, "Tracing programs must provide btf_id\n");
24866 		return -EINVAL;
24867 	}
24868 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
24869 	if (!btf) {
24870 		bpf_log(log,
24871 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
24872 		return -EINVAL;
24873 	}
24874 	t = btf_type_by_id(btf, btf_id);
24875 	if (!t) {
24876 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
24877 		return -EINVAL;
24878 	}
24879 	tname = btf_name_by_offset(btf, t->name_off);
24880 	if (!tname) {
24881 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
24882 		return -EINVAL;
24883 	}
24884 	if (tgt_prog) {
24885 		struct bpf_prog_aux *aux = tgt_prog->aux;
24886 		bool tgt_changes_pkt_data;
24887 		bool tgt_might_sleep;
24888 
24889 		if (bpf_prog_is_dev_bound(prog->aux) &&
24890 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
24891 			bpf_log(log, "Target program bound device mismatch");
24892 			return -EINVAL;
24893 		}
24894 
24895 		for (i = 0; i < aux->func_info_cnt; i++)
24896 			if (aux->func_info[i].type_id == btf_id) {
24897 				subprog = i;
24898 				break;
24899 			}
24900 		if (subprog == -1) {
24901 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
24902 			return -EINVAL;
24903 		}
24904 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
24905 			bpf_log(log,
24906 				"%s programs cannot attach to exception callback\n",
24907 				prog_extension ? "Extension" : "FENTRY/FEXIT");
24908 			return -EINVAL;
24909 		}
24910 		conservative = aux->func_info_aux[subprog].unreliable;
24911 		if (prog_extension) {
24912 			if (conservative) {
24913 				bpf_log(log,
24914 					"Cannot replace static functions\n");
24915 				return -EINVAL;
24916 			}
24917 			if (!prog->jit_requested) {
24918 				bpf_log(log,
24919 					"Extension programs should be JITed\n");
24920 				return -EINVAL;
24921 			}
24922 			tgt_changes_pkt_data = aux->func
24923 					       ? aux->func[subprog]->aux->changes_pkt_data
24924 					       : aux->changes_pkt_data;
24925 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
24926 				bpf_log(log,
24927 					"Extension program changes packet data, while original does not\n");
24928 				return -EINVAL;
24929 			}
24930 
24931 			tgt_might_sleep = aux->func
24932 					  ? aux->func[subprog]->aux->might_sleep
24933 					  : aux->might_sleep;
24934 			if (prog->aux->might_sleep && !tgt_might_sleep) {
24935 				bpf_log(log,
24936 					"Extension program may sleep, while original does not\n");
24937 				return -EINVAL;
24938 			}
24939 		}
24940 		if (!tgt_prog->jited) {
24941 			bpf_log(log, "Can attach to only JITed progs\n");
24942 			return -EINVAL;
24943 		}
24944 		if (prog_tracing) {
24945 			if (aux->attach_tracing_prog) {
24946 				/*
24947 				 * Target program is an fentry/fexit which is already attached
24948 				 * to another tracing program. More levels of nesting
24949 				 * attachment are not allowed.
24950 				 */
24951 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
24952 				return -EINVAL;
24953 			}
24954 		} else if (tgt_prog->type == prog->type) {
24955 			/*
24956 			 * To avoid potential call chain cycles, prevent attaching of a
24957 			 * program extension to another extension. It's ok to attach
24958 			 * fentry/fexit to extension program.
24959 			 */
24960 			bpf_log(log, "Cannot recursively attach\n");
24961 			return -EINVAL;
24962 		}
24963 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
24964 		    prog_extension &&
24965 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
24966 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT ||
24967 		     tgt_prog->expected_attach_type == BPF_TRACE_FSESSION)) {
24968 			/* Program extensions can extend all program types
24969 			 * except fentry/fexit. The reason is the following.
24970 			 * The fentry/fexit programs are used for performance
24971 			 * analysis, stats and can be attached to any program
24972 			 * type. When extension program is replacing XDP function
24973 			 * it is necessary to allow performance analysis of all
24974 			 * functions. Both original XDP program and its program
24975 			 * extension. Hence attaching fentry/fexit to
24976 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
24977 			 * fentry/fexit was allowed it would be possible to create
24978 			 * long call chain fentry->extension->fentry->extension
24979 			 * beyond reasonable stack size. Hence extending fentry
24980 			 * is not allowed.
24981 			 */
24982 			bpf_log(log, "Cannot extend fentry/fexit/fsession\n");
24983 			return -EINVAL;
24984 		}
24985 	} else {
24986 		if (prog_extension) {
24987 			bpf_log(log, "Cannot replace kernel functions\n");
24988 			return -EINVAL;
24989 		}
24990 	}
24991 
24992 	switch (prog->expected_attach_type) {
24993 	case BPF_TRACE_RAW_TP:
24994 		if (tgt_prog) {
24995 			bpf_log(log,
24996 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
24997 			return -EINVAL;
24998 		}
24999 		if (!btf_type_is_typedef(t)) {
25000 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
25001 				btf_id);
25002 			return -EINVAL;
25003 		}
25004 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
25005 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
25006 				btf_id, tname);
25007 			return -EINVAL;
25008 		}
25009 		tname += sizeof(prefix) - 1;
25010 
25011 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
25012 		 * names. Thus using bpf_raw_event_map to get argument names.
25013 		 */
25014 		btp = bpf_get_raw_tracepoint(tname);
25015 		if (!btp)
25016 			return -EINVAL;
25017 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
25018 					trace_symbol);
25019 		bpf_put_raw_tracepoint(btp);
25020 
25021 		if (fname)
25022 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
25023 
25024 		if (!fname || ret < 0) {
25025 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
25026 				prefix, tname);
25027 			t = btf_type_by_id(btf, t->type);
25028 			if (!btf_type_is_ptr(t))
25029 				/* should never happen in valid vmlinux build */
25030 				return -EINVAL;
25031 		} else {
25032 			t = btf_type_by_id(btf, ret);
25033 			if (!btf_type_is_func(t))
25034 				/* should never happen in valid vmlinux build */
25035 				return -EINVAL;
25036 		}
25037 
25038 		t = btf_type_by_id(btf, t->type);
25039 		if (!btf_type_is_func_proto(t))
25040 			/* should never happen in valid vmlinux build */
25041 			return -EINVAL;
25042 
25043 		break;
25044 	case BPF_TRACE_ITER:
25045 		if (!btf_type_is_func(t)) {
25046 			bpf_log(log, "attach_btf_id %u is not a function\n",
25047 				btf_id);
25048 			return -EINVAL;
25049 		}
25050 		t = btf_type_by_id(btf, t->type);
25051 		if (!btf_type_is_func_proto(t))
25052 			return -EINVAL;
25053 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
25054 		if (ret)
25055 			return ret;
25056 		break;
25057 	default:
25058 		if (!prog_extension)
25059 			return -EINVAL;
25060 		fallthrough;
25061 	case BPF_MODIFY_RETURN:
25062 	case BPF_LSM_MAC:
25063 	case BPF_LSM_CGROUP:
25064 	case BPF_TRACE_FENTRY:
25065 	case BPF_TRACE_FEXIT:
25066 	case BPF_TRACE_FSESSION:
25067 		if (prog->expected_attach_type == BPF_TRACE_FSESSION &&
25068 		    !bpf_jit_supports_fsession()) {
25069 			bpf_log(log, "JIT does not support fsession\n");
25070 			return -EOPNOTSUPP;
25071 		}
25072 		if (!btf_type_is_func(t)) {
25073 			bpf_log(log, "attach_btf_id %u is not a function\n",
25074 				btf_id);
25075 			return -EINVAL;
25076 		}
25077 		if (prog_extension &&
25078 		    btf_check_type_match(log, prog, btf, t))
25079 			return -EINVAL;
25080 		t = btf_type_by_id(btf, t->type);
25081 		if (!btf_type_is_func_proto(t))
25082 			return -EINVAL;
25083 
25084 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
25085 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
25086 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
25087 			return -EINVAL;
25088 
25089 		if (tgt_prog && conservative)
25090 			t = NULL;
25091 
25092 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
25093 		if (ret < 0)
25094 			return ret;
25095 
25096 		if (tgt_prog) {
25097 			if (subprog == 0)
25098 				addr = (long) tgt_prog->bpf_func;
25099 			else
25100 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
25101 		} else {
25102 			if (btf_is_module(btf)) {
25103 				mod = btf_try_get_module(btf);
25104 				if (mod)
25105 					addr = find_kallsyms_symbol_value(mod, tname);
25106 				else
25107 					addr = 0;
25108 			} else {
25109 				addr = kallsyms_lookup_name(tname);
25110 			}
25111 			if (!addr) {
25112 				module_put(mod);
25113 				bpf_log(log,
25114 					"The address of function %s cannot be found\n",
25115 					tname);
25116 				return -ENOENT;
25117 			}
25118 		}
25119 
25120 		if (prog->sleepable) {
25121 			ret = -EINVAL;
25122 			switch (prog->type) {
25123 			case BPF_PROG_TYPE_TRACING:
25124 
25125 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
25126 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
25127 				 */
25128 				if (!check_non_sleepable_error_inject(btf_id) &&
25129 				    within_error_injection_list(addr))
25130 					ret = 0;
25131 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
25132 				 * in the fmodret id set with the KF_SLEEPABLE flag.
25133 				 */
25134 				else {
25135 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
25136 										prog);
25137 
25138 					if (flags && (*flags & KF_SLEEPABLE))
25139 						ret = 0;
25140 				}
25141 				break;
25142 			case BPF_PROG_TYPE_LSM:
25143 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
25144 				 * Only some of them are sleepable.
25145 				 */
25146 				if (bpf_lsm_is_sleepable_hook(btf_id))
25147 					ret = 0;
25148 				break;
25149 			default:
25150 				break;
25151 			}
25152 			if (ret) {
25153 				module_put(mod);
25154 				bpf_log(log, "%s is not sleepable\n", tname);
25155 				return ret;
25156 			}
25157 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
25158 			if (tgt_prog) {
25159 				module_put(mod);
25160 				bpf_log(log, "can't modify return codes of BPF programs\n");
25161 				return -EINVAL;
25162 			}
25163 			ret = -EINVAL;
25164 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
25165 			    !check_attach_modify_return(addr, tname))
25166 				ret = 0;
25167 			if (ret) {
25168 				module_put(mod);
25169 				bpf_log(log, "%s() is not modifiable\n", tname);
25170 				return ret;
25171 			}
25172 		}
25173 
25174 		break;
25175 	}
25176 	tgt_info->tgt_addr = addr;
25177 	tgt_info->tgt_name = tname;
25178 	tgt_info->tgt_type = t;
25179 	tgt_info->tgt_mod = mod;
25180 	return 0;
25181 }
25182 
25183 BTF_SET_START(btf_id_deny)
25184 BTF_ID_UNUSED
25185 #ifdef CONFIG_SMP
25186 BTF_ID(func, ___migrate_enable)
25187 BTF_ID(func, migrate_disable)
25188 BTF_ID(func, migrate_enable)
25189 #endif
25190 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
25191 BTF_ID(func, rcu_read_unlock_strict)
25192 #endif
25193 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
25194 BTF_ID(func, preempt_count_add)
25195 BTF_ID(func, preempt_count_sub)
25196 #endif
25197 #ifdef CONFIG_PREEMPT_RCU
25198 BTF_ID(func, __rcu_read_lock)
25199 BTF_ID(func, __rcu_read_unlock)
25200 #endif
25201 BTF_SET_END(btf_id_deny)
25202 
25203 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
25204  * Currently, we must manually list all __noreturn functions here. Once a more
25205  * robust solution is implemented, this workaround can be removed.
25206  */
25207 BTF_SET_START(noreturn_deny)
25208 #ifdef CONFIG_IA32_EMULATION
25209 BTF_ID(func, __ia32_sys_exit)
25210 BTF_ID(func, __ia32_sys_exit_group)
25211 #endif
25212 #ifdef CONFIG_KUNIT
25213 BTF_ID(func, __kunit_abort)
25214 BTF_ID(func, kunit_try_catch_throw)
25215 #endif
25216 #ifdef CONFIG_MODULES
25217 BTF_ID(func, __module_put_and_kthread_exit)
25218 #endif
25219 #ifdef CONFIG_X86_64
25220 BTF_ID(func, __x64_sys_exit)
25221 BTF_ID(func, __x64_sys_exit_group)
25222 #endif
25223 BTF_ID(func, do_exit)
25224 BTF_ID(func, do_group_exit)
25225 BTF_ID(func, kthread_complete_and_exit)
25226 BTF_ID(func, kthread_exit)
25227 BTF_ID(func, make_task_dead)
25228 BTF_SET_END(noreturn_deny)
25229 
25230 static bool can_be_sleepable(struct bpf_prog *prog)
25231 {
25232 	if (prog->type == BPF_PROG_TYPE_TRACING) {
25233 		switch (prog->expected_attach_type) {
25234 		case BPF_TRACE_FENTRY:
25235 		case BPF_TRACE_FEXIT:
25236 		case BPF_MODIFY_RETURN:
25237 		case BPF_TRACE_ITER:
25238 		case BPF_TRACE_FSESSION:
25239 			return true;
25240 		default:
25241 			return false;
25242 		}
25243 	}
25244 	return prog->type == BPF_PROG_TYPE_LSM ||
25245 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
25246 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
25247 }
25248 
25249 static int check_attach_btf_id(struct bpf_verifier_env *env)
25250 {
25251 	struct bpf_prog *prog = env->prog;
25252 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
25253 	struct bpf_attach_target_info tgt_info = {};
25254 	u32 btf_id = prog->aux->attach_btf_id;
25255 	struct bpf_trampoline *tr;
25256 	int ret;
25257 	u64 key;
25258 
25259 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
25260 		if (prog->sleepable)
25261 			/* attach_btf_id checked to be zero already */
25262 			return 0;
25263 		verbose(env, "Syscall programs can only be sleepable\n");
25264 		return -EINVAL;
25265 	}
25266 
25267 	if (prog->sleepable && !can_be_sleepable(prog)) {
25268 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
25269 		return -EINVAL;
25270 	}
25271 
25272 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
25273 		return check_struct_ops_btf_id(env);
25274 
25275 	if (prog->type != BPF_PROG_TYPE_TRACING &&
25276 	    prog->type != BPF_PROG_TYPE_LSM &&
25277 	    prog->type != BPF_PROG_TYPE_EXT)
25278 		return 0;
25279 
25280 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
25281 	if (ret)
25282 		return ret;
25283 
25284 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
25285 		/* to make freplace equivalent to their targets, they need to
25286 		 * inherit env->ops and expected_attach_type for the rest of the
25287 		 * verification
25288 		 */
25289 		env->ops = bpf_verifier_ops[tgt_prog->type];
25290 		prog->expected_attach_type = tgt_prog->expected_attach_type;
25291 	}
25292 
25293 	/* store info about the attachment target that will be used later */
25294 	prog->aux->attach_func_proto = tgt_info.tgt_type;
25295 	prog->aux->attach_func_name = tgt_info.tgt_name;
25296 	prog->aux->mod = tgt_info.tgt_mod;
25297 
25298 	if (tgt_prog) {
25299 		prog->aux->saved_dst_prog_type = tgt_prog->type;
25300 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
25301 	}
25302 
25303 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
25304 		prog->aux->attach_btf_trace = true;
25305 		return 0;
25306 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
25307 		return bpf_iter_prog_supported(prog);
25308 	}
25309 
25310 	if (prog->type == BPF_PROG_TYPE_LSM) {
25311 		ret = bpf_lsm_verify_prog(&env->log, prog);
25312 		if (ret < 0)
25313 			return ret;
25314 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
25315 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
25316 		verbose(env, "Attaching tracing programs to function '%s' is rejected.\n",
25317 			tgt_info.tgt_name);
25318 		return -EINVAL;
25319 	} else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
25320 		   prog->expected_attach_type == BPF_TRACE_FSESSION ||
25321 		   prog->expected_attach_type == BPF_MODIFY_RETURN) &&
25322 		   btf_id_set_contains(&noreturn_deny, btf_id)) {
25323 		verbose(env, "Attaching fexit/fsession/fmod_ret to __noreturn function '%s' is rejected.\n",
25324 			tgt_info.tgt_name);
25325 		return -EINVAL;
25326 	}
25327 
25328 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
25329 	tr = bpf_trampoline_get(key, &tgt_info);
25330 	if (!tr)
25331 		return -ENOMEM;
25332 
25333 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
25334 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
25335 
25336 	prog->aux->dst_trampoline = tr;
25337 	return 0;
25338 }
25339 
25340 struct btf *bpf_get_btf_vmlinux(void)
25341 {
25342 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
25343 		mutex_lock(&bpf_verifier_lock);
25344 		if (!btf_vmlinux)
25345 			btf_vmlinux = btf_parse_vmlinux();
25346 		mutex_unlock(&bpf_verifier_lock);
25347 	}
25348 	return btf_vmlinux;
25349 }
25350 
25351 /*
25352  * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
25353  * this case expect that every file descriptor in the array is either a map or
25354  * a BTF. Everything else is considered to be trash.
25355  */
25356 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd)
25357 {
25358 	struct bpf_map *map;
25359 	struct btf *btf;
25360 	CLASS(fd, f)(fd);
25361 	int err;
25362 
25363 	map = __bpf_map_get(f);
25364 	if (!IS_ERR(map)) {
25365 		err = __add_used_map(env, map);
25366 		if (err < 0)
25367 			return err;
25368 		return 0;
25369 	}
25370 
25371 	btf = __btf_get_by_fd(f);
25372 	if (!IS_ERR(btf)) {
25373 		err = __add_used_btf(env, btf);
25374 		if (err < 0)
25375 			return err;
25376 		return 0;
25377 	}
25378 
25379 	verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
25380 	return PTR_ERR(map);
25381 }
25382 
25383 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr)
25384 {
25385 	size_t size = sizeof(int);
25386 	int ret;
25387 	int fd;
25388 	u32 i;
25389 
25390 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
25391 
25392 	/*
25393 	 * The only difference between old (no fd_array_cnt is given) and new
25394 	 * APIs is that in the latter case the fd_array is expected to be
25395 	 * continuous and is scanned for map fds right away
25396 	 */
25397 	if (!attr->fd_array_cnt)
25398 		return 0;
25399 
25400 	/* Check for integer overflow */
25401 	if (attr->fd_array_cnt >= (U32_MAX / size)) {
25402 		verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt);
25403 		return -EINVAL;
25404 	}
25405 
25406 	for (i = 0; i < attr->fd_array_cnt; i++) {
25407 		if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size))
25408 			return -EFAULT;
25409 
25410 		ret = add_fd_from_fd_array(env, fd);
25411 		if (ret)
25412 			return ret;
25413 	}
25414 
25415 	return 0;
25416 }
25417 
25418 /* Each field is a register bitmask */
25419 struct insn_live_regs {
25420 	u16 use;	/* registers read by instruction */
25421 	u16 def;	/* registers written by instruction */
25422 	u16 in;		/* registers that may be alive before instruction */
25423 	u16 out;	/* registers that may be alive after instruction */
25424 };
25425 
25426 /* Bitmask with 1s for all caller saved registers */
25427 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
25428 
25429 /* Compute info->{use,def} fields for the instruction */
25430 static void compute_insn_live_regs(struct bpf_verifier_env *env,
25431 				   struct bpf_insn *insn,
25432 				   struct insn_live_regs *info)
25433 {
25434 	struct call_summary cs;
25435 	u8 class = BPF_CLASS(insn->code);
25436 	u8 code = BPF_OP(insn->code);
25437 	u8 mode = BPF_MODE(insn->code);
25438 	u16 src = BIT(insn->src_reg);
25439 	u16 dst = BIT(insn->dst_reg);
25440 	u16 r0  = BIT(0);
25441 	u16 def = 0;
25442 	u16 use = 0xffff;
25443 
25444 	switch (class) {
25445 	case BPF_LD:
25446 		switch (mode) {
25447 		case BPF_IMM:
25448 			if (BPF_SIZE(insn->code) == BPF_DW) {
25449 				def = dst;
25450 				use = 0;
25451 			}
25452 			break;
25453 		case BPF_LD | BPF_ABS:
25454 		case BPF_LD | BPF_IND:
25455 			/* stick with defaults */
25456 			break;
25457 		}
25458 		break;
25459 	case BPF_LDX:
25460 		switch (mode) {
25461 		case BPF_MEM:
25462 		case BPF_MEMSX:
25463 			def = dst;
25464 			use = src;
25465 			break;
25466 		}
25467 		break;
25468 	case BPF_ST:
25469 		switch (mode) {
25470 		case BPF_MEM:
25471 			def = 0;
25472 			use = dst;
25473 			break;
25474 		}
25475 		break;
25476 	case BPF_STX:
25477 		switch (mode) {
25478 		case BPF_MEM:
25479 			def = 0;
25480 			use = dst | src;
25481 			break;
25482 		case BPF_ATOMIC:
25483 			switch (insn->imm) {
25484 			case BPF_CMPXCHG:
25485 				use = r0 | dst | src;
25486 				def = r0;
25487 				break;
25488 			case BPF_LOAD_ACQ:
25489 				def = dst;
25490 				use = src;
25491 				break;
25492 			case BPF_STORE_REL:
25493 				def = 0;
25494 				use = dst | src;
25495 				break;
25496 			default:
25497 				use = dst | src;
25498 				if (insn->imm & BPF_FETCH)
25499 					def = src;
25500 				else
25501 					def = 0;
25502 			}
25503 			break;
25504 		}
25505 		break;
25506 	case BPF_ALU:
25507 	case BPF_ALU64:
25508 		switch (code) {
25509 		case BPF_END:
25510 			use = dst;
25511 			def = dst;
25512 			break;
25513 		case BPF_MOV:
25514 			def = dst;
25515 			if (BPF_SRC(insn->code) == BPF_K)
25516 				use = 0;
25517 			else
25518 				use = src;
25519 			break;
25520 		default:
25521 			def = dst;
25522 			if (BPF_SRC(insn->code) == BPF_K)
25523 				use = dst;
25524 			else
25525 				use = dst | src;
25526 		}
25527 		break;
25528 	case BPF_JMP:
25529 	case BPF_JMP32:
25530 		switch (code) {
25531 		case BPF_JA:
25532 			def = 0;
25533 			if (BPF_SRC(insn->code) == BPF_X)
25534 				use = dst;
25535 			else
25536 				use = 0;
25537 			break;
25538 		case BPF_JCOND:
25539 			def = 0;
25540 			use = 0;
25541 			break;
25542 		case BPF_EXIT:
25543 			def = 0;
25544 			use = r0;
25545 			break;
25546 		case BPF_CALL:
25547 			def = ALL_CALLER_SAVED_REGS;
25548 			use = def & ~BIT(BPF_REG_0);
25549 			if (get_call_summary(env, insn, &cs))
25550 				use = GENMASK(cs.num_params, 1);
25551 			break;
25552 		default:
25553 			def = 0;
25554 			if (BPF_SRC(insn->code) == BPF_K)
25555 				use = dst;
25556 			else
25557 				use = dst | src;
25558 		}
25559 		break;
25560 	}
25561 
25562 	info->def = def;
25563 	info->use = use;
25564 }
25565 
25566 /* Compute may-live registers after each instruction in the program.
25567  * The register is live after the instruction I if it is read by some
25568  * instruction S following I during program execution and is not
25569  * overwritten between I and S.
25570  *
25571  * Store result in env->insn_aux_data[i].live_regs.
25572  */
25573 static int compute_live_registers(struct bpf_verifier_env *env)
25574 {
25575 	struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
25576 	struct bpf_insn *insns = env->prog->insnsi;
25577 	struct insn_live_regs *state;
25578 	int insn_cnt = env->prog->len;
25579 	int err = 0, i, j;
25580 	bool changed;
25581 
25582 	/* Use the following algorithm:
25583 	 * - define the following:
25584 	 *   - I.use : a set of all registers read by instruction I;
25585 	 *   - I.def : a set of all registers written by instruction I;
25586 	 *   - I.in  : a set of all registers that may be alive before I execution;
25587 	 *   - I.out : a set of all registers that may be alive after I execution;
25588 	 *   - insn_successors(I): a set of instructions S that might immediately
25589 	 *                         follow I for some program execution;
25590 	 * - associate separate empty sets 'I.in' and 'I.out' with each instruction;
25591 	 * - visit each instruction in a postorder and update
25592 	 *   state[i].in, state[i].out as follows:
25593 	 *
25594 	 *       state[i].out = U [state[s].in for S in insn_successors(i)]
25595 	 *       state[i].in  = (state[i].out / state[i].def) U state[i].use
25596 	 *
25597 	 *   (where U stands for set union, / stands for set difference)
25598 	 * - repeat the computation while {in,out} fields changes for
25599 	 *   any instruction.
25600 	 */
25601 	state = kvcalloc(insn_cnt, sizeof(*state), GFP_KERNEL_ACCOUNT);
25602 	if (!state) {
25603 		err = -ENOMEM;
25604 		goto out;
25605 	}
25606 
25607 	for (i = 0; i < insn_cnt; ++i)
25608 		compute_insn_live_regs(env, &insns[i], &state[i]);
25609 
25610 	changed = true;
25611 	while (changed) {
25612 		changed = false;
25613 		for (i = 0; i < env->cfg.cur_postorder; ++i) {
25614 			int insn_idx = env->cfg.insn_postorder[i];
25615 			struct insn_live_regs *live = &state[insn_idx];
25616 			struct bpf_iarray *succ;
25617 			u16 new_out = 0;
25618 			u16 new_in = 0;
25619 
25620 			succ = bpf_insn_successors(env, insn_idx);
25621 			for (int s = 0; s < succ->cnt; ++s)
25622 				new_out |= state[succ->items[s]].in;
25623 			new_in = (new_out & ~live->def) | live->use;
25624 			if (new_out != live->out || new_in != live->in) {
25625 				live->in = new_in;
25626 				live->out = new_out;
25627 				changed = true;
25628 			}
25629 		}
25630 	}
25631 
25632 	for (i = 0; i < insn_cnt; ++i)
25633 		insn_aux[i].live_regs_before = state[i].in;
25634 
25635 	if (env->log.level & BPF_LOG_LEVEL2) {
25636 		verbose(env, "Live regs before insn:\n");
25637 		for (i = 0; i < insn_cnt; ++i) {
25638 			if (env->insn_aux_data[i].scc)
25639 				verbose(env, "%3d ", env->insn_aux_data[i].scc);
25640 			else
25641 				verbose(env, "    ");
25642 			verbose(env, "%3d: ", i);
25643 			for (j = BPF_REG_0; j < BPF_REG_10; ++j)
25644 				if (insn_aux[i].live_regs_before & BIT(j))
25645 					verbose(env, "%d", j);
25646 				else
25647 					verbose(env, ".");
25648 			verbose(env, " ");
25649 			verbose_insn(env, &insns[i]);
25650 			if (bpf_is_ldimm64(&insns[i]))
25651 				i++;
25652 		}
25653 	}
25654 
25655 out:
25656 	kvfree(state);
25657 	return err;
25658 }
25659 
25660 /*
25661  * Compute strongly connected components (SCCs) on the CFG.
25662  * Assign an SCC number to each instruction, recorded in env->insn_aux[*].scc.
25663  * If instruction is a sole member of its SCC and there are no self edges,
25664  * assign it SCC number of zero.
25665  * Uses a non-recursive adaptation of Tarjan's algorithm for SCC computation.
25666  */
25667 static int compute_scc(struct bpf_verifier_env *env)
25668 {
25669 	const u32 NOT_ON_STACK = U32_MAX;
25670 
25671 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
25672 	const u32 insn_cnt = env->prog->len;
25673 	int stack_sz, dfs_sz, err = 0;
25674 	u32 *stack, *pre, *low, *dfs;
25675 	u32 i, j, t, w;
25676 	u32 next_preorder_num;
25677 	u32 next_scc_id;
25678 	bool assign_scc;
25679 	struct bpf_iarray *succ;
25680 
25681 	next_preorder_num = 1;
25682 	next_scc_id = 1;
25683 	/*
25684 	 * - 'stack' accumulates vertices in DFS order, see invariant comment below;
25685 	 * - 'pre[t] == p' => preorder number of vertex 't' is 'p';
25686 	 * - 'low[t] == n' => smallest preorder number of the vertex reachable from 't' is 'n';
25687 	 * - 'dfs' DFS traversal stack, used to emulate explicit recursion.
25688 	 */
25689 	stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
25690 	pre = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
25691 	low = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
25692 	dfs = kvcalloc(insn_cnt, sizeof(*dfs), GFP_KERNEL_ACCOUNT);
25693 	if (!stack || !pre || !low || !dfs) {
25694 		err = -ENOMEM;
25695 		goto exit;
25696 	}
25697 	/*
25698 	 * References:
25699 	 * [1] R. Tarjan "Depth-First Search and Linear Graph Algorithms"
25700 	 * [2] D. J. Pearce "A Space-Efficient Algorithm for Finding Strongly Connected Components"
25701 	 *
25702 	 * The algorithm maintains the following invariant:
25703 	 * - suppose there is a path 'u' ~> 'v', such that 'pre[v] < pre[u]';
25704 	 * - then, vertex 'u' remains on stack while vertex 'v' is on stack.
25705 	 *
25706 	 * Consequently:
25707 	 * - If 'low[v] < pre[v]', there is a path from 'v' to some vertex 'u',
25708 	 *   such that 'pre[u] == low[v]'; vertex 'u' is currently on the stack,
25709 	 *   and thus there is an SCC (loop) containing both 'u' and 'v'.
25710 	 * - If 'low[v] == pre[v]', loops containing 'v' have been explored,
25711 	 *   and 'v' can be considered the root of some SCC.
25712 	 *
25713 	 * Here is a pseudo-code for an explicitly recursive version of the algorithm:
25714 	 *
25715 	 *    NOT_ON_STACK = insn_cnt + 1
25716 	 *    pre = [0] * insn_cnt
25717 	 *    low = [0] * insn_cnt
25718 	 *    scc = [0] * insn_cnt
25719 	 *    stack = []
25720 	 *
25721 	 *    next_preorder_num = 1
25722 	 *    next_scc_id = 1
25723 	 *
25724 	 *    def recur(w):
25725 	 *        nonlocal next_preorder_num
25726 	 *        nonlocal next_scc_id
25727 	 *
25728 	 *        pre[w] = next_preorder_num
25729 	 *        low[w] = next_preorder_num
25730 	 *        next_preorder_num += 1
25731 	 *        stack.append(w)
25732 	 *        for s in successors(w):
25733 	 *            # Note: for classic algorithm the block below should look as:
25734 	 *            #
25735 	 *            # if pre[s] == 0:
25736 	 *            #     recur(s)
25737 	 *            #	    low[w] = min(low[w], low[s])
25738 	 *            # elif low[s] != NOT_ON_STACK:
25739 	 *            #     low[w] = min(low[w], pre[s])
25740 	 *            #
25741 	 *            # But replacing both 'min' instructions with 'low[w] = min(low[w], low[s])'
25742 	 *            # does not break the invariant and makes itartive version of the algorithm
25743 	 *            # simpler. See 'Algorithm #3' from [2].
25744 	 *
25745 	 *            # 's' not yet visited
25746 	 *            if pre[s] == 0:
25747 	 *                recur(s)
25748 	 *            # if 's' is on stack, pick lowest reachable preorder number from it;
25749 	 *            # if 's' is not on stack 'low[s] == NOT_ON_STACK > low[w]',
25750 	 *            # so 'min' would be a noop.
25751 	 *            low[w] = min(low[w], low[s])
25752 	 *
25753 	 *        if low[w] == pre[w]:
25754 	 *            # 'w' is the root of an SCC, pop all vertices
25755 	 *            # below 'w' on stack and assign same SCC to them.
25756 	 *            while True:
25757 	 *                t = stack.pop()
25758 	 *                low[t] = NOT_ON_STACK
25759 	 *                scc[t] = next_scc_id
25760 	 *                if t == w:
25761 	 *                    break
25762 	 *            next_scc_id += 1
25763 	 *
25764 	 *    for i in range(0, insn_cnt):
25765 	 *        if pre[i] == 0:
25766 	 *            recur(i)
25767 	 *
25768 	 * Below implementation replaces explicit recursion with array 'dfs'.
25769 	 */
25770 	for (i = 0; i < insn_cnt; i++) {
25771 		if (pre[i])
25772 			continue;
25773 		stack_sz = 0;
25774 		dfs_sz = 1;
25775 		dfs[0] = i;
25776 dfs_continue:
25777 		while (dfs_sz) {
25778 			w = dfs[dfs_sz - 1];
25779 			if (pre[w] == 0) {
25780 				low[w] = next_preorder_num;
25781 				pre[w] = next_preorder_num;
25782 				next_preorder_num++;
25783 				stack[stack_sz++] = w;
25784 			}
25785 			/* Visit 'w' successors */
25786 			succ = bpf_insn_successors(env, w);
25787 			for (j = 0; j < succ->cnt; ++j) {
25788 				if (pre[succ->items[j]]) {
25789 					low[w] = min(low[w], low[succ->items[j]]);
25790 				} else {
25791 					dfs[dfs_sz++] = succ->items[j];
25792 					goto dfs_continue;
25793 				}
25794 			}
25795 			/*
25796 			 * Preserve the invariant: if some vertex above in the stack
25797 			 * is reachable from 'w', keep 'w' on the stack.
25798 			 */
25799 			if (low[w] < pre[w]) {
25800 				dfs_sz--;
25801 				goto dfs_continue;
25802 			}
25803 			/*
25804 			 * Assign SCC number only if component has two or more elements,
25805 			 * or if component has a self reference, or if instruction is a
25806 			 * callback calling function (implicit loop).
25807 			 */
25808 			assign_scc = stack[stack_sz - 1] != w;	/* two or more elements? */
25809 			for (j = 0; j < succ->cnt; ++j) {	/* self reference? */
25810 				if (succ->items[j] == w) {
25811 					assign_scc = true;
25812 					break;
25813 				}
25814 			}
25815 			if (bpf_calls_callback(env, w)) /* implicit loop? */
25816 				assign_scc = true;
25817 			/* Pop component elements from stack */
25818 			do {
25819 				t = stack[--stack_sz];
25820 				low[t] = NOT_ON_STACK;
25821 				if (assign_scc)
25822 					aux[t].scc = next_scc_id;
25823 			} while (t != w);
25824 			if (assign_scc)
25825 				next_scc_id++;
25826 			dfs_sz--;
25827 		}
25828 	}
25829 	env->scc_info = kvcalloc(next_scc_id, sizeof(*env->scc_info), GFP_KERNEL_ACCOUNT);
25830 	if (!env->scc_info) {
25831 		err = -ENOMEM;
25832 		goto exit;
25833 	}
25834 	env->scc_cnt = next_scc_id;
25835 exit:
25836 	kvfree(stack);
25837 	kvfree(pre);
25838 	kvfree(low);
25839 	kvfree(dfs);
25840 	return err;
25841 }
25842 
25843 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
25844 {
25845 	u64 start_time = ktime_get_ns();
25846 	struct bpf_verifier_env *env;
25847 	int i, len, ret = -EINVAL, err;
25848 	u32 log_true_size;
25849 	bool is_priv;
25850 
25851 	BTF_TYPE_EMIT(enum bpf_features);
25852 
25853 	/* no program is valid */
25854 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
25855 		return -EINVAL;
25856 
25857 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
25858 	 * allocate/free it every time bpf_check() is called
25859 	 */
25860 	env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL_ACCOUNT);
25861 	if (!env)
25862 		return -ENOMEM;
25863 
25864 	env->bt.env = env;
25865 
25866 	len = (*prog)->len;
25867 	env->insn_aux_data =
25868 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
25869 	ret = -ENOMEM;
25870 	if (!env->insn_aux_data)
25871 		goto err_free_env;
25872 	for (i = 0; i < len; i++)
25873 		env->insn_aux_data[i].orig_idx = i;
25874 	env->succ = iarray_realloc(NULL, 2);
25875 	if (!env->succ)
25876 		goto err_free_env;
25877 	env->prog = *prog;
25878 	env->ops = bpf_verifier_ops[env->prog->type];
25879 
25880 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
25881 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
25882 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
25883 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
25884 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
25885 
25886 	bpf_get_btf_vmlinux();
25887 
25888 	/* grab the mutex to protect few globals used by verifier */
25889 	if (!is_priv)
25890 		mutex_lock(&bpf_verifier_lock);
25891 
25892 	/* user could have requested verbose verifier output
25893 	 * and supplied buffer to store the verification trace
25894 	 */
25895 	ret = bpf_vlog_init(&env->log, attr->log_level,
25896 			    (char __user *) (unsigned long) attr->log_buf,
25897 			    attr->log_size);
25898 	if (ret)
25899 		goto err_unlock;
25900 
25901 	ret = process_fd_array(env, attr, uattr);
25902 	if (ret)
25903 		goto skip_full_check;
25904 
25905 	mark_verifier_state_clean(env);
25906 
25907 	if (IS_ERR(btf_vmlinux)) {
25908 		/* Either gcc or pahole or kernel are broken. */
25909 		verbose(env, "in-kernel BTF is malformed\n");
25910 		ret = PTR_ERR(btf_vmlinux);
25911 		goto skip_full_check;
25912 	}
25913 
25914 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
25915 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
25916 		env->strict_alignment = true;
25917 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
25918 		env->strict_alignment = false;
25919 
25920 	if (is_priv)
25921 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
25922 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
25923 
25924 	env->explored_states = kvcalloc(state_htab_size(env),
25925 				       sizeof(struct list_head),
25926 				       GFP_KERNEL_ACCOUNT);
25927 	ret = -ENOMEM;
25928 	if (!env->explored_states)
25929 		goto skip_full_check;
25930 
25931 	for (i = 0; i < state_htab_size(env); i++)
25932 		INIT_LIST_HEAD(&env->explored_states[i]);
25933 	INIT_LIST_HEAD(&env->free_list);
25934 
25935 	ret = check_btf_info_early(env, attr, uattr);
25936 	if (ret < 0)
25937 		goto skip_full_check;
25938 
25939 	ret = add_subprog_and_kfunc(env);
25940 	if (ret < 0)
25941 		goto skip_full_check;
25942 
25943 	ret = check_subprogs(env);
25944 	if (ret < 0)
25945 		goto skip_full_check;
25946 
25947 	ret = check_btf_info(env, attr, uattr);
25948 	if (ret < 0)
25949 		goto skip_full_check;
25950 
25951 	ret = resolve_pseudo_ldimm64(env);
25952 	if (ret < 0)
25953 		goto skip_full_check;
25954 
25955 	if (bpf_prog_is_offloaded(env->prog->aux)) {
25956 		ret = bpf_prog_offload_verifier_prep(env->prog);
25957 		if (ret)
25958 			goto skip_full_check;
25959 	}
25960 
25961 	ret = check_cfg(env);
25962 	if (ret < 0)
25963 		goto skip_full_check;
25964 
25965 	ret = compute_postorder(env);
25966 	if (ret < 0)
25967 		goto skip_full_check;
25968 
25969 	ret = bpf_stack_liveness_init(env);
25970 	if (ret)
25971 		goto skip_full_check;
25972 
25973 	ret = check_attach_btf_id(env);
25974 	if (ret)
25975 		goto skip_full_check;
25976 
25977 	ret = compute_scc(env);
25978 	if (ret < 0)
25979 		goto skip_full_check;
25980 
25981 	ret = compute_live_registers(env);
25982 	if (ret < 0)
25983 		goto skip_full_check;
25984 
25985 	ret = mark_fastcall_patterns(env);
25986 	if (ret < 0)
25987 		goto skip_full_check;
25988 
25989 	ret = do_check_main(env);
25990 	ret = ret ?: do_check_subprogs(env);
25991 
25992 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
25993 		ret = bpf_prog_offload_finalize(env);
25994 
25995 skip_full_check:
25996 	kvfree(env->explored_states);
25997 
25998 	/* might decrease stack depth, keep it before passes that
25999 	 * allocate additional slots.
26000 	 */
26001 	if (ret == 0)
26002 		ret = remove_fastcall_spills_fills(env);
26003 
26004 	if (ret == 0)
26005 		ret = check_max_stack_depth(env);
26006 
26007 	/* instruction rewrites happen after this point */
26008 	if (ret == 0)
26009 		ret = optimize_bpf_loop(env);
26010 
26011 	if (is_priv) {
26012 		if (ret == 0)
26013 			opt_hard_wire_dead_code_branches(env);
26014 		if (ret == 0)
26015 			ret = opt_remove_dead_code(env);
26016 		if (ret == 0)
26017 			ret = opt_remove_nops(env);
26018 	} else {
26019 		if (ret == 0)
26020 			sanitize_dead_code(env);
26021 	}
26022 
26023 	if (ret == 0)
26024 		/* program is valid, convert *(u32*)(ctx + off) accesses */
26025 		ret = convert_ctx_accesses(env);
26026 
26027 	if (ret == 0)
26028 		ret = do_misc_fixups(env);
26029 
26030 	/* do 32-bit optimization after insn patching has done so those patched
26031 	 * insns could be handled correctly.
26032 	 */
26033 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
26034 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
26035 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
26036 								     : false;
26037 	}
26038 
26039 	if (ret == 0)
26040 		ret = fixup_call_args(env);
26041 
26042 	env->verification_time = ktime_get_ns() - start_time;
26043 	print_verification_stats(env);
26044 	env->prog->aux->verified_insns = env->insn_processed;
26045 
26046 	/* preserve original error even if log finalization is successful */
26047 	err = bpf_vlog_finalize(&env->log, &log_true_size);
26048 	if (err)
26049 		ret = err;
26050 
26051 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
26052 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
26053 				  &log_true_size, sizeof(log_true_size))) {
26054 		ret = -EFAULT;
26055 		goto err_release_maps;
26056 	}
26057 
26058 	if (ret)
26059 		goto err_release_maps;
26060 
26061 	if (env->used_map_cnt) {
26062 		/* if program passed verifier, update used_maps in bpf_prog_info */
26063 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
26064 							  sizeof(env->used_maps[0]),
26065 							  GFP_KERNEL_ACCOUNT);
26066 
26067 		if (!env->prog->aux->used_maps) {
26068 			ret = -ENOMEM;
26069 			goto err_release_maps;
26070 		}
26071 
26072 		memcpy(env->prog->aux->used_maps, env->used_maps,
26073 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
26074 		env->prog->aux->used_map_cnt = env->used_map_cnt;
26075 	}
26076 	if (env->used_btf_cnt) {
26077 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
26078 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
26079 							  sizeof(env->used_btfs[0]),
26080 							  GFP_KERNEL_ACCOUNT);
26081 		if (!env->prog->aux->used_btfs) {
26082 			ret = -ENOMEM;
26083 			goto err_release_maps;
26084 		}
26085 
26086 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
26087 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
26088 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
26089 	}
26090 	if (env->used_map_cnt || env->used_btf_cnt) {
26091 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
26092 		 * bpf_ld_imm64 instructions
26093 		 */
26094 		convert_pseudo_ld_imm64(env);
26095 	}
26096 
26097 	adjust_btf_func(env);
26098 
26099 err_release_maps:
26100 	if (ret)
26101 		release_insn_arrays(env);
26102 	if (!env->prog->aux->used_maps)
26103 		/* if we didn't copy map pointers into bpf_prog_info, release
26104 		 * them now. Otherwise free_used_maps() will release them.
26105 		 */
26106 		release_maps(env);
26107 	if (!env->prog->aux->used_btfs)
26108 		release_btfs(env);
26109 
26110 	/* extension progs temporarily inherit the attach_type of their targets
26111 	   for verification purposes, so set it back to zero before returning
26112 	 */
26113 	if (env->prog->type == BPF_PROG_TYPE_EXT)
26114 		env->prog->expected_attach_type = 0;
26115 
26116 	*prog = env->prog;
26117 
26118 	module_put(env->attach_btf_mod);
26119 err_unlock:
26120 	if (!is_priv)
26121 		mutex_unlock(&bpf_verifier_lock);
26122 	clear_insn_aux_data(env, 0, env->prog->len);
26123 	vfree(env->insn_aux_data);
26124 err_free_env:
26125 	bpf_stack_liveness_free(env);
26126 	kvfree(env->cfg.insn_postorder);
26127 	kvfree(env->scc_info);
26128 	kvfree(env->succ);
26129 	kvfree(env->gotox_tmp_buf);
26130 	kvfree(env);
26131 	return ret;
26132 }
26133